1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
55679
55680
55681
55682
55683
55684
55685
55686
55687
55688
55689
55690
55691
55692
55693
55694
55695
55696
55697
55698
55699
55700
55701
55702
55703
55704
55705
55706
55707
55708
55709
55710
55711
55712
55713
55714
55715
55716
55717
55718
55719
55720
55721
55722
55723
55724
55725
55726
55727
55728
55729
55730
55731
55732
55733
55734
55735
55736
55737
55738
55739
55740
55741
55742
55743
55744
55745
55746
55747
55748
55749
55750
55751
55752
55753
55754
55755
55756
55757
55758
55759
55760
55761
55762
55763
55764
55765
55766
55767
55768
55769
55770
55771
55772
55773
55774
55775
55776
55777
55778
55779
55780
55781
55782
55783
55784
55785
55786
55787
55788
55789
55790
55791
55792
55793
55794
55795
55796
55797
55798
55799
55800
55801
55802
55803
55804
55805
55806
55807
55808
55809
55810
55811
55812
55813
55814
55815
55816
55817
55818
55819
55820
55821
55822
55823
55824
55825
55826
55827
55828
55829
55830
55831
55832
55833
55834
55835
55836
55837
55838
55839
55840
55841
55842
55843
55844
55845
55846
55847
55848
55849
55850
55851
55852
55853
55854
55855
55856
55857
55858
55859
55860
55861
55862
55863
55864
55865
55866
55867
55868
55869
55870
55871
55872
55873
55874
55875
55876
55877
55878
55879
55880
55881
55882
55883
55884
55885
55886
55887
55888
55889
55890
55891
55892
55893
55894
55895
55896
55897
55898
55899
55900
55901
55902
55903
55904
55905
55906
55907
55908
55909
55910
55911
55912
55913
55914
55915
55916
55917
55918
55919
55920
55921
55922
55923
55924
55925
55926
55927
55928
55929
55930
55931
55932
55933
55934
55935
55936
55937
55938
55939
55940
55941
55942
55943
55944
55945
55946
55947
55948
55949
55950
55951
55952
55953
55954
55955
55956
55957
55958
55959
55960
55961
55962
55963
55964
55965
55966
55967
55968
55969
55970
55971
55972
55973
55974
55975
55976
55977
55978
55979
55980
55981
55982
55983
55984
55985
55986
55987
55988
55989
55990
55991
55992
55993
55994
55995
55996
55997
55998
55999
56000
56001
56002
56003
56004
56005
56006
56007
56008
56009
56010
56011
56012
56013
56014
56015
56016
56017
56018
56019
56020
56021
56022
56023
56024
56025
56026
56027
56028
56029
56030
56031
56032
56033
56034
56035
56036
56037
56038
56039
56040
56041
56042
56043
56044
56045
56046
56047
56048
56049
56050
56051
56052
56053
56054
56055
56056
56057
56058
56059
56060
56061
56062
56063
56064
56065
56066
56067
56068
56069
56070
56071
56072
56073
56074
56075
56076
56077
56078
56079
56080
56081
56082
56083
56084
56085
56086
56087
56088
56089
56090
56091
56092
56093
56094
56095
56096
56097
56098
56099
56100
56101
56102
56103
56104
56105
56106
56107
56108
56109
56110
56111
56112
56113
56114
56115
56116
56117
56118
56119
56120
56121
56122
56123
56124
56125
56126
56127
56128
56129
56130
56131
56132
56133
56134
56135
56136
56137
56138
56139
56140
56141
56142
56143
56144
56145
56146
56147
56148
56149
56150
56151
56152
56153
56154
56155
56156
56157
56158
56159
56160
56161
56162
56163
56164
56165
56166
56167
56168
56169
56170
56171
56172
56173
56174
56175
56176
56177
56178
56179
56180
56181
56182
56183
56184
56185
56186
56187
56188
56189
56190
56191
56192
56193
56194
56195
56196
56197
56198
56199
56200
56201
56202
56203
56204
56205
56206
56207
56208
56209
56210
56211
56212
56213
56214
56215
56216
56217
56218
56219
56220
56221
56222
56223
56224
56225
56226
56227
56228
56229
56230
56231
56232
56233
56234
56235
56236
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260
56261
56262
56263
56264
56265
56266
56267
56268
56269
56270
56271
56272
56273
56274
56275
56276
56277
56278
56279
56280
56281
56282
56283
56284
56285
56286
56287
56288
56289
56290
56291
56292
56293
56294
56295
56296
56297
56298
56299
56300
56301
56302
56303
56304
56305
56306
56307
56308
56309
56310
56311
56312
56313
56314
56315
56316
56317
56318
56319
56320
56321
56322
56323
56324
56325
56326
56327
56328
56329
56330
56331
56332
56333
56334
56335
56336
56337
56338
56339
56340
56341
56342
56343
56344
56345
56346
56347
56348
56349
56350
56351
56352
56353
56354
56355
56356
56357
56358
56359
56360
56361
56362
56363
56364
56365
56366
56367
56368
56369
56370
56371
56372
56373
56374
56375
56376
56377
56378
56379
56380
56381
56382
56383
56384
56385
56386
56387
56388
56389
56390
56391
56392
56393
56394
56395
56396
56397
56398
56399
56400
56401
56402
56403
56404
56405
56406
56407
56408
56409
56410
56411
56412
56413
56414
56415
56416
56417
56418
56419
56420
56421
56422
56423
56424
56425
56426
56427
56428
56429
56430
56431
56432
56433
56434
56435
56436
56437
56438
56439
56440
56441
56442
56443
56444
56445
56446
56447
56448
56449
56450
56451
56452
56453
56454
56455
56456
56457
56458
56459
56460
56461
56462
56463
56464
56465
56466
56467
56468
56469
56470
56471
56472
56473
56474
56475
56476
56477
56478
56479
56480
56481
56482
56483
56484
56485
56486
56487
56488
56489
56490
56491
56492
56493
56494
56495
56496
56497
56498
56499
56500
56501
56502
56503
56504
56505
56506
56507
56508
56509
56510
56511
56512
56513
56514
56515
56516
56517
56518
56519
56520
56521
56522
56523
56524
56525
56526
56527
56528
56529
56530
56531
56532
56533
56534
56535
56536
56537
56538
56539
56540
56541
56542
56543
56544
56545
56546
56547
56548
56549
56550
56551
56552
56553
56554
56555
56556
56557
56558
56559
56560
56561
56562
56563
56564
56565
56566
56567
56568
56569
56570
56571
56572
56573
56574
56575
56576
56577
56578
56579
56580
56581
56582
56583
56584
56585
56586
56587
56588
56589
56590
56591
56592
56593
56594
56595
56596
56597
56598
56599
56600
56601
56602
56603
56604
56605
56606
56607
56608
56609
56610
56611
56612
56613
56614
56615
56616
56617
56618
56619
56620
56621
56622
56623
56624
56625
56626
56627
56628
56629
56630
56631
56632
56633
56634
56635
56636
56637
56638
56639
56640
56641
56642
56643
56644
56645
56646
56647
56648
56649
56650
56651
56652
56653
56654
56655
56656
56657
56658
56659
56660
56661
56662
56663
56664
56665
56666
56667
56668
56669
56670
56671
56672
56673
56674
56675
56676
56677
56678
56679
56680
56681
56682
56683
56684
56685
56686
56687
56688
56689
56690
56691
56692
56693
56694
56695
56696
56697
56698
56699
56700
56701
56702
56703
56704
56705
56706
56707
56708
56709
56710
56711
56712
56713
56714
56715
56716
56717
56718
56719
56720
56721
56722
56723
56724
56725
56726
56727
56728
56729
56730
56731
56732
56733
56734
56735
56736
56737
56738
56739
56740
56741
56742
56743
56744
56745
56746
56747
56748
56749
56750
56751
56752
56753
56754
56755
56756
56757
56758
56759
56760
56761
56762
56763
56764
56765
56766
56767
56768
56769
56770
56771
56772
56773
56774
56775
56776
56777
56778
56779
56780
56781
56782
56783
56784
56785
56786
56787
56788
56789
56790
56791
56792
56793
56794
56795
56796
56797
56798
56799
56800
56801
56802
56803
56804
56805
56806
56807
56808
56809
56810
56811
56812
56813
56814
56815
56816
56817
56818
56819
56820
56821
56822
56823
56824
56825
56826
56827
56828
56829
56830
56831
56832
56833
56834
56835
56836
56837
56838
56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854
56855
56856
56857
56858
56859
56860
56861
56862
56863
56864
56865
56866
56867
56868
56869
56870
56871
56872
56873
56874
56875
56876
56877
56878
56879
56880
56881
56882
56883
56884
56885
56886
56887
56888
56889
56890
56891
56892
56893
56894
56895
56896
56897
56898
56899
56900
56901
56902
56903
56904
56905
56906
56907
56908
56909
56910
56911
56912
56913
56914
56915
56916
56917
56918
56919
56920
56921
56922
56923
56924
56925
56926
56927
56928
56929
56930
56931
56932
56933
56934
56935
56936
56937
56938
56939
56940
56941
56942
56943
56944
56945
56946
56947
56948
56949
56950
56951
56952
56953
56954
56955
56956
56957
56958
56959
56960
56961
56962
56963
56964
56965
56966
56967
56968
56969
56970
56971
56972
56973
56974
56975
56976
56977
56978
56979
56980
56981
56982
56983
56984
56985
56986
56987
56988
56989
56990
56991
56992
56993
56994
56995
56996
56997
56998
56999
57000
57001
57002
57003
57004
57005
57006
57007
57008
57009
57010
57011
57012
57013
57014
57015
57016
57017
57018
57019
57020
57021
57022
57023
57024
57025
57026
57027
57028
57029
57030
57031
57032
57033
57034
57035
57036
57037
57038
57039
57040
57041
57042
57043
57044
57045
57046
57047
57048
57049
57050
57051
57052
57053
57054
57055
57056
57057
57058
57059
57060
57061
57062
57063
57064
57065
57066
57067
57068
57069
57070
57071
57072
57073
57074
57075
57076
57077
57078
57079
57080
57081
57082
57083
57084
57085
57086
57087
57088
57089
57090
57091
57092
57093
57094
57095
57096
57097
57098
57099
57100
57101
57102
57103
57104
57105
57106
57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
57122
57123
57124
57125
57126
57127
57128
57129
57130
57131
57132
57133
57134
57135
57136
57137
57138
57139
57140
57141
57142
57143
57144
57145
57146
57147
57148
57149
57150
57151
57152
57153
57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169
57170
57171
57172
57173
57174
57175
57176
57177
57178
57179
57180
57181
57182
57183
57184
57185
57186
57187
57188
57189
57190
57191
57192
57193
57194
57195
57196
57197
57198
57199
57200
57201
57202
57203
57204
57205
57206
57207
57208
57209
57210
57211
57212
57213
57214
57215
57216
57217
57218
57219
57220
57221
57222
57223
57224
57225
57226
57227
57228
57229
57230
57231
57232
57233
57234
57235
57236
57237
57238
57239
57240
57241
57242
57243
57244
57245
57246
57247
57248
57249
57250
57251
57252
57253
57254
57255
57256
57257
57258
57259
57260
57261
57262
57263
57264
57265
57266
57267
57268
57269
57270
57271
57272
57273
57274
57275
57276
57277
57278
57279
57280
57281
57282
57283
57284
57285
57286
57287
57288
57289
57290
57291
57292
57293
57294
57295
57296
57297
57298
57299
57300
57301
57302
57303
57304
57305
57306
57307
57308
57309
57310
57311
57312
57313
57314
57315
57316
57317
57318
57319
57320
57321
57322
57323
57324
57325
57326
57327
57328
57329
57330
57331
57332
57333
57334
57335
57336
57337
57338
57339
57340
57341
57342
57343
57344
57345
57346
57347
57348
57349
57350
57351
57352
57353
57354
57355
57356
57357
57358
57359
57360
57361
57362
57363
57364
57365
57366
57367
57368
57369
57370
57371
57372
57373
57374
57375
57376
57377
57378
57379
57380
57381
57382
57383
57384
57385
57386
57387
57388
57389
57390
57391
57392
57393
57394
57395
57396
57397
57398
57399
57400
57401
57402
57403
57404
57405
57406
57407
57408
57409
57410
57411
57412
57413
57414
57415
57416
57417
57418
57419
57420
57421
57422
57423
57424
57425
57426
57427
57428
57429
57430
57431
57432
57433
57434
57435
57436
57437
57438
57439
57440
57441
57442
57443
57444
57445
57446
57447
57448
57449
57450
57451
57452
57453
57454
57455
57456
57457
57458
57459
57460
57461
57462
57463
57464
57465
57466
57467
57468
57469
57470
57471
57472
57473
57474
57475
57476
57477
57478
57479
57480
57481
57482
57483
57484
57485
57486
57487
57488
57489
57490
57491
57492
57493
57494
57495
57496
57497
57498
57499
57500
57501
57502
57503
57504
57505
57506
57507
57508
57509
57510
57511
57512
57513
57514
57515
57516
57517
57518
57519
57520
57521
57522
57523
57524
57525
57526
57527
57528
57529
57530
57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549
57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568
57569
57570
57571
57572
57573
57574
57575
57576
57577
57578
57579
57580
57581
57582
57583
57584
57585
57586
57587
57588
57589
57590
57591
57592
57593
57594
57595
57596
57597
57598
57599
57600
57601
57602
57603
57604
57605
57606
57607
57608
57609
57610
57611
57612
57613
57614
57615
57616
57617
57618
57619
57620
57621
57622
57623
57624
57625
57626
57627
57628
57629
57630
57631
57632
57633
57634
57635
57636
57637
57638
57639
57640
57641
57642
57643
57644
57645
57646
57647
57648
57649
57650
57651
57652
57653
57654
57655
57656
57657
57658
57659
57660
57661
57662
57663
57664
57665
57666
57667
57668
57669
57670
57671
57672
57673
57674
57675
57676
57677
57678
57679
57680
57681
57682
57683
57684
57685
57686
57687
57688
57689
57690
57691
57692
57693
57694
57695
57696
57697
57698
57699
57700
57701
57702
57703
57704
57705
57706
57707
57708
57709
57710
57711
57712
57713
57714
57715
57716
57717
57718
57719
57720
57721
57722
57723
57724
57725
57726
57727
57728
57729
57730
57731
57732
57733
57734
57735
57736
57737
57738
57739
57740
57741
57742
57743
57744
57745
57746
57747
57748
57749
57750
57751
57752
57753
57754
57755
57756
57757
57758
57759
57760
57761
57762
57763
57764
57765
57766
57767
57768
57769
57770
57771
57772
57773
57774
57775
57776
57777
57778
57779
57780
57781
57782
57783
57784
57785
57786
57787
57788
57789
57790
57791
57792
57793
57794
57795
57796
57797
57798
57799
57800
57801
57802
57803
57804
57805
57806
57807
57808
57809
57810
57811
57812
57813
57814
57815
57816
57817
57818
57819
57820
57821
57822
57823
57824
57825
57826
57827
57828
57829
57830
57831
57832
57833
57834
57835
57836
57837
57838
57839
57840
57841
57842
57843
57844
57845
57846
57847
57848
57849
57850
57851
57852
57853
57854
57855
57856
57857
57858
57859
57860
57861
57862
57863
57864
57865
57866
57867
57868
57869
57870
57871
57872
57873
57874
57875
57876
57877
57878
57879
57880
57881
57882
57883
57884
57885
57886
57887
57888
57889
57890
57891
57892
57893
57894
57895
57896
57897
57898
57899
57900
57901
57902
57903
57904
57905
57906
57907
57908
57909
57910
57911
57912
57913
57914
57915
57916
57917
57918
57919
57920
57921
57922
57923
57924
57925
57926
57927
57928
57929
57930
57931
57932
57933
57934
57935
57936
57937
57938
57939
57940
57941
57942
57943
57944
57945
57946
57947
57948
57949
57950
57951
57952
57953
57954
57955
57956
57957
57958
57959
57960
57961
57962
57963
57964
57965
57966
57967
57968
57969
57970
57971
57972
57973
57974
57975
57976
57977
57978
57979
57980
57981
57982
57983
57984
57985
57986
57987
57988
57989
57990
57991
57992
57993
57994
57995
57996
57997
57998
57999
58000
58001
58002
58003
58004
58005
58006
58007
58008
58009
58010
58011
58012
58013
58014
58015
58016
58017
58018
58019
58020
58021
58022
58023
58024
58025
58026
58027
58028
58029
58030
58031
58032
58033
58034
58035
58036
58037
58038
58039
58040
58041
58042
58043
58044
58045
58046
58047
58048
58049
58050
58051
58052
58053
58054
58055
58056
58057
58058
58059
58060
58061
58062
58063
58064
58065
58066
58067
58068
58069
58070
58071
58072
58073
58074
58075
58076
58077
58078
58079
58080
58081
58082
58083
58084
58085
58086
58087
58088
58089
58090
58091
58092
58093
58094
58095
58096
58097
58098
58099
58100
58101
58102
58103
58104
58105
58106
58107
58108
58109
58110
58111
58112
58113
58114
58115
58116
58117
58118
58119
58120
58121
58122
58123
58124
58125
58126
58127
58128
58129
58130
58131
58132
58133
58134
58135
58136
58137
58138
58139
58140
58141
58142
58143
58144
58145
58146
58147
58148
58149
58150
58151
58152
58153
58154
58155
58156
58157
58158
58159
58160
58161
58162
58163
58164
58165
58166
58167
58168
58169
58170
58171
58172
58173
58174
58175
58176
58177
58178
58179
58180
58181
58182
58183
58184
58185
58186
58187
58188
58189
58190
58191
58192
58193
58194
58195
58196
58197
58198
58199
58200
58201
58202
58203
58204
58205
58206
58207
58208
58209
58210
58211
58212
58213
58214
58215
58216
58217
58218
58219
58220
58221
58222
58223
58224
58225
58226
58227
58228
58229
58230
58231
58232
58233
58234
58235
58236
58237
58238
58239
58240
58241
58242
58243
58244
58245
58246
58247
58248
58249
58250
58251
58252
58253
58254
58255
58256
58257
58258
58259
58260
58261
58262
58263
58264
58265
58266
58267
58268
58269
58270
58271
58272
58273
58274
58275
58276
58277
58278
58279
58280
58281
58282
58283
58284
58285
58286
58287
58288
58289
58290
58291
58292
58293
58294
58295
58296
58297
58298
58299
58300
58301
58302
58303
58304
58305
58306
58307
58308
58309
58310
58311
58312
58313
58314
58315
58316
58317
58318
58319
58320
58321
58322
58323
58324
58325
58326
58327
58328
58329
58330
58331
58332
58333
58334
58335
58336
58337
58338
58339
58340
58341
58342
58343
58344
58345
58346
58347
58348
58349
58350
58351
58352
58353
58354
58355
58356
58357
58358
58359
58360
58361
58362
58363
58364
58365
58366
58367
58368
58369
58370
58371
58372
58373
58374
58375
58376
58377
58378
58379
58380
58381
58382
58383
58384
58385
58386
58387
58388
58389
58390
58391
58392
58393
58394
58395
58396
58397
58398
58399
58400
58401
58402
58403
58404
58405
58406
58407
58408
58409
58410
58411
58412
58413
58414
58415
58416
58417
58418
58419
58420
58421
58422
58423
58424
58425
58426
58427
58428
58429
58430
58431
58432
58433
58434
58435
58436
58437
58438
58439
58440
58441
58442
58443
58444
58445
58446
58447
58448
58449
58450
58451
58452
58453
58454
58455
58456
58457
58458
58459
58460
58461
58462
58463
58464
58465
58466
58467
58468
58469
58470
58471
58472
58473
58474
58475
58476
58477
58478
58479
58480
58481
58482
58483
58484
58485
58486
58487
58488
58489
58490
58491
58492
58493
58494
58495
58496
58497
58498
58499
58500
58501
58502
58503
58504
58505
58506
58507
58508
58509
58510
58511
58512
58513
58514
58515
58516
58517
58518
58519
58520
58521
58522
58523
58524
58525
58526
58527
58528
58529
58530
58531
58532
58533
58534
58535
58536
58537
58538
58539
58540
58541
58542
58543
58544
58545
58546
58547
58548
58549
58550
58551
58552
58553
58554
58555
58556
58557
58558
58559
58560
58561
58562
58563
58564
58565
58566
58567
58568
58569
58570
58571
58572
58573
58574
58575
58576
58577
58578
58579
58580
58581
58582
58583
58584
58585
58586
58587
58588
58589
58590
58591
58592
58593
58594
58595
58596
58597
58598
58599
58600
58601
58602
58603
58604
58605
58606
58607
58608
58609
58610
58611
58612
58613
58614
58615
58616
58617
58618
58619
58620
58621
58622
58623
58624
58625
58626
58627
58628
58629
58630
58631
58632
58633
58634
58635
58636
58637
58638
58639
58640
58641
58642
58643
58644
58645
58646
58647
58648
58649
58650
58651
58652
58653
58654
58655
58656
58657
58658
58659
58660
58661
58662
58663
58664
58665
58666
58667
58668
58669
58670
58671
58672
58673
58674
58675
58676
58677
58678
58679
58680
58681
58682
58683
58684
58685
58686
58687
58688
58689
58690
58691
58692
58693
58694
58695
58696
58697
58698
58699
58700
58701
58702
58703
58704
58705
58706
58707
58708
58709
58710
58711
58712
58713
58714
58715
58716
58717
58718
58719
58720
58721
58722
58723
58724
58725
58726
58727
58728
58729
58730
58731
58732
58733
58734
58735
58736
58737
58738
58739
58740
58741
58742
58743
58744
58745
58746
58747
58748
58749
58750
58751
58752
58753
58754
58755
58756
58757
58758
58759
58760
58761
58762
58763
58764
58765
58766
58767
58768
58769
58770
58771
58772
58773
58774
58775
58776
58777
58778
58779
58780
58781
58782
58783
58784
58785
58786
58787
58788
58789
58790
58791
58792
58793
58794
58795
58796
58797
58798
58799
58800
58801
58802
58803
58804
58805
58806
58807
58808
58809
58810
58811
58812
58813
58814
58815
58816
58817
58818
58819
58820
58821
58822
58823
58824
58825
58826
58827
58828
58829
58830
58831
58832
58833
58834
58835
58836
58837
58838
58839
58840
58841
58842
58843
58844
58845
58846
58847
58848
58849
58850
58851
58852
58853
58854
58855
58856
58857
58858
58859
58860
58861
58862
58863
58864
58865
58866
58867
58868
58869
58870
58871
58872
58873
58874
58875
58876
58877
58878
58879
58880
58881
58882
58883
58884
58885
58886
58887
58888
58889
58890
58891
58892
58893
58894
58895
58896
58897
58898
58899
58900
58901
58902
58903
58904
58905
58906
58907
58908
58909
58910
58911
58912
58913
58914
58915
58916
58917
58918
58919
58920
58921
58922
58923
58924
58925
58926
58927
58928
58929
58930
58931
58932
58933
58934
58935
58936
58937
58938
58939
58940
58941
58942
58943
58944
58945
58946
58947
58948
58949
58950
58951
58952
58953
58954
58955
58956
58957
58958
58959
58960
58961
58962
58963
58964
58965
58966
58967
58968
58969
58970
58971
58972
58973
58974
58975
58976
58977
58978
58979
58980
58981
58982
58983
58984
58985
58986
58987
58988
58989
58990
58991
58992
58993
58994
58995
58996
58997
58998
58999
59000
59001
59002
59003
59004
59005
59006
59007
59008
59009
59010
59011
59012
59013
59014
59015
59016
59017
59018
59019
59020
59021
59022
59023
59024
59025
59026
59027
59028
59029
59030
59031
59032
59033
59034
59035
59036
59037
59038
59039
59040
59041
59042
59043
59044
59045
59046
59047
59048
59049
59050
59051
59052
59053
59054
59055
59056
59057
59058
59059
59060
59061
59062
59063
59064
59065
59066
59067
59068
59069
59070
59071
59072
59073
59074
59075
59076
59077
59078
59079
59080
59081
59082
59083
59084
59085
59086
59087
59088
59089
59090
59091
59092
59093
59094
59095
59096
59097
59098
59099
59100
59101
59102
59103
59104
59105
59106
59107
59108
59109
59110
59111
59112
59113
59114
59115
59116
59117
59118
59119
59120
59121
59122
59123
59124
59125
59126
59127
59128
59129
59130
59131
59132
59133
59134
59135
59136
59137
59138
59139
59140
59141
59142
59143
59144
59145
59146
59147
59148
59149
59150
59151
59152
59153
59154
59155
59156
59157
59158
59159
59160
59161
59162
59163
59164
59165
59166
59167
59168
59169
59170
59171
59172
59173
59174
59175
59176
59177
59178
59179
59180
59181
59182
59183
59184
59185
59186
59187
59188
59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199
59200
59201
59202
59203
59204
59205
59206
59207
59208
59209
59210
59211
59212
59213
59214
59215
59216
59217
59218
59219
59220
59221
59222
59223
59224
59225
59226
59227
59228
59229
59230
59231
59232
59233
59234
59235
59236
59237
59238
59239
59240
59241
59242
59243
59244
59245
59246
59247
59248
59249
59250
59251
59252
59253
59254
59255
59256
59257
59258
59259
59260
59261
59262
59263
59264
59265
59266
59267
59268
59269
59270
59271
59272
59273
59274
59275
59276
59277
59278
59279
59280
59281
59282
59283
59284
59285
59286
59287
59288
59289
59290
59291
59292
59293
59294
59295
59296
59297
59298
59299
59300
59301
59302
59303
59304
59305
59306
59307
59308
59309
59310
59311
59312
59313
59314
59315
59316
59317
59318
59319
59320
59321
59322
59323
59324
59325
59326
59327
59328
59329
59330
59331
59332
59333
59334
59335
59336
59337
59338
59339
59340
59341
59342
59343
59344
59345
59346
59347
59348
59349
59350
59351
59352
59353
59354
59355
59356
59357
59358
59359
59360
59361
59362
59363
59364
59365
59366
59367
59368
59369
59370
59371
59372
59373
59374
59375
59376
59377
59378
59379
59380
59381
59382
59383
59384
59385
59386
59387
59388
59389
59390
59391
59392
59393
59394
59395
59396
59397
59398
59399
59400
59401
59402
59403
59404
59405
59406
59407
59408
59409
59410
59411
59412
59413
59414
59415
59416
59417
59418
59419
59420
59421
59422
59423
59424
59425
59426
59427
59428
59429
59430
59431
59432
59433
59434
59435
59436
59437
59438
59439
59440
59441
59442
59443
59444
59445
59446
59447
59448
59449
59450
59451
59452
59453
59454
59455
59456
59457
59458
59459
59460
59461
59462
59463
59464
59465
59466
59467
59468
59469
59470
59471
59472
59473
59474
59475
59476
59477
59478
59479
59480
59481
59482
59483
59484
59485
59486
59487
59488
59489
59490
59491
59492
59493
59494
59495
59496
59497
59498
59499
59500
59501
59502
59503
59504
59505
59506
59507
59508
59509
59510
59511
59512
59513
59514
59515
59516
59517
59518
59519
59520
59521
59522
59523
59524
59525
59526
59527
59528
59529
59530
59531
59532
59533
59534
59535
59536
59537
59538
59539
59540
59541
59542
59543
59544
59545
59546
59547
59548
59549
59550
59551
59552
59553
59554
59555
59556
59557
59558
59559
59560
59561
59562
59563
59564
59565
59566
59567
59568
59569
59570
59571
59572
59573
59574
59575
59576
59577
59578
59579
59580
59581
59582
59583
59584
59585
59586
59587
59588
59589
59590
59591
59592
59593
59594
59595
59596
59597
59598
59599
59600
59601
59602
59603
59604
59605
59606
59607
59608
59609
59610
59611
59612
59613
59614
59615
59616
59617
59618
59619
59620
59621
59622
59623
59624
59625
59626
59627
59628
59629
59630
59631
59632
59633
59634
59635
59636
59637
59638
59639
59640
59641
59642
59643
59644
59645
59646
59647
59648
59649
59650
59651
59652
59653
59654
59655
59656
59657
59658
59659
59660
59661
59662
59663
59664
59665
59666
59667
59668
59669
59670
59671
59672
59673
59674
59675
59676
59677
59678
59679
59680
59681
59682
59683
59684
59685
59686
59687
59688
59689
59690
59691
59692
59693
59694
59695
59696
59697
59698
59699
59700
59701
59702
59703
59704
59705
59706
59707
59708
59709
59710
59711
59712
59713
59714
59715
59716
59717
59718
59719
59720
59721
59722
59723
59724
59725
59726
59727
59728
59729
59730
59731
59732
59733
59734
59735
59736
59737
59738
59739
59740
59741
59742
59743
59744
59745
59746
59747
59748
59749
59750
59751
59752
59753
59754
59755
59756
59757
59758
59759
59760
59761
59762
59763
59764
59765
59766
59767
59768
59769
59770
59771
59772
59773
59774
59775
59776
59777
59778
59779
59780
59781
59782
59783
59784
59785
59786
59787
59788
59789
59790
59791
59792
59793
59794
59795
59796
59797
59798
59799
59800
59801
59802
59803
59804
59805
59806
59807
59808
59809
59810
59811
59812
59813
59814
59815
59816
59817
59818
59819
59820
59821
59822
59823
59824
59825
59826
59827
59828
59829
59830
59831
59832
59833
59834
59835
59836
59837
59838
59839
59840
59841
59842
59843
59844
59845
59846
59847
59848
59849
59850
59851
59852
59853
59854
59855
59856
59857
59858
59859
59860
59861
59862
59863
59864
59865
59866
59867
59868
59869
59870
59871
59872
59873
59874
59875
59876
59877
59878
59879
59880
59881
59882
59883
59884
59885
59886
59887
59888
59889
59890
59891
59892
59893
59894
59895
59896
59897
59898
59899
59900
59901
59902
59903
59904
59905
59906
59907
59908
59909
59910
59911
59912
59913
59914
59915
59916
59917
59918
59919
59920
59921
59922
59923
59924
59925
59926
59927
59928
59929
59930
59931
59932
59933
59934
59935
59936
59937
59938
59939
59940
59941
59942
59943
59944
59945
59946
59947
59948
59949
59950
59951
59952
59953
59954
59955
59956
59957
59958
59959
59960
59961
59962
59963
59964
59965
59966
59967
59968
59969
59970
59971
59972
59973
59974
59975
59976
59977
59978
59979
59980
59981
59982
59983
59984
59985
59986
59987
59988
59989
59990
59991
59992
59993
59994
59995
59996
59997
59998
59999
60000
60001
60002
60003
60004
60005
60006
60007
60008
60009
60010
60011
60012
60013
60014
60015
60016
60017
60018
60019
60020
60021
60022
60023
60024
60025
60026
60027
60028
60029
60030
60031
60032
60033
60034
60035
60036
60037
60038
60039
60040
60041
60042
60043
60044
60045
60046
60047
60048
60049
60050
60051
60052
60053
60054
60055
60056
60057
60058
60059
60060
60061
60062
60063
60064
60065
60066
60067
60068
60069
60070
60071
60072
60073
60074
60075
60076
60077
60078
60079
60080
60081
60082
60083
60084
60085
60086
60087
60088
60089
60090
60091
60092
60093
60094
60095
60096
60097
60098
60099
60100
60101
60102
60103
60104
60105
60106
60107
60108
60109
60110
60111
60112
60113
60114
60115
60116
60117
60118
60119
60120
60121
60122
60123
60124
60125
60126
60127
60128
60129
60130
60131
60132
60133
60134
60135
60136
60137
60138
60139
60140
60141
60142
60143
60144
60145
60146
60147
60148
60149
60150
60151
60152
60153
60154
60155
60156
60157
60158
60159
60160
60161
60162
60163
60164
60165
60166
60167
60168
60169
60170
60171
60172
60173
60174
60175
60176
60177
60178
60179
60180
60181
60182
60183
60184
60185
60186
60187
60188
60189
60190
60191
60192
60193
60194
60195
60196
60197
60198
60199
60200
60201
60202
60203
60204
60205
60206
60207
60208
60209
60210
60211
60212
60213
60214
60215
60216
60217
60218
60219
60220
60221
60222
60223
60224
60225
60226
60227
60228
60229
60230
60231
60232
60233
60234
60235
60236
60237
60238
60239
60240
60241
60242
60243
60244
60245
60246
60247
60248
60249
60250
60251
60252
60253
60254
60255
60256
60257
60258
60259
60260
60261
60262
60263
60264
60265
60266
60267
60268
60269
60270
60271
60272
60273
60274
60275
60276
60277
60278
60279
60280
60281
60282
60283
60284
60285
60286
60287
60288
60289
60290
60291
60292
60293
60294
60295
60296
60297
60298
60299
60300
60301
60302
60303
60304
60305
60306
60307
60308
60309
60310
60311
60312
60313
60314
60315
60316
60317
60318
60319
60320
60321
60322
60323
60324
60325
60326
60327
60328
60329
60330
60331
60332
60333
60334
60335
60336
60337
60338
60339
60340
60341
60342
60343
60344
60345
60346
60347
60348
60349
60350
60351
60352
60353
60354
60355
60356
60357
60358
60359
60360
60361
60362
60363
60364
60365
60366
60367
60368
60369
60370
60371
60372
60373
60374
60375
60376
60377
60378
60379
60380
60381
60382
60383
60384
60385
60386
60387
60388
60389
60390
60391
60392
60393
60394
60395
60396
60397
60398
60399
60400
60401
60402
60403
60404
60405
60406
60407
60408
60409
60410
60411
60412
60413
60414
60415
60416
60417
60418
60419
60420
60421
60422
60423
60424
60425
60426
60427
60428
60429
60430
60431
60432
60433
60434
60435
60436
60437
60438
60439
60440
60441
60442
60443
60444
60445
60446
60447
60448
60449
60450
60451
60452
60453
60454
60455
60456
60457
60458
60459
60460
60461
60462
60463
60464
60465
60466
60467
60468
60469
60470
60471
60472
60473
60474
60475
60476
60477
60478
60479
60480
60481
60482
60483
60484
60485
60486
60487
60488
60489
60490
60491
60492
60493
60494
60495
60496
60497
60498
60499
60500
60501
60502
60503
60504
60505
60506
60507
60508
60509
60510
60511
60512
60513
60514
60515
60516
60517
60518
60519
60520
60521
60522
60523
60524
60525
60526
60527
60528
60529
60530
60531
60532
60533
60534
60535
60536
60537
60538
60539
60540
60541
60542
60543
60544
60545
60546
60547
60548
60549
60550
60551
60552
60553
60554
60555
60556
60557
60558
60559
60560
60561
60562
60563
60564
60565
60566
60567
60568
60569
60570
60571
60572
60573
60574
60575
60576
60577
60578
60579
60580
60581
60582
60583
60584
60585
60586
60587
60588
60589
60590
60591
60592
60593
60594
60595
60596
60597
60598
60599
60600
60601
60602
60603
60604
60605
60606
60607
60608
60609
60610
60611
60612
60613
60614
60615
60616
60617
60618
60619
60620
60621
60622
60623
60624
60625
60626
60627
60628
60629
60630
60631
60632
60633
60634
60635
60636
60637
60638
60639
60640
60641
60642
60643
60644
60645
60646
60647
60648
60649
60650
60651
60652
60653
60654
60655
60656
60657
60658
60659
60660
60661
60662
60663
60664
60665
60666
60667
60668
60669
60670
60671
60672
60673
60674
60675
60676
60677
60678
60679
60680
60681
60682
60683
60684
60685
60686
60687
60688
60689
60690
60691
60692
60693
60694
60695
60696
60697
60698
60699
60700
60701
60702
60703
60704
60705
60706
60707
60708
60709
60710
60711
60712
60713
60714
60715
60716
60717
60718
60719
60720
60721
60722
60723
60724
60725
60726
60727
60728
60729
60730
60731
60732
60733
60734
60735
60736
60737
60738
60739
60740
60741
60742
60743
60744
60745
60746
60747
60748
60749
60750
60751
60752
60753
60754
60755
60756
60757
60758
60759
60760
60761
60762
60763
60764
60765
60766
60767
60768
60769
60770
60771
60772
60773
60774
60775
60776
60777
60778
60779
60780
60781
60782
60783
60784
60785
60786
60787
60788
60789
60790
60791
60792
60793
60794
60795
60796
60797
60798
60799
60800
60801
60802
60803
60804
60805
60806
60807
60808
60809
60810
60811
60812
60813
60814
60815
60816
60817
60818
60819
60820
60821
60822
60823
60824
60825
60826
60827
60828
60829
60830
60831
60832
60833
60834
60835
60836
60837
60838
60839
60840
60841
60842
60843
60844
60845
60846
60847
60848
60849
60850
60851
60852
60853
60854
60855
60856
60857
60858
60859
60860
60861
60862
60863
60864
60865
60866
60867
60868
60869
60870
60871
60872
60873
60874
60875
60876
60877
60878
60879
60880
60881
60882
60883
60884
60885
60886
60887
60888
60889
60890
60891
60892
60893
60894
60895
60896
60897
60898
60899
60900
60901
60902
60903
60904
60905
60906
60907
60908
60909
60910
60911
60912
60913
60914
60915
60916
60917
60918
60919
60920
60921
60922
60923
60924
60925
60926
60927
60928
60929
60930
60931
60932
60933
60934
60935
60936
60937
60938
60939
60940
60941
60942
60943
60944
60945
60946
60947
60948
60949
60950
60951
60952
60953
60954
60955
60956
60957
60958
60959
60960
60961
60962
60963
60964
60965
60966
60967
60968
60969
60970
60971
60972
60973
60974
60975
60976
60977
60978
60979
60980
60981
60982
60983
60984
60985
60986
60987
60988
60989
60990
60991
60992
60993
60994
60995
60996
60997
60998
60999
61000
61001
61002
61003
61004
61005
61006
61007
61008
61009
61010
61011
61012
61013
61014
61015
61016
61017
61018
61019
61020
61021
61022
61023
61024
61025
61026
61027
61028
61029
61030
61031
61032
61033
61034
61035
61036
61037
61038
61039
61040
61041
61042
61043
61044
61045
61046
61047
61048
61049
61050
61051
61052
61053
61054
61055
61056
61057
61058
61059
61060
61061
61062
61063
61064
61065
61066
61067
61068
61069
61070
61071
61072
61073
61074
61075
61076
61077
61078
61079
61080
61081
61082
61083
61084
61085
61086
61087
61088
61089
61090
61091
61092
61093
61094
61095
61096
61097
61098
61099
61100
61101
61102
61103
61104
61105
61106
61107
61108
61109
61110
61111
61112
61113
61114
61115
61116
61117
61118
61119
61120
61121
61122
61123
61124
61125
61126
61127
61128
61129
61130
61131
61132
61133
61134
61135
61136
61137
61138
61139
61140
61141
61142
61143
61144
61145
61146
61147
61148
61149
61150
61151
61152
61153
61154
61155
61156
61157
61158
61159
61160
61161
61162
61163
61164
61165
61166
61167
61168
61169
61170
61171
61172
61173
61174
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
61190
61191
61192
61193
61194
61195
61196
61197
61198
61199
61200
61201
61202
61203
61204
61205
61206
61207
61208
61209
61210
61211
61212
61213
61214
61215
61216
61217
61218
61219
61220
61221
61222
61223
61224
61225
61226
61227
61228
61229
61230
61231
61232
61233
61234
61235
61236
61237
61238
61239
61240
61241
61242
61243
61244
61245
61246
61247
61248
61249
61250
61251
61252
61253
61254
61255
61256
61257
61258
61259
61260
61261
61262
61263
61264
61265
61266
61267
61268
61269
61270
61271
61272
61273
61274
61275
61276
61277
61278
61279
61280
61281
61282
61283
61284
61285
61286
61287
61288
61289
61290
61291
61292
61293
61294
61295
61296
61297
61298
61299
61300
61301
61302
61303
61304
61305
61306
61307
61308
61309
61310
61311
61312
61313
61314
61315
61316
61317
61318
61319
61320
61321
61322
61323
61324
61325
61326
61327
61328
61329
61330
61331
61332
61333
61334
61335
61336
61337
61338
61339
61340
61341
61342
61343
61344
61345
61346
61347
61348
61349
61350
61351
61352
61353
61354
61355
61356
61357
61358
61359
61360
61361
61362
61363
61364
61365
61366
61367
61368
61369
61370
61371
61372
61373
61374
61375
61376
61377
61378
61379
61380
61381
61382
61383
61384
61385
61386
61387
61388
61389
61390
61391
61392
61393
61394
61395
61396
61397
61398
61399
61400
61401
61402
61403
61404
61405
61406
61407
61408
61409
61410
61411
61412
61413
61414
61415
61416
61417
61418
61419
61420
61421
61422
61423
61424
61425
61426
61427
61428
61429
61430
61431
61432
61433
61434
61435
61436
61437
61438
61439
61440
61441
61442
61443
61444
61445
61446
61447
61448
61449
61450
61451
61452
61453
61454
61455
61456
61457
61458
61459
61460
61461
61462
61463
61464
61465
61466
61467
61468
61469
61470
61471
61472
61473
61474
61475
61476
61477
61478
61479
61480
61481
61482
61483
61484
61485
61486
61487
61488
61489
61490
61491
61492
61493
61494
61495
61496
61497
61498
61499
61500
61501
61502
61503
61504
61505
61506
61507
61508
61509
61510
61511
61512
61513
61514
61515
61516
61517
61518
61519
61520
61521
61522
61523
61524
61525
61526
61527
61528
61529
61530
61531
61532
61533
61534
61535
61536
61537
61538
61539
61540
61541
61542
61543
61544
61545
61546
61547
61548
61549
61550
61551
61552
61553
61554
61555
61556
61557
61558
61559
61560
61561
61562
61563
61564
61565
61566
61567
61568
61569
61570
61571
61572
61573
61574
61575
61576
61577
61578
61579
61580
61581
61582
61583
61584
61585
61586
61587
61588
61589
61590
61591
61592
61593
61594
61595
61596
61597
61598
61599
61600
61601
61602
61603
61604
61605
61606
61607
61608
61609
61610
61611
61612
61613
61614
61615
61616
61617
61618
61619
61620
61621
61622
61623
61624
61625
61626
61627
61628
61629
61630
61631
61632
61633
61634
61635
61636
61637
61638
61639
61640
61641
61642
61643
61644
61645
61646
61647
61648
61649
61650
61651
61652
61653
61654
61655
61656
61657
61658
61659
61660
61661
61662
61663
61664
61665
61666
61667
61668
61669
61670
61671
61672
61673
61674
61675
61676
61677
61678
61679
61680
61681
61682
61683
61684
61685
61686
61687
61688
61689
61690
61691
61692
61693
61694
61695
61696
61697
61698
61699
61700
61701
61702
61703
61704
61705
61706
61707
61708
61709
61710
61711
61712
61713
61714
61715
61716
61717
61718
61719
61720
61721
61722
61723
61724
61725
61726
61727
61728
61729
61730
61731
61732
61733
61734
61735
61736
61737
61738
61739
61740
61741
61742
61743
61744
61745
61746
61747
61748
61749
61750
61751
61752
61753
61754
61755
61756
61757
61758
61759
61760
61761
61762
61763
61764
61765
61766
61767
61768
61769
61770
61771
61772
61773
61774
61775
61776
61777
61778
61779
61780
61781
61782
61783
61784
61785
61786
61787
61788
61789
61790
61791
61792
61793
61794
61795
61796
61797
61798
61799
61800
61801
61802
61803
61804
61805
61806
61807
61808
61809
61810
61811
61812
61813
61814
61815
61816
61817
61818
61819
61820
61821
61822
61823
61824
61825
61826
61827
61828
61829
61830
61831
61832
61833
61834
61835
61836
61837
61838
61839
61840
61841
61842
61843
61844
61845
61846
61847
61848
61849
61850
61851
61852
61853
61854
61855
61856
61857
61858
61859
61860
61861
61862
61863
61864
61865
61866
61867
61868
61869
61870
61871
61872
61873
61874
61875
61876
61877
61878
61879
61880
61881
61882
61883
61884
61885
61886
61887
61888
61889
61890
61891
61892
61893
61894
61895
61896
61897
61898
61899
61900
61901
61902
61903
61904
61905
61906
61907
61908
61909
61910
61911
61912
61913
61914
61915
61916
61917
61918
61919
61920
61921
61922
61923
61924
61925
61926
61927
61928
61929
61930
61931
61932
61933
61934
61935
61936
61937
61938
61939
61940
61941
61942
61943
61944
61945
61946
61947
61948
61949
61950
61951
61952
61953
61954
61955
61956
61957
61958
61959
61960
61961
61962
61963
61964
61965
61966
61967
61968
61969
61970
61971
61972
61973
61974
61975
61976
61977
61978
61979
61980
61981
61982
61983
61984
61985
61986
61987
61988
61989
61990
61991
61992
61993
61994
61995
61996
61997
61998
61999
62000
62001
62002
62003
62004
62005
62006
62007
62008
62009
62010
62011
62012
62013
62014
62015
62016
62017
62018
62019
62020
62021
62022
62023
62024
62025
62026
62027
62028
62029
62030
62031
62032
62033
62034
62035
62036
62037
62038
62039
62040
62041
62042
62043
62044
62045
62046
62047
62048
62049
62050
62051
62052
62053
62054
62055
62056
62057
62058
62059
62060
62061
62062
62063
62064
62065
62066
62067
62068
62069
62070
62071
62072
62073
62074
62075
62076
62077
62078
62079
62080
62081
62082
62083
62084
62085
62086
62087
62088
62089
62090
62091
62092
62093
62094
62095
62096
62097
62098
62099
62100
62101
62102
62103
62104
62105
62106
62107
62108
62109
62110
62111
62112
62113
62114
62115
62116
62117
62118
62119
62120
62121
62122
62123
62124
62125
62126
62127
62128
62129
62130
62131
62132
62133
62134
62135
62136
62137
62138
62139
62140
62141
62142
62143
62144
62145
62146
62147
62148
62149
62150
62151
62152
62153
62154
62155
62156
62157
62158
62159
62160
62161
62162
62163
62164
62165
62166
62167
62168
62169
62170
62171
62172
62173
62174
62175
62176
62177
62178
62179
62180
62181
62182
62183
62184
62185
62186
62187
62188
62189
62190
62191
62192
62193
62194
62195
62196
62197
62198
62199
62200
62201
62202
62203
62204
62205
62206
62207
62208
62209
62210
62211
62212
62213
62214
62215
62216
62217
62218
62219
62220
62221
62222
62223
62224
62225
62226
62227
62228
62229
62230
62231
62232
62233
62234
62235
62236
62237
62238
62239
62240
62241
62242
62243
62244
62245
62246
62247
62248
62249
62250
62251
62252
62253
62254
62255
62256
62257
62258
62259
62260
62261
62262
62263
62264
62265
62266
62267
62268
62269
62270
62271
62272
62273
62274
62275
62276
62277
62278
62279
62280
62281
62282
62283
62284
62285
62286
62287
62288
62289
62290
62291
62292
62293
62294
62295
62296
62297
62298
62299
62300
62301
62302
62303
62304
62305
62306
62307
62308
62309
62310
62311
62312
62313
62314
62315
62316
62317
62318
62319
62320
62321
62322
62323
62324
62325
62326
62327
62328
62329
62330
62331
62332
62333
62334
62335
62336
62337
62338
62339
62340
62341
62342
62343
62344
62345
62346
62347
62348
62349
62350
62351
62352
62353
62354
62355
62356
62357
62358
62359
62360
62361
62362
62363
62364
62365
62366
62367
62368
62369
62370
62371
62372
62373
62374
62375
62376
62377
62378
62379
62380
62381
62382
62383
62384
62385
62386
62387
62388
62389
62390
62391
62392
62393
62394
62395
62396
62397
62398
62399
62400
62401
62402
62403
62404
62405
62406
62407
62408
62409
62410
62411
62412
62413
62414
62415
62416
62417
62418
62419
62420
62421
62422
62423
62424
62425
62426
62427
62428
62429
62430
62431
62432
62433
62434
62435
62436
62437
62438
62439
62440
62441
62442
62443
62444
62445
62446
62447
62448
62449
62450
62451
62452
62453
62454
62455
62456
62457
62458
62459
62460
62461
62462
62463
62464
62465
62466
62467
62468
62469
62470
62471
62472
62473
62474
62475
62476
62477
62478
62479
62480
62481
62482
62483
62484
62485
62486
62487
62488
62489
62490
62491
62492
62493
62494
62495
62496
62497
62498
62499
62500
62501
62502
62503
62504
62505
62506
62507
62508
62509
62510
62511
62512
62513
62514
62515
62516
62517
62518
62519
62520
62521
62522
62523
62524
62525
62526
62527
62528
62529
62530
62531
62532
62533
62534
62535
62536
62537
62538
62539
62540
62541
62542
62543
62544
62545
62546
62547
62548
62549
62550
62551
62552
62553
62554
62555
62556
62557
62558
62559
62560
62561
62562
62563
62564
62565
62566
62567
62568
62569
62570
62571
62572
62573
62574
62575
62576
62577
62578
62579
62580
62581
62582
62583
62584
62585
62586
62587
62588
62589
62590
62591
62592
62593
62594
62595
62596
62597
62598
62599
62600
62601
62602
62603
62604
62605
62606
62607
62608
62609
62610
62611
62612
62613
62614
62615
62616
62617
62618
62619
62620
62621
62622
62623
62624
62625
62626
62627
62628
62629
62630
62631
62632
62633
62634
62635
62636
62637
62638
62639
62640
62641
62642
62643
62644
62645
62646
62647
62648
62649
62650
62651
62652
62653
62654
62655
62656
62657
62658
62659
62660
62661
62662
62663
62664
62665
62666
62667
62668
62669
62670
62671
62672
62673
62674
62675
62676
62677
62678
62679
62680
62681
62682
62683
62684
62685
62686
62687
62688
62689
62690
62691
62692
62693
62694
62695
62696
62697
62698
62699
62700
62701
62702
62703
62704
62705
62706
62707
62708
62709
62710
62711
62712
62713
62714
62715
62716
62717
62718
62719
62720
62721
62722
62723
62724
62725
62726
62727
62728
62729
62730
62731
62732
62733
62734
62735
62736
62737
62738
62739
62740
62741
62742
62743
62744
62745
62746
62747
62748
62749
62750
62751
62752
62753
62754
62755
62756
62757
62758
62759
62760
62761
62762
62763
62764
62765
62766
62767
62768
62769
62770
62771
62772
62773
62774
62775
62776
62777
62778
62779
62780
62781
62782
62783
62784
62785
62786
62787
62788
62789
62790
62791
62792
62793
62794
62795
62796
62797
62798
62799
62800
62801
62802
62803
62804
62805
62806
62807
62808
62809
62810
62811
62812
62813
62814
62815
62816
62817
62818
62819
62820
62821
62822
62823
62824
62825
62826
62827
62828
62829
62830
62831
62832
62833
62834
62835
62836
62837
62838
62839
62840
62841
62842
62843
62844
62845
62846
62847
62848
62849
62850
62851
62852
62853
62854
62855
62856
62857
62858
62859
62860
62861
62862
62863
62864
62865
62866
62867
62868
62869
62870
62871
62872
62873
62874
62875
62876
62877
62878
62879
62880
62881
62882
62883
62884
62885
62886
62887
62888
62889
62890
62891
62892
62893
62894
62895
62896
62897
62898
62899
62900
62901
62902
62903
62904
62905
62906
62907
62908
62909
62910
62911
62912
62913
62914
62915
62916
62917
62918
62919
62920
62921
62922
62923
62924
62925
62926
62927
62928
62929
62930
62931
62932
62933
62934
62935
62936
62937
62938
62939
62940
62941
62942
62943
62944
62945
62946
62947
62948
62949
62950
62951
62952
62953
62954
62955
62956
62957
62958
62959
62960
62961
62962
62963
62964
62965
62966
62967
62968
62969
62970
62971
62972
62973
62974
62975
62976
62977
62978
62979
62980
62981
62982
62983
62984
62985
62986
62987
62988
62989
62990
62991
62992
62993
62994
62995
62996
62997
62998
62999
63000
63001
63002
63003
63004
63005
63006
63007
63008
63009
63010
63011
63012
63013
63014
63015
63016
63017
63018
63019
63020
63021
63022
63023
63024
63025
63026
63027
63028
63029
63030
63031
63032
63033
63034
63035
63036
63037
63038
63039
63040
63041
63042
63043
63044
63045
63046
63047
63048
63049
63050
63051
63052
63053
63054
63055
63056
63057
63058
63059
63060
63061
63062
63063
63064
63065
63066
63067
63068
63069
63070
63071
63072
63073
63074
63075
63076
63077
63078
63079
63080
63081
63082
63083
63084
63085
63086
63087
63088
63089
63090
63091
63092
63093
63094
63095
63096
63097
63098
63099
63100
63101
63102
63103
63104
63105
63106
63107
63108
63109
63110
63111
63112
63113
63114
63115
63116
63117
63118
63119
63120
63121
63122
63123
63124
63125
63126
63127
63128
63129
63130
63131
63132
63133
63134
63135
63136
63137
63138
63139
63140
63141
63142
63143
63144
63145
63146
63147
63148
63149
63150
63151
63152
63153
63154
63155
63156
63157
63158
63159
63160
63161
63162
63163
63164
63165
63166
63167
63168
63169
63170
63171
63172
63173
63174
63175
63176
63177
63178
63179
63180
63181
63182
63183
63184
63185
63186
63187
63188
63189
63190
63191
63192
63193
63194
63195
63196
63197
63198
63199
63200
63201
63202
63203
63204
63205
63206
63207
63208
63209
63210
63211
63212
63213
63214
63215
63216
63217
63218
63219
63220
63221
63222
63223
63224
63225
63226
63227
63228
63229
63230
63231
63232
63233
63234
63235
63236
63237
63238
63239
63240
63241
63242
63243
63244
63245
63246
63247
63248
63249
63250
63251
63252
63253
63254
63255
63256
63257
63258
63259
63260
63261
63262
63263
63264
63265
63266
63267
63268
63269
63270
63271
63272
63273
63274
63275
63276
63277
63278
63279
63280
63281
63282
63283
63284
63285
63286
63287
63288
63289
63290
63291
63292
63293
63294
63295
63296
63297
63298
63299
63300
63301
63302
63303
63304
63305
63306
63307
63308
63309
63310
63311
63312
63313
63314
63315
63316
63317
63318
63319
63320
63321
63322
63323
63324
63325
63326
63327
63328
63329
63330
63331
63332
63333
63334
63335
63336
63337
63338
63339
63340
63341
63342
63343
63344
63345
63346
63347
63348
63349
63350
63351
63352
63353
63354
63355
63356
63357
63358
63359
63360
63361
63362
63363
63364
63365
63366
63367
63368
63369
63370
63371
63372
63373
63374
63375
63376
63377
63378
63379
63380
63381
63382
63383
63384
63385
63386
63387
63388
63389
63390
63391
63392
63393
63394
63395
63396
63397
63398
63399
63400
63401
63402
63403
63404
63405
63406
63407
63408
63409
63410
63411
63412
63413
63414
63415
63416
63417
63418
63419
63420
63421
63422
63423
63424
63425
63426
63427
63428
63429
63430
63431
63432
63433
63434
63435
63436
63437
63438
63439
63440
63441
63442
63443
63444
63445
63446
63447
63448
63449
63450
63451
63452
63453
63454
63455
63456
63457
63458
63459
63460
63461
63462
63463
63464
63465
63466
63467
63468
63469
63470
63471
63472
63473
63474
63475
63476
63477
63478
63479
63480
63481
63482
63483
63484
63485
63486
63487
63488
63489
63490
63491
63492
63493
63494
63495
63496
63497
63498
63499
63500
63501
63502
63503
63504
63505
63506
63507
63508
63509
63510
63511
63512
63513
63514
63515
63516
63517
63518
63519
63520
63521
63522
63523
63524
63525
63526
63527
63528
63529
63530
63531
63532
63533
63534
63535
63536
63537
63538
63539
63540
63541
63542
63543
63544
63545
63546
63547
63548
63549
63550
63551
63552
63553
63554
63555
63556
63557
63558
63559
63560
63561
63562
63563
63564
63565
63566
63567
63568
63569
63570
63571
63572
63573
63574
63575
63576
63577
63578
63579
63580
63581
63582
63583
63584
63585
63586
63587
63588
63589
63590
63591
63592
63593
63594
63595
63596
63597
63598
63599
63600
63601
63602
63603
63604
63605
63606
63607
63608
63609
63610
63611
63612
63613
63614
63615
63616
63617
63618
63619
63620
63621
63622
63623
63624
63625
63626
63627
63628
63629
63630
63631
63632
63633
63634
63635
63636
63637
63638
63639
63640
63641
63642
63643
63644
63645
63646
63647
63648
63649
63650
63651
63652
63653
63654
63655
63656
63657
63658
63659
63660
63661
63662
63663
63664
63665
63666
63667
63668
63669
63670
63671
63672
63673
63674
63675
63676
63677
63678
63679
63680
63681
63682
63683
63684
63685
63686
63687
63688
63689
63690
63691
63692
63693
63694
63695
63696
63697
63698
63699
63700
63701
63702
63703
63704
63705
63706
63707
63708
63709
63710
63711
63712
63713
63714
63715
63716
63717
63718
63719
63720
63721
63722
63723
63724
63725
63726
63727
63728
63729
63730
63731
63732
63733
63734
63735
63736
63737
63738
63739
63740
63741
63742
63743
63744
63745
63746
63747
63748
63749
63750
63751
63752
63753
63754
63755
63756
63757
63758
63759
63760
63761
63762
63763
63764
63765
63766
63767
63768
63769
63770
63771
63772
63773
63774
63775
63776
63777
63778
63779
63780
63781
63782
63783
63784
63785
63786
63787
63788
63789
63790
63791
63792
63793
63794
63795
63796
63797
63798
63799
63800
63801
63802
63803
63804
63805
63806
63807
63808
63809
63810
63811
63812
63813
63814
63815
63816
63817
63818
63819
63820
63821
63822
63823
63824
63825
63826
63827
63828
63829
63830
63831
63832
63833
63834
63835
63836
63837
63838
63839
63840
63841
63842
63843
63844
63845
63846
63847
63848
63849
63850
63851
63852
63853
63854
63855
63856
63857
63858
63859
63860
63861
63862
63863
63864
63865
63866
63867
63868
63869
63870
63871
63872
63873
63874
63875
63876
63877
63878
63879
63880
63881
63882
63883
63884
63885
63886
63887
63888
63889
63890
63891
63892
63893
63894
63895
63896
63897
63898
63899
63900
63901
63902
63903
63904
63905
63906
63907
63908
63909
63910
63911
63912
63913
63914
63915
63916
63917
63918
63919
63920
63921
63922
63923
63924
63925
63926
63927
63928
63929
63930
63931
63932
63933
63934
63935
63936
63937
63938
63939
63940
63941
63942
63943
63944
63945
63946
63947
63948
63949
63950
63951
63952
63953
63954
63955
63956
63957
63958
63959
63960
63961
63962
63963
63964
63965
63966
63967
63968
63969
63970
63971
63972
63973
63974
63975
63976
63977
63978
63979
63980
63981
63982
63983
63984
63985
63986
63987
63988
63989
63990
63991
63992
63993
63994
63995
63996
63997
63998
63999
64000
64001
64002
64003
64004
64005
64006
64007
64008
64009
64010
64011
64012
64013
64014
64015
64016
64017
64018
64019
64020
64021
64022
64023
64024
64025
64026
64027
64028
64029
64030
64031
64032
64033
64034
64035
64036
64037
64038
64039
64040
64041
64042
64043
64044
64045
64046
64047
64048
64049
64050
64051
64052
64053
64054
64055
64056
64057
64058
64059
64060
64061
64062
64063
64064
64065
64066
64067
64068
64069
64070
64071
64072
64073
64074
64075
64076
64077
64078
64079
64080
64081
64082
64083
64084
64085
64086
64087
64088
64089
64090
64091
64092
64093
64094
64095
64096
64097
64098
64099
64100
64101
64102
64103
64104
64105
64106
64107
64108
64109
64110
64111
64112
64113
64114
64115
64116
64117
64118
64119
64120
64121
64122
64123
64124
64125
64126
64127
64128
64129
64130
64131
64132
64133
64134
64135
64136
64137
64138
64139
64140
64141
64142
64143
64144
64145
64146
64147
64148
64149
64150
64151
64152
64153
64154
64155
64156
64157
64158
64159
64160
64161
64162
64163
64164
64165
64166
64167
64168
64169
64170
64171
64172
64173
64174
64175
64176
64177
64178
64179
64180
64181
64182
64183
64184
64185
64186
64187
64188
64189
64190
64191
64192
64193
64194
64195
64196
64197
64198
64199
64200
64201
64202
64203
64204
64205
64206
64207
64208
64209
64210
64211
64212
64213
64214
64215
64216
64217
64218
64219
64220
64221
64222
64223
64224
64225
64226
64227
64228
64229
64230
64231
64232
64233
64234
64235
64236
64237
64238
64239
64240
64241
64242
64243
64244
64245
64246
64247
64248
64249
64250
64251
64252
64253
64254
64255
64256
64257
64258
64259
64260
64261
64262
64263
64264
64265
64266
64267
64268
64269
64270
64271
64272
64273
64274
64275
64276
64277
64278
64279
64280
64281
64282
64283
64284
64285
64286
64287
64288
64289
64290
64291
64292
64293
64294
64295
64296
64297
64298
64299
64300
64301
64302
64303
64304
64305
64306
64307
64308
64309
64310
64311
64312
64313
64314
64315
64316
64317
64318
64319
64320
64321
64322
64323
64324
64325
64326
64327
64328
64329
64330
64331
64332
64333
64334
64335
64336
64337
64338
64339
64340
64341
64342
64343
64344
64345
64346
64347
64348
64349
64350
64351
64352
64353
64354
64355
64356
64357
64358
64359
64360
64361
64362
64363
64364
64365
64366
64367
64368
64369
64370
64371
64372
64373
64374
64375
64376
64377
64378
64379
64380
64381
64382
64383
64384
64385
64386
64387
64388
64389
64390
64391
64392
64393
64394
64395
64396
64397
64398
64399
64400
64401
64402
64403
64404
64405
64406
64407
64408
64409
64410
64411
64412
64413
64414
64415
64416
64417
64418
64419
64420
64421
64422
64423
64424
64425
64426
64427
64428
64429
64430
64431
64432
64433
64434
64435
64436
64437
64438
64439
64440
64441
64442
64443
64444
64445
64446
64447
64448
64449
64450
64451
64452
64453
64454
64455
64456
64457
64458
64459
64460
64461
64462
64463
64464
64465
64466
64467
64468
64469
64470
64471
64472
64473
64474
64475
64476
64477
64478
64479
64480
64481
64482
64483
64484
64485
64486
64487
64488
64489
64490
64491
64492
64493
64494
64495
64496
64497
64498
64499
64500
64501
64502
64503
64504
64505
64506
64507
64508
64509
64510
64511
64512
64513
64514
64515
64516
64517
64518
64519
64520
64521
64522
64523
64524
64525
64526
64527
64528
64529
64530
64531
64532
64533
64534
64535
64536
64537
64538
64539
64540
64541
64542
64543
64544
64545
64546
64547
64548
64549
64550
64551
64552
64553
64554
64555
64556
64557
64558
64559
64560
64561
64562
64563
64564
64565
64566
64567
64568
64569
64570
64571
64572
64573
64574
64575
64576
64577
64578
64579
64580
64581
64582
64583
64584
64585
64586
64587
64588
64589
64590
64591
64592
64593
64594
64595
64596
64597
64598
64599
64600
64601
64602
64603
64604
64605
64606
64607
64608
64609
64610
64611
64612
64613
64614
64615
64616
64617
64618
64619
64620
64621
64622
64623
64624
64625
64626
64627
64628
64629
64630
64631
64632
64633
64634
64635
64636
64637
64638
64639
64640
64641
64642
64643
64644
64645
64646
64647
64648
64649
64650
64651
64652
64653
64654
64655
64656
64657
64658
64659
64660
64661
64662
64663
64664
64665
64666
64667
64668
64669
64670
64671
64672
64673
64674
64675
64676
64677
64678
64679
64680
64681
64682
64683
64684
64685
64686
64687
64688
64689
64690
64691
64692
64693
64694
64695
64696
64697
64698
64699
64700
64701
64702
64703
64704
64705
64706
64707
64708
64709
64710
64711
64712
64713
64714
64715
64716
64717
64718
64719
64720
64721
64722
64723
64724
64725
64726
64727
64728
64729
64730
64731
64732
64733
64734
64735
64736
64737
64738
64739
64740
64741
64742
64743
64744
64745
64746
64747
64748
64749
64750
64751
64752
64753
64754
64755
64756
64757
64758
64759
64760
64761
64762
64763
64764
64765
64766
64767
64768
64769
64770
64771
64772
64773
64774
64775
64776
64777
64778
64779
64780
64781
64782
64783
64784
64785
64786
64787
64788
64789
64790
64791
64792
64793
64794
64795
64796
64797
64798
64799
64800
64801
64802
64803
64804
64805
64806
64807
64808
64809
64810
64811
64812
64813
64814
64815
64816
64817
64818
64819
64820
64821
64822
64823
64824
64825
64826
64827
64828
64829
64830
64831
64832
64833
64834
64835
64836
64837
64838
64839
64840
64841
64842
64843
64844
64845
64846
64847
64848
64849
64850
64851
64852
64853
64854
64855
64856
64857
64858
64859
64860
64861
64862
64863
64864
64865
64866
64867
64868
64869
64870
64871
64872
64873
64874
64875
64876
64877
64878
64879
64880
64881
64882
64883
64884
64885
64886
64887
64888
64889
64890
64891
64892
64893
64894
64895
64896
64897
64898
64899
64900
64901
64902
64903
64904
64905
64906
64907
64908
64909
64910
64911
64912
64913
64914
64915
64916
64917
64918
64919
64920
64921
64922
64923
64924
64925
64926
64927
64928
64929
64930
64931
64932
64933
64934
64935
64936
64937
64938
64939
64940
64941
64942
64943
64944
64945
64946
64947
64948
64949
64950
64951
64952
64953
64954
64955
64956
64957
64958
64959
64960
64961
64962
64963
64964
64965
64966
64967
64968
64969
64970
64971
64972
64973
64974
64975
64976
64977
64978
64979
64980
64981
64982
64983
64984
64985
64986
64987
64988
64989
64990
64991
64992
64993
64994
64995
64996
64997
64998
64999
65000
65001
65002
65003
65004
65005
65006
65007
65008
65009
65010
65011
65012
65013
65014
65015
65016
65017
65018
65019
65020
65021
65022
65023
65024
65025
65026
65027
65028
65029
65030
65031
65032
65033
65034
65035
65036
65037
65038
65039
65040
65041
65042
65043
65044
65045
65046
65047
65048
65049
65050
65051
65052
65053
65054
65055
65056
65057
65058
65059
65060
65061
65062
65063
65064
65065
65066
65067
65068
65069
65070
65071
65072
65073
65074
65075
65076
65077
65078
65079
65080
65081
65082
65083
65084
65085
65086
65087
65088
65089
65090
65091
65092
65093
65094
65095
65096
65097
65098
65099
65100
65101
65102
65103
65104
65105
65106
65107
65108
65109
65110
65111
65112
65113
65114
65115
65116
65117
65118
65119
65120
65121
65122
65123
65124
65125
65126
65127
65128
65129
65130
65131
65132
65133
65134
65135
65136
65137
65138
65139
65140
65141
65142
65143
65144
65145
65146
65147
65148
65149
65150
65151
65152
65153
65154
65155
65156
65157
65158
65159
65160
65161
65162
65163
65164
65165
65166
65167
65168
65169
65170
65171
65172
65173
65174
65175
65176
65177
65178
65179
65180
65181
65182
65183
65184
65185
65186
65187
65188
65189
65190
65191
65192
65193
65194
65195
65196
65197
65198
65199
65200
65201
65202
65203
65204
65205
65206
65207
65208
65209
65210
65211
65212
65213
65214
65215
65216
65217
65218
65219
65220
65221
65222
65223
65224
65225
65226
65227
65228
65229
65230
65231
65232
65233
65234
65235
65236
65237
65238
65239
65240
65241
65242
65243
65244
65245
65246
65247
65248
65249
65250
65251
65252
65253
65254
65255
65256
65257
65258
65259
65260
65261
65262
65263
65264
65265
65266
65267
65268
65269
65270
65271
65272
65273
65274
65275
65276
65277
65278
65279
65280
65281
65282
65283
65284
65285
65286
65287
65288
65289
65290
65291
65292
65293
65294
65295
65296
65297
65298
65299
65300
65301
65302
65303
65304
65305
65306
65307
65308
65309
65310
65311
65312
65313
65314
65315
65316
65317
65318
65319
65320
65321
65322
65323
65324
65325
65326
65327
65328
65329
65330
65331
65332
65333
65334
65335
65336
65337
65338
65339
65340
65341
65342
65343
65344
65345
65346
65347
65348
65349
65350
65351
65352
65353
65354
65355
65356
65357
65358
65359
65360
65361
65362
65363
65364
65365
65366
65367
65368
65369
65370
65371
65372
65373
65374
65375
65376
65377
65378
65379
65380
65381
65382
65383
65384
65385
65386
65387
65388
65389
65390
65391
65392
65393
65394
65395
65396
65397
65398
65399
65400
65401
65402
65403
65404
65405
65406
65407
65408
65409
65410
65411
65412
65413
65414
65415
65416
65417
65418
65419
65420
65421
65422
65423
65424
65425
65426
65427
65428
65429
65430
65431
65432
65433
65434
65435
65436
65437
65438
65439
65440
65441
65442
65443
65444
65445
65446
65447
65448
65449
65450
65451
65452
65453
65454
65455
65456
65457
65458
65459
65460
65461
65462
65463
65464
65465
65466
65467
65468
65469
65470
65471
65472
65473
65474
65475
65476
65477
65478
65479
65480
65481
65482
65483
65484
65485
65486
65487
65488
65489
65490
65491
65492
65493
65494
65495
65496
65497
65498
65499
65500
65501
65502
65503
65504
65505
65506
65507
65508
65509
65510
65511
65512
65513
65514
65515
65516
65517
65518
65519
65520
65521
65522
65523
65524
65525
65526
65527
65528
65529
65530
65531
65532
65533
65534
65535
65536
65537
65538
65539
65540
65541
65542
65543
65544
65545
65546
65547
65548
65549
65550
65551
65552
65553
65554
65555
65556
65557
65558
65559
65560
65561
65562
65563
65564
65565
65566
65567
65568
65569
65570
65571
65572
65573
65574
65575
65576
65577
65578
65579
65580
65581
65582
65583
65584
65585
65586
65587
65588
65589
65590
65591
65592
65593
65594
65595
65596
65597
65598
65599
65600
65601
65602
65603
65604
65605
65606
65607
65608
65609
65610
65611
65612
65613
65614
65615
65616
65617
65618
65619
65620
65621
65622
65623
65624
65625
65626
65627
65628
65629
65630
65631
65632
65633
65634
65635
65636
65637
65638
65639
65640
65641
65642
65643
65644
65645
65646
65647
65648
65649
65650
65651
65652
65653
65654
65655
65656
65657
65658
65659
65660
65661
65662
65663
65664
65665
65666
65667
65668
65669
65670
65671
65672
65673
65674
65675
65676
65677
65678
65679
65680
65681
65682
65683
65684
65685
65686
65687
65688
65689
65690
65691
65692
65693
65694
65695
65696
65697
65698
65699
65700
65701
65702
65703
65704
65705
65706
65707
65708
65709
65710
65711
65712
65713
65714
65715
65716
65717
65718
65719
65720
65721
65722
65723
65724
65725
65726
65727
65728
65729
65730
65731
65732
65733
65734
65735
65736
65737
65738
65739
65740
65741
65742
65743
65744
65745
65746
65747
65748
65749
65750
65751
65752
65753
65754
65755
65756
65757
65758
65759
65760
65761
65762
65763
65764
65765
65766
65767
65768
65769
65770
65771
65772
65773
65774
65775
65776
65777
65778
65779
65780
65781
65782
65783
65784
65785
65786
65787
65788
65789
65790
65791
65792
65793
65794
65795
65796
65797
65798
65799
65800
65801
65802
65803
65804
65805
65806
65807
65808
65809
65810
65811
65812
65813
65814
65815
65816
65817
65818
65819
65820
65821
65822
65823
65824
65825
65826
65827
65828
65829
65830
65831
65832
65833
65834
65835
65836
65837
65838
65839
65840
65841
65842
65843
65844
65845
65846
65847
65848
65849
65850
65851
65852
65853
65854
65855
65856
65857
65858
65859
65860
65861
65862
65863
65864
65865
65866
65867
65868
65869
65870
65871
65872
65873
65874
65875
65876
65877
65878
65879
65880
65881
65882
65883
65884
65885
65886
65887
65888
65889
65890
65891
65892
65893
65894
65895
65896
65897
65898
65899
65900
65901
65902
65903
65904
65905
65906
65907
65908
65909
65910
65911
65912
65913
65914
65915
65916
65917
65918
65919
65920
65921
65922
65923
65924
65925
65926
65927
65928
65929
65930
65931
65932
65933
65934
65935
65936
65937
65938
65939
65940
65941
65942
65943
65944
65945
65946
65947
65948
65949
65950
65951
65952
65953
65954
65955
65956
65957
65958
65959
65960
65961
65962
65963
65964
65965
65966
65967
65968
65969
65970
65971
65972
65973
65974
65975
65976
65977
65978
65979
65980
65981
65982
65983
65984
65985
65986
65987
65988
65989
65990
65991
65992
65993
65994
65995
65996
65997
65998
65999
66000
66001
66002
66003
66004
66005
66006
66007
66008
66009
66010
66011
66012
66013
66014
66015
66016
66017
66018
66019
66020
66021
66022
66023
66024
66025
66026
66027
66028
66029
66030
66031
66032
66033
66034
66035
66036
66037
66038
66039
66040
66041
66042
66043
66044
66045
66046
66047
66048
66049
66050
66051
66052
66053
66054
66055
66056
66057
66058
66059
66060
66061
66062
66063
66064
66065
66066
66067
66068
66069
66070
66071
66072
66073
66074
66075
66076
66077
66078
66079
66080
66081
66082
66083
66084
66085
66086
66087
66088
66089
66090
66091
66092
66093
66094
66095
66096
66097
66098
66099
66100
66101
66102
66103
66104
66105
66106
66107
66108
66109
66110
66111
66112
66113
66114
66115
66116
66117
66118
66119
66120
66121
66122
66123
66124
66125
66126
66127
66128
66129
66130
66131
66132
66133
66134
66135
66136
66137
66138
66139
66140
66141
66142
66143
66144
66145
66146
66147
66148
66149
66150
66151
66152
66153
66154
66155
66156
66157
66158
66159
66160
66161
66162
66163
66164
66165
66166
66167
66168
66169
66170
66171
66172
66173
66174
66175
66176
66177
66178
66179
66180
66181
66182
66183
66184
66185
66186
66187
66188
66189
66190
66191
66192
66193
66194
66195
66196
66197
66198
66199
66200
66201
66202
66203
66204
66205
66206
66207
66208
66209
66210
66211
66212
66213
66214
66215
66216
66217
66218
66219
66220
66221
66222
66223
66224
66225
66226
66227
66228
66229
66230
66231
66232
66233
66234
66235
66236
66237
66238
66239
66240
66241
66242
66243
66244
66245
66246
66247
66248
66249
66250
66251
66252
66253
66254
66255
66256
66257
66258
66259
66260
66261
66262
66263
66264
66265
66266
66267
66268
66269
66270
66271
66272
66273
66274
66275
66276
66277
66278
66279
66280
66281
66282
66283
66284
66285
66286
66287
66288
66289
66290
66291
66292
66293
66294
66295
66296
66297
66298
66299
66300
66301
66302
66303
66304
66305
66306
66307
66308
66309
66310
66311
66312
66313
66314
66315
66316
66317
66318
66319
66320
66321
66322
66323
66324
66325
66326
66327
66328
66329
66330
66331
66332
66333
66334
66335
66336
66337
66338
66339
66340
66341
66342
66343
66344
66345
66346
66347
66348
66349
66350
66351
66352
66353
66354
66355
66356
66357
66358
66359
66360
66361
66362
66363
66364
66365
66366
66367
66368
66369
66370
66371
66372
66373
66374
66375
66376
66377
66378
66379
66380
66381
66382
66383
66384
66385
66386
66387
66388
66389
66390
66391
66392
66393
66394
66395
66396
66397
66398
66399
66400
66401
66402
66403
66404
66405
66406
66407
66408
66409
66410
66411
66412
66413
66414
66415
66416
66417
66418
66419
66420
66421
66422
66423
66424
66425
66426
66427
66428
66429
66430
66431
66432
66433
66434
66435
66436
66437
66438
66439
66440
66441
66442
66443
66444
66445
66446
66447
66448
66449
66450
66451
66452
66453
66454
66455
66456
66457
66458
66459
66460
66461
66462
66463
66464
66465
66466
66467
66468
66469
66470
66471
66472
66473
66474
66475
66476
66477
66478
66479
66480
66481
66482
66483
66484
66485
66486
66487
66488
66489
66490
66491
66492
66493
66494
66495
66496
66497
66498
66499
66500
66501
66502
66503
66504
66505
66506
66507
66508
66509
66510
66511
66512
66513
66514
66515
66516
66517
66518
66519
66520
66521
66522
66523
66524
66525
66526
66527
66528
66529
66530
66531
66532
66533
66534
66535
66536
66537
66538
66539
66540
66541
66542
66543
66544
66545
66546
66547
66548
66549
66550
66551
66552
66553
66554
66555
66556
66557
66558
66559
66560
66561
66562
66563
66564
66565
66566
66567
66568
66569
66570
66571
66572
66573
66574
66575
66576
66577
66578
66579
66580
66581
66582
66583
66584
66585
66586
66587
66588
66589
66590
66591
66592
66593
66594
66595
66596
66597
66598
66599
66600
66601
66602
66603
66604
66605
66606
66607
66608
66609
66610
66611
66612
66613
66614
66615
66616
66617
66618
66619
66620
66621
66622
66623
66624
66625
66626
66627
66628
66629
66630
66631
66632
66633
66634
66635
66636
66637
66638
66639
66640
66641
66642
66643
66644
66645
66646
66647
66648
66649
66650
66651
66652
66653
66654
66655
66656
66657
66658
66659
66660
66661
66662
66663
66664
66665
66666
66667
66668
66669
66670
66671
66672
66673
66674
66675
66676
66677
66678
66679
66680
66681
66682
66683
66684
66685
66686
66687
66688
66689
66690
66691
66692
66693
66694
66695
66696
66697
66698
66699
66700
66701
66702
66703
66704
66705
66706
66707
66708
66709
66710
66711
66712
66713
66714
66715
66716
66717
66718
66719
66720
66721
66722
66723
66724
66725
66726
66727
66728
66729
66730
66731
66732
66733
66734
66735
66736
66737
66738
66739
66740
66741
66742
66743
66744
66745
66746
66747
66748
66749
66750
66751
66752
66753
66754
66755
66756
66757
66758
66759
66760
66761
66762
66763
66764
66765
66766
66767
66768
66769
66770
66771
66772
66773
66774
66775
66776
66777
66778
66779
66780
66781
66782
66783
66784
66785
66786
66787
66788
66789
66790
66791
66792
66793
66794
66795
66796
66797
66798
66799
66800
66801
66802
66803
66804
66805
66806
66807
66808
66809
66810
66811
66812
66813
66814
66815
66816
66817
66818
66819
66820
66821
66822
66823
66824
66825
66826
66827
66828
66829
66830
66831
66832
66833
66834
66835
66836
66837
66838
66839
66840
66841
66842
66843
66844
66845
66846
66847
66848
66849
66850
66851
66852
66853
66854
66855
66856
66857
66858
66859
66860
66861
66862
66863
66864
66865
66866
66867
66868
66869
66870
66871
66872
66873
66874
66875
66876
66877
66878
66879
66880
66881
66882
66883
66884
66885
66886
66887
66888
66889
66890
66891
66892
66893
66894
66895
66896
66897
66898
66899
66900
66901
66902
66903
66904
66905
66906
66907
66908
66909
66910
66911
66912
66913
66914
66915
66916
66917
66918
66919
66920
66921
66922
66923
66924
66925
66926
66927
66928
66929
66930
66931
66932
66933
66934
66935
66936
66937
66938
66939
66940
66941
66942
66943
66944
66945
66946
66947
66948
66949
66950
66951
66952
66953
66954
66955
66956
66957
66958
66959
66960
66961
66962
66963
66964
66965
66966
66967
66968
66969
66970
66971
66972
66973
66974
66975
66976
66977
66978
66979
66980
66981
66982
66983
66984
66985
66986
66987
66988
66989
66990
66991
66992
66993
66994
66995
66996
66997
66998
66999
67000
67001
67002
67003
67004
67005
67006
67007
67008
67009
67010
67011
67012
67013
67014
67015
67016
67017
67018
67019
67020
67021
67022
67023
67024
67025
67026
67027
67028
67029
67030
67031
67032
67033
67034
67035
67036
67037
67038
67039
67040
67041
67042
67043
67044
67045
67046
67047
67048
67049
67050
67051
67052
67053
67054
67055
67056
67057
67058
67059
67060
67061
67062
67063
67064
67065
67066
67067
67068
67069
67070
67071
67072
67073
67074
67075
67076
67077
67078
67079
67080
67081
67082
67083
67084
67085
67086
67087
67088
67089
67090
67091
67092
67093
67094
67095
67096
67097
67098
67099
67100
67101
67102
67103
67104
67105
67106
67107
67108
67109
67110
67111
67112
67113
67114
67115
67116
67117
67118
67119
67120
67121
67122
67123
67124
67125
67126
67127
67128
67129
67130
67131
67132
67133
67134
67135
67136
67137
67138
67139
67140
67141
67142
67143
67144
67145
67146
67147
67148
67149
67150
67151
67152
67153
67154
67155
67156
67157
67158
67159
67160
67161
67162
67163
67164
67165
67166
67167
67168
67169
67170
67171
67172
67173
67174
67175
67176
67177
67178
67179
67180
67181
67182
67183
67184
67185
67186
67187
67188
67189
67190
67191
67192
67193
67194
67195
67196
67197
67198
67199
67200
67201
67202
67203
67204
67205
67206
67207
67208
67209
67210
67211
67212
67213
67214
67215
67216
67217
67218
67219
67220
67221
67222
67223
67224
67225
67226
67227
67228
67229
67230
67231
67232
67233
67234
67235
67236
67237
67238
67239
67240
67241
67242
67243
67244
67245
67246
67247
67248
67249
67250
67251
67252
67253
67254
67255
67256
67257
67258
67259
67260
67261
67262
67263
67264
67265
67266
67267
67268
67269
67270
67271
67272
67273
67274
67275
67276
67277
67278
67279
67280
67281
67282
67283
67284
67285
67286
67287
67288
67289
67290
67291
67292
67293
67294
67295
67296
67297
67298
67299
67300
67301
67302
67303
67304
67305
67306
67307
67308
67309
67310
67311
67312
67313
67314
67315
67316
67317
67318
67319
67320
67321
67322
67323
67324
67325
67326
67327
67328
67329
67330
67331
67332
67333
67334
67335
67336
67337
67338
67339
67340
67341
67342
67343
67344
67345
67346
67347
67348
67349
67350
67351
67352
67353
67354
67355
67356
67357
67358
67359
67360
67361
67362
67363
67364
67365
67366
67367
67368
67369
67370
67371
67372
67373
67374
67375
67376
67377
67378
67379
67380
67381
67382
67383
67384
67385
67386
67387
67388
67389
67390
67391
67392
67393
67394
67395
67396
67397
67398
67399
67400
67401
67402
67403
67404
67405
67406
67407
67408
67409
67410
67411
67412
67413
67414
67415
67416
67417
67418
67419
67420
67421
67422
67423
67424
67425
67426
67427
67428
67429
67430
67431
67432
67433
67434
67435
67436
67437
67438
67439
67440
67441
67442
67443
67444
67445
67446
67447
67448
67449
67450
67451
67452
67453
67454
67455
67456
67457
67458
67459
67460
67461
67462
67463
67464
67465
67466
67467
67468
67469
67470
67471
67472
67473
67474
67475
67476
67477
67478
67479
67480
67481
67482
67483
67484
67485
67486
67487
67488
67489
67490
67491
67492
67493
67494
67495
67496
67497
67498
67499
67500
67501
67502
67503
67504
67505
67506
67507
67508
67509
67510
67511
67512
67513
67514
67515
67516
67517
67518
67519
67520
67521
67522
67523
67524
67525
67526
67527
67528
67529
67530
67531
67532
67533
67534
67535
67536
67537
67538
67539
67540
67541
67542
67543
67544
67545
67546
67547
67548
67549
67550
67551
67552
67553
67554
67555
67556
67557
67558
67559
67560
67561
67562
67563
67564
67565
67566
67567
67568
67569
67570
67571
67572
67573
67574
67575
67576
67577
67578
67579
67580
67581
67582
67583
67584
67585
67586
67587
67588
67589
67590
67591
67592
67593
67594
67595
67596
67597
67598
67599
67600
67601
67602
67603
67604
67605
67606
67607
67608
67609
67610
67611
67612
67613
67614
67615
67616
67617
67618
67619
67620
67621
67622
67623
67624
67625
67626
67627
67628
67629
67630
67631
67632
67633
67634
67635
67636
67637
67638
67639
67640
67641
67642
67643
67644
67645
67646
67647
67648
67649
67650
67651
67652
67653
67654
67655
67656
67657
67658
67659
67660
67661
67662
67663
67664
67665
67666
67667
67668
67669
67670
67671
67672
67673
67674
67675
67676
67677
67678
67679
67680
67681
67682
67683
67684
67685
67686
67687
67688
67689
67690
67691
67692
67693
67694
67695
67696
67697
67698
67699
67700
67701
67702
67703
67704
67705
67706
67707
67708
67709
67710
67711
67712
67713
67714
67715
67716
67717
67718
67719
67720
67721
67722
67723
67724
67725
67726
67727
67728
67729
67730
67731
67732
67733
67734
67735
67736
67737
67738
67739
67740
67741
67742
67743
67744
67745
67746
67747
67748
67749
67750
67751
67752
67753
67754
67755
67756
67757
67758
67759
67760
67761
67762
67763
67764
67765
67766
67767
67768
67769
67770
67771
67772
67773
67774
67775
67776
67777
67778
67779
67780
67781
67782
67783
67784
67785
67786
67787
67788
67789
67790
67791
67792
67793
67794
67795
67796
67797
67798
67799
67800
67801
67802
67803
67804
67805
67806
67807
67808
67809
67810
67811
67812
67813
67814
67815
67816
67817
67818
67819
67820
67821
67822
67823
67824
67825
67826
67827
67828
67829
67830
67831
67832
67833
67834
67835
67836
67837
67838
67839
67840
67841
67842
67843
67844
67845
67846
67847
67848
67849
67850
67851
67852
67853
67854
67855
67856
67857
67858
67859
67860
67861
67862
67863
67864
67865
67866
67867
67868
67869
67870
67871
67872
67873
67874
67875
67876
67877
67878
67879
67880
67881
67882
67883
67884
67885
67886
67887
67888
67889
67890
67891
67892
67893
67894
67895
67896
67897
67898
67899
67900
67901
67902
67903
67904
67905
67906
67907
67908
67909
67910
67911
67912
67913
67914
67915
67916
67917
67918
67919
67920
67921
67922
67923
67924
67925
67926
67927
67928
67929
67930
67931
67932
67933
67934
67935
67936
67937
67938
67939
67940
67941
67942
67943
67944
67945
67946
67947
67948
67949
67950
67951
67952
67953
67954
67955
67956
67957
67958
67959
67960
67961
67962
67963
67964
67965
67966
67967
67968
67969
67970
67971
67972
67973
67974
67975
67976
67977
67978
67979
67980
67981
67982
67983
67984
67985
67986
67987
67988
67989
67990
67991
67992
67993
67994
67995
67996
67997
67998
67999
68000
68001
68002
68003
68004
68005
68006
68007
68008
68009
68010
68011
68012
68013
68014
68015
68016
68017
68018
68019
68020
68021
68022
68023
68024
68025
68026
68027
68028
68029
68030
68031
68032
68033
68034
68035
68036
68037
68038
68039
68040
68041
68042
68043
68044
68045
68046
68047
68048
68049
68050
68051
68052
68053
68054
68055
68056
68057
68058
68059
68060
68061
68062
68063
68064
68065
68066
68067
68068
68069
68070
68071
68072
68073
68074
68075
68076
68077
68078
68079
68080
68081
68082
68083
68084
68085
68086
68087
68088
68089
68090
68091
68092
68093
68094
68095
68096
68097
68098
68099
68100
68101
68102
68103
68104
68105
68106
68107
68108
68109
68110
68111
68112
68113
68114
68115
68116
68117
68118
68119
68120
68121
68122
68123
68124
68125
68126
68127
68128
68129
68130
68131
68132
68133
68134
68135
68136
68137
68138
68139
68140
68141
68142
68143
68144
68145
68146
68147
68148
68149
68150
68151
68152
68153
68154
68155
68156
68157
68158
68159
68160
68161
68162
68163
68164
68165
68166
68167
68168
68169
68170
68171
68172
68173
68174
68175
68176
68177
68178
68179
68180
68181
68182
68183
68184
68185
68186
68187
68188
68189
68190
68191
68192
68193
68194
68195
68196
68197
68198
68199
68200
68201
68202
68203
68204
68205
68206
68207
68208
68209
68210
68211
68212
68213
68214
68215
68216
68217
68218
68219
68220
68221
68222
68223
68224
68225
68226
68227
68228
68229
68230
68231
68232
68233
68234
68235
68236
68237
68238
68239
68240
68241
68242
68243
68244
68245
68246
68247
68248
68249
68250
68251
68252
68253
68254
68255
68256
68257
68258
68259
68260
68261
68262
68263
68264
68265
68266
68267
68268
68269
68270
68271
68272
68273
68274
68275
68276
68277
68278
68279
68280
68281
68282
68283
68284
68285
68286
68287
68288
68289
68290
68291
68292
68293
68294
68295
68296
68297
68298
68299
68300
68301
68302
68303
68304
68305
68306
68307
68308
68309
68310
68311
68312
68313
68314
68315
68316
68317
68318
68319
68320
68321
68322
68323
68324
68325
68326
68327
68328
68329
68330
68331
68332
68333
68334
68335
68336
68337
68338
68339
68340
68341
68342
68343
68344
68345
68346
68347
68348
68349
68350
68351
68352
68353
68354
68355
68356
68357
68358
68359
68360
68361
68362
68363
68364
68365
68366
68367
68368
68369
68370
68371
68372
68373
68374
68375
68376
68377
68378
68379
68380
68381
68382
68383
68384
68385
68386
68387
68388
68389
68390
68391
68392
68393
68394
68395
68396
68397
68398
68399
68400
68401
68402
68403
68404
68405
68406
68407
68408
68409
68410
68411
68412
68413
68414
68415
68416
68417
68418
68419
68420
68421
68422
68423
68424
68425
68426
68427
68428
68429
68430
68431
68432
68433
68434
68435
68436
68437
68438
68439
68440
68441
68442
68443
68444
68445
68446
68447
68448
68449
68450
68451
68452
68453
68454
68455
68456
68457
68458
68459
68460
68461
68462
68463
68464
68465
68466
68467
68468
68469
68470
68471
68472
68473
68474
68475
68476
68477
68478
68479
68480
68481
68482
68483
68484
68485
68486
68487
68488
68489
68490
68491
68492
68493
68494
68495
68496
68497
68498
68499
68500
68501
68502
68503
68504
68505
68506
68507
68508
68509
68510
68511
68512
68513
68514
68515
68516
68517
68518
68519
68520
68521
68522
68523
68524
68525
68526
68527
68528
68529
68530
68531
68532
68533
68534
68535
68536
68537
68538
68539
68540
68541
68542
68543
68544
68545
68546
68547
68548
68549
68550
68551
68552
68553
68554
68555
68556
68557
68558
68559
68560
68561
68562
68563
68564
68565
68566
68567
68568
68569
68570
68571
68572
68573
68574
68575
68576
68577
68578
68579
68580
68581
68582
68583
68584
68585
68586
68587
68588
68589
68590
68591
68592
68593
68594
68595
68596
68597
68598
68599
68600
68601
68602
68603
68604
68605
68606
68607
68608
68609
68610
68611
68612
68613
68614
68615
68616
68617
68618
68619
68620
68621
68622
68623
68624
68625
68626
68627
68628
68629
68630
68631
68632
68633
68634
68635
68636
68637
68638
68639
68640
68641
68642
68643
68644
68645
68646
68647
68648
68649
68650
68651
68652
68653
68654
68655
68656
68657
68658
68659
68660
68661
68662
68663
68664
68665
68666
68667
68668
68669
68670
68671
68672
68673
68674
68675
68676
68677
68678
68679
68680
68681
68682
68683
68684
68685
68686
68687
68688
68689
68690
68691
68692
68693
68694
68695
68696
68697
68698
68699
68700
68701
68702
68703
68704
68705
68706
68707
68708
68709
68710
68711
68712
68713
68714
68715
68716
68717
68718
68719
68720
68721
68722
68723
68724
68725
68726
68727
68728
68729
68730
68731
68732
68733
68734
68735
68736
68737
68738
68739
68740
68741
68742
68743
68744
68745
68746
68747
68748
68749
68750
68751
68752
68753
68754
68755
68756
68757
68758
68759
68760
68761
68762
68763
68764
68765
68766
68767
68768
68769
68770
68771
68772
68773
68774
68775
68776
68777
68778
68779
68780
68781
68782
68783
68784
68785
68786
68787
68788
68789
68790
68791
68792
68793
68794
68795
68796
68797
68798
68799
68800
68801
68802
68803
68804
68805
68806
68807
68808
68809
68810
68811
68812
68813
68814
68815
68816
68817
68818
68819
68820
68821
68822
68823
68824
68825
68826
68827
68828
68829
68830
68831
68832
68833
68834
68835
68836
68837
68838
68839
68840
68841
68842
68843
68844
68845
68846
68847
68848
68849
68850
68851
68852
68853
68854
68855
68856
68857
68858
68859
68860
68861
68862
68863
68864
68865
68866
68867
68868
68869
68870
68871
68872
68873
68874
68875
68876
68877
68878
68879
68880
68881
68882
68883
68884
68885
68886
68887
68888
68889
68890
68891
68892
68893
68894
68895
68896
68897
68898
68899
68900
68901
68902
68903
68904
68905
68906
68907
68908
68909
68910
68911
68912
68913
68914
68915
68916
68917
68918
68919
68920
68921
68922
68923
68924
68925
68926
68927
68928
68929
68930
68931
68932
68933
68934
68935
68936
68937
68938
68939
68940
68941
68942
68943
68944
68945
68946
68947
68948
68949
68950
68951
68952
68953
68954
68955
68956
68957
68958
68959
68960
68961
68962
68963
68964
68965
68966
68967
68968
68969
68970
68971
68972
68973
68974
68975
68976
68977
68978
68979
68980
68981
68982
68983
68984
68985
68986
68987
68988
68989
68990
68991
68992
68993
68994
68995
68996
68997
68998
68999
69000
69001
69002
69003
69004
69005
69006
69007
69008
69009
69010
69011
69012
69013
69014
69015
69016
69017
69018
69019
69020
69021
69022
69023
69024
69025
69026
69027
69028
69029
69030
69031
69032
69033
69034
69035
69036
69037
69038
69039
69040
69041
69042
69043
69044
69045
69046
69047
69048
69049
69050
69051
69052
69053
69054
69055
69056
69057
69058
69059
69060
69061
69062
69063
69064
69065
69066
69067
69068
69069
69070
69071
69072
69073
69074
69075
69076
69077
69078
69079
69080
69081
69082
69083
69084
69085
69086
69087
69088
69089
69090
69091
69092
69093
69094
69095
69096
69097
69098
69099
69100
69101
69102
69103
69104
69105
69106
69107
69108
69109
69110
69111
69112
69113
69114
69115
69116
69117
69118
69119
69120
69121
69122
69123
69124
69125
69126
69127
69128
69129
69130
69131
69132
69133
69134
69135
69136
69137
69138
69139
69140
69141
69142
69143
69144
69145
69146
69147
69148
69149
69150
69151
69152
69153
69154
69155
69156
69157
69158
69159
69160
69161
69162
69163
69164
69165
69166
69167
69168
69169
69170
69171
69172
69173
69174
69175
69176
69177
69178
69179
69180
69181
69182
69183
69184
69185
69186
69187
69188
69189
69190
69191
69192
69193
69194
69195
69196
69197
69198
69199
69200
69201
69202
69203
69204
69205
69206
69207
69208
69209
69210
69211
69212
69213
69214
69215
69216
69217
69218
69219
69220
69221
69222
69223
69224
69225
69226
69227
69228
69229
69230
69231
69232
69233
69234
69235
69236
69237
69238
69239
69240
69241
69242
69243
69244
69245
69246
69247
69248
69249
69250
69251
69252
69253
69254
69255
69256
69257
69258
69259
69260
69261
69262
69263
69264
69265
69266
69267
69268
69269
69270
69271
69272
69273
69274
69275
69276
69277
69278
69279
69280
69281
69282
69283
69284
69285
69286
69287
69288
69289
69290
69291
69292
69293
69294
69295
69296
69297
69298
69299
69300
69301
69302
69303
69304
69305
69306
69307
69308
69309
69310
69311
69312
69313
69314
69315
69316
69317
69318
69319
69320
69321
69322
69323
69324
69325
69326
69327
69328
69329
69330
69331
69332
69333
69334
69335
69336
69337
69338
69339
69340
69341
69342
69343
69344
69345
69346
69347
69348
69349
69350
69351
69352
69353
69354
69355
69356
69357
69358
69359
69360
69361
69362
69363
69364
69365
69366
69367
69368
69369
69370
69371
69372
69373
69374
69375
69376
69377
69378
69379
69380
69381
69382
69383
69384
69385
69386
69387
69388
69389
69390
69391
69392
69393
69394
69395
69396
69397
69398
69399
69400
69401
69402
69403
69404
69405
69406
69407
69408
69409
69410
69411
69412
69413
69414
69415
69416
69417
69418
69419
69420
69421
69422
69423
69424
69425
69426
69427
69428
69429
69430
69431
69432
69433
69434
69435
69436
69437
69438
69439
69440
69441
69442
69443
69444
69445
69446
69447
69448
69449
69450
69451
69452
69453
69454
69455
69456
69457
69458
69459
69460
69461
69462
69463
69464
69465
69466
69467
69468
69469
69470
69471
69472
69473
69474
69475
69476
69477
69478
69479
69480
69481
69482
69483
69484
69485
69486
69487
69488
69489
69490
69491
69492
69493
69494
69495
69496
69497
69498
69499
69500
69501
69502
69503
69504
69505
69506
69507
69508
69509
69510
69511
69512
69513
69514
69515
69516
69517
69518
69519
69520
69521
69522
69523
69524
69525
69526
69527
69528
69529
69530
69531
69532
69533
69534
69535
69536
69537
69538
69539
69540
69541
69542
69543
69544
69545
69546
69547
69548
69549
69550
69551
69552
69553
69554
69555
69556
69557
69558
69559
69560
69561
69562
69563
69564
69565
69566
69567
69568
69569
69570
69571
69572
69573
69574
69575
69576
69577
69578
69579
69580
69581
69582
69583
69584
69585
69586
69587
69588
69589
69590
69591
69592
69593
69594
69595
69596
69597
69598
69599
69600
69601
69602
69603
69604
69605
69606
69607
69608
69609
69610
69611
69612
69613
69614
69615
69616
69617
69618
69619
69620
69621
69622
69623
69624
69625
69626
69627
69628
69629
69630
69631
69632
69633
69634
69635
69636
69637
69638
69639
69640
69641
69642
69643
69644
69645
69646
69647
69648
69649
69650
69651
69652
69653
69654
69655
69656
69657
69658
69659
69660
69661
69662
69663
69664
69665
69666
69667
69668
69669
69670
69671
69672
69673
69674
69675
69676
69677
69678
69679
69680
69681
69682
69683
69684
69685
69686
69687
69688
69689
69690
69691
69692
69693
69694
69695
69696
69697
69698
69699
69700
69701
69702
69703
69704
69705
69706
69707
69708
69709
69710
69711
69712
69713
69714
69715
69716
69717
69718
69719
69720
69721
69722
69723
69724
69725
69726
69727
69728
69729
69730
69731
69732
69733
69734
69735
69736
69737
69738
69739
69740
69741
69742
69743
69744
69745
69746
69747
69748
69749
69750
69751
69752
69753
69754
69755
69756
69757
69758
69759
69760
69761
69762
69763
69764
69765
69766
69767
69768
69769
69770
69771
69772
69773
69774
69775
69776
69777
69778
69779
69780
69781
69782
69783
69784
69785
69786
69787
69788
69789
69790
69791
69792
69793
69794
69795
69796
69797
69798
69799
69800
69801
69802
69803
69804
69805
69806
69807
69808
69809
69810
69811
69812
69813
69814
69815
69816
69817
69818
69819
69820
69821
69822
69823
69824
69825
69826
69827
69828
69829
69830
69831
69832
69833
69834
69835
69836
69837
69838
69839
69840
69841
69842
69843
69844
69845
69846
69847
69848
69849
69850
69851
69852
69853
69854
69855
69856
69857
69858
69859
69860
69861
69862
69863
69864
69865
69866
69867
69868
69869
69870
69871
69872
69873
69874
69875
69876
69877
69878
69879
69880
69881
69882
69883
69884
69885
69886
69887
69888
69889
69890
69891
69892
69893
69894
69895
69896
69897
69898
69899
69900
69901
69902
69903
69904
69905
69906
69907
69908
69909
69910
69911
69912
69913
69914
69915
69916
69917
69918
69919
69920
69921
69922
69923
69924
69925
69926
69927
69928
69929
69930
69931
69932
69933
69934
69935
69936
69937
69938
69939
69940
69941
69942
69943
69944
69945
69946
69947
69948
69949
69950
69951
69952
69953
69954
69955
69956
69957
69958
69959
69960
69961
69962
69963
69964
69965
69966
69967
69968
69969
69970
69971
69972
69973
69974
69975
69976
69977
69978
69979
69980
69981
69982
69983
69984
69985
69986
69987
69988
69989
69990
69991
69992
69993
69994
69995
69996
69997
69998
69999
70000
70001
70002
70003
70004
70005
70006
70007
70008
70009
70010
70011
70012
70013
70014
70015
70016
70017
70018
70019
70020
70021
70022
70023
70024
70025
70026
70027
70028
70029
70030
70031
70032
70033
70034
70035
70036
70037
70038
70039
70040
70041
70042
70043
70044
70045
70046
70047
70048
70049
70050
70051
70052
70053
70054
70055
70056
70057
70058
70059
70060
70061
70062
70063
70064
70065
70066
70067
70068
70069
70070
70071
70072
70073
70074
70075
70076
70077
70078
70079
70080
70081
70082
70083
70084
70085
70086
70087
70088
70089
70090
70091
70092
70093
70094
70095
70096
70097
70098
70099
70100
70101
70102
70103
70104
70105
70106
70107
70108
70109
70110
70111
70112
70113
70114
70115
70116
70117
70118
70119
70120
70121
70122
70123
70124
70125
70126
70127
70128
70129
70130
70131
70132
70133
70134
70135
70136
70137
70138
70139
70140
70141
70142
70143
70144
70145
70146
70147
70148
70149
70150
70151
70152
70153
70154
70155
70156
70157
70158
70159
70160
70161
70162
70163
70164
70165
70166
70167
70168
70169
70170
70171
70172
70173
70174
70175
70176
70177
70178
70179
70180
70181
70182
70183
70184
70185
70186
70187
70188
70189
70190
70191
70192
70193
70194
70195
70196
70197
70198
70199
70200
70201
70202
70203
70204
70205
70206
70207
70208
70209
70210
70211
70212
70213
70214
70215
70216
70217
70218
70219
70220
70221
70222
70223
70224
70225
70226
70227
70228
70229
70230
70231
70232
70233
70234
70235
70236
70237
70238
70239
70240
70241
70242
70243
70244
70245
70246
70247
70248
70249
70250
70251
70252
70253
70254
70255
70256
70257
70258
70259
70260
70261
70262
70263
70264
70265
70266
70267
70268
70269
70270
70271
70272
70273
70274
70275
70276
70277
70278
70279
70280
70281
70282
70283
70284
70285
70286
70287
70288
70289
70290
70291
70292
70293
70294
70295
70296
70297
70298
70299
70300
70301
70302
70303
70304
70305
70306
70307
70308
70309
70310
70311
70312
70313
70314
70315
70316
70317
70318
70319
70320
70321
70322
70323
70324
70325
70326
70327
70328
70329
70330
70331
70332
70333
70334
70335
70336
70337
70338
70339
70340
70341
70342
70343
70344
70345
70346
70347
70348
70349
70350
70351
70352
70353
70354
70355
70356
70357
70358
70359
70360
70361
70362
70363
70364
70365
70366
70367
70368
70369
70370
70371
70372
70373
70374
70375
70376
70377
70378
70379
70380
70381
70382
70383
70384
70385
70386
70387
70388
70389
70390
70391
70392
70393
70394
70395
70396
70397
70398
70399
70400
70401
70402
70403
70404
70405
70406
70407
70408
70409
70410
70411
70412
70413
70414
70415
70416
70417
70418
70419
70420
70421
70422
70423
70424
70425
70426
70427
70428
70429
70430
70431
70432
70433
70434
70435
70436
70437
70438
70439
70440
70441
70442
70443
70444
70445
70446
70447
70448
70449
70450
70451
70452
70453
70454
70455
70456
70457
70458
70459
70460
70461
70462
70463
70464
70465
70466
70467
70468
70469
70470
70471
70472
70473
70474
70475
70476
70477
70478
70479
70480
70481
70482
70483
70484
70485
70486
70487
70488
70489
70490
70491
70492
70493
70494
70495
70496
70497
70498
70499
70500
70501
70502
70503
70504
70505
70506
70507
70508
70509
70510
70511
70512
70513
70514
70515
70516
70517
70518
70519
70520
70521
70522
70523
70524
70525
70526
70527
70528
70529
70530
70531
70532
70533
70534
70535
70536
70537
70538
70539
70540
70541
70542
70543
70544
70545
70546
70547
70548
70549
70550
70551
70552
70553
70554
70555
70556
70557
70558
70559
70560
70561
70562
70563
70564
70565
70566
70567
70568
70569
70570
70571
70572
70573
70574
70575
70576
70577
70578
70579
70580
70581
70582
70583
70584
70585
70586
70587
70588
70589
70590
70591
70592
70593
70594
70595
70596
70597
70598
70599
70600
70601
70602
70603
70604
70605
70606
70607
70608
70609
70610
70611
70612
70613
70614
70615
70616
70617
70618
70619
70620
70621
70622
70623
70624
70625
70626
70627
70628
70629
70630
70631
70632
70633
70634
70635
70636
70637
70638
70639
70640
70641
70642
70643
70644
70645
70646
70647
70648
70649
70650
70651
70652
70653
70654
70655
70656
70657
70658
70659
70660
70661
70662
70663
70664
70665
70666
70667
70668
70669
70670
70671
70672
70673
70674
70675
70676
70677
70678
70679
70680
70681
70682
70683
70684
70685
70686
70687
70688
70689
70690
70691
70692
70693
70694
70695
70696
70697
70698
70699
70700
70701
70702
70703
70704
70705
70706
70707
70708
70709
70710
70711
70712
70713
70714
70715
70716
70717
70718
70719
70720
70721
70722
70723
70724
70725
70726
70727
70728
70729
70730
70731
70732
70733
70734
70735
70736
70737
70738
70739
70740
70741
70742
70743
70744
70745
70746
70747
70748
70749
70750
70751
70752
70753
70754
70755
70756
70757
70758
70759
70760
70761
70762
70763
70764
70765
70766
70767
70768
70769
70770
70771
70772
70773
70774
70775
70776
70777
70778
70779
70780
70781
70782
70783
70784
70785
70786
70787
70788
70789
70790
70791
70792
70793
70794
70795
70796
70797
70798
70799
70800
70801
70802
70803
70804
70805
70806
70807
70808
70809
70810
70811
70812
70813
70814
70815
70816
70817
70818
70819
70820
70821
70822
70823
70824
70825
70826
70827
70828
70829
70830
70831
70832
70833
70834
70835
70836
70837
70838
70839
70840
70841
70842
70843
70844
70845
70846
70847
70848
70849
70850
70851
70852
70853
70854
70855
70856
70857
70858
70859
70860
70861
70862
70863
70864
70865
70866
70867
70868
70869
70870
70871
70872
70873
70874
70875
70876
70877
70878
70879
70880
70881
70882
70883
70884
70885
70886
70887
70888
70889
70890
70891
70892
70893
70894
70895
70896
70897
70898
70899
70900
70901
70902
70903
70904
70905
70906
70907
70908
70909
70910
70911
70912
70913
70914
70915
70916
70917
70918
70919
70920
70921
70922
70923
70924
70925
70926
70927
70928
70929
70930
70931
70932
70933
70934
70935
70936
70937
70938
70939
70940
70941
70942
70943
70944
70945
70946
70947
70948
70949
70950
70951
70952
70953
70954
70955
70956
70957
70958
70959
70960
70961
70962
70963
70964
70965
70966
70967
70968
70969
70970
70971
70972
70973
70974
70975
70976
70977
70978
70979
70980
70981
70982
70983
70984
70985
70986
70987
70988
70989
70990
70991
70992
70993
70994
70995
70996
70997
70998
70999
71000
71001
71002
71003
71004
71005
71006
71007
71008
71009
71010
71011
71012
71013
71014
71015
71016
71017
71018
71019
71020
71021
71022
71023
71024
71025
71026
71027
71028
71029
71030
71031
71032
71033
71034
71035
71036
71037
71038
71039
71040
71041
71042
71043
71044
71045
71046
71047
71048
71049
71050
71051
71052
71053
71054
71055
71056
71057
71058
71059
71060
71061
71062
71063
71064
71065
71066
71067
71068
71069
71070
71071
71072
71073
71074
71075
71076
71077
71078
71079
71080
71081
71082
71083
71084
71085
71086
71087
71088
71089
71090
71091
71092
71093
71094
71095
71096
71097
71098
71099
71100
71101
71102
71103
71104
71105
71106
71107
71108
71109
71110
71111
71112
71113
71114
71115
71116
71117
71118
71119
71120
71121
71122
71123
71124
71125
71126
71127
71128
71129
71130
71131
71132
71133
71134
71135
71136
71137
71138
71139
71140
71141
71142
71143
71144
71145
71146
71147
71148
71149
71150
71151
71152
71153
71154
71155
71156
71157
71158
71159
71160
71161
71162
71163
71164
71165
71166
71167
71168
71169
71170
71171
71172
71173
71174
71175
71176
71177
71178
71179
71180
71181
71182
71183
71184
71185
71186
71187
71188
71189
71190
71191
71192
71193
71194
71195
71196
71197
71198
71199
71200
71201
71202
71203
71204
71205
71206
71207
71208
71209
71210
71211
71212
71213
71214
71215
71216
71217
71218
71219
71220
71221
71222
71223
71224
71225
71226
71227
71228
71229
71230
71231
71232
71233
71234
71235
71236
71237
71238
71239
71240
71241
71242
71243
71244
71245
71246
71247
71248
71249
71250
71251
71252
71253
71254
71255
71256
71257
71258
71259
71260
71261
71262
71263
71264
71265
71266
71267
71268
71269
71270
71271
71272
71273
71274
71275
71276
71277
71278
71279
71280
71281
71282
71283
71284
71285
71286
71287
71288
71289
71290
71291
71292
71293
71294
71295
71296
71297
71298
71299
71300
71301
71302
71303
71304
71305
71306
71307
71308
71309
71310
71311
71312
71313
71314
71315
71316
71317
71318
71319
71320
71321
71322
71323
71324
71325
71326
71327
71328
71329
71330
71331
71332
71333
71334
71335
71336
71337
71338
71339
71340
71341
71342
71343
71344
71345
71346
71347
71348
71349
71350
71351
71352
71353
71354
71355
71356
71357
71358
71359
71360
71361
71362
71363
71364
71365
71366
71367
71368
71369
71370
71371
71372
71373
71374
71375
71376
71377
71378
71379
71380
71381
71382
71383
71384
71385
71386
71387
71388
71389
71390
71391
71392
71393
71394
71395
71396
71397
71398
71399
71400
71401
71402
71403
71404
71405
71406
71407
71408
71409
71410
71411
71412
71413
71414
71415
71416
71417
71418
71419
71420
71421
71422
71423
71424
71425
71426
71427
71428
71429
71430
71431
71432
71433
71434
71435
71436
71437
71438
71439
71440
71441
71442
71443
71444
71445
71446
71447
71448
71449
71450
71451
71452
71453
71454
71455
71456
71457
71458
71459
71460
71461
71462
71463
71464
71465
71466
71467
71468
71469
71470
71471
71472
71473
71474
71475
71476
71477
71478
71479
71480
71481
71482
71483
71484
71485
71486
71487
71488
71489
71490
71491
71492
71493
71494
71495
71496
71497
71498
71499
71500
71501
71502
71503
71504
71505
71506
71507
71508
71509
71510
71511
71512
71513
71514
71515
71516
71517
71518
71519
71520
71521
71522
71523
71524
71525
71526
71527
71528
71529
71530
71531
71532
71533
71534
71535
71536
71537
71538
71539
71540
71541
71542
71543
71544
71545
71546
71547
71548
71549
71550
71551
71552
71553
71554
71555
71556
71557
71558
71559
71560
71561
71562
71563
71564
71565
71566
71567
71568
71569
71570
71571
71572
71573
71574
71575
71576
71577
71578
71579
71580
71581
71582
71583
71584
71585
71586
71587
71588
71589
71590
71591
71592
71593
71594
71595
71596
71597
71598
71599
71600
71601
71602
71603
71604
71605
71606
71607
71608
71609
71610
71611
71612
71613
71614
71615
71616
71617
71618
71619
71620
71621
71622
71623
71624
71625
71626
71627
71628
71629
71630
71631
71632
71633
71634
71635
71636
71637
71638
71639
71640
71641
71642
71643
71644
71645
71646
71647
71648
71649
71650
71651
71652
71653
71654
71655
71656
71657
71658
71659
71660
71661
71662
71663
71664
71665
71666
71667
71668
71669
71670
71671
71672
71673
71674
71675
71676
71677
71678
71679
71680
71681
71682
71683
71684
71685
71686
71687
71688
71689
71690
71691
71692
71693
71694
71695
71696
71697
71698
71699
71700
71701
71702
71703
71704
71705
71706
71707
71708
71709
71710
71711
71712
71713
71714
71715
71716
71717
71718
71719
71720
71721
71722
71723
71724
71725
71726
71727
71728
71729
71730
71731
71732
71733
71734
71735
71736
71737
71738
71739
71740
71741
71742
71743
71744
71745
71746
71747
71748
71749
71750
71751
71752
71753
71754
71755
71756
71757
71758
71759
71760
71761
71762
71763
71764
71765
71766
71767
71768
71769
71770
71771
71772
71773
71774
71775
71776
71777
71778
71779
71780
71781
71782
71783
71784
71785
71786
71787
71788
71789
71790
71791
71792
71793
71794
71795
71796
71797
71798
71799
71800
71801
71802
71803
71804
71805
71806
71807
71808
71809
71810
71811
71812
71813
71814
71815
71816
71817
71818
71819
71820
71821
71822
71823
71824
71825
71826
71827
71828
71829
71830
71831
71832
71833
71834
71835
71836
71837
71838
71839
71840
71841
71842
71843
71844
71845
71846
71847
71848
71849
71850
71851
71852
71853
71854
71855
71856
71857
71858
71859
71860
71861
71862
71863
71864
71865
71866
71867
71868
71869
71870
71871
71872
71873
71874
71875
71876
71877
71878
71879
71880
71881
71882
71883
71884
71885
71886
71887
71888
71889
71890
71891
71892
71893
71894
71895
71896
71897
71898
71899
71900
71901
71902
71903
71904
71905
71906
71907
71908
71909
71910
71911
71912
71913
71914
71915
71916
71917
71918
71919
71920
71921
71922
71923
71924
71925
71926
71927
71928
71929
71930
71931
71932
71933
71934
71935
71936
71937
71938
71939
71940
71941
71942
71943
71944
71945
71946
71947
71948
71949
71950
71951
71952
71953
71954
71955
71956
71957
71958
71959
71960
71961
71962
71963
71964
71965
71966
71967
71968
71969
71970
71971
71972
71973
71974
71975
71976
71977
71978
71979
71980
71981
71982
71983
71984
71985
71986
71987
71988
71989
71990
71991
71992
71993
71994
71995
71996
71997
71998
71999
72000
72001
72002
72003
72004
72005
72006
72007
72008
72009
72010
72011
72012
72013
72014
72015
72016
72017
72018
72019
72020
72021
72022
72023
72024
72025
72026
72027
72028
72029
72030
72031
72032
72033
72034
72035
72036
72037
72038
72039
72040
72041
72042
72043
72044
72045
72046
72047
72048
72049
72050
72051
72052
72053
72054
72055
72056
72057
72058
72059
72060
72061
72062
72063
72064
72065
72066
72067
72068
72069
72070
72071
72072
72073
72074
72075
72076
72077
72078
72079
72080
72081
72082
72083
72084
72085
72086
72087
72088
72089
72090
72091
72092
72093
72094
72095
72096
72097
72098
72099
72100
72101
72102
72103
72104
72105
72106
72107
72108
72109
72110
72111
72112
72113
72114
72115
72116
72117
72118
72119
72120
72121
72122
72123
72124
72125
72126
72127
72128
72129
72130
72131
72132
72133
72134
72135
72136
72137
72138
72139
72140
72141
72142
72143
72144
72145
72146
72147
72148
72149
72150
72151
72152
72153
72154
72155
72156
72157
72158
72159
72160
72161
72162
72163
72164
72165
72166
72167
72168
72169
72170
72171
72172
72173
72174
72175
72176
72177
72178
72179
72180
72181
72182
72183
72184
72185
72186
72187
72188
72189
72190
72191
72192
72193
72194
72195
72196
72197
72198
72199
72200
72201
72202
72203
72204
72205
72206
72207
72208
72209
72210
72211
72212
72213
72214
72215
72216
72217
72218
72219
72220
72221
72222
72223
72224
72225
72226
72227
72228
72229
72230
72231
72232
72233
72234
72235
72236
72237
72238
72239
72240
72241
72242
72243
72244
72245
72246
72247
72248
72249
72250
72251
72252
72253
72254
72255
72256
72257
72258
72259
72260
72261
72262
72263
72264
72265
72266
72267
72268
72269
72270
72271
72272
72273
72274
72275
72276
72277
72278
72279
72280
72281
72282
72283
72284
72285
72286
72287
72288
72289
72290
72291
72292
72293
72294
72295
72296
72297
72298
72299
72300
72301
72302
72303
72304
72305
72306
72307
72308
72309
72310
72311
72312
72313
72314
72315
72316
72317
72318
72319
72320
72321
72322
72323
72324
72325
72326
72327
72328
72329
72330
72331
72332
72333
72334
72335
72336
72337
72338
72339
72340
72341
72342
72343
72344
72345
72346
72347
72348
72349
72350
72351
72352
72353
72354
72355
72356
72357
72358
72359
72360
72361
72362
72363
72364
72365
72366
72367
72368
72369
72370
72371
72372
72373
72374
72375
72376
72377
72378
72379
72380
72381
72382
72383
72384
72385
72386
72387
72388
72389
72390
72391
72392
72393
72394
72395
72396
72397
72398
72399
72400
72401
72402
72403
72404
72405
72406
72407
72408
72409
72410
72411
72412
72413
72414
72415
72416
72417
72418
72419
72420
72421
72422
72423
72424
72425
72426
72427
72428
72429
72430
72431
72432
72433
72434
72435
72436
72437
72438
72439
72440
72441
72442
72443
72444
72445
72446
72447
72448
72449
72450
72451
72452
72453
72454
72455
72456
72457
72458
72459
72460
72461
72462
72463
72464
72465
72466
72467
72468
72469
72470
72471
72472
72473
72474
72475
72476
72477
72478
72479
72480
72481
72482
72483
72484
72485
72486
72487
72488
72489
72490
72491
72492
72493
72494
72495
72496
72497
72498
72499
72500
72501
72502
72503
72504
72505
72506
72507
72508
72509
72510
72511
72512
72513
72514
72515
72516
72517
72518
72519
72520
72521
72522
72523
72524
72525
72526
72527
72528
72529
72530
72531
72532
72533
72534
72535
72536
72537
72538
72539
72540
72541
72542
72543
72544
72545
72546
72547
72548
72549
72550
72551
72552
72553
72554
72555
72556
72557
72558
72559
72560
72561
72562
72563
72564
72565
72566
72567
72568
72569
72570
72571
72572
72573
72574
72575
72576
72577
72578
72579
72580
72581
72582
72583
72584
72585
72586
72587
72588
72589
72590
72591
72592
72593
72594
72595
72596
72597
72598
72599
72600
72601
72602
72603
72604
72605
72606
72607
72608
72609
72610
72611
72612
72613
72614
72615
72616
72617
72618
72619
72620
72621
72622
72623
72624
72625
72626
72627
72628
72629
72630
72631
72632
72633
72634
72635
72636
72637
72638
72639
72640
72641
72642
72643
72644
72645
72646
72647
72648
72649
72650
72651
72652
72653
72654
72655
72656
72657
72658
72659
72660
72661
72662
72663
72664
72665
72666
72667
72668
72669
72670
72671
72672
72673
72674
72675
72676
72677
72678
72679
72680
72681
72682
72683
72684
72685
72686
72687
72688
72689
72690
72691
72692
72693
72694
72695
72696
72697
72698
72699
72700
72701
72702
72703
72704
72705
72706
72707
72708
72709
72710
72711
72712
72713
72714
72715
72716
72717
72718
72719
72720
72721
72722
72723
72724
72725
72726
72727
72728
72729
72730
72731
72732
72733
72734
72735
72736
72737
72738
72739
72740
72741
72742
72743
72744
72745
72746
72747
72748
72749
72750
72751
72752
72753
72754
72755
72756
72757
72758
72759
72760
72761
72762
72763
72764
72765
72766
72767
72768
72769
72770
72771
72772
72773
72774
72775
72776
72777
72778
72779
72780
72781
72782
72783
72784
72785
72786
72787
72788
72789
72790
72791
72792
72793
72794
72795
72796
72797
72798
72799
72800
72801
72802
72803
72804
72805
72806
72807
72808
72809
72810
72811
72812
72813
72814
72815
72816
72817
72818
72819
72820
72821
72822
72823
72824
72825
72826
72827
72828
72829
72830
72831
72832
72833
72834
72835
72836
72837
72838
72839
72840
72841
72842
72843
72844
72845
72846
72847
72848
72849
72850
72851
72852
72853
72854
72855
72856
72857
72858
72859
72860
72861
72862
72863
72864
72865
72866
72867
72868
72869
72870
72871
72872
72873
72874
72875
72876
72877
72878
72879
72880
72881
72882
72883
72884
72885
72886
72887
72888
72889
72890
72891
72892
72893
72894
72895
72896
72897
72898
72899
72900
72901
72902
72903
72904
72905
72906
72907
72908
72909
72910
72911
72912
72913
72914
72915
72916
72917
72918
72919
72920
72921
72922
72923
72924
72925
72926
72927
72928
72929
72930
72931
72932
72933
72934
72935
72936
72937
72938
72939
72940
72941
72942
72943
72944
72945
72946
72947
72948
72949
72950
72951
72952
72953
72954
72955
72956
72957
72958
72959
72960
72961
72962
72963
72964
72965
72966
72967
72968
72969
72970
72971
72972
72973
72974
72975
72976
72977
72978
72979
72980
72981
72982
72983
72984
72985
72986
72987
72988
72989
72990
72991
72992
72993
72994
72995
72996
72997
72998
72999
73000
73001
73002
73003
73004
73005
73006
73007
73008
73009
73010
73011
73012
73013
73014
73015
73016
73017
73018
73019
73020
73021
73022
73023
73024
73025
73026
73027
73028
73029
73030
73031
73032
73033
73034
73035
73036
73037
73038
73039
73040
73041
73042
73043
73044
73045
73046
73047
73048
73049
73050
73051
73052
73053
73054
73055
73056
73057
73058
73059
73060
73061
73062
73063
73064
73065
73066
73067
73068
73069
73070
73071
73072
73073
73074
73075
73076
73077
73078
73079
73080
73081
73082
73083
73084
73085
73086
73087
73088
73089
73090
73091
73092
73093
73094
73095
73096
73097
73098
73099
73100
73101
73102
73103
73104
73105
73106
73107
73108
73109
73110
73111
73112
73113
73114
73115
73116
73117
73118
73119
73120
73121
73122
73123
73124
73125
73126
73127
73128
73129
73130
73131
73132
73133
73134
73135
73136
73137
73138
73139
73140
73141
73142
73143
73144
73145
73146
73147
73148
73149
73150
73151
73152
73153
73154
73155
73156
73157
73158
73159
73160
73161
73162
73163
73164
73165
73166
73167
73168
73169
73170
73171
73172
73173
73174
73175
73176
73177
73178
73179
73180
73181
73182
73183
73184
73185
73186
73187
73188
73189
73190
73191
73192
73193
73194
73195
73196
73197
73198
73199
73200
73201
73202
73203
73204
73205
73206
73207
73208
73209
73210
73211
73212
73213
73214
73215
73216
73217
73218
73219
73220
73221
73222
73223
73224
73225
73226
73227
73228
73229
73230
73231
73232
73233
73234
73235
73236
73237
73238
73239
73240
73241
73242
73243
73244
73245
73246
73247
73248
73249
73250
73251
73252
73253
73254
73255
73256
73257
73258
73259
73260
73261
73262
73263
73264
73265
73266
73267
73268
73269
73270
73271
73272
73273
73274
73275
73276
73277
73278
73279
73280
73281
73282
73283
73284
73285
73286
73287
73288
73289
73290
73291
73292
73293
73294
73295
73296
73297
73298
73299
73300
73301
73302
73303
73304
73305
73306
73307
73308
73309
73310
73311
73312
73313
73314
73315
73316
73317
73318
73319
73320
73321
73322
73323
73324
73325
73326
73327
73328
73329
73330
73331
73332
73333
73334
73335
73336
73337
73338
73339
73340
73341
73342
73343
73344
73345
73346
73347
73348
73349
73350
73351
73352
73353
73354
73355
73356
73357
73358
73359
73360
73361
73362
73363
73364
73365
73366
73367
73368
73369
73370
73371
73372
73373
73374
73375
73376
73377
73378
73379
73380
73381
73382
73383
73384
73385
73386
73387
73388
73389
73390
73391
73392
73393
73394
73395
73396
73397
73398
73399
73400
73401
73402
73403
73404
73405
73406
73407
73408
73409
73410
73411
73412
73413
73414
73415
73416
73417
73418
73419
73420
73421
73422
73423
73424
73425
73426
73427
73428
73429
73430
73431
73432
73433
73434
73435
73436
73437
73438
73439
73440
73441
73442
73443
73444
73445
73446
73447
73448
73449
73450
73451
73452
73453
73454
73455
73456
73457
73458
73459
73460
73461
73462
73463
73464
73465
73466
73467
73468
73469
73470
73471
73472
73473
73474
73475
73476
73477
73478
73479
73480
73481
73482
73483
73484
73485
73486
73487
73488
73489
73490
73491
73492
73493
73494
73495
73496
73497
73498
73499
73500
73501
73502
73503
73504
73505
73506
73507
73508
73509
73510
73511
73512
73513
73514
73515
73516
73517
73518
73519
73520
73521
73522
73523
73524
73525
73526
73527
73528
73529
73530
73531
73532
73533
73534
73535
73536
73537
73538
73539
73540
73541
73542
73543
73544
73545
73546
73547
73548
73549
73550
73551
73552
73553
73554
73555
73556
73557
73558
73559
73560
73561
73562
73563
73564
73565
73566
73567
73568
73569
73570
73571
73572
73573
73574
73575
73576
73577
73578
73579
73580
73581
73582
73583
73584
73585
73586
73587
73588
73589
73590
73591
73592
73593
73594
73595
73596
73597
73598
73599
73600
73601
73602
73603
73604
73605
73606
73607
73608
73609
73610
73611
73612
73613
73614
73615
73616
73617
73618
73619
73620
73621
73622
73623
73624
73625
73626
73627
73628
73629
73630
73631
73632
73633
73634
73635
73636
73637
73638
73639
73640
73641
73642
73643
73644
73645
73646
73647
73648
73649
73650
73651
73652
73653
73654
73655
73656
73657
73658
73659
73660
73661
73662
73663
73664
73665
73666
73667
73668
73669
73670
73671
73672
73673
73674
73675
73676
73677
73678
73679
73680
73681
73682
73683
73684
73685
73686
73687
73688
73689
73690
73691
73692
73693
73694
73695
73696
73697
73698
73699
73700
73701
73702
73703
73704
73705
73706
73707
73708
73709
73710
73711
73712
73713
73714
73715
73716
73717
73718
73719
73720
73721
73722
73723
73724
73725
73726
73727
73728
73729
73730
73731
73732
73733
73734
73735
73736
73737
73738
73739
73740
73741
73742
73743
73744
73745
73746
73747
73748
73749
73750
73751
73752
73753
73754
73755
73756
73757
73758
73759
73760
73761
73762
73763
73764
73765
73766
73767
73768
73769
73770
73771
73772
73773
73774
73775
73776
73777
73778
73779
73780
73781
73782
73783
73784
73785
73786
73787
73788
73789
73790
73791
73792
73793
73794
73795
73796
73797
73798
73799
73800
73801
73802
73803
73804
73805
73806
73807
73808
73809
73810
73811
73812
73813
73814
73815
73816
73817
73818
73819
73820
73821
73822
73823
73824
73825
73826
73827
73828
73829
73830
73831
73832
73833
73834
73835
73836
73837
73838
73839
73840
73841
73842
73843
73844
73845
73846
73847
73848
73849
73850
73851
73852
73853
73854
73855
73856
73857
73858
73859
73860
73861
73862
73863
73864
73865
73866
73867
73868
73869
73870
73871
73872
73873
73874
73875
73876
73877
73878
73879
73880
73881
73882
73883
73884
73885
73886
73887
73888
73889
73890
73891
73892
73893
73894
73895
73896
73897
73898
73899
73900
73901
73902
73903
73904
73905
73906
73907
73908
73909
73910
73911
73912
73913
73914
73915
73916
73917
73918
73919
73920
73921
73922
73923
73924
73925
73926
73927
73928
73929
73930
73931
73932
73933
73934
73935
73936
73937
73938
73939
73940
73941
73942
73943
73944
73945
73946
73947
73948
73949
73950
73951
73952
73953
73954
73955
73956
73957
73958
73959
73960
73961
73962
73963
73964
73965
73966
73967
73968
73969
73970
73971
73972
73973
73974
73975
73976
73977
73978
73979
73980
73981
73982
73983
73984
73985
73986
73987
73988
73989
73990
73991
73992
73993
73994
73995
73996
73997
73998
73999
74000
74001
74002
74003
74004
74005
74006
74007
74008
74009
74010
74011
74012
74013
74014
74015
74016
74017
74018
74019
74020
74021
74022
74023
74024
74025
74026
74027
74028
74029
74030
74031
74032
74033
74034
74035
74036
74037
74038
74039
74040
74041
74042
74043
74044
74045
74046
74047
74048
74049
74050
74051
74052
74053
74054
74055
74056
74057
74058
74059
74060
74061
74062
74063
74064
74065
74066
74067
74068
74069
74070
74071
74072
74073
74074
74075
74076
74077
74078
74079
74080
74081
74082
74083
74084
74085
74086
74087
74088
74089
74090
74091
74092
74093
74094
74095
74096
74097
74098
74099
74100
74101
74102
74103
74104
74105
74106
74107
74108
74109
74110
74111
74112
74113
74114
74115
74116
74117
74118
74119
74120
74121
74122
74123
74124
74125
74126
74127
74128
74129
74130
74131
74132
74133
74134
74135
74136
74137
74138
74139
74140
74141
74142
74143
74144
74145
74146
74147
74148
74149
74150
74151
74152
74153
74154
74155
74156
74157
74158
74159
74160
74161
74162
74163
74164
74165
74166
74167
74168
74169
74170
74171
74172
74173
74174
74175
74176
74177
74178
74179
74180
74181
74182
74183
74184
74185
74186
74187
74188
74189
74190
74191
74192
74193
74194
74195
74196
74197
74198
74199
74200
74201
74202
74203
74204
74205
74206
74207
74208
74209
74210
74211
74212
74213
74214
74215
74216
74217
74218
74219
74220
74221
74222
74223
74224
74225
74226
74227
74228
74229
74230
74231
74232
74233
74234
74235
74236
74237
74238
74239
74240
74241
74242
74243
74244
74245
74246
74247
74248
74249
74250
74251
74252
74253
74254
74255
74256
74257
74258
74259
74260
74261
74262
74263
74264
74265
74266
74267
74268
74269
74270
74271
74272
74273
74274
74275
74276
74277
74278
74279
74280
74281
74282
74283
74284
74285
74286
74287
74288
74289
74290
74291
74292
74293
74294
74295
74296
74297
74298
74299
74300
74301
74302
74303
74304
74305
74306
74307
74308
74309
74310
74311
74312
74313
74314
74315
74316
74317
74318
74319
74320
74321
74322
74323
74324
74325
74326
74327
74328
74329
74330
74331
74332
74333
74334
74335
74336
74337
74338
74339
74340
74341
74342
74343
74344
74345
74346
74347
74348
74349
74350
74351
74352
74353
74354
74355
74356
74357
74358
74359
74360
74361
74362
74363
74364
74365
74366
74367
74368
74369
74370
74371
74372
74373
74374
74375
74376
74377
74378
74379
74380
74381
74382
74383
74384
74385
74386
74387
74388
74389
74390
74391
74392
74393
74394
74395
74396
74397
74398
74399
74400
74401
74402
74403
74404
74405
74406
74407
74408
74409
74410
74411
74412
74413
74414
74415
74416
74417
74418
74419
74420
74421
74422
74423
74424
74425
74426
74427
74428
74429
74430
74431
74432
74433
74434
74435
74436
74437
74438
74439
74440
74441
74442
74443
74444
74445
74446
74447
74448
74449
74450
74451
74452
74453
74454
74455
74456
74457
74458
74459
74460
74461
74462
74463
74464
74465
74466
74467
74468
74469
74470
74471
74472
74473
74474
74475
74476
74477
74478
74479
74480
74481
74482
74483
74484
74485
74486
74487
74488
74489
74490
74491
74492
74493
74494
74495
74496
74497
74498
74499
74500
74501
74502
74503
74504
74505
74506
74507
74508
74509
74510
74511
74512
74513
74514
74515
74516
74517
74518
74519
74520
74521
74522
74523
74524
74525
74526
74527
74528
74529
74530
74531
74532
74533
74534
74535
74536
74537
74538
74539
74540
74541
74542
74543
74544
74545
74546
74547
74548
74549
74550
74551
74552
74553
74554
74555
74556
74557
74558
74559
74560
74561
74562
74563
74564
74565
74566
74567
74568
74569
74570
74571
74572
74573
74574
74575
74576
74577
74578
74579
74580
74581
74582
74583
74584
74585
74586
74587
74588
74589
74590
74591
74592
74593
74594
74595
74596
74597
74598
74599
74600
74601
74602
74603
74604
74605
74606
74607
74608
74609
74610
74611
74612
74613
74614
74615
74616
74617
74618
74619
74620
74621
74622
74623
74624
74625
74626
74627
74628
74629
74630
74631
74632
74633
74634
74635
74636
74637
74638
74639
74640
74641
74642
74643
74644
74645
74646
74647
74648
74649
74650
74651
74652
74653
74654
74655
74656
74657
74658
74659
74660
74661
74662
74663
74664
74665
74666
74667
74668
74669
74670
74671
74672
74673
74674
74675
74676
74677
74678
74679
74680
74681
74682
74683
74684
74685
74686
74687
74688
74689
74690
74691
74692
74693
74694
74695
74696
74697
74698
74699
74700
74701
74702
74703
74704
74705
74706
74707
74708
74709
74710
74711
74712
74713
74714
74715
74716
74717
74718
74719
74720
74721
74722
74723
74724
74725
74726
74727
74728
74729
74730
74731
74732
74733
74734
74735
74736
74737
74738
74739
74740
74741
74742
74743
74744
74745
74746
74747
74748
74749
74750
74751
74752
74753
74754
74755
74756
74757
74758
74759
74760
74761
74762
74763
74764
74765
74766
74767
74768
74769
74770
74771
74772
74773
74774
74775
74776
74777
74778
74779
74780
74781
74782
74783
74784
74785
74786
74787
74788
74789
74790
74791
74792
74793
74794
74795
74796
74797
74798
74799
74800
74801
74802
74803
74804
74805
74806
74807
74808
74809
74810
74811
74812
74813
74814
74815
74816
74817
74818
74819
74820
74821
74822
74823
74824
74825
74826
74827
74828
74829
74830
74831
74832
74833
74834
74835
74836
74837
74838
74839
74840
74841
74842
74843
74844
74845
74846
74847
74848
74849
74850
74851
74852
74853
74854
74855
74856
74857
74858
74859
74860
74861
74862
74863
74864
74865
74866
74867
74868
74869
74870
74871
74872
74873
74874
74875
74876
74877
74878
74879
74880
74881
74882
74883
74884
74885
74886
74887
74888
74889
74890
74891
74892
74893
74894
74895
74896
74897
74898
74899
74900
74901
74902
74903
74904
74905
74906
74907
74908
74909
74910
74911
74912
74913
74914
74915
74916
74917
74918
74919
74920
74921
74922
74923
74924
74925
74926
74927
74928
74929
74930
74931
74932
74933
74934
74935
74936
74937
74938
74939
74940
74941
74942
74943
74944
74945
74946
74947
74948
74949
74950
74951
74952
74953
74954
74955
74956
74957
74958
74959
74960
74961
74962
74963
74964
74965
74966
74967
74968
74969
74970
74971
74972
74973
74974
74975
74976
74977
74978
74979
74980
74981
74982
74983
74984
74985
74986
74987
74988
74989
74990
74991
74992
74993
74994
74995
74996
74997
74998
74999
75000
75001
75002
75003
75004
75005
75006
75007
75008
75009
75010
75011
75012
75013
75014
75015
75016
75017
75018
75019
75020
75021
75022
75023
75024
75025
75026
75027
75028
75029
75030
75031
75032
75033
75034
75035
75036
75037
75038
75039
75040
75041
75042
75043
75044
75045
75046
75047
75048
75049
75050
75051
75052
75053
75054
75055
75056
75057
75058
75059
75060
75061
75062
75063
75064
75065
75066
75067
75068
75069
75070
75071
75072
75073
75074
75075
75076
75077
75078
75079
75080
75081
75082
75083
75084
75085
75086
75087
75088
75089
75090
75091
75092
75093
75094
75095
75096
75097
75098
75099
75100
75101
75102
75103
75104
75105
75106
75107
75108
75109
75110
75111
75112
75113
75114
75115
75116
75117
75118
75119
75120
75121
75122
75123
75124
75125
75126
75127
75128
75129
75130
75131
75132
75133
75134
75135
75136
75137
75138
75139
75140
75141
75142
75143
75144
75145
75146
75147
75148
75149
75150
75151
75152
75153
75154
75155
75156
75157
75158
75159
75160
75161
75162
75163
75164
75165
75166
75167
75168
75169
75170
75171
75172
75173
75174
75175
75176
75177
75178
75179
75180
75181
75182
75183
75184
75185
75186
75187
75188
75189
75190
75191
75192
75193
75194
75195
75196
75197
75198
75199
75200
75201
75202
75203
75204
75205
75206
75207
75208
75209
75210
75211
75212
75213
75214
75215
75216
75217
75218
75219
75220
75221
75222
75223
75224
75225
75226
75227
75228
75229
75230
75231
75232
75233
75234
75235
75236
75237
75238
75239
75240
75241
75242
75243
75244
75245
75246
75247
75248
75249
75250
75251
75252
75253
75254
75255
75256
75257
75258
75259
75260
75261
75262
75263
75264
75265
75266
75267
75268
75269
75270
75271
75272
75273
75274
75275
75276
75277
75278
75279
75280
75281
75282
75283
75284
75285
75286
75287
75288
75289
75290
75291
75292
75293
75294
75295
75296
75297
75298
75299
75300
75301
75302
75303
75304
75305
75306
75307
75308
75309
75310
75311
75312
75313
75314
75315
75316
75317
75318
75319
75320
75321
75322
75323
75324
75325
75326
75327
75328
75329
75330
75331
75332
75333
75334
75335
75336
75337
75338
75339
75340
75341
75342
75343
75344
75345
75346
75347
75348
75349
75350
75351
75352
75353
75354
75355
75356
75357
75358
75359
75360
75361
75362
75363
75364
75365
75366
75367
75368
75369
75370
75371
75372
75373
75374
75375
75376
75377
75378
75379
75380
75381
75382
75383
75384
75385
75386
75387
75388
75389
75390
75391
75392
75393
75394
75395
75396
75397
75398
75399
75400
75401
75402
75403
75404
75405
75406
75407
75408
75409
75410
75411
75412
75413
75414
75415
75416
75417
75418
75419
75420
75421
75422
75423
75424
75425
75426
75427
75428
75429
75430
75431
75432
75433
75434
75435
75436
75437
75438
75439
75440
75441
75442
75443
75444
75445
75446
75447
75448
75449
75450
75451
75452
75453
75454
75455
75456
75457
75458
75459
75460
75461
75462
75463
75464
75465
75466
75467
75468
75469
75470
75471
75472
75473
75474
75475
75476
75477
75478
75479
75480
75481
75482
75483
75484
75485
75486
75487
75488
75489
75490
75491
75492
75493
75494
75495
75496
75497
75498
75499
75500
75501
75502
75503
75504
75505
75506
75507
75508
75509
75510
75511
75512
75513
75514
75515
75516
75517
75518
75519
75520
75521
75522
75523
75524
75525
75526
75527
75528
75529
75530
75531
75532
75533
75534
75535
75536
75537
75538
75539
75540
75541
75542
75543
75544
75545
75546
75547
75548
75549
75550
75551
75552
75553
75554
75555
75556
75557
75558
75559
75560
75561
75562
75563
75564
75565
75566
75567
75568
75569
75570
75571
75572
75573
75574
75575
75576
75577
75578
75579
75580
75581
75582
75583
75584
75585
75586
75587
75588
75589
75590
75591
75592
75593
75594
75595
75596
75597
75598
75599
75600
75601
75602
75603
75604
75605
75606
75607
75608
75609
75610
75611
75612
75613
75614
75615
75616
75617
75618
75619
75620
75621
75622
75623
75624
75625
75626
75627
75628
75629
75630
75631
75632
75633
75634
75635
75636
75637
75638
75639
75640
75641
75642
75643
75644
75645
75646
75647
75648
75649
75650
75651
75652
75653
75654
75655
75656
75657
75658
75659
75660
75661
75662
75663
75664
75665
75666
75667
75668
75669
75670
75671
75672
75673
75674
75675
75676
75677
75678
75679
75680
75681
75682
75683
75684
75685
75686
75687
75688
75689
75690
75691
75692
75693
75694
75695
75696
75697
75698
75699
75700
75701
75702
75703
75704
75705
75706
75707
75708
75709
75710
75711
75712
75713
75714
75715
75716
75717
75718
75719
75720
75721
75722
75723
75724
75725
75726
75727
75728
75729
75730
75731
75732
75733
75734
75735
75736
75737
75738
75739
75740
75741
75742
75743
75744
75745
75746
75747
75748
75749
75750
75751
75752
75753
75754
75755
75756
75757
75758
75759
75760
75761
75762
75763
75764
75765
75766
75767
75768
75769
75770
75771
75772
75773
75774
75775
75776
75777
75778
75779
75780
75781
75782
75783
75784
75785
75786
75787
75788
75789
75790
75791
75792
75793
75794
75795
75796
75797
75798
75799
75800
75801
75802
75803
75804
75805
75806
75807
75808
75809
75810
75811
75812
75813
75814
75815
75816
75817
75818
75819
75820
75821
75822
75823
75824
75825
75826
75827
75828
75829
75830
75831
75832
75833
75834
75835
75836
75837
75838
75839
75840
75841
75842
75843
75844
75845
75846
75847
75848
75849
75850
75851
75852
75853
75854
75855
75856
75857
75858
75859
75860
75861
75862
75863
75864
75865
75866
75867
75868
75869
75870
75871
75872
75873
75874
75875
75876
75877
75878
75879
75880
75881
75882
75883
75884
75885
75886
75887
75888
75889
75890
75891
75892
75893
75894
75895
75896
75897
75898
75899
75900
75901
75902
75903
75904
75905
75906
75907
75908
75909
75910
75911
75912
75913
75914
75915
75916
75917
75918
75919
75920
75921
75922
75923
75924
75925
75926
75927
75928
75929
75930
75931
75932
75933
75934
75935
75936
75937
75938
75939
75940
75941
75942
75943
75944
75945
75946
75947
75948
75949
75950
75951
75952
75953
75954
75955
75956
75957
75958
75959
75960
75961
75962
75963
75964
75965
75966
75967
75968
75969
75970
75971
75972
75973
75974
75975
75976
75977
75978
75979
75980
75981
75982
75983
75984
75985
75986
75987
75988
75989
75990
75991
75992
75993
75994
75995
75996
75997
75998
75999
76000
76001
76002
76003
76004
76005
76006
76007
76008
76009
76010
76011
76012
76013
76014
76015
76016
76017
76018
76019
76020
76021
76022
76023
76024
76025
76026
76027
76028
76029
76030
76031
76032
76033
76034
76035
76036
76037
76038
76039
76040
76041
76042
76043
76044
76045
76046
76047
76048
76049
76050
76051
76052
76053
76054
76055
76056
76057
76058
76059
76060
76061
76062
76063
76064
76065
76066
76067
76068
76069
76070
76071
76072
76073
76074
76075
76076
76077
76078
76079
76080
76081
76082
76083
76084
76085
76086
76087
76088
76089
76090
76091
76092
76093
76094
76095
76096
76097
76098
76099
76100
76101
76102
76103
76104
76105
76106
76107
76108
76109
76110
76111
76112
76113
76114
76115
76116
76117
76118
76119
76120
76121
76122
76123
76124
76125
76126
76127
76128
76129
76130
76131
76132
76133
76134
76135
76136
76137
76138
76139
76140
76141
76142
76143
76144
76145
76146
76147
76148
76149
76150
76151
76152
76153
76154
76155
76156
76157
76158
76159
76160
76161
76162
76163
76164
76165
76166
76167
76168
76169
76170
76171
76172
76173
76174
76175
76176
76177
76178
76179
76180
76181
76182
76183
76184
76185
76186
76187
76188
76189
76190
76191
76192
76193
76194
76195
76196
76197
76198
76199
76200
76201
76202
76203
76204
76205
76206
76207
76208
76209
76210
76211
76212
76213
76214
76215
76216
76217
76218
76219
76220
76221
76222
76223
76224
76225
76226
76227
76228
76229
76230
76231
76232
76233
76234
76235
76236
76237
76238
76239
76240
76241
76242
76243
76244
76245
76246
76247
76248
76249
76250
76251
76252
76253
76254
76255
76256
76257
76258
76259
76260
76261
76262
76263
76264
76265
76266
76267
76268
76269
76270
76271
76272
76273
76274
76275
76276
76277
76278
76279
76280
76281
76282
76283
76284
76285
76286
76287
76288
76289
76290
76291
76292
76293
76294
76295
76296
76297
76298
76299
76300
76301
76302
76303
76304
76305
76306
76307
76308
76309
76310
76311
76312
76313
76314
76315
76316
76317
76318
76319
76320
76321
76322
76323
76324
76325
76326
76327
76328
76329
76330
76331
76332
76333
76334
76335
76336
76337
76338
76339
76340
76341
76342
76343
76344
76345
76346
76347
76348
76349
76350
76351
76352
76353
76354
76355
76356
76357
76358
76359
76360
76361
76362
76363
76364
76365
76366
76367
76368
76369
76370
76371
76372
76373
76374
76375
76376
76377
76378
76379
76380
76381
76382
76383
76384
76385
76386
76387
76388
76389
76390
76391
76392
76393
76394
76395
76396
76397
76398
76399
76400
76401
76402
76403
76404
76405
76406
76407
76408
76409
76410
76411
76412
76413
76414
76415
76416
76417
76418
76419
76420
76421
76422
76423
76424
76425
76426
76427
76428
76429
76430
76431
76432
76433
76434
76435
76436
76437
76438
76439
76440
76441
76442
76443
76444
76445
76446
76447
76448
76449
76450
76451
76452
76453
76454
76455
76456
76457
76458
76459
76460
76461
76462
76463
76464
76465
76466
76467
76468
76469
76470
76471
76472
76473
76474
76475
76476
76477
76478
76479
76480
76481
76482
76483
76484
76485
76486
76487
76488
76489
76490
76491
76492
76493
76494
76495
76496
76497
76498
76499
76500
76501
76502
76503
76504
76505
76506
76507
76508
76509
76510
76511
76512
76513
76514
76515
76516
76517
76518
76519
76520
76521
76522
76523
76524
76525
76526
76527
76528
76529
76530
76531
76532
76533
76534
76535
76536
76537
76538
76539
76540
76541
76542
76543
76544
76545
76546
76547
76548
76549
76550
76551
76552
76553
76554
76555
76556
76557
76558
76559
76560
76561
76562
76563
76564
76565
76566
76567
76568
76569
76570
76571
76572
76573
76574
76575
76576
76577
76578
76579
76580
76581
76582
76583
76584
76585
76586
76587
76588
76589
76590
76591
76592
76593
76594
76595
76596
76597
76598
76599
76600
76601
76602
76603
76604
76605
76606
76607
76608
76609
76610
76611
76612
76613
76614
76615
76616
76617
76618
76619
76620
76621
76622
76623
76624
76625
76626
76627
76628
76629
76630
76631
76632
76633
76634
76635
76636
76637
76638
76639
76640
76641
76642
76643
76644
76645
76646
76647
76648
76649
76650
76651
76652
76653
76654
76655
76656
76657
76658
76659
76660
76661
76662
76663
76664
76665
76666
76667
76668
76669
76670
76671
76672
76673
76674
76675
76676
76677
76678
76679
76680
76681
76682
76683
76684
76685
76686
76687
76688
76689
76690
76691
76692
76693
76694
76695
76696
76697
76698
76699
76700
76701
76702
76703
76704
76705
76706
76707
76708
76709
76710
76711
76712
76713
76714
76715
76716
76717
76718
76719
76720
76721
76722
76723
76724
76725
76726
76727
76728
76729
76730
76731
76732
76733
76734
76735
76736
76737
76738
76739
76740
76741
76742
76743
76744
76745
76746
76747
76748
76749
76750
76751
76752
76753
76754
76755
76756
76757
76758
76759
76760
76761
76762
76763
76764
76765
76766
76767
76768
76769
76770
76771
76772
76773
76774
76775
76776
76777
76778
76779
76780
76781
76782
76783
76784
76785
76786
76787
76788
76789
76790
76791
76792
76793
76794
76795
76796
76797
76798
76799
76800
76801
76802
76803
76804
76805
76806
76807
76808
76809
76810
76811
76812
76813
76814
76815
76816
76817
76818
76819
76820
76821
76822
76823
76824
76825
76826
76827
76828
76829
76830
76831
76832
76833
76834
76835
76836
76837
76838
76839
76840
76841
76842
76843
76844
76845
76846
76847
76848
76849
76850
76851
76852
76853
76854
76855
76856
76857
76858
76859
76860
76861
76862
76863
76864
76865
76866
76867
76868
76869
76870
76871
76872
76873
76874
76875
76876
76877
76878
76879
76880
76881
76882
76883
76884
76885
76886
76887
76888
76889
76890
76891
76892
76893
76894
76895
76896
76897
76898
76899
76900
76901
76902
76903
76904
76905
76906
76907
76908
76909
76910
76911
76912
76913
76914
76915
76916
76917
76918
76919
76920
76921
76922
76923
76924
76925
76926
76927
76928
76929
76930
76931
76932
76933
76934
76935
76936
76937
76938
76939
76940
76941
76942
76943
76944
76945
76946
76947
76948
76949
76950
76951
76952
76953
76954
76955
76956
76957
76958
76959
76960
76961
76962
76963
76964
76965
76966
76967
76968
76969
76970
76971
76972
76973
76974
76975
76976
76977
76978
76979
76980
76981
76982
76983
76984
76985
76986
76987
76988
76989
76990
76991
76992
76993
76994
76995
76996
76997
76998
76999
77000
77001
77002
77003
77004
77005
77006
77007
77008
77009
77010
77011
77012
77013
77014
77015
77016
77017
77018
77019
77020
77021
77022
77023
77024
77025
77026
77027
77028
77029
77030
77031
77032
77033
77034
77035
77036
77037
77038
77039
77040
77041
77042
77043
77044
77045
77046
77047
77048
77049
77050
77051
77052
77053
77054
77055
77056
77057
77058
77059
77060
77061
77062
77063
77064
77065
77066
77067
77068
77069
77070
77071
77072
77073
77074
77075
77076
77077
77078
77079
77080
77081
77082
77083
77084
77085
77086
77087
77088
77089
77090
77091
77092
77093
77094
77095
77096
77097
77098
77099
77100
77101
77102
77103
77104
77105
77106
77107
77108
77109
77110
77111
77112
77113
77114
77115
77116
77117
77118
77119
77120
77121
77122
77123
77124
77125
77126
77127
77128
77129
77130
77131
77132
77133
77134
77135
77136
77137
77138
77139
77140
77141
77142
77143
77144
77145
77146
77147
77148
77149
77150
77151
77152
77153
77154
77155
77156
77157
77158
77159
77160
77161
77162
77163
77164
77165
77166
77167
77168
77169
77170
77171
77172
77173
77174
77175
77176
77177
77178
77179
77180
77181
77182
77183
77184
77185
77186
77187
77188
77189
77190
77191
77192
77193
77194
77195
77196
77197
77198
77199
77200
77201
77202
77203
77204
77205
77206
77207
77208
77209
77210
77211
77212
77213
77214
77215
77216
77217
77218
77219
77220
77221
77222
77223
77224
77225
77226
77227
77228
77229
77230
77231
77232
77233
77234
77235
77236
77237
77238
77239
77240
77241
77242
77243
77244
77245
77246
77247
77248
77249
77250
77251
77252
77253
77254
77255
77256
77257
77258
77259
77260
77261
77262
77263
77264
77265
77266
77267
77268
77269
77270
77271
77272
77273
77274
77275
77276
77277
77278
77279
77280
77281
77282
77283
77284
77285
77286
77287
77288
77289
77290
77291
77292
77293
77294
77295
77296
77297
77298
77299
77300
77301
77302
77303
77304
77305
77306
77307
77308
77309
77310
77311
77312
77313
77314
77315
77316
77317
77318
77319
77320
77321
77322
77323
77324
77325
77326
77327
77328
77329
77330
77331
77332
77333
77334
77335
77336
77337
77338
77339
77340
77341
77342
77343
77344
77345
77346
77347
77348
77349
77350
77351
77352
77353
77354
77355
77356
77357
77358
77359
77360
77361
77362
77363
77364
77365
77366
77367
77368
77369
77370
77371
77372
77373
77374
77375
77376
77377
77378
77379
77380
77381
77382
77383
77384
77385
77386
77387
77388
77389
77390
77391
77392
77393
77394
77395
77396
77397
77398
77399
77400
77401
77402
77403
77404
77405
77406
77407
77408
77409
77410
77411
77412
77413
77414
77415
77416
77417
77418
77419
77420
77421
77422
77423
77424
77425
77426
77427
77428
77429
77430
77431
77432
77433
77434
77435
77436
77437
77438
77439
77440
77441
77442
77443
77444
77445
77446
77447
77448
77449
77450
77451
77452
77453
77454
77455
77456
77457
77458
77459
77460
77461
77462
77463
77464
77465
77466
77467
77468
77469
77470
77471
77472
77473
77474
77475
77476
77477
77478
77479
77480
77481
77482
77483
77484
77485
77486
77487
77488
77489
77490
77491
77492
77493
77494
77495
77496
77497
77498
77499
77500
77501
77502
77503
77504
77505
77506
77507
77508
77509
77510
77511
77512
77513
77514
77515
77516
77517
77518
77519
77520
77521
77522
77523
77524
77525
77526
77527
77528
77529
77530
77531
77532
77533
77534
77535
77536
77537
77538
77539
77540
77541
77542
77543
77544
77545
77546
77547
77548
77549
77550
77551
77552
77553
77554
77555
77556
77557
77558
77559
77560
77561
77562
77563
77564
77565
77566
77567
77568
77569
77570
77571
77572
77573
77574
77575
77576
77577
77578
77579
77580
77581
77582
77583
77584
77585
77586
77587
77588
77589
77590
77591
77592
77593
77594
77595
77596
77597
77598
77599
77600
77601
77602
77603
77604
77605
77606
77607
77608
77609
77610
77611
77612
77613
77614
77615
77616
77617
77618
77619
77620
77621
77622
77623
77624
77625
77626
77627
77628
77629
77630
77631
77632
77633
77634
77635
77636
77637
77638
77639
77640
77641
77642
77643
77644
77645
77646
77647
77648
77649
77650
77651
77652
77653
77654
77655
77656
77657
77658
77659
77660
77661
77662
77663
77664
77665
77666
77667
77668
77669
77670
77671
77672
77673
77674
77675
77676
77677
77678
77679
77680
77681
77682
77683
77684
77685
77686
77687
77688
77689
77690
77691
77692
77693
77694
77695
77696
77697
77698
77699
77700
77701
77702
77703
77704
77705
77706
77707
77708
77709
77710
77711
77712
77713
77714
77715
77716
77717
77718
77719
77720
77721
77722
77723
77724
77725
77726
77727
77728
77729
77730
77731
77732
77733
77734
77735
77736
77737
77738
77739
77740
77741
77742
77743
77744
77745
77746
77747
77748
77749
77750
77751
77752
77753
77754
77755
77756
77757
77758
77759
77760
77761
77762
77763
77764
77765
77766
77767
77768
77769
77770
77771
77772
77773
77774
77775
77776
77777
77778
77779
77780
77781
77782
77783
77784
77785
77786
77787
77788
77789
77790
77791
77792
77793
77794
77795
77796
77797
77798
77799
77800
77801
77802
77803
77804
77805
77806
77807
77808
77809
77810
77811
77812
77813
77814
77815
77816
77817
77818
77819
77820
77821
77822
77823
77824
77825
77826
77827
77828
77829
77830
77831
77832
77833
77834
77835
77836
77837
77838
77839
77840
77841
77842
77843
77844
77845
77846
77847
77848
77849
77850
77851
77852
77853
77854
77855
77856
77857
77858
77859
77860
77861
77862
77863
77864
77865
77866
77867
77868
77869
77870
77871
77872
77873
77874
77875
77876
77877
77878
77879
77880
77881
77882
77883
77884
77885
77886
77887
77888
77889
77890
77891
77892
77893
77894
77895
77896
77897
77898
77899
77900
77901
77902
77903
77904
77905
77906
77907
77908
77909
77910
77911
77912
77913
77914
77915
77916
77917
77918
77919
77920
77921
77922
77923
77924
77925
77926
77927
77928
77929
77930
77931
77932
77933
77934
77935
77936
77937
77938
77939
77940
77941
77942
77943
77944
77945
77946
77947
77948
77949
77950
77951
77952
77953
77954
77955
77956
77957
77958
77959
77960
77961
77962
77963
77964
77965
77966
77967
77968
77969
77970
77971
77972
77973
77974
77975
77976
77977
77978
77979
77980
77981
77982
77983
77984
77985
77986
77987
77988
77989
77990
77991
77992
77993
77994
77995
77996
77997
77998
77999
78000
78001
78002
78003
78004
78005
78006
78007
78008
78009
78010
78011
78012
78013
78014
78015
78016
78017
78018
78019
78020
78021
78022
78023
78024
78025
78026
78027
78028
78029
78030
78031
78032
78033
78034
78035
78036
78037
78038
78039
78040
78041
78042
78043
78044
78045
78046
78047
78048
78049
78050
78051
78052
78053
78054
78055
78056
78057
78058
78059
78060
78061
78062
78063
78064
78065
78066
78067
78068
78069
78070
78071
78072
78073
78074
78075
78076
78077
78078
78079
78080
78081
78082
78083
78084
78085
78086
78087
78088
78089
78090
78091
78092
78093
78094
78095
78096
78097
78098
78099
78100
78101
78102
78103
78104
78105
78106
78107
78108
78109
78110
78111
78112
78113
78114
78115
78116
78117
78118
78119
78120
78121
78122
78123
78124
78125
78126
78127
78128
78129
78130
78131
78132
78133
78134
78135
78136
78137
78138
78139
78140
78141
78142
78143
78144
78145
78146
78147
78148
78149
78150
78151
78152
78153
78154
78155
78156
78157
78158
78159
78160
78161
78162
78163
78164
78165
78166
78167
78168
78169
78170
78171
78172
78173
78174
78175
78176
78177
78178
78179
78180
78181
78182
78183
78184
78185
78186
78187
78188
78189
78190
78191
78192
78193
78194
78195
78196
78197
78198
78199
78200
78201
78202
78203
78204
78205
78206
78207
78208
78209
78210
78211
78212
78213
78214
78215
78216
78217
78218
78219
78220
78221
78222
78223
78224
78225
78226
78227
78228
78229
78230
78231
78232
78233
78234
78235
78236
78237
78238
78239
78240
78241
78242
78243
78244
78245
78246
78247
78248
78249
78250
78251
78252
78253
78254
78255
78256
78257
78258
78259
78260
78261
78262
78263
78264
78265
78266
78267
78268
78269
78270
78271
78272
78273
78274
78275
78276
78277
78278
78279
78280
78281
78282
78283
78284
78285
78286
78287
78288
78289
78290
78291
78292
78293
78294
78295
78296
78297
78298
78299
78300
78301
78302
78303
78304
78305
78306
78307
78308
78309
78310
78311
78312
78313
78314
78315
78316
78317
78318
78319
78320
78321
78322
78323
78324
78325
78326
78327
78328
78329
78330
78331
78332
78333
78334
78335
78336
78337
78338
78339
78340
78341
78342
78343
78344
78345
78346
78347
78348
78349
78350
78351
78352
78353
78354
78355
78356
78357
78358
78359
78360
78361
78362
78363
78364
78365
78366
78367
78368
78369
78370
78371
78372
78373
78374
78375
78376
78377
78378
78379
78380
78381
78382
78383
78384
78385
78386
78387
78388
78389
78390
78391
78392
78393
78394
78395
78396
78397
78398
78399
78400
78401
78402
78403
78404
78405
78406
78407
78408
78409
78410
78411
78412
78413
78414
78415
78416
78417
78418
78419
78420
78421
78422
78423
78424
78425
78426
78427
78428
78429
78430
78431
78432
78433
78434
78435
78436
78437
78438
78439
78440
78441
78442
78443
78444
78445
78446
78447
78448
78449
78450
78451
78452
78453
78454
78455
78456
78457
78458
78459
78460
78461
78462
78463
78464
78465
78466
78467
78468
78469
78470
78471
78472
78473
78474
78475
78476
78477
78478
78479
78480
78481
78482
78483
78484
78485
78486
78487
78488
78489
78490
78491
78492
78493
78494
78495
78496
78497
78498
78499
78500
78501
78502
78503
78504
78505
78506
78507
78508
78509
78510
78511
78512
78513
78514
78515
78516
78517
78518
78519
78520
78521
78522
78523
78524
78525
78526
78527
78528
78529
78530
78531
78532
78533
78534
78535
78536
78537
78538
78539
78540
78541
78542
78543
78544
78545
78546
78547
78548
78549
78550
78551
78552
78553
78554
78555
78556
78557
78558
78559
78560
78561
78562
78563
78564
78565
78566
78567
78568
78569
78570
78571
78572
78573
78574
78575
78576
78577
78578
78579
78580
78581
78582
78583
78584
78585
78586
78587
78588
78589
78590
78591
78592
78593
78594
78595
78596
78597
78598
78599
78600
78601
78602
78603
78604
78605
78606
78607
78608
78609
78610
78611
78612
78613
78614
78615
78616
78617
78618
78619
78620
78621
78622
78623
78624
78625
78626
78627
78628
78629
78630
78631
78632
78633
78634
78635
78636
78637
78638
78639
78640
78641
78642
78643
78644
78645
78646
78647
78648
78649
78650
78651
78652
78653
78654
78655
78656
78657
78658
78659
78660
78661
78662
78663
78664
78665
78666
78667
78668
78669
78670
78671
78672
78673
78674
78675
78676
78677
78678
78679
78680
78681
78682
78683
78684
78685
78686
78687
78688
78689
78690
78691
78692
78693
78694
78695
78696
78697
78698
78699
78700
78701
78702
78703
78704
78705
78706
78707
78708
78709
78710
78711
78712
78713
78714
78715
78716
78717
78718
78719
78720
78721
78722
78723
78724
78725
78726
78727
78728
78729
78730
78731
78732
78733
78734
78735
78736
78737
78738
78739
78740
78741
78742
78743
78744
78745
78746
78747
78748
78749
78750
78751
78752
78753
78754
78755
78756
78757
78758
78759
78760
78761
78762
78763
78764
78765
78766
78767
78768
78769
78770
78771
78772
78773
78774
78775
78776
78777
78778
78779
78780
78781
78782
78783
78784
78785
78786
78787
78788
78789
78790
78791
78792
78793
78794
78795
78796
78797
78798
78799
78800
78801
78802
78803
78804
78805
78806
78807
78808
78809
78810
78811
78812
78813
78814
78815
78816
78817
78818
78819
78820
78821
78822
78823
78824
78825
78826
78827
78828
78829
78830
78831
78832
78833
78834
78835
78836
78837
78838
78839
78840
78841
78842
78843
78844
78845
78846
78847
78848
78849
78850
78851
78852
78853
78854
78855
78856
78857
78858
78859
78860
78861
78862
78863
78864
78865
78866
78867
78868
78869
78870
78871
78872
78873
78874
78875
78876
78877
78878
78879
78880
78881
78882
78883
78884
78885
78886
78887
78888
78889
78890
78891
78892
78893
78894
78895
78896
78897
78898
78899
78900
78901
78902
78903
78904
78905
78906
78907
78908
78909
78910
78911
78912
78913
78914
78915
78916
78917
78918
78919
78920
78921
78922
78923
78924
78925
78926
78927
78928
78929
78930
78931
78932
78933
78934
78935
78936
78937
78938
78939
78940
78941
78942
78943
78944
78945
78946
78947
78948
78949
78950
78951
78952
78953
78954
78955
78956
78957
78958
78959
78960
78961
78962
78963
78964
78965
78966
78967
78968
78969
78970
78971
78972
78973
78974
78975
78976
78977
78978
78979
78980
78981
78982
78983
78984
78985
78986
78987
78988
78989
78990
78991
78992
78993
78994
78995
78996
78997
78998
78999
79000
79001
79002
79003
79004
79005
79006
79007
79008
79009
79010
79011
79012
79013
79014
79015
79016
79017
79018
79019
79020
79021
79022
79023
79024
79025
79026
79027
79028
79029
79030
79031
79032
79033
79034
79035
79036
79037
79038
79039
79040
79041
79042
79043
79044
79045
79046
79047
79048
79049
79050
79051
79052
79053
79054
79055
79056
79057
79058
79059
79060
79061
79062
79063
79064
79065
79066
79067
79068
79069
79070
79071
79072
79073
79074
79075
79076
79077
79078
79079
79080
79081
79082
79083
79084
79085
79086
79087
79088
79089
79090
79091
79092
79093
79094
79095
79096
79097
79098
79099
79100
79101
79102
79103
79104
79105
79106
79107
79108
79109
79110
79111
79112
79113
79114
79115
79116
79117
79118
79119
79120
79121
79122
79123
79124
79125
79126
79127
79128
79129
79130
79131
79132
79133
79134
79135
79136
79137
79138
79139
79140
79141
79142
79143
79144
79145
79146
79147
79148
79149
79150
79151
79152
79153
79154
79155
79156
79157
79158
79159
79160
79161
79162
79163
79164
79165
79166
79167
79168
79169
79170
79171
79172
79173
79174
79175
79176
79177
79178
79179
79180
79181
79182
79183
79184
79185
79186
79187
79188
79189
79190
79191
79192
79193
79194
79195
79196
79197
79198
79199
79200
79201
79202
79203
79204
79205
79206
79207
79208
79209
79210
79211
79212
79213
79214
79215
79216
79217
79218
79219
79220
79221
79222
79223
79224
79225
79226
79227
79228
79229
79230
79231
79232
79233
79234
79235
79236
79237
79238
79239
79240
79241
79242
79243
79244
79245
79246
79247
79248
79249
79250
79251
79252
79253
79254
79255
79256
79257
79258
79259
79260
79261
79262
79263
79264
79265
79266
79267
79268
79269
79270
79271
79272
79273
79274
79275
79276
79277
79278
79279
79280
79281
79282
79283
79284
79285
79286
79287
79288
79289
79290
79291
79292
79293
79294
79295
79296
79297
79298
79299
79300
79301
79302
79303
79304
79305
79306
79307
79308
79309
79310
79311
79312
79313
79314
79315
79316
79317
79318
79319
79320
79321
79322
79323
79324
79325
79326
79327
79328
79329
79330
79331
79332
79333
79334
79335
79336
79337
79338
79339
79340
79341
79342
79343
79344
79345
79346
79347
79348
79349
79350
79351
79352
79353
79354
79355
79356
79357
79358
79359
79360
79361
79362
79363
79364
79365
79366
79367
79368
79369
79370
79371
79372
79373
79374
79375
79376
79377
79378
79379
79380
79381
79382
79383
79384
79385
79386
79387
79388
79389
79390
79391
79392
79393
79394
79395
79396
79397
79398
79399
79400
79401
79402
79403
79404
79405
79406
79407
79408
79409
79410
79411
79412
79413
79414
79415
79416
79417
79418
79419
79420
79421
79422
79423
79424
79425
79426
79427
79428
79429
79430
79431
79432
79433
79434
79435
79436
79437
79438
79439
79440
79441
79442
79443
79444
79445
79446
79447
79448
79449
79450
79451
79452
79453
79454
79455
79456
79457
79458
79459
79460
79461
79462
79463
79464
79465
79466
79467
79468
79469
79470
79471
79472
79473
79474
79475
79476
79477
79478
79479
79480
79481
79482
79483
79484
79485
79486
79487
79488
79489
79490
79491
79492
79493
79494
79495
79496
79497
79498
79499
79500
79501
79502
79503
79504
79505
79506
79507
79508
79509
79510
79511
79512
79513
79514
79515
79516
79517
79518
79519
79520
79521
79522
79523
79524
79525
79526
79527
79528
79529
79530
79531
79532
79533
79534
79535
79536
79537
79538
79539
79540
79541
79542
79543
79544
79545
79546
79547
79548
79549
79550
79551
79552
79553
79554
79555
79556
79557
79558
79559
79560
79561
79562
79563
79564
79565
79566
79567
79568
79569
79570
79571
79572
79573
79574
79575
79576
79577
79578
79579
79580
79581
79582
79583
79584
79585
79586
79587
79588
79589
79590
79591
79592
79593
79594
79595
79596
79597
79598
79599
79600
79601
79602
79603
79604
79605
79606
79607
79608
79609
79610
79611
79612
79613
79614
79615
79616
79617
79618
79619
79620
79621
79622
79623
79624
79625
79626
79627
79628
79629
79630
79631
79632
79633
79634
79635
79636
79637
79638
79639
79640
79641
79642
79643
79644
79645
79646
79647
79648
79649
79650
79651
79652
79653
79654
79655
79656
79657
79658
79659
79660
79661
79662
79663
79664
79665
79666
79667
79668
79669
79670
79671
79672
79673
79674
79675
79676
79677
79678
79679
79680
79681
79682
79683
79684
79685
79686
79687
79688
79689
79690
79691
79692
79693
79694
79695
79696
79697
79698
79699
79700
79701
79702
79703
79704
79705
79706
79707
79708
79709
79710
79711
79712
79713
79714
79715
79716
79717
79718
79719
79720
79721
79722
79723
79724
79725
79726
79727
79728
79729
79730
79731
79732
79733
79734
79735
79736
79737
79738
79739
79740
79741
79742
79743
79744
79745
79746
79747
79748
79749
79750
79751
79752
79753
79754
79755
79756
79757
79758
79759
79760
79761
79762
79763
79764
79765
79766
79767
79768
79769
79770
79771
79772
79773
79774
79775
79776
79777
79778
79779
79780
79781
79782
79783
79784
79785
79786
79787
79788
79789
79790
79791
79792
79793
79794
79795
79796
79797
79798
79799
79800
79801
79802
79803
79804
79805
79806
79807
79808
79809
79810
79811
79812
79813
79814
79815
79816
79817
79818
79819
79820
79821
79822
79823
79824
79825
79826
79827
79828
79829
79830
79831
79832
79833
79834
79835
79836
79837
79838
79839
79840
79841
79842
79843
79844
79845
79846
79847
79848
79849
79850
79851
79852
79853
79854
79855
79856
79857
79858
79859
79860
79861
79862
79863
79864
79865
79866
79867
79868
79869
79870
79871
79872
79873
79874
79875
79876
79877
79878
79879
79880
79881
79882
79883
79884
79885
79886
79887
79888
79889
79890
79891
79892
79893
79894
79895
79896
79897
79898
79899
79900
79901
79902
79903
79904
79905
79906
79907
79908
79909
79910
79911
79912
79913
79914
79915
79916
79917
79918
79919
79920
79921
79922
79923
79924
79925
79926
79927
79928
79929
79930
79931
79932
79933
79934
79935
79936
79937
79938
79939
79940
79941
79942
79943
79944
79945
79946
79947
79948
79949
79950
79951
79952
79953
79954
79955
79956
79957
79958
79959
79960
79961
79962
79963
79964
79965
79966
79967
79968
79969
79970
79971
79972
79973
79974
79975
79976
79977
79978
79979
79980
79981
79982
79983
79984
79985
79986
79987
79988
79989
79990
79991
79992
79993
79994
79995
79996
79997
79998
79999
80000
80001
80002
80003
80004
80005
80006
80007
80008
80009
80010
80011
80012
80013
80014
80015
80016
80017
80018
80019
80020
80021
80022
80023
80024
80025
80026
80027
80028
80029
80030
80031
80032
80033
80034
80035
80036
80037
80038
80039
80040
80041
80042
80043
80044
80045
80046
80047
80048
80049
80050
80051
80052
80053
80054
80055
80056
80057
80058
80059
80060
80061
80062
80063
80064
80065
80066
80067
80068
80069
80070
80071
80072
80073
80074
80075
80076
80077
80078
80079
80080
80081
80082
80083
80084
80085
80086
80087
80088
80089
80090
80091
80092
80093
80094
80095
80096
80097
80098
80099
80100
80101
80102
80103
80104
80105
80106
80107
80108
80109
80110
80111
80112
80113
80114
80115
80116
80117
80118
80119
80120
80121
80122
80123
80124
80125
80126
80127
80128
80129
80130
80131
80132
80133
80134
80135
80136
80137
80138
80139
80140
80141
80142
80143
80144
80145
80146
80147
80148
80149
80150
80151
80152
80153
80154
80155
80156
80157
80158
80159
80160
80161
80162
80163
80164
80165
80166
80167
80168
80169
80170
80171
80172
80173
80174
80175
80176
80177
80178
80179
80180
80181
80182
80183
80184
80185
80186
80187
80188
80189
80190
80191
80192
80193
80194
80195
80196
80197
80198
80199
80200
80201
80202
80203
80204
80205
80206
80207
80208
80209
80210
80211
80212
80213
80214
80215
80216
80217
80218
80219
80220
80221
80222
80223
80224
80225
80226
80227
80228
80229
80230
80231
80232
80233
80234
80235
80236
80237
80238
80239
80240
80241
80242
80243
80244
80245
80246
80247
80248
80249
80250
80251
80252
80253
80254
80255
80256
80257
80258
80259
80260
80261
80262
80263
80264
80265
80266
80267
80268
80269
80270
80271
80272
80273
80274
80275
80276
80277
80278
80279
80280
80281
80282
80283
80284
80285
80286
80287
80288
80289
80290
80291
80292
80293
80294
80295
80296
80297
80298
80299
80300
80301
80302
80303
80304
80305
80306
80307
80308
80309
80310
80311
80312
80313
80314
80315
80316
80317
80318
80319
80320
80321
80322
80323
80324
80325
80326
80327
80328
80329
80330
80331
80332
80333
80334
80335
80336
80337
80338
80339
80340
80341
80342
80343
80344
80345
80346
80347
80348
80349
80350
80351
80352
80353
80354
80355
80356
80357
80358
80359
80360
80361
80362
80363
80364
80365
80366
80367
80368
80369
80370
80371
80372
80373
80374
80375
80376
80377
80378
80379
80380
80381
80382
80383
80384
80385
80386
80387
80388
80389
80390
80391
80392
80393
80394
80395
80396
80397
80398
80399
80400
80401
80402
80403
80404
80405
80406
80407
80408
80409
80410
80411
80412
80413
80414
80415
80416
80417
80418
80419
80420
80421
80422
80423
80424
80425
80426
80427
80428
80429
80430
80431
80432
80433
80434
80435
80436
80437
80438
80439
80440
80441
80442
80443
80444
80445
80446
80447
80448
80449
80450
80451
80452
80453
80454
80455
80456
80457
80458
80459
80460
80461
80462
80463
80464
80465
80466
80467
80468
80469
80470
80471
80472
80473
80474
80475
80476
80477
80478
80479
80480
80481
80482
80483
80484
80485
80486
80487
80488
80489
80490
80491
80492
80493
80494
80495
80496
80497
80498
80499
80500
80501
80502
80503
80504
80505
80506
80507
80508
80509
80510
80511
80512
80513
80514
80515
80516
80517
80518
80519
80520
80521
80522
80523
80524
80525
80526
80527
80528
80529
80530
80531
80532
80533
80534
80535
80536
80537
80538
80539
80540
80541
80542
80543
80544
80545
80546
80547
80548
80549
80550
80551
80552
80553
80554
80555
80556
80557
80558
80559
80560
80561
80562
80563
80564
80565
80566
80567
80568
80569
80570
80571
80572
80573
80574
80575
80576
80577
80578
80579
80580
80581
80582
80583
80584
80585
80586
80587
80588
80589
80590
80591
80592
80593
80594
80595
80596
80597
80598
80599
80600
80601
80602
80603
80604
80605
80606
80607
80608
80609
80610
80611
80612
80613
80614
80615
80616
80617
80618
80619
80620
80621
80622
80623
80624
80625
80626
80627
80628
80629
80630
80631
80632
80633
80634
80635
80636
80637
80638
80639
80640
80641
80642
80643
80644
80645
80646
80647
80648
80649
80650
80651
80652
80653
80654
80655
80656
80657
80658
80659
80660
80661
80662
80663
80664
80665
80666
80667
80668
80669
80670
80671
80672
80673
80674
80675
80676
80677
80678
80679
80680
80681
80682
80683
80684
80685
80686
80687
80688
80689
80690
80691
80692
80693
80694
80695
80696
80697
80698
80699
80700
80701
80702
80703
80704
80705
80706
80707
80708
80709
80710
80711
80712
80713
80714
80715
80716
80717
80718
80719
80720
80721
80722
80723
80724
80725
80726
80727
80728
80729
80730
80731
80732
80733
80734
80735
80736
80737
80738
80739
80740
80741
80742
80743
80744
80745
80746
80747
80748
80749
80750
80751
80752
80753
80754
80755
80756
80757
80758
80759
80760
80761
80762
80763
80764
80765
80766
80767
80768
80769
80770
80771
80772
80773
80774
80775
80776
80777
80778
80779
80780
80781
80782
80783
80784
80785
80786
80787
80788
80789
80790
80791
80792
80793
80794
80795
80796
80797
80798
80799
80800
80801
80802
80803
80804
80805
80806
80807
80808
80809
80810
80811
80812
80813
80814
80815
80816
80817
80818
80819
80820
80821
80822
80823
80824
80825
80826
80827
80828
80829
80830
80831
80832
80833
80834
80835
80836
80837
80838
80839
80840
80841
80842
80843
80844
80845
80846
80847
80848
80849
80850
80851
80852
80853
80854
80855
80856
80857
80858
80859
80860
80861
80862
80863
80864
80865
80866
80867
80868
80869
80870
80871
80872
80873
80874
80875
80876
80877
80878
80879
80880
80881
80882
80883
80884
80885
80886
80887
80888
80889
80890
80891
80892
80893
80894
80895
80896
80897
80898
80899
80900
80901
80902
80903
80904
80905
80906
80907
80908
80909
80910
80911
80912
80913
80914
80915
80916
80917
80918
80919
80920
80921
80922
80923
80924
80925
80926
80927
80928
80929
80930
80931
80932
80933
80934
80935
80936
80937
80938
80939
80940
80941
80942
80943
80944
80945
80946
80947
80948
80949
80950
80951
80952
80953
80954
80955
80956
80957
80958
80959
80960
80961
80962
80963
80964
80965
80966
80967
80968
80969
80970
80971
80972
80973
80974
80975
80976
80977
80978
80979
80980
80981
80982
80983
80984
80985
80986
80987
80988
80989
80990
80991
80992
80993
80994
80995
80996
80997
80998
80999
81000
81001
81002
81003
81004
81005
81006
81007
81008
81009
81010
81011
81012
81013
81014
81015
81016
81017
81018
81019
81020
81021
81022
81023
81024
81025
81026
81027
81028
81029
81030
81031
81032
81033
81034
81035
81036
81037
81038
81039
81040
81041
81042
81043
81044
81045
81046
81047
81048
81049
81050
81051
81052
81053
81054
81055
81056
81057
81058
81059
81060
81061
81062
81063
81064
81065
81066
81067
81068
81069
81070
81071
81072
81073
81074
81075
81076
81077
81078
81079
81080
81081
81082
81083
81084
81085
81086
81087
81088
81089
81090
81091
81092
81093
81094
81095
81096
81097
81098
81099
81100
81101
81102
81103
81104
81105
81106
81107
81108
81109
81110
81111
81112
81113
81114
81115
81116
81117
81118
81119
81120
81121
81122
81123
81124
81125
81126
81127
81128
81129
81130
81131
81132
81133
81134
81135
81136
81137
81138
81139
81140
81141
81142
81143
81144
81145
81146
81147
81148
81149
81150
81151
81152
81153
81154
81155
81156
81157
81158
81159
81160
81161
81162
81163
81164
81165
81166
81167
81168
81169
81170
81171
81172
81173
81174
81175
81176
81177
81178
81179
81180
81181
81182
81183
81184
81185
81186
81187
81188
81189
81190
81191
81192
81193
81194
81195
81196
81197
81198
81199
81200
81201
81202
81203
81204
81205
81206
81207
81208
81209
81210
81211
81212
81213
81214
81215
81216
81217
81218
81219
81220
81221
81222
81223
81224
81225
81226
81227
81228
81229
81230
81231
81232
81233
81234
81235
81236
81237
81238
81239
81240
81241
81242
81243
81244
81245
81246
81247
81248
81249
81250
81251
81252
81253
81254
81255
81256
81257
81258
81259
81260
81261
81262
81263
81264
81265
81266
81267
81268
81269
81270
81271
81272
81273
81274
81275
81276
81277
81278
81279
81280
81281
81282
81283
81284
81285
81286
81287
81288
81289
81290
81291
81292
81293
81294
81295
81296
81297
81298
81299
81300
81301
81302
81303
81304
81305
81306
81307
81308
81309
81310
81311
81312
81313
81314
81315
81316
81317
81318
81319
81320
81321
81322
81323
81324
81325
81326
81327
81328
81329
81330
81331
81332
81333
81334
81335
81336
81337
81338
81339
81340
81341
81342
81343
81344
81345
81346
81347
81348
81349
81350
81351
81352
81353
81354
81355
81356
81357
81358
81359
81360
81361
81362
81363
81364
81365
81366
81367
81368
81369
81370
81371
81372
81373
81374
81375
81376
81377
81378
81379
81380
81381
81382
81383
81384
81385
81386
81387
81388
81389
81390
81391
81392
81393
81394
81395
81396
81397
81398
81399
81400
81401
81402
81403
81404
81405
81406
81407
81408
81409
81410
81411
81412
81413
81414
81415
81416
81417
81418
81419
81420
81421
81422
81423
81424
81425
81426
81427
81428
81429
81430
81431
81432
81433
81434
81435
81436
81437
81438
81439
81440
81441
81442
81443
81444
81445
81446
81447
81448
81449
81450
81451
81452
81453
81454
81455
81456
81457
81458
81459
81460
81461
81462
81463
81464
81465
81466
81467
81468
81469
81470
81471
81472
81473
81474
81475
81476
81477
81478
81479
81480
81481
81482
81483
81484
81485
81486
81487
81488
81489
81490
81491
81492
81493
81494
81495
81496
81497
81498
81499
81500
81501
81502
81503
81504
81505
81506
81507
81508
81509
81510
81511
81512
81513
81514
81515
81516
81517
81518
81519
81520
81521
81522
81523
81524
81525
81526
81527
81528
81529
81530
81531
81532
81533
81534
81535
81536
81537
81538
81539
81540
81541
81542
81543
81544
81545
81546
81547
81548
81549
81550
81551
81552
81553
81554
81555
81556
81557
81558
81559
81560
81561
81562
81563
81564
81565
81566
81567
81568
81569
81570
81571
81572
81573
81574
81575
81576
81577
81578
81579
81580
81581
81582
81583
81584
81585
81586
81587
81588
81589
81590
81591
81592
81593
81594
81595
81596
81597
81598
81599
81600
81601
81602
81603
81604
81605
81606
81607
81608
81609
81610
81611
81612
81613
81614
81615
81616
81617
81618
81619
81620
81621
81622
81623
81624
81625
81626
81627
81628
81629
81630
81631
81632
81633
81634
81635
81636
81637
81638
81639
81640
81641
81642
81643
81644
81645
81646
81647
81648
81649
81650
81651
81652
81653
81654
81655
81656
81657
81658
81659
81660
81661
81662
81663
81664
81665
81666
81667
81668
81669
81670
81671
81672
81673
81674
81675
81676
81677
81678
81679
81680
81681
81682
81683
81684
81685
81686
81687
81688
81689
81690
81691
81692
81693
81694
81695
81696
81697
81698
81699
81700
81701
81702
81703
81704
81705
81706
81707
81708
81709
81710
81711
81712
81713
81714
81715
81716
81717
81718
81719
81720
81721
81722
81723
81724
81725
81726
81727
81728
81729
81730
81731
81732
81733
81734
81735
81736
81737
81738
81739
81740
81741
81742
81743
81744
81745
81746
81747
81748
81749
81750
81751
81752
81753
81754
81755
81756
81757
81758
81759
81760
81761
81762
81763
81764
81765
81766
81767
81768
81769
81770
81771
81772
81773
81774
81775
81776
81777
81778
81779
81780
81781
81782
81783
81784
81785
81786
81787
81788
81789
81790
81791
81792
81793
81794
81795
81796
81797
81798
81799
81800
81801
81802
81803
81804
81805
81806
81807
81808
81809
81810
81811
81812
81813
81814
81815
81816
81817
81818
81819
81820
81821
81822
81823
81824
81825
81826
81827
81828
81829
81830
81831
81832
81833
81834
81835
81836
81837
81838
81839
81840
81841
81842
81843
81844
81845
81846
81847
81848
81849
81850
81851
81852
81853
81854
81855
81856
81857
81858
81859
81860
81861
81862
81863
81864
81865
81866
81867
81868
81869
81870
81871
81872
81873
81874
81875
81876
81877
81878
81879
81880
81881
81882
81883
81884
81885
81886
81887
81888
81889
81890
81891
81892
81893
81894
81895
81896
81897
81898
81899
81900
81901
81902
81903
81904
81905
81906
81907
81908
81909
81910
81911
81912
81913
81914
81915
81916
81917
81918
81919
81920
81921
81922
81923
81924
81925
81926
81927
81928
81929
81930
81931
81932
81933
81934
81935
81936
81937
81938
81939
81940
81941
81942
81943
81944
81945
81946
81947
81948
81949
81950
81951
81952
81953
81954
81955
81956
81957
81958
81959
81960
81961
81962
81963
81964
81965
81966
81967
81968
81969
81970
81971
81972
81973
81974
81975
81976
81977
81978
81979
81980
81981
81982
81983
81984
81985
81986
81987
81988
81989
81990
81991
81992
81993
81994
81995
81996
81997
81998
81999
82000
82001
82002
82003
82004
82005
82006
82007
82008
82009
82010
82011
82012
82013
82014
82015
82016
82017
82018
82019
82020
82021
82022
82023
82024
82025
82026
82027
82028
82029
82030
82031
82032
82033
82034
82035
82036
82037
82038
82039
82040
82041
82042
82043
82044
82045
82046
82047
82048
82049
82050
82051
82052
82053
82054
82055
82056
82057
82058
82059
82060
82061
82062
82063
82064
82065
82066
82067
82068
82069
82070
82071
82072
82073
82074
82075
82076
82077
82078
82079
82080
82081
82082
82083
82084
82085
82086
82087
82088
82089
82090
82091
82092
82093
82094
82095
82096
82097
82098
82099
82100
82101
82102
82103
82104
82105
82106
82107
82108
82109
82110
82111
82112
82113
82114
82115
82116
82117
82118
82119
82120
82121
82122
82123
82124
82125
82126
82127
82128
82129
82130
82131
82132
82133
82134
82135
82136
82137
82138
82139
82140
82141
82142
82143
82144
82145
82146
82147
82148
82149
82150
82151
82152
82153
82154
82155
82156
82157
82158
82159
82160
82161
82162
82163
82164
82165
82166
82167
82168
82169
82170
82171
82172
82173
82174
82175
82176
82177
82178
82179
82180
82181
82182
82183
82184
82185
82186
82187
82188
82189
82190
82191
82192
82193
82194
82195
82196
82197
82198
82199
82200
82201
82202
82203
82204
82205
82206
82207
82208
82209
82210
82211
82212
82213
82214
82215
82216
82217
82218
82219
82220
82221
82222
82223
82224
82225
82226
82227
82228
82229
82230
82231
82232
82233
82234
82235
82236
82237
82238
82239
82240
82241
82242
82243
82244
82245
82246
82247
82248
82249
82250
82251
82252
82253
82254
82255
82256
82257
82258
82259
82260
82261
82262
82263
82264
82265
82266
82267
82268
82269
82270
82271
82272
82273
82274
82275
82276
82277
82278
82279
82280
82281
82282
82283
82284
82285
82286
82287
82288
82289
82290
82291
82292
82293
82294
82295
82296
82297
82298
82299
82300
82301
82302
82303
82304
82305
82306
82307
82308
82309
82310
82311
82312
82313
82314
82315
82316
82317
82318
82319
82320
82321
82322
82323
82324
82325
82326
82327
82328
82329
82330
82331
82332
82333
82334
82335
82336
82337
82338
82339
82340
82341
82342
82343
82344
82345
82346
82347
82348
82349
82350
82351
82352
82353
82354
82355
82356
82357
82358
82359
82360
82361
82362
82363
82364
82365
82366
82367
82368
82369
82370
82371
82372
82373
82374
82375
82376
82377
82378
82379
82380
82381
82382
82383
82384
82385
82386
82387
82388
82389
82390
82391
82392
82393
82394
82395
82396
82397
82398
82399
82400
82401
82402
82403
82404
82405
82406
82407
82408
82409
82410
82411
82412
82413
82414
82415
82416
82417
82418
82419
82420
82421
82422
82423
82424
82425
82426
82427
82428
82429
82430
82431
82432
82433
82434
82435
82436
82437
82438
82439
82440
82441
82442
82443
82444
82445
82446
82447
82448
82449
82450
82451
82452
82453
82454
82455
82456
82457
82458
82459
82460
82461
82462
82463
82464
82465
82466
82467
82468
82469
82470
82471
82472
82473
82474
82475
82476
82477
82478
82479
82480
82481
82482
82483
82484
82485
82486
82487
82488
82489
82490
82491
82492
82493
82494
82495
82496
82497
82498
82499
82500
82501
82502
82503
82504
82505
82506
82507
82508
82509
82510
82511
82512
82513
82514
82515
82516
82517
82518
82519
82520
82521
82522
82523
82524
82525
82526
82527
82528
82529
82530
82531
82532
82533
82534
82535
82536
82537
82538
82539
82540
82541
82542
82543
82544
82545
82546
82547
82548
82549
82550
82551
82552
82553
82554
82555
82556
82557
82558
82559
82560
82561
82562
82563
82564
82565
82566
82567
82568
82569
82570
82571
82572
82573
82574
82575
82576
82577
82578
82579
82580
82581
82582
82583
82584
82585
82586
82587
82588
82589
82590
82591
82592
82593
82594
82595
82596
82597
82598
82599
82600
82601
82602
82603
82604
82605
82606
82607
82608
82609
82610
82611
82612
82613
82614
82615
82616
82617
82618
82619
82620
82621
82622
82623
82624
82625
82626
82627
82628
82629
82630
82631
82632
82633
82634
82635
82636
82637
82638
82639
82640
82641
82642
82643
82644
82645
82646
82647
82648
82649
82650
82651
82652
82653
82654
82655
82656
82657
82658
82659
82660
82661
82662
82663
82664
82665
82666
82667
82668
82669
82670
82671
82672
82673
82674
82675
82676
82677
82678
82679
82680
82681
82682
82683
82684
82685
82686
82687
82688
82689
82690
82691
82692
82693
82694
82695
82696
82697
82698
82699
82700
82701
82702
82703
82704
82705
82706
82707
82708
82709
82710
82711
82712
82713
82714
82715
82716
82717
82718
82719
82720
82721
82722
82723
82724
82725
82726
82727
82728
82729
82730
82731
82732
82733
82734
82735
82736
82737
82738
82739
82740
82741
82742
82743
82744
82745
82746
82747
82748
82749
82750
82751
82752
82753
82754
82755
82756
82757
82758
82759
82760
82761
82762
82763
82764
82765
82766
82767
82768
82769
82770
82771
82772
82773
82774
82775
82776
82777
82778
82779
82780
82781
82782
82783
82784
82785
82786
82787
82788
82789
82790
82791
82792
82793
82794
82795
82796
82797
82798
82799
82800
82801
82802
82803
82804
82805
82806
82807
82808
82809
82810
82811
82812
82813
82814
82815
82816
82817
82818
82819
82820
82821
82822
82823
82824
82825
82826
82827
82828
82829
82830
82831
82832
82833
82834
82835
82836
82837
82838
82839
82840
82841
82842
82843
82844
82845
82846
82847
82848
82849
82850
82851
82852
82853
82854
82855
82856
82857
82858
82859
82860
82861
82862
82863
82864
82865
82866
82867
82868
82869
82870
82871
82872
82873
82874
82875
82876
82877
82878
82879
82880
82881
82882
82883
82884
82885
82886
82887
82888
82889
82890
82891
82892
82893
82894
82895
82896
82897
82898
82899
82900
82901
82902
82903
82904
82905
82906
82907
82908
82909
82910
82911
82912
82913
82914
82915
82916
82917
82918
82919
82920
82921
82922
82923
82924
82925
82926
82927
82928
82929
82930
82931
82932
82933
82934
82935
82936
82937
82938
82939
82940
82941
82942
82943
82944
82945
82946
82947
82948
82949
82950
82951
82952
82953
82954
82955
82956
82957
82958
82959
82960
82961
82962
82963
82964
82965
82966
82967
82968
82969
82970
82971
82972
82973
82974
82975
82976
82977
82978
82979
82980
82981
82982
82983
82984
82985
82986
82987
82988
82989
82990
82991
82992
82993
82994
82995
82996
82997
82998
82999
83000
83001
83002
83003
83004
83005
83006
83007
83008
83009
83010
83011
83012
83013
83014
83015
83016
83017
83018
83019
83020
83021
83022
83023
83024
83025
83026
83027
83028
83029
83030
83031
83032
83033
83034
83035
83036
83037
83038
83039
83040
83041
83042
83043
83044
83045
83046
83047
83048
83049
83050
83051
83052
83053
83054
83055
83056
83057
83058
83059
83060
83061
83062
83063
83064
83065
83066
83067
83068
83069
83070
83071
83072
83073
83074
83075
83076
83077
83078
83079
83080
83081
83082
83083
83084
83085
83086
83087
83088
83089
83090
83091
83092
83093
83094
83095
83096
83097
83098
83099
83100
83101
83102
83103
83104
83105
83106
83107
83108
83109
83110
83111
83112
83113
83114
83115
83116
83117
83118
83119
83120
83121
83122
83123
83124
83125
83126
83127
83128
83129
83130
83131
83132
83133
83134
83135
83136
83137
83138
83139
83140
83141
83142
83143
83144
83145
83146
83147
83148
83149
83150
83151
83152
83153
83154
83155
83156
83157
83158
83159
83160
83161
83162
83163
83164
83165
83166
83167
83168
83169
83170
83171
83172
83173
83174
83175
83176
83177
83178
83179
83180
83181
83182
83183
83184
83185
83186
83187
83188
83189
83190
83191
83192
83193
83194
83195
83196
83197
83198
83199
83200
83201
83202
83203
83204
83205
83206
83207
83208
83209
83210
83211
83212
83213
83214
83215
83216
83217
83218
83219
83220
83221
83222
83223
83224
83225
83226
83227
83228
83229
83230
83231
83232
83233
83234
83235
83236
83237
83238
83239
83240
83241
83242
83243
83244
83245
83246
83247
83248
83249
83250
83251
83252
83253
83254
83255
83256
83257
83258
83259
83260
83261
83262
83263
83264
83265
83266
83267
83268
83269
83270
83271
83272
83273
83274
83275
83276
83277
83278
83279
83280
83281
83282
83283
83284
83285
83286
83287
83288
83289
83290
83291
83292
83293
83294
83295
83296
83297
83298
83299
83300
83301
83302
83303
83304
83305
83306
83307
83308
83309
83310
83311
83312
83313
83314
83315
83316
83317
83318
83319
83320
83321
83322
83323
83324
83325
83326
83327
83328
83329
83330
83331
83332
83333
83334
83335
83336
83337
83338
83339
83340
83341
83342
83343
83344
83345
83346
83347
83348
83349
83350
83351
83352
83353
83354
83355
83356
83357
83358
83359
83360
83361
83362
83363
83364
83365
83366
83367
83368
83369
83370
83371
83372
83373
83374
83375
83376
83377
83378
83379
83380
83381
83382
83383
83384
83385
83386
83387
83388
83389
83390
83391
83392
83393
83394
83395
83396
83397
83398
83399
83400
83401
83402
83403
83404
83405
83406
83407
83408
83409
83410
83411
83412
83413
83414
83415
83416
83417
83418
83419
83420
83421
83422
83423
83424
83425
83426
83427
83428
83429
83430
83431
83432
83433
83434
83435
83436
83437
83438
83439
83440
83441
83442
83443
83444
83445
83446
83447
83448
83449
83450
83451
83452
83453
83454
83455
83456
83457
83458
83459
83460
83461
83462
83463
83464
83465
83466
83467
83468
83469
83470
83471
83472
83473
83474
83475
83476
83477
83478
83479
83480
83481
83482
83483
83484
83485
83486
83487
83488
83489
83490
83491
83492
83493
83494
83495
83496
83497
83498
83499
83500
83501
83502
83503
83504
83505
83506
83507
83508
83509
83510
83511
83512
83513
83514
83515
83516
83517
83518
83519
83520
83521
83522
83523
83524
83525
83526
83527
83528
83529
83530
83531
83532
83533
83534
83535
83536
83537
83538
83539
83540
83541
83542
83543
83544
83545
83546
83547
83548
83549
83550
83551
83552
83553
83554
83555
83556
83557
83558
83559
83560
83561
83562
83563
83564
83565
83566
83567
83568
83569
83570
83571
83572
83573
83574
83575
83576
83577
83578
83579
83580
83581
83582
83583
83584
83585
83586
83587
83588
83589
83590
83591
83592
83593
83594
83595
83596
83597
83598
83599
83600
83601
83602
83603
83604
83605
83606
83607
83608
83609
83610
83611
83612
83613
83614
83615
83616
83617
83618
83619
83620
83621
83622
83623
83624
83625
83626
83627
83628
83629
83630
83631
83632
83633
83634
83635
83636
83637
83638
83639
83640
83641
83642
83643
83644
83645
83646
83647
83648
83649
83650
83651
83652
83653
83654
83655
83656
83657
83658
83659
83660
83661
83662
83663
83664
83665
83666
83667
83668
83669
83670
83671
83672
83673
83674
83675
83676
83677
83678
83679
83680
83681
83682
83683
83684
83685
83686
83687
83688
83689
83690
83691
83692
83693
83694
83695
83696
83697
83698
83699
83700
83701
83702
83703
83704
83705
83706
83707
83708
83709
83710
83711
83712
83713
83714
83715
83716
83717
83718
83719
83720
83721
83722
83723
83724
83725
83726
83727
83728
83729
83730
83731
83732
83733
83734
83735
83736
83737
83738
83739
83740
83741
83742
83743
83744
83745
83746
83747
83748
83749
83750
83751
83752
83753
83754
83755
83756
83757
83758
83759
83760
83761
83762
83763
83764
83765
83766
83767
83768
83769
83770
83771
83772
83773
83774
83775
83776
83777
83778
83779
83780
83781
83782
83783
83784
83785
83786
83787
83788
83789
83790
83791
83792
83793
83794
83795
83796
83797
83798
83799
83800
83801
83802
83803
83804
83805
83806
83807
83808
83809
83810
83811
83812
83813
83814
83815
83816
83817
83818
83819
83820
83821
83822
83823
83824
83825
83826
83827
83828
83829
83830
83831
83832
83833
83834
83835
83836
83837
83838
83839
83840
83841
83842
83843
83844
83845
83846
83847
83848
83849
83850
83851
83852
83853
83854
83855
83856
83857
83858
83859
83860
83861
83862
83863
83864
83865
83866
83867
83868
83869
83870
83871
83872
83873
83874
83875
83876
83877
83878
83879
83880
83881
83882
83883
83884
83885
83886
83887
83888
83889
83890
83891
83892
83893
83894
83895
83896
83897
83898
83899
83900
83901
83902
83903
83904
83905
83906
83907
83908
83909
83910
83911
83912
83913
83914
83915
83916
83917
83918
83919
83920
83921
83922
83923
83924
83925
83926
83927
83928
83929
83930
83931
83932
83933
83934
83935
83936
83937
83938
83939
83940
83941
83942
83943
83944
83945
83946
83947
83948
83949
83950
83951
83952
83953
83954
83955
83956
83957
83958
83959
83960
83961
83962
83963
83964
83965
83966
83967
83968
83969
83970
83971
83972
83973
83974
83975
83976
83977
83978
83979
83980
83981
83982
83983
83984
83985
83986
83987
83988
83989
83990
83991
83992
83993
83994
83995
83996
83997
83998
83999
84000
84001
84002
84003
84004
84005
84006
84007
84008
84009
84010
84011
84012
84013
84014
84015
84016
84017
84018
84019
84020
84021
84022
84023
84024
84025
84026
84027
84028
84029
84030
84031
84032
84033
84034
84035
84036
84037
84038
84039
84040
84041
84042
84043
84044
84045
84046
84047
84048
84049
84050
84051
84052
84053
84054
84055
84056
84057
84058
84059
84060
84061
84062
84063
84064
84065
84066
84067
84068
84069
84070
84071
84072
84073
84074
84075
84076
84077
84078
84079
84080
84081
84082
84083
84084
84085
84086
84087
84088
84089
84090
84091
84092
84093
84094
84095
84096
84097
84098
84099
84100
84101
84102
84103
84104
84105
84106
84107
84108
84109
84110
84111
84112
84113
84114
84115
84116
84117
84118
84119
84120
84121
84122
84123
84124
84125
84126
84127
84128
84129
84130
84131
84132
84133
84134
84135
84136
84137
84138
84139
84140
84141
84142
84143
84144
84145
84146
84147
84148
84149
84150
84151
84152
84153
84154
84155
84156
84157
84158
84159
84160
84161
84162
84163
84164
84165
84166
84167
84168
84169
84170
84171
84172
84173
84174
84175
84176
84177
84178
84179
84180
84181
84182
84183
84184
84185
84186
84187
84188
84189
84190
84191
84192
84193
84194
84195
84196
84197
84198
84199
84200
84201
84202
84203
84204
84205
84206
84207
84208
84209
84210
84211
84212
84213
84214
84215
84216
84217
84218
84219
84220
84221
84222
84223
84224
84225
84226
84227
84228
84229
84230
84231
84232
84233
84234
84235
84236
84237
84238
84239
84240
84241
84242
84243
84244
84245
84246
84247
84248
84249
84250
84251
84252
84253
84254
84255
84256
84257
84258
84259
84260
84261
84262
84263
84264
84265
84266
84267
84268
84269
84270
84271
84272
84273
84274
84275
84276
84277
84278
84279
84280
84281
84282
84283
84284
84285
84286
84287
84288
84289
84290
84291
84292
84293
84294
84295
84296
84297
84298
84299
84300
84301
84302
84303
84304
84305
84306
84307
84308
84309
84310
84311
84312
84313
84314
84315
84316
84317
84318
84319
84320
84321
84322
84323
84324
84325
84326
84327
84328
84329
84330
84331
84332
84333
84334
84335
84336
84337
84338
84339
84340
84341
84342
84343
84344
84345
84346
84347
84348
84349
84350
84351
84352
84353
84354
84355
84356
84357
84358
84359
84360
84361
84362
84363
84364
84365
84366
84367
84368
84369
84370
84371
84372
84373
84374
84375
84376
84377
84378
84379
84380
84381
84382
84383
84384
84385
84386
84387
84388
84389
84390
84391
84392
84393
84394
84395
84396
84397
84398
84399
84400
84401
84402
84403
84404
84405
84406
84407
84408
84409
84410
84411
84412
84413
84414
84415
84416
84417
84418
84419
84420
84421
84422
84423
84424
84425
84426
84427
84428
84429
84430
84431
84432
84433
84434
84435
84436
84437
84438
84439
84440
84441
84442
84443
84444
84445
84446
84447
84448
84449
84450
84451
84452
84453
84454
84455
84456
84457
84458
84459
84460
84461
84462
84463
84464
84465
84466
84467
84468
84469
84470
84471
84472
84473
84474
84475
84476
84477
84478
84479
84480
84481
84482
84483
84484
84485
84486
84487
84488
84489
84490
84491
84492
84493
84494
84495
84496
84497
84498
84499
84500
84501
84502
84503
84504
84505
84506
84507
84508
84509
84510
84511
84512
84513
84514
84515
84516
84517
84518
84519
84520
84521
84522
84523
84524
84525
84526
84527
84528
84529
84530
84531
84532
84533
84534
84535
84536
84537
84538
84539
84540
84541
84542
84543
84544
84545
84546
84547
84548
84549
84550
84551
84552
84553
84554
84555
84556
84557
84558
84559
84560
84561
84562
84563
84564
84565
84566
84567
84568
84569
84570
84571
84572
84573
84574
84575
84576
84577
84578
84579
84580
84581
84582
84583
84584
84585
84586
84587
84588
84589
84590
84591
84592
84593
84594
84595
84596
84597
84598
84599
84600
84601
84602
84603
84604
84605
84606
84607
84608
84609
84610
84611
84612
84613
84614
84615
84616
84617
84618
84619
84620
84621
84622
84623
84624
84625
84626
84627
84628
84629
84630
84631
84632
84633
84634
84635
84636
84637
84638
84639
84640
84641
84642
84643
84644
84645
84646
84647
84648
84649
84650
84651
84652
84653
84654
84655
84656
84657
84658
84659
84660
84661
84662
84663
84664
84665
84666
84667
84668
84669
84670
84671
84672
84673
84674
84675
84676
84677
84678
84679
84680
84681
84682
84683
84684
84685
84686
84687
84688
84689
84690
84691
84692
84693
84694
84695
84696
84697
84698
84699
84700
84701
84702
84703
84704
84705
84706
84707
84708
84709
84710
84711
84712
84713
84714
84715
84716
84717
84718
84719
84720
84721
84722
84723
84724
84725
84726
84727
84728
84729
84730
84731
84732
84733
84734
84735
84736
84737
84738
84739
84740
84741
84742
84743
84744
84745
84746
84747
84748
84749
84750
84751
84752
84753
84754
84755
84756
84757
84758
84759
84760
84761
84762
84763
84764
84765
84766
84767
84768
84769
84770
84771
84772
84773
84774
84775
84776
84777
84778
84779
84780
84781
84782
84783
84784
84785
84786
84787
84788
84789
84790
84791
84792
84793
84794
84795
84796
84797
84798
84799
84800
84801
84802
84803
84804
84805
84806
84807
84808
84809
84810
84811
84812
84813
84814
84815
84816
84817
84818
84819
84820
84821
84822
84823
84824
84825
84826
84827
84828
84829
84830
84831
84832
84833
84834
84835
84836
84837
84838
84839
84840
84841
84842
84843
84844
84845
84846
84847
84848
84849
84850
84851
84852
84853
84854
84855
84856
84857
84858
84859
84860
84861
84862
84863
84864
84865
84866
84867
84868
84869
84870
84871
84872
84873
84874
84875
84876
84877
84878
84879
84880
84881
84882
84883
84884
84885
84886
84887
84888
84889
84890
84891
84892
84893
84894
84895
84896
84897
84898
84899
84900
84901
84902
84903
84904
84905
84906
84907
84908
84909
84910
84911
84912
84913
84914
84915
84916
84917
84918
84919
84920
84921
84922
84923
84924
84925
84926
84927
84928
84929
84930
84931
84932
84933
84934
84935
84936
84937
84938
84939
84940
84941
84942
84943
84944
84945
84946
84947
84948
84949
84950
84951
84952
84953
84954
84955
84956
84957
84958
84959
84960
84961
84962
84963
84964
84965
84966
84967
84968
84969
84970
84971
84972
84973
84974
84975
84976
84977
84978
84979
84980
84981
84982
84983
84984
84985
84986
84987
84988
84989
84990
84991
84992
84993
84994
84995
84996
84997
84998
84999
85000
85001
85002
85003
85004
85005
85006
85007
85008
85009
85010
85011
85012
85013
85014
85015
85016
85017
85018
85019
85020
85021
85022
85023
85024
85025
85026
85027
85028
85029
85030
85031
85032
85033
85034
85035
85036
85037
85038
85039
85040
85041
85042
85043
85044
85045
85046
85047
85048
85049
85050
85051
85052
85053
85054
85055
85056
85057
85058
85059
85060
85061
85062
85063
85064
85065
85066
85067
85068
85069
85070
85071
85072
85073
85074
85075
85076
85077
85078
85079
85080
85081
85082
85083
85084
85085
85086
85087
85088
85089
85090
85091
85092
85093
85094
85095
85096
85097
85098
85099
85100
85101
85102
85103
85104
85105
85106
85107
85108
85109
85110
85111
85112
85113
85114
85115
85116
85117
85118
85119
85120
85121
85122
85123
85124
85125
85126
85127
85128
85129
85130
85131
85132
85133
85134
85135
85136
85137
85138
85139
85140
85141
85142
85143
85144
85145
85146
85147
85148
85149
85150
85151
85152
85153
85154
85155
85156
85157
85158
85159
85160
85161
85162
85163
85164
85165
85166
85167
85168
85169
85170
85171
85172
85173
85174
85175
85176
85177
85178
85179
85180
85181
85182
85183
85184
85185
85186
85187
85188
85189
85190
85191
85192
85193
85194
85195
85196
85197
85198
85199
85200
85201
85202
85203
85204
85205
85206
85207
85208
85209
85210
85211
85212
85213
85214
85215
85216
85217
85218
85219
85220
85221
85222
85223
85224
85225
85226
85227
85228
85229
85230
85231
85232
85233
85234
85235
85236
85237
85238
85239
85240
85241
85242
85243
85244
85245
85246
85247
85248
85249
85250
85251
85252
85253
85254
85255
85256
85257
85258
85259
85260
85261
85262
85263
85264
85265
85266
85267
85268
85269
85270
85271
85272
85273
85274
85275
85276
85277
85278
85279
85280
85281
85282
85283
85284
85285
85286
85287
85288
85289
85290
85291
85292
85293
85294
85295
85296
85297
85298
85299
85300
85301
85302
85303
85304
85305
85306
85307
85308
85309
85310
85311
85312
85313
85314
85315
85316
85317
85318
85319
85320
85321
85322
85323
85324
85325
85326
85327
85328
85329
85330
85331
85332
85333
85334
85335
85336
85337
85338
85339
85340
85341
85342
85343
85344
85345
85346
85347
85348
85349
85350
85351
85352
85353
85354
85355
85356
85357
85358
85359
85360
85361
85362
85363
85364
85365
85366
85367
85368
85369
85370
85371
85372
85373
85374
85375
85376
85377
85378
85379
85380
85381
85382
85383
85384
85385
85386
85387
85388
85389
85390
85391
85392
85393
85394
85395
85396
85397
85398
85399
85400
85401
85402
85403
85404
85405
85406
85407
85408
85409
85410
85411
85412
85413
85414
85415
85416
85417
85418
85419
85420
85421
85422
85423
85424
85425
85426
85427
85428
85429
85430
85431
85432
85433
85434
85435
85436
85437
85438
85439
85440
85441
85442
85443
85444
85445
85446
85447
85448
85449
85450
85451
85452
85453
85454
85455
85456
85457
85458
85459
85460
85461
85462
85463
85464
85465
85466
85467
85468
85469
85470
85471
85472
85473
85474
85475
85476
85477
85478
85479
85480
85481
85482
85483
85484
85485
85486
85487
85488
85489
85490
85491
85492
85493
85494
85495
85496
85497
85498
85499
85500
85501
85502
85503
85504
85505
85506
85507
85508
85509
85510
85511
85512
85513
85514
85515
85516
85517
85518
85519
85520
85521
85522
85523
85524
85525
85526
85527
85528
85529
85530
85531
85532
85533
85534
85535
85536
85537
85538
85539
85540
85541
85542
85543
85544
85545
85546
85547
85548
85549
85550
85551
85552
85553
85554
85555
85556
85557
85558
85559
85560
85561
85562
85563
85564
85565
85566
85567
85568
85569
85570
85571
85572
85573
85574
85575
85576
85577
85578
85579
85580
85581
85582
85583
85584
85585
85586
85587
85588
85589
85590
85591
85592
85593
85594
85595
85596
85597
85598
85599
85600
85601
85602
85603
85604
85605
85606
85607
85608
85609
85610
85611
85612
85613
85614
85615
85616
85617
85618
85619
85620
85621
85622
85623
85624
85625
85626
85627
85628
85629
85630
85631
85632
85633
85634
85635
85636
85637
85638
85639
85640
85641
85642
85643
85644
85645
85646
85647
85648
85649
85650
85651
85652
85653
85654
85655
85656
85657
85658
85659
85660
85661
85662
85663
85664
85665
85666
85667
85668
85669
85670
85671
85672
85673
85674
85675
85676
85677
85678
85679
85680
85681
85682
85683
85684
85685
85686
85687
85688
85689
85690
85691
85692
85693
85694
85695
85696
85697
85698
85699
85700
85701
85702
85703
85704
85705
85706
85707
85708
85709
85710
85711
85712
85713
85714
85715
85716
85717
85718
85719
85720
85721
85722
85723
85724
85725
85726
85727
85728
85729
85730
85731
85732
85733
85734
85735
85736
85737
85738
85739
85740
85741
85742
85743
85744
85745
85746
85747
85748
85749
85750
85751
85752
85753
85754
85755
85756
85757
85758
85759
85760
85761
85762
85763
85764
85765
85766
85767
85768
85769
85770
85771
85772
85773
85774
85775
85776
85777
85778
85779
85780
85781
85782
85783
85784
85785
85786
85787
85788
85789
85790
85791
85792
85793
85794
85795
85796
85797
85798
85799
85800
85801
85802
85803
85804
85805
85806
85807
85808
85809
85810
85811
85812
85813
85814
85815
85816
85817
85818
85819
85820
85821
85822
85823
85824
85825
85826
85827
85828
85829
85830
85831
85832
85833
85834
85835
85836
85837
85838
85839
85840
85841
85842
85843
85844
85845
85846
85847
85848
85849
85850
85851
85852
85853
85854
85855
85856
85857
85858
85859
85860
85861
85862
85863
85864
85865
85866
85867
85868
85869
85870
85871
85872
85873
85874
85875
85876
85877
85878
85879
85880
85881
85882
85883
85884
85885
85886
85887
85888
85889
85890
85891
85892
85893
85894
85895
85896
85897
85898
85899
85900
85901
85902
85903
85904
85905
85906
85907
85908
85909
85910
85911
85912
85913
85914
85915
85916
85917
85918
85919
85920
85921
85922
85923
85924
85925
85926
85927
85928
85929
85930
85931
85932
85933
85934
85935
85936
85937
85938
85939
85940
85941
85942
85943
85944
85945
85946
85947
85948
85949
85950
85951
85952
85953
85954
85955
85956
85957
85958
85959
85960
85961
85962
85963
85964
85965
85966
85967
85968
85969
85970
85971
85972
85973
85974
85975
85976
85977
85978
85979
85980
85981
85982
85983
85984
85985
85986
85987
85988
85989
85990
85991
85992
85993
85994
85995
85996
85997
85998
85999
86000
86001
86002
86003
86004
86005
86006
86007
86008
86009
86010
86011
86012
86013
86014
86015
86016
86017
86018
86019
86020
86021
86022
86023
86024
86025
86026
86027
86028
86029
86030
86031
86032
86033
86034
86035
86036
86037
86038
86039
86040
86041
86042
86043
86044
86045
86046
86047
86048
86049
86050
86051
86052
86053
86054
86055
86056
86057
86058
86059
86060
86061
86062
86063
86064
86065
86066
86067
86068
86069
86070
86071
86072
86073
86074
86075
86076
86077
86078
86079
86080
86081
86082
86083
86084
86085
86086
86087
86088
86089
86090
86091
86092
86093
86094
86095
86096
86097
86098
86099
86100
86101
86102
86103
86104
86105
86106
86107
86108
86109
86110
86111
86112
86113
86114
86115
86116
86117
86118
86119
86120
86121
86122
86123
86124
86125
86126
86127
86128
86129
86130
86131
86132
86133
86134
86135
86136
86137
86138
86139
86140
86141
86142
86143
86144
86145
86146
86147
86148
86149
86150
86151
86152
86153
86154
86155
86156
86157
86158
86159
86160
86161
86162
86163
86164
86165
86166
86167
86168
86169
86170
86171
86172
86173
86174
86175
86176
86177
86178
86179
86180
86181
86182
86183
86184
86185
86186
86187
86188
86189
86190
86191
86192
86193
86194
86195
86196
86197
86198
86199
86200
86201
86202
86203
86204
86205
86206
86207
86208
86209
86210
86211
86212
86213
86214
86215
86216
86217
86218
86219
86220
86221
86222
86223
86224
86225
86226
86227
86228
86229
86230
86231
86232
86233
86234
86235
86236
86237
86238
86239
86240
86241
86242
86243
86244
86245
86246
86247
86248
86249
86250
86251
86252
86253
86254
86255
86256
86257
86258
86259
86260
86261
86262
86263
86264
86265
86266
86267
86268
86269
86270
86271
86272
86273
86274
86275
86276
86277
86278
86279
86280
86281
86282
86283
86284
86285
86286
86287
86288
86289
86290
86291
86292
86293
86294
86295
86296
86297
86298
86299
86300
86301
86302
86303
86304
86305
86306
86307
86308
86309
86310
86311
86312
86313
86314
86315
86316
86317
86318
86319
86320
86321
86322
86323
86324
86325
86326
86327
86328
86329
86330
86331
86332
86333
86334
86335
86336
86337
86338
86339
86340
86341
86342
86343
86344
86345
86346
86347
86348
86349
86350
86351
86352
86353
86354
86355
86356
86357
86358
86359
86360
86361
86362
86363
86364
86365
86366
86367
86368
86369
86370
86371
86372
86373
86374
86375
86376
86377
86378
86379
86380
86381
86382
86383
86384
86385
86386
86387
86388
86389
86390
86391
86392
86393
86394
86395
86396
86397
86398
86399
86400
86401
86402
86403
86404
86405
86406
86407
86408
86409
86410
86411
86412
86413
86414
86415
86416
86417
86418
86419
86420
86421
86422
86423
86424
86425
86426
86427
86428
86429
86430
86431
86432
86433
86434
86435
86436
86437
86438
86439
86440
86441
86442
86443
86444
86445
86446
86447
86448
86449
86450
86451
86452
86453
86454
86455
86456
86457
86458
86459
86460
86461
86462
86463
86464
86465
86466
86467
86468
86469
86470
86471
86472
86473
86474
86475
86476
86477
86478
86479
86480
86481
86482
86483
86484
86485
86486
86487
86488
86489
86490
86491
86492
86493
86494
86495
86496
86497
86498
86499
86500
86501
86502
86503
86504
86505
86506
86507
86508
86509
86510
86511
86512
86513
86514
86515
86516
86517
86518
86519
86520
86521
86522
86523
86524
86525
86526
86527
86528
86529
86530
86531
86532
86533
86534
86535
86536
86537
86538
86539
86540
86541
86542
86543
86544
86545
86546
86547
86548
86549
86550
86551
86552
86553
86554
86555
86556
86557
86558
86559
86560
86561
86562
86563
86564
86565
86566
86567
86568
86569
86570
86571
86572
86573
86574
86575
86576
86577
86578
86579
86580
86581
86582
86583
86584
86585
86586
86587
86588
86589
86590
86591
86592
86593
86594
86595
86596
86597
86598
86599
86600
86601
86602
86603
86604
86605
86606
86607
86608
86609
86610
86611
86612
86613
86614
86615
86616
86617
86618
86619
86620
86621
86622
86623
86624
86625
86626
86627
86628
86629
86630
86631
86632
86633
86634
86635
86636
86637
86638
86639
86640
86641
86642
86643
86644
86645
86646
86647
86648
86649
86650
86651
86652
86653
86654
86655
86656
86657
86658
86659
86660
86661
86662
86663
86664
86665
86666
86667
86668
86669
86670
86671
86672
86673
86674
86675
86676
86677
86678
86679
86680
86681
86682
86683
86684
86685
86686
86687
86688
86689
86690
86691
86692
86693
86694
86695
86696
86697
86698
86699
86700
86701
86702
86703
86704
86705
86706
86707
86708
86709
86710
86711
86712
86713
86714
86715
86716
86717
86718
86719
86720
86721
86722
86723
86724
86725
86726
86727
86728
86729
86730
86731
86732
86733
86734
86735
86736
86737
86738
86739
86740
86741
86742
86743
86744
86745
86746
86747
86748
86749
86750
86751
86752
86753
86754
86755
86756
86757
86758
86759
86760
86761
86762
86763
86764
86765
86766
86767
86768
86769
86770
86771
86772
86773
86774
86775
86776
86777
86778
86779
86780
86781
86782
86783
86784
86785
86786
86787
86788
86789
86790
86791
86792
86793
86794
86795
86796
86797
86798
86799
86800
86801
86802
86803
86804
86805
86806
86807
86808
86809
86810
86811
86812
86813
86814
86815
86816
86817
86818
86819
86820
86821
86822
86823
86824
86825
86826
86827
86828
86829
86830
86831
86832
86833
86834
86835
86836
86837
86838
86839
86840
86841
86842
86843
86844
86845
86846
86847
86848
86849
86850
86851
86852
86853
86854
86855
86856
86857
86858
86859
86860
86861
86862
86863
86864
86865
86866
86867
86868
86869
86870
86871
86872
86873
86874
86875
86876
86877
86878
86879
86880
86881
86882
86883
86884
86885
86886
86887
86888
86889
86890
86891
86892
86893
86894
86895
86896
86897
86898
86899
86900
86901
86902
86903
86904
86905
86906
86907
86908
86909
86910
86911
86912
86913
86914
86915
86916
86917
86918
86919
86920
86921
86922
86923
86924
86925
86926
86927
86928
86929
86930
86931
86932
86933
86934
86935
86936
86937
86938
86939
86940
86941
86942
86943
86944
86945
86946
86947
86948
86949
86950
86951
86952
86953
86954
86955
86956
86957
86958
86959
86960
86961
86962
86963
86964
86965
86966
86967
86968
86969
86970
86971
86972
86973
86974
86975
86976
86977
86978
86979
86980
86981
86982
86983
86984
86985
86986
86987
86988
86989
86990
86991
86992
86993
86994
86995
86996
86997
86998
86999
87000
87001
87002
87003
87004
87005
87006
87007
87008
87009
87010
87011
87012
87013
87014
87015
87016
87017
87018
87019
87020
87021
87022
87023
87024
87025
87026
87027
87028
87029
87030
87031
87032
87033
87034
87035
87036
87037
87038
87039
87040
87041
87042
87043
87044
87045
87046
87047
87048
87049
87050
87051
87052
87053
87054
87055
87056
87057
87058
87059
87060
87061
87062
87063
87064
87065
87066
87067
87068
87069
87070
87071
87072
87073
87074
87075
87076
87077
87078
87079
87080
87081
87082
87083
87084
87085
87086
87087
87088
87089
87090
87091
87092
87093
87094
87095
87096
87097
87098
87099
87100
87101
87102
87103
87104
87105
87106
87107
87108
87109
87110
87111
87112
87113
87114
87115
87116
87117
87118
87119
87120
87121
87122
87123
87124
87125
87126
87127
87128
87129
87130
87131
87132
87133
87134
87135
87136
87137
87138
87139
87140
87141
87142
87143
87144
87145
87146
87147
87148
87149
87150
87151
87152
87153
87154
87155
87156
87157
87158
87159
87160
87161
87162
87163
87164
87165
87166
87167
87168
87169
87170
87171
87172
87173
87174
87175
87176
87177
87178
87179
87180
87181
87182
87183
87184
87185
87186
87187
87188
87189
87190
87191
87192
87193
87194
87195
87196
87197
87198
87199
87200
87201
87202
87203
87204
87205
87206
87207
87208
87209
87210
87211
87212
87213
87214
87215
87216
87217
87218
87219
87220
87221
87222
87223
87224
87225
87226
87227
87228
87229
87230
87231
87232
87233
87234
87235
87236
87237
87238
87239
87240
87241
87242
87243
87244
87245
87246
87247
87248
87249
87250
87251
87252
87253
87254
87255
87256
87257
87258
87259
87260
87261
87262
87263
87264
87265
87266
87267
87268
87269
87270
87271
87272
87273
87274
87275
87276
87277
87278
87279
87280
87281
87282
87283
87284
87285
87286
87287
87288
87289
87290
87291
87292
87293
87294
87295
87296
87297
87298
87299
87300
87301
87302
87303
87304
87305
87306
87307
87308
87309
87310
87311
87312
87313
87314
87315
87316
87317
87318
87319
87320
87321
87322
87323
87324
87325
87326
87327
87328
87329
87330
87331
87332
87333
87334
87335
87336
87337
87338
87339
87340
87341
87342
87343
87344
87345
87346
87347
87348
87349
87350
87351
87352
87353
87354
87355
87356
87357
87358
87359
87360
87361
87362
87363
87364
87365
87366
87367
87368
87369
87370
87371
87372
87373
87374
87375
87376
87377
87378
87379
87380
87381
87382
87383
87384
87385
87386
87387
87388
87389
87390
87391
87392
87393
87394
87395
87396
87397
87398
87399
87400
87401
87402
87403
87404
87405
87406
87407
87408
87409
87410
87411
87412
87413
87414
87415
87416
87417
87418
87419
87420
87421
87422
87423
87424
87425
87426
87427
87428
87429
87430
87431
87432
87433
87434
87435
87436
87437
87438
87439
87440
87441
87442
87443
87444
87445
87446
87447
87448
87449
87450
87451
87452
87453
87454
87455
87456
87457
87458
87459
87460
87461
87462
87463
87464
87465
87466
87467
87468
87469
87470
87471
87472
87473
87474
87475
87476
87477
87478
87479
87480
87481
87482
87483
87484
87485
87486
87487
87488
87489
87490
87491
87492
87493
87494
87495
87496
87497
87498
87499
87500
87501
87502
87503
87504
87505
87506
87507
87508
87509
87510
87511
87512
87513
87514
87515
87516
87517
87518
87519
87520
87521
87522
87523
87524
87525
87526
87527
87528
87529
87530
87531
87532
87533
87534
87535
87536
87537
87538
87539
87540
87541
87542
87543
87544
87545
87546
87547
87548
87549
87550
87551
87552
87553
87554
87555
87556
87557
87558
87559
87560
87561
87562
87563
87564
87565
87566
87567
87568
87569
87570
87571
87572
87573
87574
87575
87576
87577
87578
87579
87580
87581
87582
87583
87584
87585
87586
87587
87588
87589
87590
87591
87592
87593
87594
87595
87596
87597
87598
87599
87600
87601
87602
87603
87604
87605
87606
87607
87608
87609
87610
87611
87612
87613
87614
87615
87616
87617
87618
87619
87620
87621
87622
87623
87624
87625
87626
87627
87628
87629
87630
87631
87632
87633
87634
87635
87636
87637
87638
87639
87640
87641
87642
87643
87644
87645
87646
87647
87648
87649
87650
87651
87652
87653
87654
87655
87656
87657
87658
87659
87660
87661
87662
87663
87664
87665
87666
87667
87668
87669
87670
87671
87672
87673
87674
87675
87676
87677
87678
87679
87680
87681
87682
87683
87684
87685
87686
87687
87688
87689
87690
87691
87692
87693
87694
87695
87696
87697
87698
87699
87700
87701
87702
87703
87704
87705
87706
87707
87708
87709
87710
87711
87712
87713
87714
87715
87716
87717
87718
87719
87720
87721
87722
87723
87724
87725
87726
87727
87728
87729
87730
87731
87732
87733
87734
87735
87736
87737
87738
87739
87740
87741
87742
87743
87744
87745
87746
87747
87748
87749
87750
87751
87752
87753
87754
87755
87756
87757
87758
87759
87760
87761
87762
87763
87764
87765
87766
87767
87768
87769
87770
87771
87772
87773
87774
87775
87776
87777
87778
87779
87780
87781
87782
87783
87784
87785
87786
87787
87788
87789
87790
87791
87792
87793
87794
87795
87796
87797
87798
87799
87800
87801
87802
87803
87804
87805
87806
87807
87808
87809
87810
87811
87812
87813
87814
87815
87816
87817
87818
87819
87820
87821
87822
87823
87824
87825
87826
87827
87828
87829
87830
87831
87832
87833
87834
87835
87836
87837
87838
87839
87840
87841
87842
87843
87844
87845
87846
87847
87848
87849
87850
87851
87852
87853
87854
87855
87856
87857
87858
87859
87860
87861
87862
87863
87864
87865
87866
87867
87868
87869
87870
87871
87872
87873
87874
87875
87876
87877
87878
87879
87880
87881
87882
87883
87884
87885
87886
87887
87888
87889
87890
87891
87892
87893
87894
87895
87896
87897
87898
87899
87900
87901
87902
87903
87904
87905
87906
87907
87908
87909
87910
87911
87912
87913
87914
87915
87916
87917
87918
87919
87920
87921
87922
87923
87924
87925
87926
87927
87928
87929
87930
87931
87932
87933
87934
87935
87936
87937
87938
87939
87940
87941
87942
87943
87944
87945
87946
87947
87948
87949
87950
87951
87952
87953
87954
87955
87956
87957
87958
87959
87960
87961
87962
87963
87964
87965
87966
87967
87968
87969
87970
87971
87972
87973
87974
87975
87976
87977
87978
87979
87980
87981
87982
87983
87984
87985
87986
87987
87988
87989
87990
87991
87992
87993
87994
87995
87996
87997
87998
87999
88000
88001
88002
88003
88004
88005
88006
88007
88008
88009
88010
88011
88012
88013
88014
88015
88016
88017
88018
88019
88020
88021
88022
88023
88024
88025
88026
88027
88028
88029
88030
88031
88032
88033
88034
88035
88036
88037
88038
88039
88040
88041
88042
88043
88044
88045
88046
88047
88048
88049
88050
88051
88052
88053
88054
88055
88056
88057
88058
88059
88060
88061
88062
88063
88064
88065
88066
88067
88068
88069
88070
88071
88072
88073
88074
88075
88076
88077
88078
88079
88080
88081
88082
88083
88084
88085
88086
88087
88088
88089
88090
88091
88092
88093
88094
88095
88096
88097
88098
88099
88100
88101
88102
88103
88104
88105
88106
88107
88108
88109
88110
88111
88112
88113
88114
88115
88116
88117
88118
88119
88120
88121
88122
88123
88124
88125
88126
88127
88128
88129
88130
88131
88132
88133
88134
88135
88136
88137
88138
88139
88140
88141
88142
88143
88144
88145
88146
88147
88148
88149
88150
88151
88152
88153
88154
88155
88156
88157
88158
88159
88160
88161
88162
88163
88164
88165
88166
88167
88168
88169
88170
88171
88172
88173
88174
88175
88176
88177
88178
88179
88180
88181
88182
88183
88184
88185
88186
88187
88188
88189
88190
88191
88192
88193
88194
88195
88196
88197
88198
88199
88200
88201
88202
88203
88204
88205
88206
88207
88208
88209
88210
88211
88212
88213
88214
88215
88216
88217
88218
88219
88220
88221
88222
88223
88224
88225
88226
88227
88228
88229
88230
88231
88232
88233
88234
88235
88236
88237
88238
88239
88240
88241
88242
88243
88244
88245
88246
88247
88248
88249
88250
88251
88252
88253
88254
88255
88256
88257
88258
88259
88260
88261
88262
88263
88264
88265
88266
88267
88268
88269
88270
88271
88272
88273
88274
88275
88276
88277
88278
88279
88280
88281
88282
88283
88284
88285
88286
88287
88288
88289
88290
88291
88292
88293
88294
88295
88296
88297
88298
88299
88300
88301
88302
88303
88304
88305
88306
88307
88308
88309
88310
88311
88312
88313
88314
88315
88316
88317
88318
88319
88320
88321
88322
88323
88324
88325
88326
88327
88328
88329
88330
88331
88332
88333
88334
88335
88336
88337
88338
88339
88340
88341
88342
88343
88344
88345
88346
88347
88348
88349
88350
88351
88352
88353
88354
88355
88356
88357
88358
88359
88360
88361
88362
88363
88364
88365
88366
88367
88368
88369
88370
88371
88372
88373
88374
88375
88376
88377
88378
88379
88380
88381
88382
88383
88384
88385
88386
88387
88388
88389
88390
88391
88392
88393
88394
88395
88396
88397
88398
88399
88400
88401
88402
88403
88404
88405
88406
88407
88408
88409
88410
88411
88412
88413
88414
88415
88416
88417
88418
88419
88420
88421
88422
88423
88424
88425
88426
88427
88428
88429
88430
88431
88432
88433
88434
88435
88436
88437
88438
88439
88440
88441
88442
88443
88444
88445
88446
88447
88448
88449
88450
88451
88452
88453
88454
88455
88456
88457
88458
88459
88460
88461
88462
88463
88464
88465
88466
88467
88468
88469
88470
88471
88472
88473
88474
88475
88476
88477
88478
88479
88480
88481
88482
88483
88484
88485
88486
88487
88488
88489
88490
88491
88492
88493
88494
88495
88496
88497
88498
88499
88500
88501
88502
88503
88504
88505
88506
88507
88508
88509
88510
88511
88512
88513
88514
88515
88516
88517
88518
88519
88520
88521
88522
88523
88524
88525
88526
88527
88528
88529
88530
88531
88532
88533
88534
88535
88536
88537
88538
88539
88540
88541
88542
88543
88544
88545
88546
88547
88548
88549
88550
88551
88552
88553
88554
88555
88556
88557
88558
88559
88560
88561
88562
88563
88564
88565
88566
88567
88568
88569
88570
88571
88572
88573
88574
88575
88576
88577
88578
88579
88580
88581
88582
88583
88584
88585
88586
88587
88588
88589
88590
88591
88592
88593
88594
88595
88596
88597
88598
88599
88600
88601
88602
88603
88604
88605
88606
88607
88608
88609
88610
88611
88612
88613
88614
88615
88616
88617
88618
88619
88620
88621
88622
88623
88624
88625
88626
88627
88628
88629
88630
88631
88632
88633
88634
88635
88636
88637
88638
88639
88640
88641
88642
88643
88644
88645
88646
88647
88648
88649
88650
88651
88652
88653
88654
88655
88656
88657
88658
88659
88660
88661
88662
88663
88664
88665
88666
88667
88668
88669
88670
88671
88672
88673
88674
88675
88676
88677
88678
88679
88680
88681
88682
88683
88684
88685
88686
88687
88688
88689
88690
88691
88692
88693
88694
88695
88696
88697
88698
88699
88700
88701
88702
88703
88704
88705
88706
88707
88708
88709
88710
88711
88712
88713
88714
88715
88716
88717
88718
88719
88720
88721
88722
88723
88724
88725
88726
88727
88728
88729
88730
88731
88732
88733
88734
88735
88736
88737
88738
88739
88740
88741
88742
88743
88744
88745
88746
88747
88748
88749
88750
88751
88752
88753
88754
88755
88756
88757
88758
88759
88760
88761
88762
88763
88764
88765
88766
88767
88768
88769
88770
88771
88772
88773
88774
88775
88776
88777
88778
88779
88780
88781
88782
88783
88784
88785
88786
88787
88788
88789
88790
88791
88792
88793
88794
88795
88796
88797
88798
88799
88800
88801
88802
88803
88804
88805
88806
88807
88808
88809
88810
88811
88812
88813
88814
88815
88816
88817
88818
88819
88820
88821
88822
88823
88824
88825
88826
88827
88828
88829
88830
88831
88832
88833
88834
88835
88836
88837
88838
88839
88840
88841
88842
88843
88844
88845
88846
88847
88848
88849
88850
88851
88852
88853
88854
88855
88856
88857
88858
88859
88860
88861
88862
88863
88864
88865
88866
88867
88868
88869
88870
88871
88872
88873
88874
88875
88876
88877
88878
88879
88880
88881
88882
88883
88884
88885
88886
88887
88888
88889
88890
88891
88892
88893
88894
88895
88896
88897
88898
88899
88900
88901
88902
88903
88904
88905
88906
88907
88908
88909
88910
88911
88912
88913
88914
88915
88916
88917
88918
88919
88920
88921
88922
88923
88924
88925
88926
88927
88928
88929
88930
88931
88932
88933
88934
88935
88936
88937
88938
88939
88940
88941
88942
88943
88944
88945
88946
88947
88948
88949
88950
88951
88952
88953
88954
88955
88956
88957
88958
88959
88960
88961
88962
88963
88964
88965
88966
88967
88968
88969
88970
88971
88972
88973
88974
88975
88976
88977
88978
88979
88980
88981
88982
88983
88984
88985
88986
88987
88988
88989
88990
88991
88992
88993
88994
88995
88996
88997
88998
88999
89000
89001
89002
89003
89004
89005
89006
89007
89008
89009
89010
89011
89012
89013
89014
89015
89016
89017
89018
89019
89020
89021
89022
89023
89024
89025
89026
89027
89028
89029
89030
89031
89032
89033
89034
89035
89036
89037
89038
89039
89040
89041
89042
89043
89044
89045
89046
89047
89048
89049
89050
89051
89052
89053
89054
89055
89056
89057
89058
89059
89060
89061
89062
89063
89064
89065
89066
89067
89068
89069
89070
89071
89072
89073
89074
89075
89076
89077
89078
89079
89080
89081
89082
89083
89084
89085
89086
89087
89088
89089
89090
89091
89092
89093
89094
89095
89096
89097
89098
89099
89100
89101
89102
89103
89104
89105
89106
89107
89108
89109
89110
89111
89112
89113
89114
89115
89116
89117
89118
89119
89120
89121
89122
89123
89124
89125
89126
89127
89128
89129
89130
89131
89132
89133
89134
89135
89136
89137
89138
89139
89140
89141
89142
89143
89144
89145
89146
89147
89148
89149
89150
89151
89152
89153
89154
89155
89156
89157
89158
89159
89160
89161
89162
89163
89164
89165
89166
89167
89168
89169
89170
89171
89172
89173
89174
89175
89176
89177
89178
89179
89180
89181
89182
89183
89184
89185
89186
89187
89188
89189
89190
89191
89192
89193
89194
89195
89196
89197
89198
89199
89200
89201
89202
89203
89204
89205
89206
89207
89208
89209
89210
89211
89212
89213
89214
89215
89216
89217
89218
89219
89220
89221
89222
89223
89224
89225
89226
89227
89228
89229
89230
89231
89232
89233
89234
89235
89236
89237
89238
89239
89240
89241
89242
89243
89244
89245
89246
89247
89248
89249
89250
89251
89252
89253
89254
89255
89256
89257
89258
89259
89260
89261
89262
89263
89264
89265
89266
89267
89268
89269
89270
89271
89272
89273
89274
89275
89276
89277
89278
89279
89280
89281
89282
89283
89284
89285
89286
89287
89288
89289
89290
89291
89292
89293
89294
89295
89296
89297
89298
89299
89300
89301
89302
89303
89304
89305
89306
89307
89308
89309
89310
89311
89312
89313
89314
89315
89316
89317
89318
89319
89320
89321
89322
89323
89324
89325
89326
89327
89328
89329
89330
89331
89332
89333
89334
89335
89336
89337
89338
89339
89340
89341
89342
89343
89344
89345
89346
89347
89348
89349
89350
89351
89352
89353
89354
89355
89356
89357
89358
89359
89360
89361
89362
89363
89364
89365
89366
89367
89368
89369
89370
89371
89372
89373
89374
89375
89376
89377
89378
89379
89380
89381
89382
89383
89384
89385
89386
89387
89388
89389
89390
89391
89392
89393
89394
89395
89396
89397
89398
89399
89400
89401
89402
89403
89404
89405
89406
89407
89408
89409
89410
89411
89412
89413
89414
89415
89416
89417
89418
89419
89420
89421
89422
89423
89424
89425
89426
89427
89428
89429
89430
89431
89432
89433
89434
89435
89436
89437
89438
89439
89440
89441
89442
89443
89444
89445
89446
89447
89448
89449
89450
89451
89452
89453
89454
89455
89456
89457
89458
89459
89460
89461
89462
89463
89464
89465
89466
89467
89468
89469
89470
89471
89472
89473
89474
89475
89476
89477
89478
89479
89480
89481
89482
89483
89484
89485
89486
89487
89488
89489
89490
89491
89492
89493
89494
89495
89496
89497
89498
89499
89500
89501
89502
89503
89504
89505
89506
89507
89508
89509
89510
89511
89512
89513
89514
89515
89516
89517
89518
89519
89520
89521
89522
89523
89524
89525
89526
89527
89528
89529
89530
89531
89532
89533
89534
89535
89536
89537
89538
89539
89540
89541
89542
89543
89544
89545
89546
89547
89548
89549
89550
89551
89552
89553
89554
89555
89556
89557
89558
89559
89560
89561
89562
89563
89564
89565
89566
89567
89568
89569
89570
89571
89572
89573
89574
89575
89576
89577
89578
89579
89580
89581
89582
89583
89584
89585
89586
89587
89588
89589
89590
89591
89592
89593
89594
89595
89596
89597
89598
89599
89600
89601
89602
89603
89604
89605
89606
89607
89608
89609
89610
89611
89612
89613
89614
89615
89616
89617
89618
89619
89620
89621
89622
89623
89624
89625
89626
89627
89628
89629
89630
89631
89632
89633
89634
89635
89636
89637
89638
89639
89640
89641
89642
89643
89644
89645
89646
89647
89648
89649
89650
89651
89652
89653
89654
89655
89656
89657
89658
89659
89660
89661
89662
89663
89664
89665
89666
89667
89668
89669
89670
89671
89672
89673
89674
89675
89676
89677
89678
89679
89680
89681
89682
89683
89684
89685
89686
89687
89688
89689
89690
89691
89692
89693
89694
89695
89696
89697
89698
89699
89700
89701
89702
89703
89704
89705
89706
89707
89708
89709
89710
89711
89712
89713
89714
89715
89716
89717
89718
89719
89720
89721
89722
89723
89724
89725
89726
89727
89728
89729
89730
89731
89732
89733
89734
89735
89736
89737
89738
89739
89740
89741
89742
89743
89744
89745
89746
89747
89748
89749
89750
89751
89752
89753
89754
89755
89756
89757
89758
89759
89760
89761
89762
89763
89764
89765
89766
89767
89768
89769
89770
89771
89772
89773
89774
89775
89776
89777
89778
89779
89780
89781
89782
89783
89784
89785
89786
89787
89788
89789
89790
89791
89792
89793
89794
89795
89796
89797
89798
89799
89800
89801
89802
89803
89804
89805
89806
89807
89808
89809
89810
89811
89812
89813
89814
89815
89816
89817
89818
89819
89820
89821
89822
89823
89824
89825
89826
89827
89828
89829
89830
89831
89832
89833
89834
89835
89836
89837
89838
89839
89840
89841
89842
89843
89844
89845
89846
89847
89848
89849
89850
89851
89852
89853
89854
89855
89856
89857
89858
89859
89860
89861
89862
89863
89864
89865
89866
89867
89868
89869
89870
89871
89872
89873
89874
89875
89876
89877
89878
89879
89880
89881
89882
89883
89884
89885
89886
89887
89888
89889
89890
89891
89892
89893
89894
89895
89896
89897
89898
89899
89900
89901
89902
89903
89904
89905
89906
89907
89908
89909
89910
89911
89912
89913
89914
89915
89916
89917
89918
89919
89920
89921
89922
89923
89924
89925
89926
89927
89928
89929
89930
89931
89932
89933
89934
89935
89936
89937
89938
89939
89940
89941
89942
89943
89944
89945
89946
89947
89948
89949
89950
89951
89952
89953
89954
89955
89956
89957
89958
89959
89960
89961
89962
89963
89964
89965
89966
89967
89968
89969
89970
89971
89972
89973
89974
89975
89976
89977
89978
89979
89980
89981
89982
89983
89984
89985
89986
89987
89988
89989
89990
89991
89992
89993
89994
89995
89996
89997
89998
89999
90000
90001
90002
90003
90004
90005
90006
90007
90008
90009
90010
90011
90012
90013
90014
90015
90016
90017
90018
90019
90020
90021
90022
90023
90024
90025
90026
90027
90028
90029
90030
90031
90032
90033
90034
90035
90036
90037
90038
90039
90040
90041
90042
90043
90044
90045
90046
90047
90048
90049
90050
90051
90052
90053
90054
90055
90056
90057
90058
90059
90060
90061
90062
90063
90064
90065
90066
90067
90068
90069
90070
90071
90072
90073
90074
90075
90076
90077
90078
90079
90080
90081
90082
90083
90084
90085
90086
90087
90088
90089
90090
90091
90092
90093
90094
90095
90096
90097
90098
90099
90100
90101
90102
90103
90104
90105
90106
90107
90108
90109
90110
90111
90112
90113
90114
90115
90116
90117
90118
90119
90120
90121
90122
90123
90124
90125
90126
90127
90128
90129
90130
90131
90132
90133
90134
90135
90136
90137
90138
90139
90140
90141
90142
90143
90144
90145
90146
90147
90148
90149
90150
90151
90152
90153
90154
90155
90156
90157
90158
90159
90160
90161
90162
90163
90164
90165
90166
90167
90168
90169
90170
90171
90172
90173
90174
90175
90176
90177
90178
90179
90180
90181
90182
90183
90184
90185
90186
90187
90188
90189
90190
90191
90192
90193
90194
90195
90196
90197
90198
90199
90200
90201
90202
90203
90204
90205
90206
90207
90208
90209
90210
90211
90212
90213
90214
90215
90216
90217
90218
90219
90220
90221
90222
90223
90224
90225
90226
90227
90228
90229
90230
90231
90232
90233
90234
90235
90236
90237
90238
90239
90240
90241
90242
90243
90244
90245
90246
90247
90248
90249
90250
90251
90252
90253
90254
90255
90256
90257
90258
90259
90260
90261
90262
90263
90264
90265
90266
90267
90268
90269
90270
90271
90272
90273
90274
90275
90276
90277
90278
90279
90280
90281
90282
90283
90284
90285
90286
90287
90288
90289
90290
90291
90292
90293
90294
90295
90296
90297
90298
90299
90300
90301
90302
90303
90304
90305
90306
90307
90308
90309
90310
90311
90312
90313
90314
90315
90316
90317
90318
90319
90320
90321
90322
90323
90324
90325
90326
90327
90328
90329
90330
90331
90332
90333
90334
90335
90336
90337
90338
90339
90340
90341
90342
90343
90344
90345
90346
90347
90348
90349
90350
90351
90352
90353
90354
90355
90356
90357
90358
90359
90360
90361
90362
90363
90364
90365
90366
90367
90368
90369
90370
90371
90372
90373
90374
90375
90376
90377
90378
90379
90380
90381
90382
90383
90384
90385
90386
90387
90388
90389
90390
90391
90392
90393
90394
90395
90396
90397
90398
90399
90400
90401
90402
90403
90404
90405
90406
90407
90408
90409
90410
90411
90412
90413
90414
90415
90416
90417
90418
90419
90420
90421
90422
90423
90424
90425
90426
90427
90428
90429
90430
90431
90432
90433
90434
90435
90436
90437
90438
90439
90440
90441
90442
90443
90444
90445
90446
90447
90448
90449
90450
90451
90452
90453
90454
90455
90456
90457
90458
90459
90460
90461
90462
90463
90464
90465
90466
90467
90468
90469
90470
90471
90472
90473
90474
90475
90476
90477
90478
90479
90480
90481
90482
90483
90484
90485
90486
90487
90488
90489
90490
90491
90492
90493
90494
90495
90496
90497
90498
90499
90500
90501
90502
90503
90504
90505
90506
90507
90508
90509
90510
90511
90512
90513
90514
90515
90516
90517
90518
90519
90520
90521
90522
90523
90524
90525
90526
90527
90528
90529
90530
90531
90532
90533
90534
90535
90536
90537
90538
90539
90540
90541
90542
90543
90544
90545
90546
90547
90548
90549
90550
90551
90552
90553
90554
90555
90556
90557
90558
90559
90560
90561
90562
90563
90564
90565
90566
90567
90568
90569
90570
90571
90572
90573
90574
90575
90576
90577
90578
90579
90580
90581
90582
90583
90584
90585
90586
90587
90588
90589
90590
90591
90592
90593
90594
90595
90596
90597
90598
90599
90600
90601
90602
90603
90604
90605
90606
90607
90608
90609
90610
90611
90612
90613
90614
90615
90616
90617
90618
90619
90620
90621
90622
90623
90624
90625
90626
90627
90628
90629
90630
90631
90632
90633
90634
90635
90636
90637
90638
90639
90640
90641
90642
90643
90644
90645
90646
90647
90648
90649
90650
90651
90652
90653
90654
90655
90656
90657
90658
90659
90660
90661
90662
90663
90664
90665
90666
90667
90668
90669
90670
90671
90672
90673
90674
90675
90676
90677
90678
90679
90680
90681
90682
90683
90684
90685
90686
90687
90688
90689
90690
90691
90692
90693
90694
90695
90696
90697
90698
90699
90700
90701
90702
90703
90704
90705
90706
90707
90708
90709
90710
90711
90712
90713
90714
90715
90716
90717
90718
90719
90720
90721
90722
90723
90724
90725
90726
90727
90728
90729
90730
90731
90732
90733
90734
90735
90736
90737
90738
90739
90740
90741
90742
90743
90744
90745
90746
90747
90748
90749
90750
90751
90752
90753
90754
90755
90756
90757
90758
90759
90760
90761
90762
90763
90764
90765
90766
90767
90768
90769
90770
90771
90772
90773
90774
90775
90776
90777
90778
90779
90780
90781
90782
90783
90784
90785
90786
90787
90788
90789
90790
90791
90792
90793
90794
90795
90796
90797
90798
90799
90800
90801
90802
90803
90804
90805
90806
90807
90808
90809
90810
90811
90812
90813
90814
90815
90816
90817
90818
90819
90820
90821
90822
90823
90824
90825
90826
90827
90828
90829
90830
90831
90832
90833
90834
90835
90836
90837
90838
90839
90840
90841
90842
90843
90844
90845
90846
90847
90848
90849
90850
90851
90852
90853
90854
90855
90856
90857
90858
90859
90860
90861
90862
90863
90864
90865
90866
90867
90868
90869
90870
90871
90872
90873
90874
90875
90876
90877
90878
90879
90880
90881
90882
90883
90884
90885
90886
90887
90888
90889
90890
90891
90892
90893
90894
90895
90896
90897
90898
90899
90900
90901
90902
90903
90904
90905
90906
90907
90908
90909
90910
90911
90912
90913
90914
90915
90916
90917
90918
90919
90920
90921
90922
90923
90924
90925
90926
90927
90928
90929
90930
90931
90932
90933
90934
90935
90936
90937
90938
90939
90940
90941
90942
90943
90944
90945
90946
90947
90948
90949
90950
90951
90952
90953
90954
90955
90956
90957
90958
90959
90960
90961
90962
90963
90964
90965
90966
90967
90968
90969
90970
90971
90972
90973
90974
90975
90976
90977
90978
90979
90980
90981
90982
90983
90984
90985
90986
90987
90988
90989
90990
90991
90992
90993
90994
90995
90996
90997
90998
90999
91000
91001
91002
91003
91004
91005
91006
91007
91008
91009
91010
91011
91012
91013
91014
91015
91016
91017
91018
91019
91020
91021
91022
91023
91024
91025
91026
91027
91028
91029
91030
91031
91032
91033
91034
91035
91036
91037
91038
91039
91040
91041
91042
91043
91044
91045
91046
91047
91048
91049
91050
91051
91052
91053
91054
91055
91056
91057
91058
91059
91060
91061
91062
91063
91064
91065
91066
91067
91068
91069
91070
91071
91072
91073
91074
91075
91076
91077
91078
91079
91080
91081
91082
91083
91084
91085
91086
91087
91088
91089
91090
91091
91092
91093
91094
91095
91096
91097
91098
91099
91100
91101
91102
91103
91104
91105
91106
91107
91108
91109
91110
91111
91112
91113
91114
91115
91116
91117
91118
91119
91120
91121
91122
91123
91124
91125
91126
91127
91128
91129
91130
91131
91132
91133
91134
91135
91136
91137
91138
91139
91140
91141
91142
91143
91144
91145
91146
91147
91148
91149
91150
91151
91152
91153
91154
91155
91156
91157
91158
91159
91160
91161
91162
91163
91164
91165
91166
91167
91168
91169
91170
91171
91172
91173
91174
91175
91176
91177
91178
91179
91180
91181
91182
91183
91184
91185
91186
91187
91188
91189
91190
91191
91192
91193
91194
91195
91196
91197
91198
91199
91200
91201
91202
91203
91204
91205
91206
91207
91208
91209
91210
91211
91212
91213
91214
91215
91216
91217
91218
91219
91220
91221
91222
91223
91224
91225
91226
91227
91228
91229
91230
91231
91232
91233
91234
91235
91236
91237
91238
91239
91240
91241
91242
91243
91244
91245
91246
91247
91248
91249
91250
91251
91252
91253
91254
91255
91256
91257
91258
91259
91260
91261
91262
91263
91264
91265
91266
91267
91268
91269
91270
91271
91272
91273
91274
91275
91276
91277
91278
91279
91280
91281
91282
91283
91284
91285
91286
91287
91288
91289
91290
91291
91292
91293
91294
91295
91296
91297
91298
91299
91300
91301
91302
91303
91304
91305
91306
91307
91308
91309
91310
91311
91312
91313
91314
91315
91316
91317
91318
91319
91320
91321
91322
91323
91324
91325
91326
91327
91328
91329
91330
91331
91332
91333
91334
91335
91336
91337
91338
91339
91340
91341
91342
91343
91344
91345
91346
91347
91348
91349
91350
91351
91352
91353
91354
91355
91356
91357
91358
91359
91360
91361
91362
91363
91364
91365
91366
91367
91368
91369
91370
91371
91372
91373
91374
91375
91376
91377
91378
91379
91380
91381
91382
91383
91384
91385
91386
91387
91388
91389
91390
91391
91392
91393
91394
91395
91396
91397
91398
91399
91400
91401
91402
91403
91404
91405
91406
91407
91408
91409
91410
91411
91412
91413
91414
91415
91416
91417
91418
91419
91420
91421
91422
91423
91424
91425
91426
91427
91428
91429
91430
91431
91432
91433
91434
91435
91436
91437
91438
91439
91440
91441
91442
91443
91444
91445
91446
91447
91448
91449
91450
91451
91452
91453
91454
91455
91456
91457
91458
91459
91460
91461
91462
91463
91464
91465
91466
91467
91468
91469
91470
91471
91472
91473
91474
91475
91476
91477
91478
91479
91480
91481
91482
91483
91484
91485
91486
91487
91488
91489
91490
91491
91492
91493
91494
91495
91496
91497
91498
91499
91500
91501
91502
91503
91504
91505
91506
91507
91508
91509
91510
91511
91512
91513
91514
91515
91516
91517
91518
91519
91520
91521
91522
91523
91524
91525
91526
91527
91528
91529
91530
91531
91532
91533
91534
91535
91536
91537
91538
91539
91540
91541
91542
91543
91544
91545
91546
91547
91548
91549
91550
91551
91552
91553
91554
91555
91556
91557
91558
91559
91560
91561
91562
91563
91564
91565
91566
91567
91568
91569
91570
91571
91572
91573
91574
91575
91576
91577
91578
91579
91580
91581
91582
91583
91584
91585
91586
91587
91588
91589
91590
91591
91592
91593
91594
91595
91596
91597
91598
91599
91600
91601
91602
91603
91604
91605
91606
91607
91608
91609
91610
91611
91612
91613
91614
91615
91616
91617
91618
91619
91620
91621
91622
91623
91624
91625
91626
91627
91628
91629
91630
91631
91632
91633
91634
91635
91636
91637
91638
91639
91640
91641
91642
91643
91644
91645
91646
91647
91648
91649
91650
91651
91652
91653
91654
91655
91656
91657
91658
91659
91660
91661
91662
91663
91664
91665
91666
91667
91668
91669
91670
91671
91672
91673
91674
91675
91676
91677
91678
91679
91680
91681
91682
91683
91684
91685
91686
91687
91688
91689
91690
91691
91692
91693
91694
91695
91696
91697
91698
91699
91700
91701
91702
91703
91704
91705
91706
91707
91708
91709
91710
91711
91712
91713
91714
91715
91716
91717
91718
91719
91720
91721
91722
91723
91724
91725
91726
91727
91728
91729
91730
91731
91732
91733
91734
91735
91736
91737
91738
91739
91740
91741
91742
91743
91744
91745
91746
91747
91748
91749
91750
91751
91752
91753
91754
91755
91756
91757
91758
91759
91760
91761
91762
91763
91764
91765
91766
91767
91768
91769
91770
91771
91772
91773
91774
91775
91776
91777
91778
91779
91780
91781
91782
91783
91784
91785
91786
91787
91788
91789
91790
91791
91792
91793
91794
91795
91796
91797
91798
91799
91800
91801
91802
91803
91804
91805
91806
91807
91808
91809
91810
91811
91812
91813
91814
91815
91816
91817
91818
91819
91820
91821
91822
91823
91824
91825
91826
91827
91828
91829
91830
91831
91832
91833
91834
91835
91836
91837
91838
91839
91840
91841
91842
91843
91844
91845
91846
91847
91848
91849
91850
91851
91852
91853
91854
91855
91856
91857
91858
91859
91860
91861
91862
91863
91864
91865
91866
91867
91868
91869
91870
91871
91872
91873
91874
91875
91876
91877
91878
91879
91880
91881
91882
91883
91884
91885
91886
91887
91888
91889
91890
91891
91892
91893
91894
91895
91896
91897
91898
91899
91900
91901
91902
91903
91904
91905
91906
91907
91908
91909
91910
91911
91912
91913
91914
91915
91916
91917
91918
91919
91920
91921
91922
91923
91924
91925
91926
91927
91928
91929
91930
91931
91932
91933
91934
91935
91936
91937
91938
91939
91940
91941
91942
91943
91944
91945
91946
91947
91948
91949
91950
91951
91952
91953
91954
91955
91956
91957
91958
91959
91960
91961
91962
91963
91964
91965
91966
91967
91968
91969
91970
91971
91972
91973
91974
91975
91976
91977
91978
91979
91980
91981
91982
91983
91984
91985
91986
91987
91988
91989
91990
91991
91992
91993
91994
91995
91996
91997
91998
91999
92000
92001
92002
92003
92004
92005
92006
92007
92008
92009
92010
92011
92012
92013
92014
92015
92016
92017
92018
92019
92020
92021
92022
92023
92024
92025
92026
92027
92028
92029
92030
92031
92032
92033
92034
92035
92036
92037
92038
92039
92040
92041
92042
92043
92044
92045
92046
92047
92048
92049
92050
92051
92052
92053
92054
92055
92056
92057
92058
92059
92060
92061
92062
92063
92064
92065
92066
92067
92068
92069
92070
92071
92072
92073
92074
92075
92076
92077
92078
92079
92080
92081
92082
92083
92084
92085
92086
92087
92088
92089
92090
92091
92092
92093
92094
92095
92096
92097
92098
92099
92100
92101
92102
92103
92104
92105
92106
92107
92108
92109
92110
92111
92112
92113
92114
92115
92116
92117
92118
92119
92120
92121
92122
92123
92124
92125
92126
92127
92128
92129
92130
92131
92132
92133
92134
92135
92136
92137
92138
92139
92140
92141
92142
92143
92144
92145
92146
92147
92148
92149
92150
92151
92152
92153
92154
92155
92156
92157
92158
92159
92160
92161
92162
92163
92164
92165
92166
92167
92168
92169
92170
92171
92172
92173
92174
92175
92176
92177
92178
92179
92180
92181
92182
92183
92184
92185
92186
92187
92188
92189
92190
92191
92192
92193
92194
92195
92196
92197
92198
92199
92200
92201
92202
92203
92204
92205
92206
92207
92208
92209
92210
92211
92212
92213
92214
92215
92216
92217
92218
92219
92220
92221
92222
92223
92224
92225
92226
92227
92228
92229
92230
92231
92232
92233
92234
92235
92236
92237
92238
92239
92240
92241
92242
92243
92244
92245
92246
92247
92248
92249
92250
92251
92252
92253
92254
92255
92256
92257
92258
92259
92260
92261
92262
92263
92264
92265
92266
92267
92268
92269
92270
92271
92272
92273
92274
92275
92276
92277
92278
92279
92280
92281
92282
92283
92284
92285
92286
92287
92288
92289
92290
92291
92292
92293
92294
92295
92296
92297
92298
92299
92300
92301
92302
92303
92304
92305
92306
92307
92308
92309
92310
92311
92312
92313
92314
92315
92316
92317
92318
92319
92320
92321
92322
92323
92324
92325
92326
92327
92328
92329
92330
92331
92332
92333
92334
92335
92336
92337
92338
92339
92340
92341
92342
92343
92344
92345
92346
92347
92348
92349
92350
92351
92352
92353
92354
92355
92356
92357
92358
92359
92360
92361
92362
92363
92364
92365
92366
92367
92368
92369
92370
92371
92372
92373
92374
92375
92376
92377
92378
92379
92380
92381
92382
92383
92384
92385
92386
92387
92388
92389
92390
92391
92392
92393
92394
92395
92396
92397
92398
92399
92400
92401
92402
92403
92404
92405
92406
92407
92408
92409
92410
92411
92412
92413
92414
92415
92416
92417
92418
92419
92420
92421
92422
92423
92424
92425
92426
92427
92428
92429
92430
92431
92432
92433
92434
92435
92436
92437
92438
92439
92440
92441
92442
92443
92444
92445
92446
92447
92448
92449
92450
92451
92452
92453
92454
92455
92456
92457
92458
92459
92460
92461
92462
92463
92464
92465
92466
92467
92468
92469
92470
92471
92472
92473
92474
92475
92476
92477
92478
92479
92480
92481
92482
92483
92484
92485
92486
92487
92488
92489
92490
92491
92492
92493
92494
92495
92496
92497
92498
92499
92500
92501
92502
92503
92504
92505
92506
92507
92508
92509
92510
92511
92512
92513
92514
92515
92516
92517
92518
92519
92520
92521
92522
92523
92524
92525
92526
92527
92528
92529
92530
92531
92532
92533
92534
92535
92536
92537
92538
92539
92540
92541
92542
92543
92544
92545
92546
92547
92548
92549
92550
92551
92552
92553
92554
92555
92556
92557
92558
92559
92560
92561
92562
92563
92564
92565
92566
92567
92568
92569
92570
92571
92572
92573
92574
92575
92576
92577
92578
92579
92580
92581
92582
92583
92584
92585
92586
92587
92588
92589
92590
92591
92592
92593
92594
92595
92596
92597
92598
92599
92600
92601
92602
92603
92604
92605
92606
92607
92608
92609
92610
92611
92612
92613
92614
92615
92616
92617
92618
92619
92620
92621
92622
92623
92624
92625
92626
92627
92628
92629
92630
92631
92632
92633
92634
92635
92636
92637
92638
92639
92640
92641
92642
92643
92644
92645
92646
92647
92648
92649
92650
92651
92652
92653
92654
92655
92656
92657
92658
92659
92660
92661
92662
92663
92664
92665
92666
92667
92668
92669
92670
92671
92672
92673
92674
92675
92676
92677
92678
92679
92680
92681
92682
92683
92684
92685
92686
92687
92688
92689
92690
92691
92692
92693
92694
92695
92696
92697
92698
92699
92700
92701
92702
92703
92704
92705
92706
92707
92708
92709
92710
92711
92712
92713
92714
92715
92716
92717
92718
92719
92720
92721
92722
92723
92724
92725
92726
92727
92728
92729
92730
92731
92732
92733
92734
92735
92736
92737
92738
92739
92740
92741
92742
92743
92744
92745
92746
92747
92748
92749
92750
92751
92752
92753
92754
92755
92756
92757
92758
92759
92760
92761
92762
92763
92764
92765
92766
92767
92768
92769
92770
92771
92772
92773
92774
92775
92776
92777
92778
92779
92780
92781
92782
92783
92784
92785
92786
92787
92788
92789
92790
92791
92792
92793
92794
92795
92796
92797
92798
92799
92800
92801
92802
92803
92804
92805
92806
92807
92808
92809
92810
92811
92812
92813
92814
92815
92816
92817
92818
92819
92820
92821
92822
92823
92824
92825
92826
92827
92828
92829
92830
92831
92832
92833
92834
92835
92836
92837
92838
92839
92840
92841
92842
92843
92844
92845
92846
92847
92848
92849
92850
92851
92852
92853
92854
92855
92856
92857
92858
92859
92860
92861
92862
92863
92864
92865
92866
92867
92868
92869
92870
92871
92872
92873
92874
92875
92876
92877
92878
92879
92880
92881
92882
92883
92884
92885
92886
92887
92888
92889
92890
92891
92892
92893
92894
92895
92896
92897
92898
92899
92900
92901
92902
92903
92904
92905
92906
92907
92908
92909
92910
92911
92912
92913
92914
92915
92916
92917
92918
92919
92920
92921
92922
92923
92924
92925
92926
92927
92928
92929
92930
92931
92932
92933
92934
92935
92936
92937
92938
92939
92940
92941
92942
92943
92944
92945
92946
92947
92948
92949
92950
92951
92952
92953
92954
92955
92956
92957
92958
92959
92960
92961
92962
92963
92964
92965
92966
92967
92968
92969
92970
92971
92972
92973
92974
92975
92976
92977
92978
92979
92980
92981
92982
92983
92984
92985
92986
92987
92988
92989
92990
92991
92992
92993
92994
92995
92996
92997
92998
92999
93000
93001
93002
93003
93004
93005
93006
93007
93008
93009
93010
93011
93012
93013
93014
93015
93016
93017
93018
93019
93020
93021
93022
93023
93024
93025
93026
93027
93028
93029
93030
93031
93032
93033
93034
93035
93036
93037
93038
93039
93040
93041
93042
93043
93044
93045
93046
93047
93048
93049
93050
93051
93052
93053
93054
93055
93056
93057
93058
93059
93060
93061
93062
93063
93064
93065
93066
93067
93068
93069
93070
93071
93072
93073
93074
93075
93076
93077
93078
93079
93080
93081
93082
93083
93084
93085
93086
93087
93088
93089
93090
93091
93092
93093
93094
93095
93096
93097
93098
93099
93100
93101
93102
93103
93104
93105
93106
93107
93108
93109
93110
93111
93112
93113
93114
93115
93116
93117
93118
93119
93120
93121
93122
93123
93124
93125
93126
93127
93128
93129
93130
93131
93132
93133
93134
93135
93136
93137
93138
93139
93140
93141
93142
93143
93144
93145
93146
93147
93148
93149
93150
93151
93152
93153
93154
93155
93156
93157
93158
93159
93160
93161
93162
93163
93164
93165
93166
93167
93168
93169
93170
93171
93172
93173
93174
93175
93176
93177
93178
93179
93180
93181
93182
93183
93184
93185
93186
93187
93188
93189
93190
93191
93192
93193
93194
93195
93196
93197
93198
93199
93200
93201
93202
93203
93204
93205
93206
93207
93208
93209
93210
93211
93212
93213
93214
93215
93216
93217
93218
93219
93220
93221
93222
93223
93224
93225
93226
93227
93228
93229
93230
93231
93232
93233
93234
93235
93236
93237
93238
93239
93240
93241
93242
93243
93244
93245
93246
93247
93248
93249
93250
93251
93252
93253
93254
93255
93256
93257
93258
93259
93260
93261
93262
93263
93264
93265
93266
93267
93268
93269
93270
93271
93272
93273
93274
93275
93276
93277
93278
93279
93280
93281
93282
93283
93284
93285
93286
93287
93288
93289
93290
93291
93292
93293
93294
93295
93296
93297
93298
93299
93300
93301
93302
93303
93304
93305
93306
93307
93308
93309
93310
93311
93312
93313
93314
93315
93316
93317
93318
93319
93320
93321
93322
93323
93324
93325
93326
93327
93328
93329
93330
93331
93332
93333
93334
93335
93336
93337
93338
93339
93340
93341
93342
93343
93344
93345
93346
93347
93348
93349
93350
93351
93352
93353
93354
93355
93356
93357
93358
93359
93360
93361
93362
93363
93364
93365
93366
93367
93368
93369
93370
93371
93372
93373
93374
93375
93376
93377
93378
93379
93380
93381
93382
93383
93384
93385
93386
93387
93388
93389
93390
93391
93392
93393
93394
93395
93396
93397
93398
93399
93400
93401
93402
93403
93404
93405
93406
93407
93408
93409
93410
93411
93412
93413
93414
93415
93416
93417
93418
93419
93420
93421
93422
93423
93424
93425
93426
93427
93428
93429
93430
93431
93432
93433
93434
93435
93436
93437
93438
93439
93440
93441
93442
93443
93444
93445
93446
93447
93448
93449
93450
93451
93452
93453
93454
93455
93456
93457
93458
93459
93460
93461
93462
93463
93464
93465
93466
93467
93468
93469
93470
93471
93472
93473
93474
93475
93476
93477
93478
93479
93480
93481
93482
93483
93484
93485
93486
93487
93488
93489
93490
93491
93492
93493
93494
93495
93496
93497
93498
93499
93500
93501
93502
93503
93504
93505
93506
93507
93508
93509
93510
93511
93512
93513
93514
93515
93516
93517
93518
93519
93520
93521
93522
93523
93524
93525
93526
93527
93528
93529
93530
93531
93532
93533
93534
93535
93536
93537
93538
93539
93540
93541
93542
93543
93544
93545
93546
93547
93548
93549
93550
93551
93552
93553
93554
93555
93556
93557
93558
93559
93560
93561
93562
93563
93564
93565
93566
93567
93568
93569
93570
93571
93572
93573
93574
93575
93576
93577
93578
93579
93580
93581
93582
93583
93584
93585
93586
93587
93588
93589
93590
93591
93592
93593
93594
93595
93596
93597
93598
93599
93600
93601
93602
93603
93604
93605
93606
93607
93608
93609
93610
93611
93612
93613
93614
93615
93616
93617
93618
93619
93620
93621
93622
93623
93624
93625
93626
93627
93628
93629
93630
93631
93632
93633
93634
93635
93636
93637
93638
93639
93640
93641
93642
93643
93644
93645
93646
93647
93648
93649
93650
93651
93652
93653
93654
93655
93656
93657
93658
93659
93660
93661
93662
93663
93664
93665
93666
93667
93668
93669
93670
93671
93672
93673
93674
93675
93676
93677
93678
93679
93680
93681
93682
93683
93684
93685
93686
93687
93688
93689
93690
93691
93692
93693
93694
93695
93696
93697
93698
93699
93700
93701
93702
93703
93704
93705
93706
93707
93708
93709
93710
93711
93712
93713
93714
93715
93716
93717
93718
93719
93720
93721
93722
93723
93724
93725
93726
93727
93728
93729
93730
93731
93732
93733
93734
93735
93736
93737
93738
93739
93740
93741
93742
93743
93744
93745
93746
93747
93748
93749
93750
93751
93752
93753
93754
93755
93756
93757
93758
93759
93760
93761
93762
93763
93764
93765
93766
93767
93768
93769
93770
93771
93772
93773
93774
93775
93776
93777
93778
93779
93780
93781
93782
93783
93784
93785
93786
93787
93788
93789
93790
93791
93792
93793
93794
93795
93796
93797
93798
93799
93800
93801
93802
93803
93804
93805
93806
93807
93808
93809
93810
93811
93812
93813
93814
93815
93816
93817
93818
93819
93820
93821
93822
93823
93824
93825
93826
93827
93828
93829
93830
93831
93832
93833
93834
93835
93836
93837
93838
93839
93840
93841
93842
93843
93844
93845
93846
93847
93848
93849
93850
93851
93852
93853
93854
93855
93856
93857
93858
93859
93860
93861
93862
93863
93864
93865
93866
93867
93868
93869
93870
93871
93872
93873
93874
93875
93876
93877
93878
93879
93880
93881
93882
93883
93884
93885
93886
93887
93888
93889
93890
93891
93892
93893
93894
93895
93896
93897
93898
93899
93900
93901
93902
93903
93904
93905
93906
93907
93908
93909
93910
93911
93912
93913
93914
93915
93916
93917
93918
93919
93920
93921
93922
93923
93924
93925
93926
93927
93928
93929
93930
93931
93932
93933
93934
93935
93936
93937
93938
93939
93940
93941
93942
93943
93944
93945
93946
93947
93948
93949
93950
93951
93952
93953
93954
93955
93956
93957
93958
93959
93960
93961
93962
93963
93964
93965
93966
93967
93968
93969
93970
93971
93972
93973
93974
93975
93976
93977
93978
93979
93980
93981
93982
93983
93984
93985
93986
93987
93988
93989
93990
93991
93992
93993
93994
93995
93996
93997
93998
93999
94000
94001
94002
94003
94004
94005
94006
94007
94008
94009
94010
94011
94012
94013
94014
94015
94016
94017
94018
94019
94020
94021
94022
94023
94024
94025
94026
94027
94028
94029
94030
94031
94032
94033
94034
94035
94036
94037
94038
94039
94040
94041
94042
94043
94044
94045
94046
94047
94048
94049
94050
94051
94052
94053
94054
94055
94056
94057
94058
94059
94060
94061
94062
94063
94064
94065
94066
94067
94068
94069
94070
94071
94072
94073
94074
94075
94076
94077
94078
94079
94080
94081
94082
94083
94084
94085
94086
94087
94088
94089
94090
94091
94092
94093
94094
94095
94096
94097
94098
94099
94100
94101
94102
94103
94104
94105
94106
94107
94108
94109
94110
94111
94112
94113
94114
94115
94116
94117
94118
94119
94120
94121
94122
94123
94124
94125
94126
94127
94128
94129
94130
94131
94132
94133
94134
94135
94136
94137
94138
94139
94140
94141
94142
94143
94144
94145
94146
94147
94148
94149
94150
94151
94152
94153
94154
94155
94156
94157
94158
94159
94160
94161
94162
94163
94164
94165
94166
94167
94168
94169
94170
94171
94172
94173
94174
94175
94176
94177
94178
94179
94180
94181
94182
94183
94184
94185
94186
94187
94188
94189
94190
94191
94192
94193
94194
94195
94196
94197
94198
94199
94200
94201
94202
94203
94204
94205
94206
94207
94208
94209
94210
94211
94212
94213
94214
94215
94216
94217
94218
94219
94220
94221
94222
94223
94224
94225
94226
94227
94228
94229
94230
94231
94232
94233
94234
94235
94236
94237
94238
94239
94240
94241
94242
94243
94244
94245
94246
94247
94248
94249
94250
94251
94252
94253
94254
94255
94256
94257
94258
94259
94260
94261
94262
94263
94264
94265
94266
94267
94268
94269
94270
94271
94272
94273
94274
94275
94276
94277
94278
94279
94280
94281
94282
94283
94284
94285
94286
94287
94288
94289
94290
94291
94292
94293
94294
94295
94296
94297
94298
94299
94300
94301
94302
94303
94304
94305
94306
94307
94308
94309
94310
94311
94312
94313
94314
94315
94316
94317
94318
94319
94320
94321
94322
94323
94324
94325
94326
94327
94328
94329
94330
94331
94332
94333
94334
94335
94336
94337
94338
94339
94340
94341
94342
94343
94344
94345
94346
94347
94348
94349
94350
94351
94352
94353
94354
94355
94356
94357
94358
94359
94360
94361
94362
94363
94364
94365
94366
94367
94368
94369
94370
94371
94372
94373
94374
94375
94376
94377
94378
94379
94380
94381
94382
94383
94384
94385
94386
94387
94388
94389
94390
94391
94392
94393
94394
94395
94396
94397
94398
94399
94400
94401
94402
94403
94404
94405
94406
94407
94408
94409
94410
94411
94412
94413
94414
94415
94416
94417
94418
94419
94420
94421
94422
94423
94424
94425
94426
94427
94428
94429
94430
94431
94432
94433
94434
94435
94436
94437
94438
94439
94440
94441
94442
94443
94444
94445
94446
94447
94448
94449
94450
94451
94452
94453
94454
94455
94456
94457
94458
94459
94460
94461
94462
94463
94464
94465
94466
94467
94468
94469
94470
94471
94472
94473
94474
94475
94476
94477
94478
94479
94480
94481
94482
94483
94484
94485
94486
94487
94488
94489
94490
94491
94492
94493
94494
94495
94496
94497
94498
94499
94500
94501
94502
94503
94504
94505
94506
94507
94508
94509
94510
94511
94512
94513
94514
94515
94516
94517
94518
94519
94520
94521
94522
94523
94524
94525
94526
94527
94528
94529
94530
94531
94532
94533
94534
94535
94536
94537
94538
94539
94540
94541
94542
94543
94544
94545
94546
94547
94548
94549
94550
94551
94552
94553
94554
94555
94556
94557
94558
94559
94560
94561
94562
94563
94564
94565
94566
94567
94568
94569
94570
94571
94572
94573
94574
94575
94576
94577
94578
94579
94580
94581
94582
94583
94584
94585
94586
94587
94588
94589
94590
94591
94592
94593
94594
94595
94596
94597
94598
94599
94600
94601
94602
94603
94604
94605
94606
94607
94608
94609
94610
94611
94612
94613
94614
94615
94616
94617
94618
94619
94620
94621
94622
94623
94624
94625
94626
94627
94628
94629
94630
94631
94632
94633
94634
94635
94636
94637
94638
94639
94640
94641
94642
94643
94644
94645
94646
94647
94648
94649
94650
94651
94652
94653
94654
94655
94656
94657
94658
94659
94660
94661
94662
94663
94664
94665
94666
94667
94668
94669
94670
94671
94672
94673
94674
94675
94676
94677
94678
94679
94680
94681
94682
94683
94684
94685
94686
94687
94688
94689
94690
94691
94692
94693
94694
94695
94696
94697
94698
94699
94700
94701
94702
94703
94704
94705
94706
94707
94708
94709
94710
94711
94712
94713
94714
94715
94716
94717
94718
94719
94720
94721
94722
94723
94724
94725
94726
94727
94728
94729
94730
94731
94732
94733
94734
94735
94736
94737
94738
94739
94740
94741
94742
94743
94744
94745
94746
94747
94748
94749
94750
94751
94752
94753
94754
94755
94756
94757
94758
94759
94760
94761
94762
94763
94764
94765
94766
94767
94768
94769
94770
94771
94772
94773
94774
94775
94776
94777
94778
94779
94780
94781
94782
94783
94784
94785
94786
94787
94788
94789
94790
94791
94792
94793
94794
94795
94796
94797
94798
94799
94800
94801
94802
94803
94804
94805
94806
94807
94808
94809
94810
94811
94812
94813
94814
94815
94816
94817
94818
94819
94820
94821
94822
94823
94824
94825
94826
94827
94828
94829
94830
94831
94832
94833
94834
94835
94836
94837
94838
94839
94840
94841
94842
94843
94844
94845
94846
94847
94848
94849
94850
94851
94852
94853
94854
94855
94856
94857
94858
94859
94860
94861
94862
94863
94864
94865
94866
94867
94868
94869
94870
94871
94872
94873
94874
94875
94876
94877
94878
94879
94880
94881
94882
94883
94884
94885
94886
94887
94888
94889
94890
94891
94892
94893
94894
94895
94896
94897
94898
94899
94900
94901
94902
94903
94904
94905
94906
94907
94908
94909
94910
94911
94912
94913
94914
94915
94916
94917
94918
94919
94920
94921
94922
94923
94924
94925
94926
94927
94928
94929
94930
94931
94932
94933
94934
94935
94936
94937
94938
94939
94940
94941
94942
94943
94944
94945
94946
94947
94948
94949
94950
94951
94952
94953
94954
94955
94956
94957
94958
94959
94960
94961
94962
94963
94964
94965
94966
94967
94968
94969
94970
94971
94972
94973
94974
94975
94976
94977
94978
94979
94980
94981
94982
94983
94984
94985
94986
94987
94988
94989
94990
94991
94992
94993
94994
94995
94996
94997
94998
94999
95000
95001
95002
95003
95004
95005
95006
95007
95008
95009
95010
95011
95012
95013
95014
95015
95016
95017
95018
95019
95020
95021
95022
95023
95024
95025
95026
95027
95028
95029
95030
95031
95032
95033
95034
95035
95036
95037
95038
95039
95040
95041
95042
95043
95044
95045
95046
95047
95048
95049
95050
95051
95052
95053
95054
95055
95056
95057
95058
95059
95060
95061
95062
95063
95064
95065
95066
95067
95068
95069
95070
95071
95072
95073
95074
95075
95076
95077
95078
95079
95080
95081
95082
95083
95084
95085
95086
95087
95088
95089
95090
95091
95092
95093
95094
95095
95096
95097
95098
95099
95100
95101
95102
95103
95104
95105
95106
95107
95108
95109
95110
95111
95112
95113
95114
95115
95116
95117
95118
95119
95120
95121
95122
95123
95124
95125
95126
95127
95128
95129
95130
95131
95132
95133
95134
95135
95136
95137
95138
95139
95140
95141
95142
95143
95144
95145
95146
95147
95148
95149
95150
95151
95152
95153
95154
95155
95156
95157
95158
95159
95160
95161
95162
95163
95164
95165
95166
95167
95168
95169
95170
95171
95172
95173
95174
95175
95176
95177
95178
95179
95180
95181
95182
95183
95184
95185
95186
95187
95188
95189
95190
95191
95192
95193
95194
95195
95196
95197
95198
95199
95200
95201
95202
95203
95204
95205
95206
95207
95208
95209
95210
95211
95212
95213
95214
95215
95216
95217
95218
95219
95220
95221
95222
95223
95224
95225
95226
95227
95228
95229
95230
95231
95232
95233
95234
95235
95236
95237
95238
95239
95240
95241
95242
95243
95244
95245
95246
95247
95248
95249
95250
95251
95252
95253
95254
95255
95256
95257
95258
95259
95260
95261
95262
95263
95264
95265
95266
95267
95268
95269
95270
95271
95272
95273
95274
95275
95276
95277
95278
95279
95280
95281
95282
95283
95284
95285
95286
95287
95288
95289
95290
95291
95292
95293
95294
95295
95296
95297
95298
95299
95300
95301
95302
95303
95304
95305
95306
95307
95308
95309
95310
95311
95312
95313
95314
95315
95316
95317
95318
95319
95320
95321
95322
95323
95324
95325
95326
95327
95328
95329
95330
95331
95332
95333
95334
95335
95336
95337
95338
95339
95340
95341
95342
95343
95344
95345
95346
95347
95348
95349
95350
95351
95352
95353
95354
95355
95356
95357
95358
95359
95360
95361
95362
95363
95364
95365
95366
95367
95368
95369
95370
95371
95372
95373
95374
95375
95376
95377
95378
95379
95380
95381
95382
95383
95384
95385
95386
95387
95388
95389
95390
95391
95392
95393
95394
95395
95396
95397
95398
95399
95400
95401
95402
95403
95404
95405
95406
95407
95408
95409
95410
95411
95412
95413
95414
95415
95416
95417
95418
95419
95420
95421
95422
95423
95424
95425
95426
95427
95428
95429
95430
95431
95432
95433
95434
95435
95436
95437
95438
95439
95440
95441
95442
95443
95444
95445
95446
95447
95448
95449
95450
95451
95452
95453
95454
95455
95456
95457
95458
95459
95460
95461
95462
95463
95464
95465
95466
95467
95468
95469
95470
95471
95472
95473
95474
95475
95476
95477
95478
95479
95480
95481
95482
95483
95484
95485
95486
95487
95488
95489
95490
95491
95492
95493
95494
95495
95496
95497
95498
95499
95500
95501
95502
95503
95504
95505
95506
95507
95508
95509
95510
95511
95512
95513
95514
95515
95516
95517
95518
95519
95520
95521
95522
95523
95524
95525
95526
95527
95528
95529
95530
95531
95532
95533
95534
95535
95536
95537
95538
95539
95540
95541
95542
95543
95544
95545
95546
95547
95548
95549
95550
95551
95552
95553
95554
95555
95556
95557
95558
95559
95560
95561
95562
95563
95564
95565
95566
95567
95568
95569
95570
95571
95572
95573
95574
95575
95576
95577
95578
95579
95580
95581
95582
95583
95584
95585
95586
95587
95588
95589
95590
95591
95592
95593
95594
95595
95596
95597
95598
95599
95600
95601
95602
95603
95604
95605
95606
95607
95608
95609
95610
95611
95612
95613
95614
95615
95616
95617
95618
95619
95620
95621
95622
95623
95624
95625
95626
95627
95628
95629
95630
95631
95632
95633
95634
95635
95636
95637
95638
95639
95640
95641
95642
95643
95644
95645
95646
95647
95648
95649
95650
95651
95652
95653
95654
95655
95656
95657
95658
95659
95660
95661
95662
95663
95664
95665
95666
95667
95668
95669
95670
95671
95672
95673
95674
95675
95676
95677
95678
95679
95680
95681
95682
95683
95684
95685
95686
95687
95688
95689
95690
95691
95692
95693
95694
95695
95696
95697
95698
95699
95700
95701
95702
95703
95704
95705
95706
95707
95708
95709
95710
95711
95712
95713
95714
95715
95716
95717
95718
95719
95720
95721
95722
95723
95724
95725
95726
95727
95728
95729
95730
95731
95732
95733
95734
95735
95736
95737
95738
95739
95740
95741
95742
95743
95744
95745
95746
95747
95748
95749
95750
95751
95752
95753
95754
95755
95756
95757
95758
95759
95760
95761
95762
95763
95764
95765
95766
95767
95768
95769
95770
95771
95772
95773
95774
95775
95776
95777
95778
95779
95780
95781
95782
95783
95784
95785
95786
95787
95788
95789
95790
95791
95792
95793
95794
95795
95796
95797
95798
95799
95800
95801
95802
95803
95804
95805
95806
95807
95808
95809
95810
95811
95812
95813
95814
95815
95816
95817
95818
95819
95820
95821
95822
95823
95824
95825
95826
95827
95828
95829
95830
95831
95832
95833
95834
95835
95836
95837
95838
95839
95840
95841
95842
95843
95844
95845
95846
95847
95848
95849
95850
95851
95852
95853
95854
95855
95856
95857
95858
95859
95860
95861
95862
95863
95864
95865
95866
95867
95868
95869
95870
95871
95872
95873
95874
95875
95876
95877
95878
95879
95880
95881
95882
95883
95884
95885
95886
95887
95888
95889
95890
95891
95892
95893
95894
95895
95896
95897
95898
95899
95900
95901
95902
95903
95904
95905
95906
95907
95908
95909
95910
95911
95912
95913
95914
95915
95916
95917
95918
95919
95920
95921
95922
95923
95924
95925
95926
95927
95928
95929
95930
95931
95932
95933
95934
95935
95936
95937
95938
95939
95940
95941
95942
95943
95944
95945
95946
95947
95948
95949
95950
95951
95952
95953
95954
95955
95956
95957
95958
95959
95960
95961
95962
95963
95964
95965
95966
95967
95968
95969
95970
95971
95972
95973
95974
95975
95976
95977
95978
95979
95980
95981
95982
95983
95984
95985
95986
95987
95988
95989
95990
95991
95992
95993
95994
95995
95996
95997
95998
95999
96000
96001
96002
96003
96004
96005
96006
96007
96008
96009
96010
96011
96012
96013
96014
96015
96016
96017
96018
96019
96020
96021
96022
96023
96024
96025
96026
96027
96028
96029
96030
96031
96032
96033
96034
96035
96036
96037
96038
96039
96040
96041
96042
96043
96044
96045
96046
96047
96048
96049
96050
96051
96052
96053
96054
96055
96056
96057
96058
96059
96060
96061
96062
96063
96064
96065
96066
96067
96068
96069
96070
96071
96072
96073
96074
96075
96076
96077
96078
96079
96080
96081
96082
96083
96084
96085
96086
96087
96088
96089
96090
96091
96092
96093
96094
96095
96096
96097
96098
96099
96100
96101
96102
96103
96104
96105
96106
96107
96108
96109
96110
96111
96112
96113
96114
96115
96116
96117
96118
96119
96120
96121
96122
96123
96124
96125
96126
96127
96128
96129
96130
96131
96132
96133
96134
96135
96136
96137
96138
96139
96140
96141
96142
96143
96144
96145
96146
96147
96148
96149
96150
96151
96152
96153
96154
96155
96156
96157
96158
96159
96160
96161
96162
96163
96164
96165
96166
96167
96168
96169
96170
96171
96172
96173
96174
96175
96176
96177
96178
96179
96180
96181
96182
96183
96184
96185
96186
96187
96188
96189
96190
96191
96192
96193
96194
96195
96196
96197
96198
96199
96200
96201
96202
96203
96204
96205
96206
96207
96208
96209
96210
96211
96212
96213
96214
96215
96216
96217
96218
96219
96220
96221
96222
96223
96224
96225
96226
96227
96228
96229
96230
96231
96232
96233
96234
96235
96236
96237
96238
96239
96240
96241
96242
96243
96244
96245
96246
96247
96248
96249
96250
96251
96252
96253
96254
96255
96256
96257
96258
96259
96260
96261
96262
96263
96264
96265
96266
96267
96268
96269
96270
96271
96272
96273
96274
96275
96276
96277
96278
96279
96280
96281
96282
96283
96284
96285
96286
96287
96288
96289
96290
96291
96292
96293
96294
96295
96296
96297
96298
96299
96300
96301
96302
96303
96304
96305
96306
96307
96308
96309
96310
96311
96312
96313
96314
96315
96316
96317
96318
96319
96320
96321
96322
96323
96324
96325
96326
96327
96328
96329
96330
96331
96332
96333
96334
96335
96336
96337
96338
96339
96340
96341
96342
96343
96344
96345
96346
96347
96348
96349
96350
96351
96352
96353
96354
96355
96356
96357
96358
96359
96360
96361
96362
96363
96364
96365
96366
96367
96368
96369
96370
96371
96372
96373
96374
96375
96376
96377
96378
96379
96380
96381
96382
96383
96384
96385
96386
96387
96388
96389
96390
96391
96392
96393
96394
96395
96396
96397
96398
96399
96400
96401
96402
96403
96404
96405
96406
96407
96408
96409
96410
96411
96412
96413
96414
96415
96416
96417
96418
96419
96420
96421
96422
96423
96424
96425
96426
96427
96428
96429
96430
96431
96432
96433
96434
96435
96436
96437
96438
96439
96440
96441
96442
96443
96444
96445
96446
96447
96448
96449
96450
96451
96452
96453
96454
96455
96456
96457
96458
96459
96460
96461
96462
96463
96464
96465
96466
96467
96468
96469
96470
96471
96472
96473
96474
96475
96476
96477
96478
96479
96480
96481
96482
96483
96484
96485
96486
96487
96488
96489
96490
96491
96492
96493
96494
96495
96496
96497
96498
96499
96500
96501
96502
96503
96504
96505
96506
96507
96508
96509
96510
96511
96512
96513
96514
96515
96516
96517
96518
96519
96520
96521
96522
96523
96524
96525
96526
96527
96528
96529
96530
96531
96532
96533
96534
96535
96536
96537
96538
96539
96540
96541
96542
96543
96544
96545
96546
96547
96548
96549
96550
96551
96552
96553
96554
96555
96556
96557
96558
96559
96560
96561
96562
96563
96564
96565
96566
96567
96568
96569
96570
96571
96572
96573
96574
96575
96576
96577
96578
96579
96580
96581
96582
96583
96584
96585
96586
96587
96588
96589
96590
96591
96592
96593
96594
96595
96596
96597
96598
96599
96600
96601
96602
96603
96604
96605
96606
96607
96608
96609
96610
96611
96612
96613
96614
96615
96616
96617
96618
96619
96620
96621
96622
96623
96624
96625
96626
96627
96628
96629
96630
96631
96632
96633
96634
96635
96636
96637
96638
96639
96640
96641
96642
96643
96644
96645
96646
96647
96648
96649
96650
96651
96652
96653
96654
96655
96656
96657
96658
96659
96660
96661
96662
96663
96664
96665
96666
96667
96668
96669
96670
96671
96672
96673
96674
96675
96676
96677
96678
96679
96680
96681
96682
96683
96684
96685
96686
96687
96688
96689
96690
96691
96692
96693
96694
96695
96696
96697
96698
96699
96700
96701
96702
96703
96704
96705
96706
96707
96708
96709
96710
96711
96712
96713
96714
96715
96716
96717
96718
96719
96720
96721
96722
96723
96724
96725
96726
96727
96728
96729
96730
96731
96732
96733
96734
96735
96736
96737
96738
96739
96740
96741
96742
96743
96744
96745
96746
96747
96748
96749
96750
96751
96752
96753
96754
96755
96756
96757
96758
96759
96760
96761
96762
96763
96764
96765
96766
96767
96768
96769
96770
96771
96772
96773
96774
96775
96776
96777
96778
96779
96780
96781
96782
96783
96784
96785
96786
96787
96788
96789
96790
96791
96792
96793
96794
96795
96796
96797
96798
96799
96800
96801
96802
96803
96804
96805
96806
96807
96808
96809
96810
96811
96812
96813
96814
96815
96816
96817
96818
96819
96820
96821
96822
96823
96824
96825
96826
96827
96828
96829
96830
96831
96832
96833
96834
96835
96836
96837
96838
96839
96840
96841
96842
96843
96844
96845
96846
96847
96848
96849
96850
96851
96852
96853
96854
96855
96856
96857
96858
96859
96860
96861
96862
96863
96864
96865
96866
96867
96868
96869
96870
96871
96872
96873
96874
96875
96876
96877
96878
96879
96880
96881
96882
96883
96884
96885
96886
96887
96888
96889
96890
96891
96892
96893
96894
96895
96896
96897
96898
96899
96900
96901
96902
96903
96904
96905
96906
96907
96908
96909
96910
96911
96912
96913
96914
96915
96916
96917
96918
96919
96920
96921
96922
96923
96924
96925
96926
96927
96928
96929
96930
96931
96932
96933
96934
96935
96936
96937
96938
96939
96940
96941
96942
96943
96944
96945
96946
96947
96948
96949
96950
96951
96952
96953
96954
96955
96956
96957
96958
96959
96960
96961
96962
96963
96964
96965
96966
96967
96968
96969
96970
96971
96972
96973
96974
96975
96976
96977
96978
96979
96980
96981
96982
96983
96984
96985
96986
96987
96988
96989
96990
96991
96992
96993
96994
96995
96996
96997
96998
96999
97000
97001
97002
97003
97004
97005
97006
97007
97008
97009
97010
97011
97012
97013
97014
97015
97016
97017
97018
97019
97020
97021
97022
97023
97024
97025
97026
97027
97028
97029
97030
97031
97032
97033
97034
97035
97036
97037
97038
97039
97040
97041
97042
97043
97044
97045
97046
97047
97048
97049
97050
97051
97052
97053
97054
97055
97056
97057
97058
97059
97060
97061
97062
97063
97064
97065
97066
97067
97068
97069
97070
97071
97072
97073
97074
97075
97076
97077
97078
97079
97080
97081
97082
97083
97084
97085
97086
97087
97088
97089
97090
97091
97092
97093
97094
97095
97096
97097
97098
97099
97100
97101
97102
97103
97104
97105
97106
97107
97108
97109
97110
97111
97112
97113
97114
97115
97116
97117
97118
97119
97120
97121
97122
97123
97124
97125
97126
97127
97128
97129
97130
97131
97132
97133
97134
97135
97136
97137
97138
97139
97140
97141
97142
97143
97144
97145
97146
97147
97148
97149
97150
97151
97152
97153
97154
97155
97156
97157
97158
97159
97160
97161
97162
97163
97164
97165
97166
97167
97168
97169
97170
97171
97172
97173
97174
97175
97176
97177
97178
97179
97180
97181
97182
97183
97184
97185
97186
97187
97188
97189
97190
97191
97192
97193
97194
97195
97196
97197
97198
97199
97200
97201
97202
97203
97204
97205
97206
97207
97208
97209
97210
97211
97212
97213
97214
97215
97216
97217
97218
97219
97220
97221
97222
97223
97224
97225
97226
97227
97228
97229
97230
97231
97232
97233
97234
97235
97236
97237
97238
97239
97240
97241
97242
97243
97244
97245
97246
97247
97248
97249
97250
97251
97252
97253
97254
97255
97256
97257
97258
97259
97260
97261
97262
97263
97264
97265
97266
97267
97268
97269
97270
97271
97272
97273
97274
97275
97276
97277
97278
97279
97280
97281
97282
97283
97284
97285
97286
97287
97288
97289
97290
97291
97292
97293
97294
97295
97296
97297
97298
97299
97300
97301
97302
97303
97304
97305
97306
97307
97308
97309
97310
97311
97312
97313
97314
97315
97316
97317
97318
97319
97320
97321
97322
97323
97324
97325
97326
97327
97328
97329
97330
97331
97332
97333
97334
97335
97336
97337
97338
97339
97340
97341
97342
97343
97344
97345
97346
97347
97348
97349
97350
97351
97352
97353
97354
97355
97356
97357
97358
97359
97360
97361
97362
97363
97364
97365
97366
97367
97368
97369
97370
97371
97372
97373
97374
97375
97376
97377
97378
97379
97380
97381
97382
97383
97384
97385
97386
97387
97388
97389
97390
97391
97392
97393
97394
97395
97396
97397
97398
97399
97400
97401
97402
97403
97404
97405
97406
97407
97408
97409
97410
97411
97412
97413
97414
97415
97416
97417
97418
97419
97420
97421
97422
97423
97424
97425
97426
97427
97428
97429
97430
97431
97432
97433
97434
97435
97436
97437
97438
97439
97440
97441
97442
97443
97444
97445
97446
97447
97448
97449
97450
97451
97452
97453
97454
97455
97456
97457
97458
97459
97460
97461
97462
97463
97464
97465
97466
97467
97468
97469
97470
97471
97472
97473
97474
97475
97476
97477
97478
97479
97480
97481
97482
97483
97484
97485
97486
97487
97488
97489
97490
97491
97492
97493
97494
97495
97496
97497
97498
97499
97500
97501
97502
97503
97504
97505
97506
97507
97508
97509
97510
97511
97512
97513
97514
97515
97516
97517
97518
97519
97520
97521
97522
97523
97524
97525
97526
97527
97528
97529
97530
97531
97532
97533
97534
97535
97536
97537
97538
97539
97540
97541
97542
97543
97544
97545
97546
97547
97548
97549
97550
97551
97552
97553
97554
97555
97556
97557
97558
97559
97560
97561
97562
97563
97564
97565
97566
97567
97568
97569
97570
97571
97572
97573
97574
97575
97576
97577
97578
97579
97580
97581
97582
97583
97584
97585
97586
97587
97588
97589
97590
97591
97592
97593
97594
97595
97596
97597
97598
97599
97600
97601
97602
97603
97604
97605
97606
97607
97608
97609
97610
97611
97612
97613
97614
97615
97616
97617
97618
97619
97620
97621
97622
97623
97624
97625
97626
97627
97628
97629
97630
97631
97632
97633
97634
97635
97636
97637
97638
97639
97640
97641
97642
97643
97644
97645
97646
97647
97648
97649
97650
97651
97652
97653
97654
97655
97656
97657
97658
97659
97660
97661
97662
97663
97664
97665
97666
97667
97668
97669
97670
97671
97672
97673
97674
97675
97676
97677
97678
97679
97680
97681
97682
97683
97684
97685
97686
97687
97688
97689
97690
97691
97692
97693
97694
97695
97696
97697
97698
97699
97700
97701
97702
97703
97704
97705
97706
97707
97708
97709
97710
97711
97712
97713
97714
97715
97716
97717
97718
97719
97720
97721
97722
97723
97724
97725
97726
97727
97728
97729
97730
97731
97732
97733
97734
97735
97736
97737
97738
97739
97740
97741
97742
97743
97744
97745
97746
97747
97748
97749
97750
97751
97752
97753
97754
97755
97756
97757
97758
97759
97760
97761
97762
97763
97764
97765
97766
97767
97768
97769
97770
97771
97772
97773
97774
97775
97776
97777
97778
97779
97780
97781
97782
97783
97784
97785
97786
97787
97788
97789
97790
97791
97792
97793
97794
97795
97796
97797
97798
97799
97800
97801
97802
97803
97804
97805
97806
97807
97808
97809
97810
97811
97812
97813
97814
97815
97816
97817
97818
97819
97820
97821
97822
97823
97824
97825
97826
97827
97828
97829
97830
97831
97832
97833
97834
97835
97836
97837
97838
97839
97840
97841
97842
97843
97844
97845
97846
97847
97848
97849
97850
97851
97852
97853
97854
97855
97856
97857
97858
97859
97860
97861
97862
97863
97864
97865
97866
97867
97868
97869
97870
97871
97872
97873
97874
97875
97876
97877
97878
97879
97880
97881
97882
97883
97884
97885
97886
97887
97888
97889
97890
97891
97892
97893
97894
97895
97896
97897
97898
97899
97900
97901
97902
97903
97904
97905
97906
97907
97908
97909
97910
97911
97912
97913
97914
97915
97916
97917
97918
97919
97920
97921
97922
97923
97924
97925
97926
97927
97928
97929
97930
97931
97932
97933
97934
97935
97936
97937
97938
97939
97940
97941
97942
97943
97944
97945
97946
97947
97948
97949
97950
97951
97952
97953
97954
97955
97956
97957
97958
97959
97960
97961
97962
97963
97964
97965
97966
97967
97968
97969
97970
97971
97972
97973
97974
97975
97976
97977
97978
97979
97980
97981
97982
97983
97984
97985
97986
97987
97988
97989
97990
97991
97992
97993
97994
97995
97996
97997
97998
97999
98000
98001
98002
98003
98004
98005
98006
98007
98008
98009
98010
98011
98012
98013
98014
98015
98016
98017
98018
98019
98020
98021
98022
98023
98024
98025
98026
98027
98028
98029
98030
98031
98032
98033
98034
98035
98036
98037
98038
98039
98040
98041
98042
98043
98044
98045
98046
98047
98048
98049
98050
98051
98052
98053
98054
98055
98056
98057
98058
98059
98060
98061
98062
98063
98064
98065
98066
98067
98068
98069
98070
98071
98072
98073
98074
98075
98076
98077
98078
98079
98080
98081
98082
98083
98084
98085
98086
98087
98088
98089
98090
98091
98092
98093
98094
98095
98096
98097
98098
98099
98100
98101
98102
98103
98104
98105
98106
98107
98108
98109
98110
98111
98112
98113
98114
98115
98116
98117
98118
98119
98120
98121
98122
98123
98124
98125
98126
98127
98128
98129
98130
98131
98132
98133
98134
98135
98136
98137
98138
98139
98140
98141
98142
98143
98144
98145
98146
98147
98148
98149
98150
98151
98152
98153
98154
98155
98156
98157
98158
98159
98160
98161
98162
98163
98164
98165
98166
98167
98168
98169
98170
98171
98172
98173
98174
98175
98176
98177
98178
98179
98180
98181
98182
98183
98184
98185
98186
98187
98188
98189
98190
98191
98192
98193
98194
98195
98196
98197
98198
98199
98200
98201
98202
98203
98204
98205
98206
98207
98208
98209
98210
98211
98212
98213
98214
98215
98216
98217
98218
98219
98220
98221
98222
98223
98224
98225
98226
98227
98228
98229
98230
98231
98232
98233
98234
98235
98236
98237
98238
98239
98240
98241
98242
98243
98244
98245
98246
98247
98248
98249
98250
98251
98252
98253
98254
98255
98256
98257
98258
98259
98260
98261
98262
98263
98264
98265
98266
98267
98268
98269
98270
98271
98272
98273
98274
98275
98276
98277
98278
98279
98280
98281
98282
98283
98284
98285
98286
98287
98288
98289
98290
98291
98292
98293
98294
98295
98296
98297
98298
98299
98300
98301
98302
98303
98304
98305
98306
98307
98308
98309
98310
98311
98312
98313
98314
98315
98316
98317
98318
98319
98320
98321
98322
98323
98324
98325
98326
98327
98328
98329
98330
98331
98332
98333
98334
98335
98336
98337
98338
98339
98340
98341
98342
98343
98344
98345
98346
98347
98348
98349
98350
98351
98352
98353
98354
98355
98356
98357
98358
98359
98360
98361
98362
98363
98364
98365
98366
98367
98368
98369
98370
98371
98372
98373
98374
98375
98376
98377
98378
98379
98380
98381
98382
98383
98384
98385
98386
98387
98388
98389
98390
98391
98392
98393
98394
98395
98396
98397
98398
98399
98400
98401
98402
98403
98404
98405
98406
98407
98408
98409
98410
98411
98412
98413
98414
98415
98416
98417
98418
98419
98420
98421
98422
98423
98424
98425
98426
98427
98428
98429
98430
98431
98432
98433
98434
98435
98436
98437
98438
98439
98440
98441
98442
98443
98444
98445
98446
98447
98448
98449
98450
98451
98452
98453
98454
98455
98456
98457
98458
98459
98460
98461
98462
98463
98464
98465
98466
98467
98468
98469
98470
98471
98472
98473
98474
98475
98476
98477
98478
98479
98480
98481
98482
98483
98484
98485
98486
98487
98488
98489
98490
98491
98492
98493
98494
98495
98496
98497
98498
98499
98500
98501
98502
98503
98504
98505
98506
98507
98508
98509
98510
98511
98512
98513
98514
98515
98516
98517
98518
98519
98520
98521
98522
98523
98524
98525
98526
98527
98528
98529
98530
98531
98532
98533
98534
98535
98536
98537
98538
98539
98540
98541
98542
98543
98544
98545
98546
98547
98548
98549
98550
98551
98552
98553
98554
98555
98556
98557
98558
98559
98560
98561
98562
98563
98564
98565
98566
98567
98568
98569
98570
98571
98572
98573
98574
98575
98576
98577
98578
98579
98580
98581
98582
98583
98584
98585
98586
98587
98588
98589
98590
98591
98592
98593
98594
98595
98596
98597
98598
98599
98600
98601
98602
98603
98604
98605
98606
98607
98608
98609
98610
98611
98612
98613
98614
98615
98616
98617
98618
98619
98620
98621
98622
98623
98624
98625
98626
98627
98628
98629
98630
98631
98632
98633
98634
98635
98636
98637
98638
98639
98640
98641
98642
98643
98644
98645
98646
98647
98648
98649
98650
98651
98652
98653
98654
98655
98656
98657
98658
98659
98660
98661
98662
98663
98664
98665
98666
98667
98668
98669
98670
98671
98672
98673
98674
98675
98676
98677
98678
98679
98680
98681
98682
98683
98684
98685
98686
98687
98688
98689
98690
98691
98692
98693
98694
98695
98696
98697
98698
98699
98700
98701
98702
98703
98704
98705
98706
98707
98708
98709
98710
98711
98712
98713
98714
98715
98716
98717
98718
98719
98720
98721
98722
98723
98724
98725
98726
98727
98728
98729
98730
98731
98732
98733
98734
98735
98736
98737
98738
98739
98740
98741
98742
98743
98744
98745
98746
98747
98748
98749
98750
98751
98752
98753
98754
98755
98756
98757
98758
98759
98760
98761
98762
98763
98764
98765
98766
98767
98768
98769
98770
98771
98772
98773
98774
98775
98776
98777
98778
98779
98780
98781
98782
98783
98784
98785
98786
98787
98788
98789
98790
98791
98792
98793
98794
98795
98796
98797
98798
98799
98800
98801
98802
98803
98804
98805
98806
98807
98808
98809
98810
98811
98812
98813
98814
98815
98816
98817
98818
98819
98820
98821
98822
98823
98824
98825
98826
98827
98828
98829
98830
98831
98832
98833
98834
98835
98836
98837
98838
98839
98840
98841
98842
98843
98844
98845
98846
98847
98848
98849
98850
98851
98852
98853
98854
98855
98856
98857
98858
98859
98860
98861
98862
98863
98864
98865
98866
98867
98868
98869
98870
98871
98872
98873
98874
98875
98876
98877
98878
98879
98880
98881
98882
98883
98884
98885
98886
98887
98888
98889
98890
98891
98892
98893
98894
98895
98896
98897
98898
98899
98900
98901
98902
98903
98904
98905
98906
98907
98908
98909
98910
98911
98912
98913
98914
98915
98916
98917
98918
98919
98920
98921
98922
98923
98924
98925
98926
98927
98928
98929
98930
98931
98932
98933
98934
98935
98936
98937
98938
98939
98940
98941
98942
98943
98944
98945
98946
98947
98948
98949
98950
98951
98952
98953
98954
98955
98956
98957
98958
98959
98960
98961
98962
98963
98964
98965
98966
98967
98968
98969
98970
98971
98972
98973
98974
98975
98976
98977
98978
98979
98980
98981
98982
98983
98984
98985
98986
98987
98988
98989
98990
98991
98992
98993
98994
98995
98996
98997
98998
98999
99000
99001
99002
99003
99004
99005
99006
99007
99008
99009
99010
99011
99012
99013
99014
99015
99016
99017
99018
99019
99020
99021
99022
99023
99024
99025
99026
99027
99028
99029
99030
99031
99032
99033
99034
99035
99036
99037
99038
99039
99040
99041
99042
99043
99044
99045
99046
99047
99048
99049
99050
99051
99052
99053
99054
99055
99056
99057
99058
99059
99060
99061
99062
99063
99064
99065
99066
99067
99068
99069
99070
99071
99072
99073
99074
99075
99076
99077
99078
99079
99080
99081
99082
99083
99084
99085
99086
99087
99088
99089
99090
99091
99092
99093
99094
99095
99096
99097
99098
99099
99100
99101
99102
99103
99104
99105
99106
99107
99108
99109
99110
99111
99112
99113
99114
99115
99116
99117
99118
99119
99120
99121
99122
99123
99124
99125
99126
99127
99128
99129
99130
99131
99132
99133
99134
99135
99136
99137
99138
99139
99140
99141
99142
99143
99144
99145
99146
99147
99148
99149
99150
99151
99152
99153
99154
99155
99156
99157
99158
99159
99160
99161
99162
99163
99164
99165
99166
99167
99168
99169
99170
99171
99172
99173
99174
99175
99176
99177
99178
99179
99180
99181
99182
99183
99184
99185
99186
99187
99188
99189
99190
99191
99192
99193
99194
99195
99196
99197
99198
99199
99200
99201
99202
99203
99204
99205
99206
99207
99208
99209
99210
99211
99212
99213
99214
99215
99216
99217
99218
99219
99220
99221
99222
99223
99224
99225
99226
99227
99228
99229
99230
99231
99232
99233
99234
99235
99236
99237
99238
99239
99240
99241
99242
99243
99244
99245
99246
99247
99248
99249
99250
99251
99252
99253
99254
99255
99256
99257
99258
99259
99260
99261
99262
99263
99264
99265
99266
99267
99268
99269
99270
99271
99272
99273
99274
99275
99276
99277
99278
99279
99280
99281
99282
99283
99284
99285
99286
99287
99288
99289
99290
99291
99292
99293
99294
99295
99296
99297
99298
99299
99300
99301
99302
99303
99304
99305
99306
99307
99308
99309
99310
99311
99312
99313
99314
99315
99316
99317
99318
99319
99320
99321
99322
99323
99324
99325
99326
99327
99328
99329
99330
99331
99332
99333
99334
99335
99336
99337
99338
99339
99340
99341
99342
99343
99344
99345
99346
99347
99348
99349
99350
99351
99352
99353
99354
99355
99356
99357
99358
99359
99360
99361
99362
99363
99364
99365
99366
99367
99368
99369
99370
99371
99372
99373
99374
99375
99376
99377
99378
99379
99380
99381
99382
99383
99384
99385
99386
99387
99388
99389
99390
99391
99392
99393
99394
99395
99396
99397
99398
99399
99400
99401
99402
99403
99404
99405
99406
99407
99408
99409
99410
99411
99412
99413
99414
99415
99416
99417
99418
99419
99420
99421
99422
99423
99424
99425
99426
99427
99428
99429
99430
99431
99432
99433
99434
99435
99436
99437
99438
99439
99440
99441
99442
99443
99444
99445
99446
99447
99448
99449
99450
99451
99452
99453
99454
99455
99456
99457
99458
99459
99460
99461
99462
99463
99464
99465
99466
99467
99468
99469
99470
99471
99472
99473
99474
99475
99476
99477
99478
99479
99480
99481
99482
99483
99484
99485
99486
99487
99488
99489
99490
99491
99492
99493
99494
99495
99496
99497
99498
99499
99500
99501
99502
99503
99504
99505
99506
99507
99508
99509
99510
99511
99512
99513
99514
99515
99516
99517
99518
99519
99520
99521
99522
99523
99524
99525
99526
99527
99528
99529
99530
99531
99532
99533
99534
99535
99536
99537
99538
99539
99540
99541
99542
99543
99544
99545
99546
99547
99548
99549
99550
99551
99552
99553
99554
99555
99556
99557
99558
99559
99560
99561
99562
99563
99564
99565
99566
99567
99568
99569
99570
99571
99572
99573
99574
99575
99576
99577
99578
99579
99580
99581
99582
99583
99584
99585
99586
99587
99588
99589
99590
99591
99592
99593
99594
99595
99596
99597
99598
99599
99600
99601
99602
99603
99604
99605
99606
99607
99608
99609
99610
99611
99612
99613
99614
99615
99616
99617
99618
99619
99620
99621
99622
99623
99624
99625
99626
99627
99628
99629
99630
99631
99632
99633
99634
99635
99636
99637
99638
99639
99640
99641
99642
99643
99644
99645
99646
99647
99648
99649
99650
99651
99652
99653
99654
99655
99656
99657
99658
99659
99660
99661
99662
99663
99664
99665
99666
99667
99668
99669
99670
99671
99672
99673
99674
99675
99676
99677
99678
99679
99680
99681
99682
99683
99684
99685
99686
99687
99688
99689
99690
99691
99692
99693
99694
99695
99696
99697
99698
99699
99700
99701
99702
99703
99704
99705
99706
99707
99708
99709
99710
99711
99712
99713
99714
99715
99716
99717
99718
99719
99720
99721
99722
99723
99724
99725
99726
99727
99728
99729
99730
99731
99732
99733
99734
99735
99736
99737
99738
99739
99740
99741
99742
99743
99744
99745
99746
99747
99748
99749
99750
99751
99752
99753
99754
99755
99756
99757
99758
99759
99760
99761
99762
99763
99764
99765
99766
99767
99768
99769
99770
99771
99772
99773
99774
99775
99776
99777
99778
99779
99780
99781
99782
99783
99784
99785
99786
99787
99788
99789
99790
99791
99792
99793
99794
99795
99796
99797
99798
99799
99800
99801
99802
99803
99804
99805
99806
99807
99808
99809
99810
99811
99812
99813
99814
99815
99816
99817
99818
99819
99820
99821
99822
99823
99824
99825
99826
99827
99828
99829
99830
99831
99832
99833
99834
99835
99836
99837
99838
99839
99840
99841
99842
99843
99844
99845
99846
99847
99848
99849
99850
99851
99852
99853
99854
99855
99856
99857
99858
99859
99860
99861
99862
99863
99864
99865
99866
99867
99868
99869
99870
99871
99872
99873
99874
99875
99876
99877
99878
99879
99880
99881
99882
99883
99884
99885
99886
99887
99888
99889
99890
99891
99892
99893
99894
99895
99896
99897
99898
99899
99900
99901
99902
99903
99904
99905
99906
99907
99908
99909
99910
99911
99912
99913
99914
99915
99916
99917
99918
99919
99920
99921
99922
99923
99924
99925
99926
99927
99928
99929
99930
99931
99932
99933
99934
99935
99936
99937
99938
99939
99940
99941
99942
99943
99944
99945
99946
99947
99948
99949
99950
99951
99952
99953
99954
99955
99956
99957
99958
99959
99960
99961
99962
99963
99964
99965
99966
99967
99968
99969
99970
99971
99972
99973
99974
99975
99976
99977
99978
99979
99980
99981
99982
99983
99984
99985
99986
99987
99988
99989
99990
99991
99992
99993
99994
99995
99996
99997
99998
99999
100000
100001
100002
100003
100004
100005
100006
100007
100008
100009
100010
100011
100012
100013
100014
100015
100016
100017
100018
100019
100020
100021
100022
100023
100024
100025
100026
100027
100028
100029
100030
100031
100032
100033
100034
100035
100036
100037
100038
100039
100040
100041
100042
100043
100044
100045
100046
100047
100048
100049
100050
100051
100052
100053
100054
100055
100056
100057
100058
100059
100060
100061
100062
100063
100064
100065
100066
100067
100068
100069
100070
100071
100072
100073
100074
100075
100076
100077
100078
100079
100080
100081
100082
100083
100084
100085
100086
100087
100088
100089
100090
100091
100092
100093
100094
100095
100096
100097
100098
100099
100100
100101
100102
100103
100104
100105
100106
100107
100108
100109
100110
100111
100112
100113
100114
100115
100116
100117
100118
100119
100120
100121
100122
100123
100124
100125
100126
100127
100128
100129
100130
100131
100132
100133
100134
100135
100136
100137
100138
100139
100140
100141
100142
100143
100144
100145
100146
100147
100148
100149
100150
100151
100152
100153
100154
100155
100156
100157
100158
100159
100160
100161
100162
100163
100164
100165
100166
100167
100168
100169
100170
100171
100172
100173
100174
100175
100176
100177
100178
100179
100180
100181
100182
100183
100184
100185
100186
100187
100188
100189
100190
100191
100192
100193
100194
100195
100196
100197
100198
100199
100200
100201
100202
100203
100204
100205
100206
100207
100208
100209
100210
100211
100212
100213
100214
100215
100216
100217
100218
100219
100220
100221
100222
100223
100224
100225
100226
100227
100228
100229
100230
100231
100232
100233
100234
100235
100236
100237
100238
100239
100240
100241
100242
100243
100244
100245
100246
100247
100248
100249
100250
100251
100252
100253
100254
100255
100256
100257
100258
100259
100260
100261
100262
100263
100264
100265
100266
100267
100268
100269
100270
100271
100272
100273
100274
100275
100276
100277
100278
100279
100280
100281
100282
100283
100284
100285
100286
100287
100288
100289
100290
100291
100292
100293
100294
100295
100296
100297
100298
100299
100300
100301
100302
100303
100304
100305
100306
100307
100308
100309
100310
100311
100312
100313
100314
100315
100316
100317
100318
100319
100320
100321
100322
100323
100324
100325
100326
100327
100328
100329
100330
100331
100332
100333
100334
100335
100336
100337
100338
100339
100340
100341
100342
100343
100344
100345
100346
100347
100348
100349
100350
100351
100352
100353
100354
100355
100356
100357
100358
100359
100360
100361
100362
100363
100364
100365
100366
100367
100368
100369
100370
100371
100372
100373
100374
100375
100376
100377
100378
100379
100380
100381
100382
100383
100384
100385
100386
100387
100388
100389
100390
100391
100392
100393
100394
100395
100396
100397
100398
100399
100400
100401
100402
100403
100404
100405
100406
100407
100408
100409
100410
100411
100412
100413
100414
100415
100416
100417
100418
100419
100420
100421
100422
100423
100424
100425
100426
100427
100428
100429
100430
100431
100432
100433
100434
100435
100436
100437
100438
100439
100440
100441
100442
100443
100444
100445
100446
100447
100448
100449
100450
100451
100452
100453
100454
100455
100456
100457
100458
100459
100460
100461
100462
100463
100464
100465
100466
100467
100468
100469
100470
100471
100472
100473
100474
100475
100476
100477
100478
100479
100480
100481
100482
100483
100484
100485
100486
100487
100488
100489
100490
100491
100492
100493
100494
100495
100496
100497
100498
100499
100500
100501
100502
100503
100504
100505
100506
100507
100508
100509
100510
100511
100512
100513
100514
100515
100516
100517
100518
100519
100520
100521
100522
100523
100524
100525
100526
100527
100528
100529
100530
100531
100532
100533
100534
100535
100536
100537
100538
100539
100540
100541
100542
100543
100544
100545
100546
100547
100548
100549
100550
100551
100552
100553
100554
100555
100556
100557
100558
100559
100560
100561
100562
100563
100564
100565
100566
100567
100568
100569
100570
100571
100572
100573
100574
100575
100576
100577
100578
100579
100580
100581
100582
100583
100584
100585
100586
100587
100588
100589
100590
100591
100592
100593
100594
100595
100596
100597
100598
100599
100600
100601
100602
100603
100604
100605
100606
100607
100608
100609
100610
100611
100612
100613
100614
100615
100616
100617
100618
100619
100620
100621
100622
100623
100624
100625
100626
100627
100628
100629
100630
100631
100632
100633
100634
100635
100636
100637
100638
100639
100640
100641
100642
100643
100644
100645
100646
100647
100648
100649
100650
100651
100652
100653
100654
100655
100656
100657
100658
100659
100660
100661
100662
100663
100664
100665
100666
100667
100668
100669
100670
100671
100672
100673
100674
100675
100676
100677
100678
100679
100680
100681
100682
100683
100684
100685
100686
100687
100688
100689
100690
100691
100692
100693
100694
100695
100696
100697
100698
100699
100700
100701
100702
100703
100704
100705
100706
100707
100708
100709
100710
100711
100712
100713
100714
100715
100716
100717
100718
100719
100720
100721
100722
100723
100724
100725
100726
100727
100728
100729
100730
100731
100732
100733
100734
100735
100736
100737
100738
100739
100740
100741
100742
100743
100744
100745
100746
100747
100748
100749
100750
100751
100752
100753
100754
100755
100756
100757
100758
100759
100760
100761
100762
100763
100764
100765
100766
100767
100768
100769
100770
100771
100772
100773
100774
100775
100776
100777
100778
100779
100780
100781
100782
100783
100784
100785
100786
100787
100788
100789
100790
100791
100792
100793
100794
100795
100796
100797
100798
100799
100800
100801
100802
100803
100804
100805
100806
100807
100808
100809
100810
100811
100812
100813
100814
100815
100816
100817
100818
100819
100820
100821
100822
100823
100824
100825
100826
100827
100828
100829
100830
100831
100832
100833
100834
100835
100836
100837
100838
100839
100840
100841
100842
100843
100844
100845
100846
100847
100848
100849
100850
100851
100852
100853
100854
100855
100856
100857
100858
100859
100860
100861
100862
100863
100864
100865
100866
100867
100868
100869
100870
100871
100872
100873
100874
100875
100876
100877
100878
100879
100880
100881
100882
100883
100884
100885
100886
100887
100888
100889
100890
100891
100892
100893
100894
100895
100896
100897
100898
100899
100900
100901
100902
100903
100904
100905
100906
100907
100908
100909
100910
100911
100912
100913
100914
100915
100916
100917
100918
100919
100920
100921
100922
100923
100924
100925
100926
100927
100928
100929
100930
100931
100932
100933
100934
100935
100936
100937
100938
100939
100940
100941
100942
100943
100944
100945
100946
100947
100948
100949
100950
100951
100952
100953
100954
100955
100956
100957
100958
100959
100960
100961
100962
100963
100964
100965
100966
100967
100968
100969
100970
100971
100972
100973
100974
100975
100976
100977
100978
100979
100980
100981
100982
100983
100984
100985
100986
100987
100988
100989
100990
100991
100992
100993
100994
100995
100996
100997
100998
100999
101000
101001
101002
101003
101004
101005
101006
101007
101008
101009
101010
101011
101012
101013
101014
101015
101016
101017
101018
101019
101020
101021
101022
101023
101024
101025
101026
101027
101028
101029
101030
101031
101032
101033
101034
101035
101036
101037
101038
101039
101040
101041
101042
101043
101044
101045
101046
101047
101048
101049
101050
101051
101052
101053
101054
101055
101056
101057
101058
101059
101060
101061
101062
101063
101064
101065
101066
101067
101068
101069
101070
101071
101072
101073
101074
101075
101076
101077
101078
101079
101080
101081
101082
101083
101084
101085
101086
101087
101088
101089
101090
101091
101092
101093
101094
101095
101096
101097
101098
101099
101100
101101
101102
101103
101104
101105
101106
101107
101108
101109
101110
101111
101112
101113
101114
101115
101116
101117
101118
101119
101120
101121
101122
101123
101124
101125
101126
101127
101128
101129
101130
101131
101132
101133
101134
101135
101136
101137
101138
101139
101140
101141
101142
101143
101144
101145
101146
101147
101148
101149
101150
101151
101152
101153
101154
101155
101156
101157
101158
101159
101160
101161
101162
101163
101164
101165
101166
101167
101168
101169
101170
101171
101172
101173
101174
101175
101176
101177
101178
101179
101180
101181
101182
101183
101184
101185
101186
101187
101188
101189
101190
101191
101192
101193
101194
101195
101196
101197
101198
101199
101200
101201
101202
101203
101204
101205
101206
101207
101208
101209
101210
101211
101212
101213
101214
101215
101216
101217
101218
101219
101220
101221
101222
101223
101224
101225
101226
101227
101228
101229
101230
101231
101232
101233
101234
101235
101236
101237
101238
101239
101240
101241
101242
101243
101244
101245
101246
101247
101248
101249
101250
101251
101252
101253
101254
101255
101256
101257
101258
101259
101260
101261
101262
101263
101264
101265
101266
101267
101268
101269
101270
101271
101272
101273
101274
101275
101276
101277
101278
101279
101280
101281
101282
101283
101284
101285
101286
101287
101288
101289
101290
101291
101292
101293
101294
101295
101296
101297
101298
101299
101300
101301
101302
101303
101304
101305
101306
101307
101308
101309
101310
101311
101312
101313
101314
101315
101316
101317
101318
101319
101320
101321
101322
101323
101324
101325
101326
101327
101328
101329
101330
101331
101332
101333
101334
101335
101336
101337
101338
101339
101340
101341
101342
101343
101344
101345
101346
101347
101348
101349
101350
101351
101352
101353
101354
101355
101356
101357
101358
101359
101360
101361
101362
101363
101364
101365
101366
101367
101368
101369
101370
101371
101372
101373
101374
101375
101376
101377
101378
101379
101380
101381
101382
101383
101384
101385
101386
101387
101388
101389
101390
101391
101392
101393
101394
101395
101396
101397
101398
101399
101400
101401
101402
101403
101404
101405
101406
101407
101408
101409
101410
101411
101412
101413
101414
101415
101416
101417
101418
101419
101420
101421
101422
101423
101424
101425
101426
101427
101428
101429
101430
101431
101432
101433
101434
101435
101436
101437
101438
101439
101440
101441
101442
101443
101444
101445
101446
101447
101448
101449
101450
101451
101452
101453
101454
101455
101456
101457
101458
101459
101460
101461
101462
101463
101464
101465
101466
101467
101468
101469
101470
101471
101472
101473
101474
101475
101476
101477
101478
101479
101480
101481
101482
101483
101484
101485
101486
101487
101488
101489
101490
101491
101492
101493
101494
101495
101496
101497
101498
101499
101500
101501
101502
101503
101504
101505
101506
101507
101508
101509
101510
101511
101512
101513
101514
101515
101516
101517
101518
101519
101520
101521
101522
101523
101524
101525
101526
101527
101528
101529
101530
101531
101532
101533
101534
101535
101536
101537
101538
101539
101540
101541
101542
101543
101544
101545
101546
101547
101548
101549
101550
101551
101552
101553
101554
101555
101556
101557
101558
101559
101560
101561
101562
101563
101564
101565
101566
101567
101568
101569
101570
101571
101572
101573
101574
101575
101576
101577
101578
101579
101580
101581
101582
101583
101584
101585
101586
101587
101588
101589
101590
101591
101592
101593
101594
101595
101596
101597
101598
101599
101600
101601
101602
101603
101604
101605
101606
101607
101608
101609
101610
101611
101612
101613
101614
101615
101616
101617
101618
101619
101620
101621
101622
101623
101624
101625
101626
101627
101628
101629
101630
101631
101632
101633
101634
101635
101636
101637
101638
101639
101640
101641
101642
101643
101644
101645
101646
101647
101648
101649
101650
101651
101652
101653
101654
101655
101656
101657
101658
101659
101660
101661
101662
101663
101664
101665
101666
101667
101668
101669
101670
101671
101672
101673
101674
101675
101676
101677
101678
101679
101680
101681
101682
101683
101684
101685
101686
101687
101688
101689
101690
101691
101692
101693
101694
101695
101696
101697
101698
101699
101700
101701
101702
101703
101704
101705
101706
101707
101708
101709
101710
101711
101712
101713
101714
101715
101716
101717
101718
101719
101720
101721
101722
101723
101724
101725
101726
101727
101728
101729
101730
101731
101732
101733
101734
101735
101736
101737
101738
101739
101740
101741
101742
101743
101744
101745
101746
101747
101748
101749
101750
101751
101752
101753
101754
101755
101756
101757
101758
101759
101760
101761
101762
101763
101764
101765
101766
101767
101768
101769
101770
101771
101772
101773
101774
101775
101776
101777
101778
101779
101780
101781
101782
101783
101784
101785
101786
101787
101788
101789
101790
101791
101792
101793
101794
101795
101796
101797
101798
101799
101800
101801
101802
101803
101804
101805
101806
101807
101808
101809
101810
101811
101812
101813
101814
101815
101816
101817
101818
101819
101820
101821
101822
101823
101824
101825
101826
101827
101828
101829
101830
101831
101832
101833
101834
101835
101836
101837
101838
101839
101840
101841
101842
101843
101844
101845
101846
101847
101848
101849
101850
101851
101852
101853
101854
101855
101856
101857
101858
101859
101860
101861
101862
101863
101864
101865
101866
101867
101868
101869
101870
101871
101872
101873
101874
101875
101876
101877
101878
101879
101880
101881
101882
101883
101884
101885
101886
101887
101888
101889
101890
101891
101892
101893
101894
101895
101896
101897
101898
101899
101900
101901
101902
101903
101904
101905
101906
101907
101908
101909
101910
101911
101912
101913
101914
101915
101916
101917
101918
101919
101920
101921
101922
101923
101924
101925
101926
101927
101928
101929
101930
101931
101932
101933
101934
101935
101936
101937
101938
101939
101940
101941
101942
101943
101944
101945
101946
101947
101948
101949
101950
101951
101952
101953
101954
101955
101956
101957
101958
101959
101960
101961
101962
101963
101964
101965
101966
101967
101968
101969
101970
101971
101972
101973
101974
101975
101976
101977
101978
101979
101980
101981
101982
101983
101984
101985
101986
101987
101988
101989
101990
101991
101992
101993
101994
101995
101996
101997
101998
101999
102000
102001
102002
102003
102004
102005
102006
102007
102008
102009
102010
102011
102012
102013
102014
102015
102016
102017
102018
102019
102020
102021
102022
102023
102024
102025
102026
102027
102028
102029
102030
102031
102032
102033
102034
102035
102036
102037
102038
102039
102040
102041
102042
102043
102044
102045
102046
102047
102048
102049
102050
102051
102052
102053
102054
102055
102056
102057
102058
102059
102060
102061
102062
102063
102064
102065
102066
102067
102068
102069
102070
102071
102072
102073
102074
102075
102076
102077
102078
102079
102080
102081
102082
102083
102084
102085
102086
102087
102088
102089
102090
102091
102092
102093
102094
102095
102096
102097
102098
102099
102100
102101
102102
102103
102104
102105
102106
102107
102108
102109
102110
102111
102112
102113
102114
102115
102116
102117
102118
102119
102120
102121
102122
102123
102124
102125
102126
102127
102128
102129
102130
102131
102132
102133
102134
102135
102136
102137
102138
102139
102140
102141
102142
102143
102144
102145
102146
102147
102148
102149
102150
102151
102152
102153
102154
102155
102156
102157
102158
102159
102160
102161
102162
102163
102164
102165
102166
102167
102168
102169
102170
102171
102172
102173
102174
102175
102176
102177
102178
102179
102180
102181
102182
102183
102184
102185
102186
102187
102188
102189
102190
102191
102192
102193
102194
102195
102196
102197
102198
102199
102200
102201
102202
102203
102204
102205
102206
102207
102208
102209
102210
102211
102212
102213
102214
102215
102216
102217
102218
102219
102220
102221
102222
102223
102224
102225
102226
102227
102228
102229
102230
102231
102232
102233
102234
102235
102236
102237
102238
102239
102240
102241
102242
102243
102244
102245
102246
102247
102248
102249
102250
102251
102252
102253
102254
102255
102256
102257
102258
102259
102260
102261
102262
102263
102264
102265
102266
102267
102268
102269
102270
102271
102272
102273
102274
102275
102276
102277
102278
102279
102280
102281
102282
102283
102284
102285
102286
102287
102288
102289
102290
102291
102292
102293
102294
102295
102296
102297
102298
102299
102300
102301
102302
102303
102304
102305
102306
102307
102308
102309
102310
102311
102312
102313
102314
102315
102316
102317
102318
102319
102320
102321
102322
102323
102324
102325
102326
102327
102328
102329
102330
102331
102332
102333
102334
102335
102336
102337
102338
102339
102340
102341
102342
102343
102344
102345
102346
102347
102348
102349
102350
102351
102352
102353
102354
102355
102356
102357
102358
102359
102360
102361
102362
102363
102364
102365
102366
102367
102368
102369
102370
102371
102372
102373
102374
102375
102376
102377
102378
102379
102380
102381
102382
102383
102384
102385
102386
102387
102388
102389
102390
102391
102392
102393
102394
102395
102396
102397
102398
102399
102400
102401
102402
102403
102404
102405
102406
102407
102408
102409
102410
102411
102412
102413
102414
102415
102416
102417
102418
102419
102420
102421
102422
102423
102424
102425
102426
102427
102428
102429
102430
102431
102432
102433
102434
102435
102436
102437
102438
102439
102440
102441
102442
102443
102444
102445
102446
102447
102448
102449
102450
102451
102452
102453
102454
102455
102456
102457
102458
102459
102460
102461
102462
102463
102464
102465
102466
102467
102468
102469
102470
102471
102472
102473
102474
102475
102476
102477
102478
102479
102480
102481
102482
102483
102484
102485
102486
102487
102488
102489
102490
102491
102492
102493
102494
102495
102496
102497
102498
102499
102500
102501
102502
102503
102504
102505
102506
102507
102508
102509
102510
102511
102512
102513
102514
102515
102516
102517
102518
102519
102520
102521
102522
102523
102524
102525
102526
102527
102528
102529
102530
102531
102532
102533
102534
102535
102536
102537
102538
102539
102540
102541
102542
102543
102544
102545
102546
102547
102548
102549
102550
102551
102552
102553
102554
102555
102556
102557
102558
102559
102560
102561
102562
102563
102564
102565
102566
102567
102568
102569
102570
102571
102572
102573
102574
102575
102576
102577
102578
102579
102580
102581
102582
102583
102584
102585
102586
102587
102588
102589
102590
102591
102592
102593
102594
102595
102596
102597
102598
102599
102600
102601
102602
102603
102604
102605
102606
102607
102608
102609
102610
102611
102612
102613
102614
102615
102616
102617
102618
102619
102620
102621
102622
102623
102624
102625
102626
102627
102628
102629
102630
102631
102632
102633
102634
102635
102636
102637
102638
102639
102640
102641
102642
102643
102644
102645
102646
102647
102648
102649
102650
102651
102652
102653
102654
102655
102656
102657
102658
102659
102660
102661
102662
102663
102664
102665
102666
102667
102668
102669
102670
102671
102672
102673
102674
102675
102676
102677
102678
102679
102680
102681
102682
102683
102684
102685
102686
102687
102688
102689
102690
102691
102692
102693
102694
102695
102696
102697
102698
102699
102700
102701
102702
102703
102704
102705
102706
102707
102708
102709
102710
102711
102712
102713
102714
102715
102716
102717
102718
102719
102720
102721
102722
102723
102724
102725
102726
102727
102728
102729
102730
102731
102732
102733
102734
102735
102736
102737
102738
102739
102740
102741
102742
102743
102744
102745
102746
102747
102748
102749
102750
102751
102752
102753
102754
102755
102756
102757
102758
102759
102760
102761
102762
102763
102764
102765
102766
102767
102768
102769
102770
102771
102772
102773
102774
102775
102776
102777
102778
102779
102780
102781
102782
102783
102784
102785
102786
102787
102788
102789
102790
102791
102792
102793
102794
102795
102796
102797
102798
102799
102800
102801
102802
102803
102804
102805
102806
102807
102808
102809
102810
102811
102812
102813
102814
102815
102816
102817
102818
102819
102820
102821
102822
102823
102824
102825
102826
102827
102828
102829
102830
102831
102832
102833
102834
102835
102836
102837
102838
102839
102840
102841
102842
102843
102844
102845
102846
102847
102848
102849
102850
102851
102852
102853
102854
102855
102856
102857
102858
102859
102860
102861
102862
102863
102864
102865
102866
102867
102868
102869
102870
102871
102872
102873
102874
102875
102876
102877
102878
102879
102880
102881
102882
102883
102884
102885
102886
102887
102888
102889
102890
102891
102892
102893
102894
102895
102896
102897
102898
102899
102900
102901
102902
102903
102904
102905
102906
102907
102908
102909
102910
102911
102912
102913
102914
102915
102916
102917
102918
102919
102920
102921
102922
102923
102924
102925
102926
102927
102928
102929
102930
102931
102932
102933
102934
102935
102936
102937
102938
102939
102940
102941
102942
102943
102944
102945
102946
102947
102948
102949
102950
102951
102952
102953
102954
102955
102956
102957
102958
102959
102960
102961
102962
102963
102964
102965
102966
102967
102968
102969
102970
102971
102972
102973
102974
102975
102976
102977
102978
102979
102980
102981
102982
102983
102984
102985
102986
102987
102988
102989
102990
102991
102992
102993
102994
102995
102996
102997
102998
102999
103000
103001
103002
103003
103004
103005
103006
103007
103008
103009
103010
103011
103012
103013
103014
103015
103016
103017
103018
103019
103020
103021
103022
103023
103024
103025
103026
103027
103028
103029
103030
103031
103032
103033
103034
103035
103036
103037
103038
103039
103040
103041
103042
103043
103044
103045
103046
103047
103048
103049
103050
103051
103052
103053
103054
103055
103056
103057
103058
103059
103060
103061
103062
103063
103064
103065
103066
103067
103068
103069
103070
103071
103072
103073
103074
103075
103076
103077
103078
103079
103080
103081
103082
103083
103084
103085
103086
103087
103088
103089
103090
103091
103092
103093
103094
103095
103096
103097
103098
103099
103100
103101
103102
103103
103104
103105
103106
103107
103108
103109
103110
103111
103112
103113
103114
103115
103116
103117
103118
103119
103120
103121
103122
103123
103124
103125
103126
103127
103128
103129
103130
103131
103132
103133
103134
103135
103136
103137
103138
103139
103140
103141
103142
103143
103144
103145
103146
103147
103148
103149
103150
103151
103152
103153
103154
103155
103156
103157
103158
103159
103160
103161
103162
103163
103164
103165
103166
103167
103168
103169
103170
103171
103172
103173
103174
103175
103176
103177
103178
103179
103180
103181
103182
103183
103184
103185
103186
103187
103188
103189
103190
103191
103192
103193
103194
103195
103196
103197
103198
103199
103200
103201
103202
103203
103204
103205
103206
103207
103208
103209
103210
103211
103212
103213
103214
103215
103216
103217
103218
103219
103220
103221
103222
103223
103224
103225
103226
103227
103228
103229
103230
103231
103232
103233
103234
103235
103236
103237
103238
103239
103240
103241
103242
103243
103244
103245
103246
103247
103248
103249
103250
103251
103252
103253
103254
103255
103256
103257
103258
103259
103260
103261
103262
103263
103264
103265
103266
103267
103268
103269
103270
103271
103272
103273
103274
103275
103276
103277
103278
103279
103280
103281
103282
103283
103284
103285
103286
103287
103288
103289
103290
103291
103292
103293
103294
103295
103296
103297
103298
103299
103300
103301
103302
103303
103304
103305
103306
103307
103308
103309
103310
103311
103312
103313
103314
103315
103316
103317
103318
103319
103320
103321
103322
103323
103324
103325
103326
103327
103328
103329
103330
103331
103332
103333
103334
103335
103336
103337
103338
103339
103340
103341
103342
103343
103344
103345
103346
103347
103348
103349
103350
103351
103352
103353
103354
103355
103356
103357
103358
103359
103360
103361
103362
103363
103364
103365
103366
103367
103368
103369
103370
103371
103372
103373
103374
103375
103376
103377
103378
103379
103380
103381
103382
103383
103384
103385
103386
103387
103388
103389
103390
103391
103392
103393
103394
103395
103396
103397
103398
103399
103400
103401
103402
103403
103404
103405
103406
103407
103408
103409
103410
103411
103412
103413
103414
103415
103416
103417
103418
103419
103420
103421
103422
103423
103424
103425
103426
103427
103428
103429
103430
103431
103432
103433
103434
103435
103436
103437
103438
103439
103440
103441
103442
103443
103444
103445
103446
103447
103448
103449
103450
103451
103452
103453
103454
103455
103456
103457
103458
103459
103460
103461
103462
103463
103464
103465
103466
103467
103468
103469
103470
103471
103472
103473
103474
103475
103476
103477
103478
103479
103480
103481
103482
103483
103484
103485
103486
103487
103488
103489
103490
103491
103492
103493
103494
103495
103496
103497
103498
103499
103500
103501
103502
103503
103504
103505
103506
103507
103508
103509
103510
103511
103512
103513
103514
103515
103516
103517
103518
103519
103520
103521
103522
103523
103524
103525
103526
103527
103528
103529
103530
103531
103532
103533
103534
103535
103536
103537
103538
103539
103540
103541
103542
103543
103544
103545
103546
103547
103548
103549
103550
103551
103552
103553
103554
103555
103556
103557
103558
103559
103560
103561
103562
103563
103564
103565
103566
103567
103568
103569
103570
103571
103572
103573
103574
103575
103576
103577
103578
103579
103580
103581
103582
103583
103584
103585
103586
103587
103588
103589
103590
103591
103592
103593
103594
103595
103596
103597
103598
103599
103600
103601
103602
103603
103604
103605
103606
103607
103608
103609
103610
103611
103612
103613
103614
103615
103616
103617
103618
103619
103620
103621
103622
103623
103624
103625
103626
103627
103628
103629
103630
103631
103632
103633
103634
103635
103636
103637
103638
103639
103640
103641
103642
103643
103644
103645
103646
103647
103648
103649
103650
103651
103652
103653
103654
103655
103656
103657
103658
103659
103660
103661
103662
103663
103664
103665
103666
103667
103668
103669
103670
103671
103672
103673
103674
103675
103676
103677
103678
103679
103680
103681
103682
103683
103684
103685
103686
103687
103688
103689
103690
103691
103692
103693
103694
103695
103696
103697
103698
103699
103700
103701
103702
103703
103704
103705
103706
103707
103708
103709
103710
103711
103712
103713
103714
103715
103716
103717
103718
103719
103720
103721
103722
103723
103724
103725
103726
103727
103728
103729
103730
103731
103732
103733
103734
103735
103736
103737
103738
103739
103740
103741
103742
103743
103744
103745
103746
103747
103748
103749
103750
103751
103752
103753
103754
103755
103756
103757
103758
103759
103760
103761
103762
103763
103764
103765
103766
103767
103768
103769
103770
103771
103772
103773
103774
103775
103776
103777
103778
103779
103780
103781
103782
103783
103784
103785
103786
103787
103788
103789
103790
103791
103792
103793
103794
103795
103796
103797
103798
103799
103800
103801
103802
103803
103804
103805
103806
103807
103808
103809
103810
103811
103812
103813
103814
103815
103816
103817
103818
103819
103820
103821
103822
103823
103824
103825
103826
103827
103828
103829
103830
103831
103832
103833
103834
103835
103836
103837
103838
103839
103840
103841
103842
103843
103844
103845
103846
103847
103848
103849
103850
103851
103852
103853
103854
103855
103856
103857
103858
103859
103860
103861
103862
103863
103864
103865
103866
103867
103868
103869
103870
103871
103872
103873
103874
103875
103876
103877
103878
103879
103880
103881
103882
103883
103884
103885
103886
103887
103888
103889
103890
103891
103892
103893
103894
103895
103896
103897
103898
103899
103900
103901
103902
103903
103904
103905
103906
103907
103908
103909
103910
103911
103912
103913
103914
103915
103916
103917
103918
103919
103920
103921
103922
103923
103924
103925
103926
103927
103928
103929
103930
103931
103932
103933
103934
103935
103936
103937
103938
103939
103940
103941
103942
103943
103944
103945
103946
103947
103948
103949
103950
103951
103952
103953
103954
103955
103956
103957
103958
103959
103960
103961
103962
103963
103964
103965
103966
103967
103968
103969
103970
103971
103972
103973
103974
103975
103976
103977
103978
103979
103980
103981
103982
103983
103984
103985
103986
103987
103988
103989
103990
103991
103992
103993
103994
103995
103996
103997
103998
103999
104000
104001
104002
104003
104004
104005
104006
104007
104008
104009
104010
104011
104012
104013
104014
104015
104016
104017
104018
104019
104020
104021
104022
104023
104024
104025
104026
104027
104028
104029
104030
104031
104032
104033
104034
104035
104036
104037
104038
104039
104040
104041
104042
104043
104044
104045
104046
104047
104048
104049
104050
104051
104052
104053
104054
104055
104056
104057
104058
104059
104060
104061
104062
104063
104064
104065
104066
104067
104068
104069
104070
104071
104072
104073
104074
104075
104076
104077
104078
104079
104080
104081
104082
104083
104084
104085
104086
104087
104088
104089
104090
104091
104092
104093
104094
104095
104096
104097
104098
104099
104100
104101
104102
104103
104104
104105
104106
104107
104108
104109
104110
104111
104112
104113
104114
104115
104116
104117
104118
104119
104120
104121
104122
104123
104124
104125
104126
104127
104128
104129
104130
104131
104132
104133
104134
104135
104136
104137
104138
104139
104140
104141
104142
104143
104144
104145
104146
104147
104148
104149
104150
104151
104152
104153
104154
104155
104156
104157
104158
104159
104160
104161
104162
104163
104164
104165
104166
104167
104168
104169
104170
104171
104172
104173
104174
104175
104176
104177
104178
104179
104180
104181
104182
104183
104184
104185
104186
104187
104188
104189
104190
104191
104192
104193
104194
104195
104196
104197
104198
104199
104200
104201
104202
104203
104204
104205
104206
104207
104208
104209
104210
104211
104212
104213
104214
104215
104216
104217
104218
104219
104220
104221
104222
104223
104224
104225
104226
104227
104228
104229
104230
104231
104232
104233
104234
104235
104236
104237
104238
104239
104240
104241
104242
104243
104244
104245
104246
104247
104248
104249
104250
104251
104252
104253
104254
104255
104256
104257
104258
104259
104260
104261
104262
104263
104264
104265
104266
104267
104268
104269
104270
104271
104272
104273
104274
104275
104276
104277
104278
104279
104280
104281
104282
104283
104284
104285
104286
104287
104288
104289
104290
104291
104292
104293
104294
104295
104296
104297
104298
104299
104300
104301
104302
104303
104304
104305
104306
104307
104308
104309
104310
104311
104312
104313
104314
104315
104316
104317
104318
104319
104320
104321
104322
104323
104324
104325
104326
104327
104328
104329
104330
104331
104332
104333
104334
104335
104336
104337
104338
104339
104340
104341
104342
104343
104344
104345
104346
104347
104348
104349
104350
104351
104352
104353
104354
104355
104356
104357
104358
104359
104360
104361
104362
104363
104364
104365
104366
104367
104368
104369
104370
104371
104372
104373
104374
104375
104376
104377
104378
104379
104380
104381
104382
104383
104384
104385
104386
104387
104388
104389
104390
104391
104392
104393
104394
104395
104396
104397
104398
104399
104400
104401
104402
104403
104404
104405
104406
104407
104408
104409
104410
104411
104412
104413
104414
104415
104416
104417
104418
104419
104420
104421
104422
104423
104424
104425
104426
104427
104428
104429
104430
104431
104432
104433
104434
104435
104436
104437
104438
104439
104440
104441
104442
104443
104444
104445
104446
104447
104448
104449
104450
104451
104452
104453
104454
104455
104456
104457
104458
104459
104460
104461
104462
104463
104464
104465
104466
104467
104468
104469
104470
104471
104472
104473
104474
104475
104476
104477
104478
104479
104480
104481
104482
104483
104484
104485
104486
104487
104488
104489
104490
104491
104492
104493
104494
104495
104496
104497
104498
104499
104500
104501
104502
104503
104504
104505
104506
104507
104508
104509
104510
104511
104512
104513
104514
104515
104516
104517
104518
104519
104520
104521
104522
104523
104524
104525
104526
104527
104528
104529
104530
104531
104532
104533
104534
104535
104536
104537
104538
104539
104540
104541
104542
104543
104544
104545
104546
104547
104548
104549
104550
104551
104552
104553
104554
104555
104556
104557
104558
104559
104560
104561
104562
104563
104564
104565
104566
104567
104568
104569
104570
104571
104572
104573
104574
104575
104576
104577
104578
104579
104580
104581
104582
104583
104584
104585
104586
104587
104588
104589
104590
104591
104592
104593
104594
104595
104596
104597
104598
104599
104600
104601
104602
104603
104604
104605
104606
104607
104608
104609
104610
104611
104612
104613
104614
104615
104616
104617
104618
104619
104620
104621
104622
104623
104624
104625
104626
104627
104628
104629
104630
104631
104632
104633
104634
104635
104636
104637
104638
104639
104640
104641
104642
104643
104644
104645
104646
104647
104648
104649
104650
104651
104652
104653
104654
104655
104656
104657
104658
104659
104660
104661
104662
104663
104664
104665
104666
104667
104668
104669
104670
104671
104672
104673
104674
104675
104676
104677
104678
104679
104680
104681
104682
104683
104684
104685
104686
104687
104688
104689
104690
104691
104692
104693
104694
104695
104696
104697
104698
104699
104700
104701
104702
104703
104704
104705
104706
104707
104708
104709
104710
104711
104712
104713
104714
104715
104716
104717
104718
104719
104720
104721
104722
104723
104724
104725
104726
104727
104728
104729
104730
104731
104732
104733
104734
104735
104736
104737
104738
104739
104740
104741
104742
104743
104744
104745
104746
104747
104748
104749
104750
104751
104752
104753
104754
104755
104756
104757
104758
104759
104760
104761
104762
104763
104764
104765
104766
104767
104768
104769
104770
104771
104772
104773
104774
104775
104776
104777
104778
104779
104780
104781
104782
104783
104784
104785
104786
104787
104788
104789
104790
104791
104792
104793
104794
104795
104796
104797
104798
104799
104800
104801
104802
104803
104804
104805
104806
104807
104808
104809
104810
104811
104812
104813
104814
104815
104816
104817
104818
104819
104820
104821
104822
104823
104824
104825
104826
104827
104828
104829
104830
104831
104832
104833
104834
104835
104836
104837
104838
104839
104840
104841
104842
104843
104844
104845
104846
104847
104848
104849
104850
104851
104852
104853
104854
104855
104856
104857
104858
104859
104860
104861
104862
104863
104864
104865
104866
104867
104868
104869
104870
104871
104872
104873
104874
104875
104876
104877
104878
104879
104880
104881
104882
104883
104884
104885
104886
104887
104888
104889
104890
104891
104892
104893
104894
104895
104896
104897
104898
104899
104900
104901
104902
104903
104904
104905
104906
104907
104908
104909
104910
104911
104912
104913
104914
104915
104916
104917
104918
104919
104920
104921
104922
104923
104924
104925
104926
104927
104928
104929
104930
104931
104932
104933
104934
104935
104936
104937
104938
104939
104940
104941
104942
104943
104944
104945
104946
104947
104948
104949
104950
104951
104952
104953
104954
104955
104956
104957
104958
104959
104960
104961
104962
104963
104964
104965
104966
104967
104968
104969
104970
104971
104972
104973
104974
104975
104976
104977
104978
104979
104980
104981
104982
104983
104984
104985
104986
104987
104988
104989
104990
104991
104992
104993
104994
104995
104996
104997
104998
104999
105000
105001
105002
105003
105004
105005
105006
105007
105008
105009
105010
105011
105012
105013
105014
105015
105016
105017
105018
105019
105020
105021
105022
105023
105024
105025
105026
105027
105028
105029
105030
105031
105032
105033
105034
105035
105036
105037
105038
105039
105040
105041
105042
105043
105044
105045
105046
105047
105048
105049
105050
105051
105052
105053
105054
105055
105056
105057
105058
105059
105060
105061
105062
105063
105064
105065
105066
105067
105068
105069
105070
105071
105072
105073
105074
105075
105076
105077
105078
105079
105080
105081
105082
105083
105084
105085
105086
105087
105088
105089
105090
105091
105092
105093
105094
105095
105096
105097
105098
105099
105100
105101
105102
105103
105104
105105
105106
105107
105108
105109
105110
105111
105112
105113
105114
105115
105116
105117
105118
105119
105120
105121
105122
105123
105124
105125
105126
105127
105128
105129
105130
105131
105132
105133
105134
105135
105136
105137
105138
105139
105140
105141
105142
105143
105144
105145
105146
105147
105148
105149
105150
105151
105152
105153
105154
105155
105156
105157
105158
105159
105160
105161
105162
105163
105164
105165
105166
105167
105168
105169
105170
105171
105172
105173
105174
105175
105176
105177
105178
105179
105180
105181
105182
105183
105184
105185
105186
105187
105188
105189
105190
105191
105192
105193
105194
105195
105196
105197
105198
105199
105200
105201
105202
105203
105204
105205
105206
105207
105208
105209
105210
105211
105212
105213
105214
105215
105216
105217
105218
105219
105220
105221
105222
105223
105224
105225
105226
105227
105228
105229
105230
105231
105232
105233
105234
105235
105236
105237
105238
105239
105240
105241
105242
105243
105244
105245
105246
105247
105248
105249
105250
105251
105252
105253
105254
105255
105256
105257
105258
105259
105260
105261
105262
105263
105264
105265
105266
105267
105268
105269
105270
105271
105272
105273
105274
105275
105276
105277
105278
105279
105280
105281
105282
105283
105284
105285
105286
105287
105288
105289
105290
105291
105292
105293
105294
105295
105296
105297
105298
105299
105300
105301
105302
105303
105304
105305
105306
105307
105308
105309
105310
105311
105312
105313
105314
105315
105316
105317
105318
105319
105320
105321
105322
105323
105324
105325
105326
105327
105328
105329
105330
105331
105332
105333
105334
105335
105336
105337
105338
105339
105340
105341
105342
105343
105344
105345
105346
105347
105348
105349
105350
105351
105352
105353
105354
105355
105356
105357
105358
105359
105360
105361
105362
105363
105364
105365
105366
105367
105368
105369
105370
105371
105372
105373
105374
105375
105376
105377
105378
105379
105380
105381
105382
105383
105384
105385
105386
105387
105388
105389
105390
105391
105392
105393
105394
105395
105396
105397
105398
105399
105400
105401
105402
105403
105404
105405
105406
105407
105408
105409
105410
105411
105412
105413
105414
105415
105416
105417
105418
105419
105420
105421
105422
105423
105424
105425
105426
105427
105428
105429
105430
105431
105432
105433
105434
105435
105436
105437
105438
105439
105440
105441
105442
105443
105444
105445
105446
105447
105448
105449
105450
105451
105452
105453
105454
105455
105456
105457
105458
105459
105460
105461
105462
105463
105464
105465
105466
105467
105468
105469
105470
105471
105472
105473
105474
105475
105476
105477
105478
105479
105480
105481
105482
105483
105484
105485
105486
105487
105488
105489
105490
105491
105492
105493
105494
105495
105496
105497
105498
105499
105500
105501
105502
105503
105504
105505
105506
105507
105508
105509
105510
105511
105512
105513
105514
105515
105516
105517
105518
105519
105520
105521
105522
105523
105524
105525
105526
105527
105528
105529
105530
105531
105532
105533
105534
105535
105536
105537
105538
105539
105540
105541
105542
105543
105544
105545
105546
105547
105548
105549
105550
105551
105552
105553
105554
105555
105556
105557
105558
105559
105560
105561
105562
105563
105564
105565
105566
105567
105568
105569
105570
105571
105572
105573
105574
105575
105576
105577
105578
105579
105580
105581
105582
105583
105584
105585
105586
105587
105588
105589
105590
105591
105592
105593
105594
105595
105596
105597
105598
105599
105600
105601
105602
105603
105604
105605
105606
105607
105608
105609
105610
105611
105612
105613
105614
105615
105616
105617
105618
105619
105620
105621
105622
105623
105624
105625
105626
105627
105628
105629
105630
105631
105632
105633
105634
105635
105636
105637
105638
105639
105640
105641
105642
105643
105644
105645
105646
105647
105648
105649
105650
105651
105652
105653
105654
105655
105656
105657
105658
105659
105660
105661
105662
105663
105664
105665
105666
105667
105668
105669
105670
105671
105672
105673
105674
105675
105676
105677
105678
105679
105680
105681
105682
105683
105684
105685
105686
105687
105688
105689
105690
105691
105692
105693
105694
105695
105696
105697
105698
105699
105700
105701
105702
105703
105704
105705
105706
105707
105708
105709
105710
105711
105712
105713
105714
105715
105716
105717
105718
105719
105720
105721
105722
105723
105724
105725
105726
105727
105728
105729
105730
105731
105732
105733
105734
105735
105736
105737
105738
105739
105740
105741
105742
105743
105744
105745
105746
105747
105748
105749
105750
105751
105752
105753
105754
105755
105756
105757
105758
105759
105760
105761
105762
105763
105764
105765
105766
105767
105768
105769
105770
105771
105772
105773
105774
105775
105776
105777
105778
105779
105780
105781
105782
105783
105784
105785
105786
105787
105788
105789
105790
105791
105792
105793
105794
105795
105796
105797
105798
105799
105800
105801
105802
105803
105804
105805
105806
105807
105808
105809
105810
105811
105812
105813
105814
105815
105816
105817
105818
105819
105820
105821
105822
105823
105824
105825
105826
105827
105828
105829
105830
105831
105832
105833
105834
105835
105836
105837
105838
105839
105840
105841
105842
105843
105844
105845
105846
105847
105848
105849
105850
105851
105852
105853
105854
105855
105856
105857
105858
105859
105860
105861
105862
105863
105864
105865
105866
105867
105868
105869
105870
105871
105872
105873
105874
105875
105876
105877
105878
105879
105880
105881
105882
105883
105884
105885
105886
105887
105888
105889
105890
105891
105892
105893
105894
105895
105896
105897
105898
105899
105900
105901
105902
105903
105904
105905
105906
105907
105908
105909
105910
105911
105912
105913
105914
105915
105916
105917
105918
105919
105920
105921
105922
105923
105924
105925
105926
105927
105928
105929
105930
105931
105932
105933
105934
105935
105936
105937
105938
105939
105940
105941
105942
105943
105944
105945
105946
105947
105948
105949
105950
105951
105952
105953
105954
105955
105956
105957
105958
105959
105960
105961
105962
105963
105964
105965
105966
105967
105968
105969
105970
105971
105972
105973
105974
105975
105976
105977
105978
105979
105980
105981
105982
105983
105984
105985
105986
105987
105988
105989
105990
105991
105992
105993
105994
105995
105996
105997
105998
105999
106000
106001
106002
106003
106004
106005
106006
106007
106008
106009
106010
106011
106012
106013
106014
106015
106016
106017
106018
106019
106020
106021
106022
106023
106024
106025
106026
106027
106028
106029
106030
106031
106032
106033
106034
106035
106036
106037
106038
106039
106040
106041
106042
106043
106044
106045
106046
106047
106048
106049
106050
106051
106052
106053
106054
106055
106056
106057
106058
106059
106060
106061
106062
106063
106064
106065
106066
106067
106068
106069
106070
106071
106072
106073
106074
106075
106076
106077
106078
106079
106080
106081
106082
106083
106084
106085
106086
106087
106088
106089
106090
106091
106092
106093
106094
106095
106096
106097
106098
106099
106100
106101
106102
106103
106104
106105
106106
106107
106108
106109
106110
106111
106112
106113
106114
106115
106116
106117
106118
106119
106120
106121
106122
106123
106124
106125
106126
106127
106128
106129
106130
106131
106132
106133
106134
106135
106136
106137
106138
106139
106140
106141
106142
106143
106144
106145
106146
106147
106148
106149
106150
106151
106152
106153
106154
106155
106156
106157
106158
106159
106160
106161
106162
106163
106164
106165
106166
106167
106168
106169
106170
106171
106172
106173
106174
106175
106176
106177
106178
106179
106180
106181
106182
106183
106184
106185
106186
106187
106188
106189
106190
106191
106192
106193
106194
106195
106196
106197
106198
106199
106200
106201
106202
106203
106204
106205
106206
106207
106208
106209
106210
106211
106212
106213
106214
106215
106216
106217
106218
106219
106220
106221
106222
106223
106224
106225
106226
106227
106228
106229
106230
106231
106232
106233
106234
106235
106236
106237
106238
106239
106240
106241
106242
106243
106244
106245
106246
106247
106248
106249
106250
106251
106252
106253
106254
106255
106256
106257
106258
106259
106260
106261
106262
106263
106264
106265
106266
106267
106268
106269
106270
106271
106272
106273
106274
106275
106276
106277
106278
106279
106280
106281
106282
106283
106284
106285
106286
106287
106288
106289
106290
106291
106292
106293
106294
106295
106296
106297
106298
106299
106300
106301
106302
106303
106304
106305
106306
106307
106308
106309
106310
106311
106312
106313
106314
106315
106316
106317
106318
106319
106320
106321
106322
106323
106324
106325
106326
106327
106328
106329
106330
106331
106332
106333
106334
106335
106336
106337
106338
106339
106340
106341
106342
106343
106344
106345
106346
106347
106348
106349
106350
106351
106352
106353
106354
106355
106356
106357
106358
106359
106360
106361
106362
106363
106364
106365
106366
106367
106368
106369
106370
106371
106372
106373
106374
106375
106376
106377
106378
106379
106380
106381
106382
106383
106384
106385
106386
106387
106388
106389
106390
106391
106392
106393
106394
106395
106396
106397
106398
106399
106400
106401
106402
106403
106404
106405
106406
106407
106408
106409
106410
106411
106412
106413
106414
106415
106416
106417
106418
106419
106420
106421
106422
106423
106424
106425
106426
106427
106428
106429
106430
106431
106432
106433
106434
106435
106436
106437
106438
106439
106440
106441
106442
106443
106444
106445
106446
106447
106448
106449
106450
106451
106452
106453
106454
106455
106456
106457
106458
106459
106460
106461
106462
106463
106464
106465
106466
106467
106468
106469
106470
106471
106472
106473
106474
106475
106476
106477
106478
106479
106480
106481
106482
106483
106484
106485
106486
106487
106488
106489
106490
106491
106492
106493
106494
106495
106496
106497
106498
106499
106500
106501
106502
106503
106504
106505
106506
106507
106508
106509
106510
106511
106512
106513
106514
106515
106516
106517
106518
106519
106520
106521
106522
106523
106524
106525
106526
106527
106528
106529
106530
106531
106532
106533
106534
106535
106536
106537
106538
106539
106540
106541
106542
106543
106544
106545
106546
106547
106548
106549
106550
106551
106552
106553
106554
106555
106556
106557
106558
106559
106560
106561
106562
106563
106564
106565
106566
106567
106568
106569
106570
106571
106572
106573
106574
106575
106576
106577
106578
106579
106580
106581
106582
106583
106584
106585
106586
106587
106588
106589
106590
106591
106592
106593
106594
106595
106596
106597
106598
106599
106600
106601
106602
106603
106604
106605
106606
106607
106608
106609
106610
106611
106612
106613
106614
106615
106616
106617
106618
106619
106620
106621
106622
106623
106624
106625
106626
106627
106628
106629
106630
106631
106632
106633
106634
106635
106636
106637
106638
106639
106640
106641
106642
106643
106644
106645
106646
106647
106648
106649
106650
106651
106652
106653
106654
106655
106656
106657
106658
106659
106660
106661
106662
106663
106664
106665
106666
106667
106668
106669
106670
106671
106672
106673
106674
106675
106676
106677
106678
106679
106680
106681
106682
106683
106684
106685
106686
106687
106688
106689
106690
106691
106692
106693
106694
106695
106696
106697
106698
106699
106700
106701
106702
106703
106704
106705
106706
106707
106708
106709
106710
106711
106712
106713
106714
106715
106716
106717
106718
106719
106720
106721
106722
106723
106724
106725
106726
106727
106728
106729
106730
106731
106732
106733
106734
106735
106736
106737
106738
106739
106740
106741
106742
106743
106744
106745
106746
106747
106748
106749
106750
106751
106752
106753
106754
106755
106756
106757
106758
106759
106760
106761
106762
106763
106764
106765
106766
106767
106768
106769
106770
106771
106772
106773
106774
106775
106776
106777
106778
106779
106780
106781
106782
106783
106784
106785
106786
106787
106788
106789
106790
106791
106792
106793
106794
106795
106796
106797
106798
106799
106800
106801
106802
106803
106804
106805
106806
106807
106808
106809
106810
106811
106812
106813
106814
106815
106816
106817
106818
106819
106820
106821
106822
106823
106824
106825
106826
106827
106828
106829
106830
106831
106832
106833
106834
106835
106836
106837
106838
106839
106840
106841
106842
106843
106844
106845
106846
106847
106848
106849
106850
106851
106852
106853
106854
106855
106856
106857
106858
106859
106860
106861
106862
106863
106864
106865
106866
106867
106868
106869
106870
106871
106872
106873
106874
106875
106876
106877
106878
106879
106880
106881
106882
106883
106884
106885
106886
106887
106888
106889
106890
106891
106892
106893
106894
106895
106896
106897
106898
106899
106900
106901
106902
106903
106904
106905
106906
106907
106908
106909
106910
106911
106912
106913
106914
106915
106916
106917
106918
106919
106920
106921
106922
106923
106924
106925
106926
106927
106928
106929
106930
106931
106932
106933
106934
106935
106936
106937
106938
106939
106940
106941
106942
106943
106944
106945
106946
106947
106948
106949
106950
106951
106952
106953
106954
106955
106956
106957
106958
106959
106960
106961
106962
106963
106964
106965
106966
106967
106968
106969
106970
106971
106972
106973
106974
106975
106976
106977
106978
106979
106980
106981
106982
106983
106984
106985
106986
106987
106988
106989
106990
106991
106992
106993
106994
106995
106996
106997
106998
106999
107000
107001
107002
107003
107004
107005
107006
107007
107008
107009
107010
107011
107012
107013
107014
107015
107016
107017
107018
107019
107020
107021
107022
107023
107024
107025
107026
107027
107028
107029
107030
107031
107032
107033
107034
107035
107036
107037
107038
107039
107040
107041
107042
107043
107044
107045
107046
107047
107048
107049
107050
107051
107052
107053
107054
107055
107056
107057
107058
107059
107060
107061
107062
107063
107064
107065
107066
107067
107068
107069
107070
107071
107072
107073
107074
107075
107076
107077
107078
107079
107080
107081
107082
107083
107084
107085
107086
107087
107088
107089
107090
107091
107092
107093
107094
107095
107096
107097
107098
107099
107100
107101
107102
107103
107104
107105
107106
107107
107108
107109
107110
107111
107112
107113
107114
107115
107116
107117
107118
107119
107120
107121
107122
107123
107124
107125
107126
107127
107128
107129
107130
107131
107132
107133
107134
107135
107136
107137
107138
107139
107140
107141
107142
107143
107144
107145
107146
107147
107148
107149
107150
107151
107152
107153
107154
107155
107156
107157
107158
107159
107160
107161
107162
107163
107164
107165
107166
107167
107168
107169
107170
107171
107172
107173
107174
107175
107176
107177
107178
107179
107180
107181
107182
107183
107184
107185
107186
107187
107188
107189
107190
107191
107192
107193
107194
107195
107196
107197
107198
107199
107200
107201
107202
107203
107204
107205
107206
107207
107208
107209
107210
107211
107212
107213
107214
107215
107216
107217
107218
107219
107220
107221
107222
107223
107224
107225
107226
107227
107228
107229
107230
107231
107232
107233
107234
107235
107236
107237
107238
107239
107240
107241
107242
107243
107244
107245
107246
107247
107248
107249
107250
107251
107252
107253
107254
107255
107256
107257
107258
107259
107260
107261
107262
107263
107264
107265
107266
107267
107268
107269
107270
107271
107272
107273
107274
107275
107276
107277
107278
107279
107280
107281
107282
107283
107284
107285
107286
107287
107288
107289
107290
107291
107292
107293
107294
107295
107296
107297
107298
107299
107300
107301
107302
107303
107304
107305
107306
107307
107308
107309
107310
107311
107312
107313
107314
107315
107316
107317
107318
107319
107320
107321
107322
107323
107324
107325
107326
107327
107328
107329
107330
107331
107332
107333
107334
107335
107336
107337
107338
107339
107340
107341
107342
107343
107344
107345
107346
107347
107348
107349
107350
107351
107352
107353
107354
107355
107356
107357
107358
107359
107360
107361
107362
107363
107364
107365
107366
107367
107368
107369
107370
107371
107372
107373
107374
107375
107376
107377
107378
107379
107380
107381
107382
107383
107384
107385
107386
107387
107388
107389
107390
107391
107392
107393
107394
107395
107396
107397
107398
107399
107400
107401
107402
107403
107404
107405
107406
107407
107408
107409
107410
107411
107412
107413
107414
107415
107416
107417
107418
107419
107420
107421
107422
107423
107424
107425
107426
107427
107428
107429
107430
107431
107432
107433
107434
107435
107436
107437
107438
107439
107440
107441
107442
107443
107444
107445
107446
107447
107448
107449
107450
107451
107452
107453
107454
107455
107456
107457
107458
107459
107460
107461
107462
107463
107464
107465
107466
107467
107468
107469
107470
107471
107472
107473
107474
107475
107476
107477
107478
107479
107480
107481
107482
107483
107484
107485
107486
107487
107488
107489
107490
107491
107492
107493
107494
107495
107496
107497
107498
107499
107500
107501
107502
107503
107504
107505
107506
107507
107508
107509
107510
107511
107512
107513
107514
107515
107516
107517
107518
107519
107520
107521
107522
107523
107524
107525
107526
107527
107528
107529
107530
107531
107532
107533
107534
107535
107536
107537
107538
107539
107540
107541
107542
107543
107544
107545
107546
107547
107548
107549
107550
107551
107552
107553
107554
107555
107556
107557
107558
107559
107560
107561
107562
107563
107564
107565
107566
107567
107568
107569
107570
107571
107572
107573
107574
107575
107576
107577
107578
107579
107580
107581
107582
107583
107584
107585
107586
107587
107588
107589
107590
107591
107592
107593
107594
107595
107596
107597
107598
107599
107600
107601
107602
107603
107604
107605
107606
107607
107608
107609
107610
107611
107612
107613
107614
107615
107616
107617
107618
107619
107620
107621
107622
107623
107624
107625
107626
107627
107628
107629
107630
107631
107632
107633
107634
107635
107636
107637
107638
107639
107640
107641
107642
107643
107644
107645
107646
107647
107648
107649
107650
107651
107652
107653
107654
107655
107656
107657
107658
107659
107660
107661
107662
107663
107664
107665
107666
107667
107668
107669
107670
107671
107672
107673
107674
107675
107676
107677
107678
107679
107680
107681
107682
107683
107684
107685
107686
107687
107688
107689
107690
107691
107692
107693
107694
107695
107696
107697
107698
107699
107700
107701
107702
107703
107704
107705
107706
107707
107708
107709
107710
107711
107712
107713
107714
107715
107716
107717
107718
107719
107720
107721
107722
107723
107724
107725
107726
107727
107728
107729
107730
107731
107732
107733
107734
107735
107736
107737
107738
107739
107740
107741
107742
107743
107744
107745
107746
107747
107748
107749
107750
107751
107752
107753
107754
107755
107756
107757
107758
107759
107760
107761
107762
107763
107764
107765
107766
107767
107768
107769
107770
107771
107772
107773
107774
107775
107776
107777
107778
107779
107780
107781
107782
107783
107784
107785
107786
107787
107788
107789
107790
107791
107792
107793
107794
107795
107796
107797
107798
107799
107800
107801
107802
107803
107804
107805
107806
107807
107808
107809
107810
107811
107812
107813
107814
107815
107816
107817
107818
107819
107820
107821
107822
107823
107824
107825
107826
107827
107828
107829
107830
107831
107832
107833
107834
107835
107836
107837
107838
107839
107840
107841
107842
107843
107844
107845
107846
107847
107848
107849
107850
107851
107852
107853
107854
107855
107856
107857
107858
107859
107860
107861
107862
107863
107864
107865
107866
107867
107868
107869
107870
107871
107872
107873
107874
107875
107876
107877
107878
107879
107880
107881
107882
107883
107884
107885
107886
107887
107888
107889
107890
107891
107892
107893
107894
107895
107896
107897
107898
107899
107900
107901
107902
107903
107904
107905
107906
107907
107908
107909
107910
107911
107912
107913
107914
107915
107916
107917
107918
107919
107920
107921
107922
107923
107924
107925
107926
107927
107928
107929
107930
107931
107932
107933
107934
107935
107936
107937
107938
107939
107940
107941
107942
107943
107944
107945
107946
107947
107948
107949
107950
107951
107952
107953
107954
107955
107956
107957
107958
107959
107960
107961
107962
107963
107964
107965
107966
107967
107968
107969
107970
107971
107972
107973
107974
107975
107976
107977
107978
107979
107980
107981
107982
107983
107984
107985
107986
107987
107988
107989
107990
107991
107992
107993
107994
107995
107996
107997
107998
107999
108000
108001
108002
108003
108004
108005
108006
108007
108008
108009
108010
108011
108012
108013
108014
108015
108016
108017
108018
108019
108020
108021
108022
108023
108024
108025
108026
108027
108028
108029
108030
108031
108032
108033
108034
108035
108036
108037
108038
108039
108040
108041
108042
108043
108044
108045
108046
108047
108048
108049
108050
108051
108052
108053
108054
108055
108056
108057
108058
108059
108060
108061
108062
108063
108064
108065
108066
108067
108068
108069
108070
108071
108072
108073
108074
108075
108076
108077
108078
108079
108080
108081
108082
108083
108084
108085
108086
108087
108088
108089
108090
108091
108092
108093
108094
108095
108096
108097
108098
108099
108100
108101
108102
108103
108104
108105
108106
108107
108108
108109
108110
108111
108112
108113
108114
108115
108116
108117
108118
108119
108120
108121
108122
108123
108124
108125
108126
108127
108128
108129
108130
108131
108132
108133
108134
108135
108136
108137
108138
108139
108140
108141
108142
108143
108144
108145
108146
108147
108148
108149
108150
108151
108152
108153
108154
108155
108156
108157
108158
108159
108160
108161
108162
108163
108164
108165
108166
108167
108168
108169
108170
108171
108172
108173
108174
108175
108176
108177
108178
108179
108180
108181
108182
108183
108184
108185
108186
108187
108188
108189
108190
108191
108192
108193
108194
108195
108196
108197
108198
108199
108200
108201
108202
108203
108204
108205
108206
108207
108208
108209
108210
108211
108212
108213
108214
108215
108216
108217
108218
108219
108220
108221
108222
108223
108224
108225
108226
108227
108228
108229
108230
108231
108232
108233
108234
108235
108236
108237
108238
108239
108240
108241
108242
108243
108244
108245
108246
108247
108248
108249
108250
108251
108252
108253
108254
108255
108256
108257
108258
108259
108260
108261
108262
108263
108264
108265
108266
108267
108268
108269
108270
108271
108272
108273
108274
108275
108276
108277
108278
108279
108280
108281
108282
108283
108284
108285
108286
108287
108288
108289
108290
108291
108292
108293
108294
108295
108296
108297
108298
108299
108300
108301
108302
108303
108304
108305
108306
108307
108308
108309
108310
108311
108312
108313
108314
108315
108316
108317
108318
108319
108320
108321
108322
108323
108324
108325
108326
108327
108328
108329
108330
108331
108332
108333
108334
108335
108336
108337
108338
108339
108340
108341
108342
108343
108344
108345
108346
108347
108348
108349
108350
108351
108352
108353
108354
108355
108356
108357
108358
108359
108360
108361
108362
108363
108364
108365
108366
108367
108368
108369
108370
108371
108372
108373
108374
108375
108376
108377
108378
108379
108380
108381
108382
108383
108384
108385
108386
108387
108388
108389
108390
108391
108392
108393
108394
108395
108396
108397
108398
108399
108400
108401
108402
108403
108404
108405
108406
108407
108408
108409
108410
108411
108412
108413
108414
108415
108416
108417
108418
108419
108420
108421
108422
108423
108424
108425
108426
108427
108428
108429
108430
108431
108432
108433
108434
108435
108436
108437
108438
108439
108440
108441
108442
108443
108444
108445
108446
108447
108448
108449
108450
108451
108452
108453
108454
108455
108456
108457
108458
108459
108460
108461
108462
108463
108464
108465
108466
108467
108468
108469
108470
108471
108472
108473
108474
108475
108476
108477
108478
108479
108480
108481
108482
108483
108484
108485
108486
108487
108488
108489
108490
108491
108492
108493
108494
108495
108496
108497
108498
108499
108500
108501
108502
108503
108504
108505
108506
108507
108508
108509
108510
108511
108512
108513
108514
108515
108516
108517
108518
108519
108520
108521
108522
108523
108524
108525
108526
108527
108528
108529
108530
108531
108532
108533
108534
108535
108536
108537
108538
108539
108540
108541
108542
108543
108544
108545
108546
108547
108548
108549
108550
108551
108552
108553
108554
108555
108556
108557
108558
108559
108560
108561
108562
108563
108564
108565
108566
108567
108568
108569
108570
108571
108572
108573
108574
108575
108576
108577
108578
108579
108580
108581
108582
108583
108584
108585
108586
108587
108588
108589
108590
108591
108592
108593
108594
108595
108596
108597
108598
108599
108600
108601
108602
108603
108604
108605
108606
108607
108608
108609
108610
108611
108612
108613
108614
108615
108616
108617
108618
108619
108620
108621
108622
108623
108624
108625
108626
108627
108628
108629
108630
108631
108632
108633
108634
108635
108636
108637
108638
108639
108640
108641
108642
108643
108644
108645
108646
108647
108648
108649
108650
108651
108652
108653
108654
108655
108656
108657
108658
108659
108660
108661
108662
108663
108664
108665
108666
108667
108668
108669
108670
108671
108672
108673
108674
108675
108676
108677
108678
108679
108680
108681
108682
108683
108684
108685
108686
108687
108688
108689
108690
108691
108692
108693
108694
108695
108696
108697
108698
108699
108700
108701
108702
108703
108704
108705
108706
108707
108708
108709
108710
108711
108712
108713
108714
108715
108716
108717
108718
108719
108720
108721
108722
108723
108724
108725
108726
108727
108728
108729
108730
108731
108732
108733
108734
108735
108736
108737
108738
108739
108740
108741
108742
108743
108744
108745
108746
108747
108748
108749
108750
108751
108752
108753
108754
108755
108756
108757
108758
108759
108760
108761
108762
108763
108764
108765
108766
108767
108768
108769
108770
108771
108772
108773
108774
108775
108776
108777
108778
108779
108780
108781
108782
108783
108784
108785
108786
108787
108788
108789
108790
108791
108792
108793
108794
108795
108796
108797
108798
108799
108800
108801
108802
108803
108804
108805
108806
108807
108808
108809
108810
108811
108812
108813
108814
108815
108816
108817
108818
108819
108820
108821
108822
108823
108824
108825
108826
108827
108828
108829
108830
108831
108832
108833
108834
108835
108836
108837
108838
108839
108840
108841
108842
108843
108844
108845
108846
108847
108848
108849
108850
108851
108852
108853
108854
108855
108856
108857
108858
108859
108860
108861
108862
108863
108864
108865
108866
108867
108868
108869
108870
108871
108872
108873
108874
108875
108876
108877
108878
108879
108880
108881
108882
108883
108884
108885
108886
108887
108888
108889
108890
108891
108892
108893
108894
108895
108896
108897
108898
108899
108900
108901
108902
108903
108904
108905
108906
108907
108908
108909
108910
108911
108912
108913
108914
108915
108916
108917
108918
108919
108920
108921
108922
108923
108924
108925
108926
108927
108928
108929
108930
108931
108932
108933
108934
108935
108936
108937
108938
108939
108940
108941
108942
108943
108944
108945
108946
108947
108948
108949
108950
108951
108952
108953
108954
108955
108956
108957
108958
108959
108960
108961
108962
108963
108964
108965
108966
108967
108968
108969
108970
108971
108972
108973
108974
108975
108976
108977
108978
108979
108980
108981
108982
108983
108984
108985
108986
108987
108988
108989
108990
108991
108992
108993
108994
108995
108996
108997
108998
108999
109000
109001
109002
109003
109004
109005
109006
109007
109008
109009
109010
109011
109012
109013
109014
109015
109016
109017
109018
109019
109020
109021
109022
109023
109024
109025
109026
109027
109028
109029
109030
109031
109032
109033
109034
109035
109036
109037
109038
109039
109040
109041
109042
109043
109044
109045
109046
109047
109048
109049
109050
109051
109052
109053
109054
109055
109056
109057
109058
109059
109060
109061
109062
109063
109064
109065
109066
109067
109068
109069
109070
109071
109072
109073
109074
109075
109076
109077
109078
109079
109080
109081
109082
109083
109084
109085
109086
109087
109088
109089
109090
109091
109092
109093
109094
109095
109096
109097
109098
109099
109100
109101
109102
109103
109104
109105
109106
109107
109108
109109
109110
109111
109112
109113
109114
109115
109116
109117
109118
109119
109120
109121
109122
109123
109124
109125
109126
109127
109128
109129
109130
109131
109132
109133
109134
109135
109136
109137
109138
109139
109140
109141
109142
109143
109144
109145
109146
109147
109148
109149
109150
109151
109152
109153
109154
109155
109156
109157
109158
109159
109160
109161
109162
109163
109164
109165
109166
109167
109168
109169
109170
109171
109172
109173
109174
109175
109176
109177
109178
109179
109180
109181
109182
109183
109184
109185
109186
109187
109188
109189
109190
109191
109192
109193
109194
109195
109196
109197
109198
109199
109200
109201
109202
109203
109204
109205
109206
109207
109208
109209
109210
109211
109212
109213
109214
109215
109216
109217
109218
109219
109220
109221
109222
109223
109224
109225
109226
109227
109228
109229
109230
109231
109232
109233
109234
109235
109236
109237
109238
109239
109240
109241
109242
109243
109244
109245
109246
109247
109248
109249
109250
109251
109252
109253
109254
109255
109256
109257
109258
109259
109260
109261
109262
109263
109264
109265
109266
109267
109268
109269
109270
109271
109272
109273
109274
109275
109276
109277
109278
109279
109280
109281
109282
109283
109284
109285
109286
109287
109288
109289
109290
109291
109292
109293
109294
109295
109296
109297
109298
109299
109300
109301
109302
109303
109304
109305
109306
109307
109308
109309
109310
109311
109312
109313
109314
109315
109316
109317
109318
109319
109320
109321
109322
109323
109324
109325
109326
109327
109328
109329
109330
109331
109332
109333
109334
109335
109336
109337
109338
109339
109340
109341
109342
109343
109344
109345
109346
109347
109348
109349
109350
109351
109352
109353
109354
109355
109356
109357
109358
109359
109360
109361
109362
109363
109364
109365
109366
109367
109368
109369
109370
109371
109372
109373
109374
109375
109376
109377
109378
109379
109380
109381
109382
109383
109384
109385
109386
109387
109388
109389
109390
109391
109392
109393
109394
109395
109396
109397
109398
109399
109400
109401
109402
109403
109404
109405
109406
109407
109408
109409
109410
109411
109412
109413
109414
109415
109416
109417
109418
109419
109420
109421
109422
109423
109424
109425
109426
109427
109428
109429
109430
109431
109432
109433
109434
109435
109436
109437
109438
109439
109440
109441
109442
109443
109444
109445
109446
109447
109448
109449
109450
109451
109452
109453
109454
109455
109456
109457
109458
109459
109460
109461
109462
109463
109464
109465
109466
109467
109468
109469
109470
109471
109472
109473
109474
109475
109476
109477
109478
109479
109480
109481
109482
109483
109484
109485
109486
109487
109488
109489
109490
109491
109492
109493
109494
109495
109496
109497
109498
109499
109500
109501
109502
109503
109504
109505
109506
109507
109508
109509
109510
109511
109512
109513
109514
109515
109516
109517
109518
109519
109520
109521
109522
109523
109524
109525
109526
109527
109528
109529
109530
109531
109532
109533
109534
109535
109536
109537
109538
109539
109540
109541
109542
109543
109544
109545
109546
109547
109548
109549
109550
109551
109552
109553
109554
109555
109556
109557
109558
109559
109560
109561
109562
109563
109564
109565
109566
109567
109568
109569
109570
109571
109572
109573
109574
109575
109576
109577
109578
109579
109580
109581
109582
109583
109584
109585
109586
109587
109588
109589
109590
109591
109592
109593
109594
109595
109596
109597
109598
109599
109600
109601
109602
109603
109604
109605
109606
109607
109608
109609
109610
109611
109612
109613
109614
109615
109616
109617
109618
109619
109620
109621
109622
109623
109624
109625
109626
109627
109628
109629
109630
109631
109632
109633
109634
109635
109636
109637
109638
109639
109640
109641
109642
109643
109644
109645
109646
109647
109648
109649
109650
109651
109652
109653
109654
109655
109656
109657
109658
109659
109660
109661
109662
109663
109664
109665
109666
109667
109668
109669
109670
109671
109672
109673
109674
109675
109676
109677
109678
109679
109680
109681
109682
109683
109684
109685
109686
109687
109688
109689
109690
109691
109692
109693
109694
109695
109696
109697
109698
109699
109700
109701
109702
109703
109704
109705
109706
109707
109708
109709
109710
109711
109712
109713
109714
109715
109716
109717
109718
109719
109720
109721
109722
109723
109724
109725
109726
109727
109728
109729
109730
109731
109732
109733
109734
109735
109736
109737
109738
109739
109740
109741
109742
109743
109744
109745
109746
109747
109748
109749
109750
109751
109752
109753
109754
109755
109756
109757
109758
109759
109760
109761
109762
109763
109764
109765
109766
109767
109768
109769
109770
109771
109772
109773
109774
109775
109776
109777
109778
109779
109780
109781
109782
109783
109784
109785
109786
109787
109788
109789
109790
109791
109792
109793
109794
109795
109796
109797
109798
109799
109800
109801
109802
109803
109804
109805
109806
109807
109808
109809
109810
109811
109812
109813
109814
109815
109816
109817
109818
109819
109820
109821
109822
109823
109824
109825
109826
109827
109828
109829
109830
109831
109832
109833
109834
109835
109836
109837
109838
109839
109840
109841
109842
109843
109844
109845
109846
109847
109848
109849
109850
109851
109852
109853
109854
109855
109856
109857
109858
109859
109860
109861
109862
109863
109864
109865
109866
109867
109868
109869
109870
109871
109872
109873
109874
109875
109876
109877
109878
109879
109880
109881
109882
109883
109884
109885
109886
109887
109888
109889
109890
109891
109892
109893
109894
109895
109896
109897
109898
109899
109900
109901
109902
109903
109904
109905
109906
109907
109908
109909
109910
109911
109912
109913
109914
109915
109916
109917
109918
109919
109920
109921
109922
109923
109924
109925
109926
109927
109928
109929
109930
109931
109932
109933
109934
109935
109936
109937
109938
109939
109940
109941
109942
109943
109944
109945
109946
109947
109948
109949
109950
109951
109952
109953
109954
109955
109956
109957
109958
109959
109960
109961
109962
109963
109964
109965
109966
109967
109968
109969
109970
109971
109972
109973
109974
109975
109976
109977
109978
109979
109980
109981
109982
109983
109984
109985
109986
109987
109988
109989
109990
109991
109992
109993
109994
109995
109996
109997
109998
109999
110000
110001
110002
110003
110004
110005
110006
110007
110008
110009
110010
110011
110012
110013
110014
110015
110016
110017
110018
110019
110020
110021
110022
110023
110024
110025
110026
110027
110028
110029
110030
110031
110032
110033
110034
110035
110036
110037
110038
110039
110040
110041
110042
110043
110044
110045
110046
110047
110048
110049
110050
110051
110052
110053
110054
110055
110056
110057
110058
110059
110060
110061
110062
110063
110064
110065
110066
110067
110068
110069
110070
110071
110072
110073
110074
110075
110076
110077
110078
110079
110080
110081
110082
110083
110084
110085
110086
110087
110088
110089
110090
110091
110092
110093
110094
110095
110096
110097
110098
110099
110100
110101
110102
110103
110104
110105
110106
110107
110108
110109
110110
110111
110112
110113
110114
110115
110116
110117
110118
110119
110120
110121
110122
110123
110124
110125
110126
110127
110128
110129
110130
110131
110132
110133
110134
110135
110136
110137
110138
110139
110140
110141
110142
110143
110144
110145
110146
110147
110148
110149
110150
110151
110152
110153
110154
110155
110156
110157
110158
110159
110160
110161
110162
110163
110164
110165
110166
110167
110168
110169
110170
110171
110172
110173
110174
110175
110176
110177
110178
110179
110180
110181
110182
110183
110184
110185
110186
110187
110188
110189
110190
110191
110192
110193
110194
110195
110196
110197
110198
110199
110200
110201
110202
110203
110204
110205
110206
110207
110208
110209
110210
110211
110212
110213
110214
110215
110216
110217
110218
110219
110220
110221
110222
110223
110224
110225
110226
110227
110228
110229
110230
110231
110232
110233
110234
110235
110236
110237
110238
110239
110240
110241
110242
110243
110244
110245
110246
110247
110248
110249
110250
110251
110252
110253
110254
110255
110256
110257
110258
110259
110260
110261
110262
110263
110264
110265
110266
110267
110268
110269
110270
110271
110272
110273
110274
110275
110276
110277
110278
110279
110280
110281
110282
110283
110284
110285
110286
110287
110288
110289
110290
110291
110292
110293
110294
110295
110296
110297
110298
110299
110300
110301
110302
110303
110304
110305
110306
110307
110308
110309
110310
110311
110312
110313
110314
110315
110316
110317
110318
110319
110320
110321
110322
110323
110324
110325
110326
110327
110328
110329
110330
110331
110332
110333
110334
110335
110336
110337
110338
110339
110340
110341
110342
110343
110344
110345
110346
110347
110348
110349
110350
110351
110352
110353
110354
110355
110356
110357
110358
110359
110360
110361
110362
110363
110364
110365
110366
110367
110368
110369
110370
110371
110372
110373
110374
110375
110376
110377
110378
110379
110380
110381
110382
110383
110384
110385
110386
110387
110388
110389
110390
110391
110392
110393
110394
110395
110396
110397
110398
110399
110400
110401
110402
110403
110404
110405
110406
110407
110408
110409
110410
110411
110412
110413
110414
110415
110416
110417
110418
110419
110420
110421
110422
110423
110424
110425
110426
110427
110428
110429
110430
110431
110432
110433
110434
110435
110436
110437
110438
110439
110440
110441
110442
110443
110444
110445
110446
110447
110448
110449
110450
110451
110452
110453
110454
110455
110456
110457
110458
110459
110460
110461
110462
110463
110464
110465
110466
110467
110468
110469
110470
110471
110472
110473
110474
110475
110476
110477
110478
110479
110480
110481
110482
110483
110484
110485
110486
110487
110488
110489
110490
110491
110492
110493
110494
110495
110496
110497
110498
110499
110500
110501
110502
110503
110504
110505
110506
110507
110508
110509
110510
110511
110512
110513
110514
110515
110516
110517
110518
110519
110520
110521
110522
110523
110524
110525
110526
110527
110528
110529
110530
110531
110532
110533
110534
110535
110536
110537
110538
110539
110540
110541
110542
110543
110544
110545
110546
110547
110548
110549
110550
110551
110552
110553
110554
110555
110556
110557
110558
110559
110560
110561
110562
110563
110564
110565
110566
110567
110568
110569
110570
110571
110572
110573
110574
110575
110576
110577
110578
110579
110580
110581
110582
110583
110584
110585
110586
110587
110588
110589
110590
110591
110592
110593
110594
110595
110596
110597
110598
110599
110600
110601
110602
110603
110604
110605
110606
110607
110608
110609
110610
110611
110612
110613
110614
110615
110616
110617
110618
110619
110620
110621
110622
110623
110624
110625
110626
110627
110628
110629
110630
110631
110632
110633
110634
110635
110636
110637
110638
110639
110640
110641
110642
110643
110644
110645
110646
110647
110648
110649
110650
110651
110652
110653
110654
110655
110656
110657
110658
110659
110660
110661
110662
110663
110664
110665
110666
110667
110668
110669
110670
110671
110672
110673
110674
110675
110676
110677
110678
110679
110680
110681
110682
110683
110684
110685
110686
110687
110688
110689
110690
110691
110692
110693
110694
110695
110696
110697
110698
110699
110700
110701
110702
110703
110704
110705
110706
110707
110708
110709
110710
110711
110712
110713
110714
110715
110716
110717
110718
110719
110720
110721
110722
110723
110724
110725
110726
110727
110728
110729
110730
110731
110732
110733
110734
110735
110736
110737
110738
110739
110740
110741
110742
110743
110744
110745
110746
110747
110748
110749
110750
110751
110752
110753
110754
110755
110756
110757
110758
110759
110760
110761
110762
110763
110764
110765
110766
110767
110768
110769
110770
110771
110772
110773
110774
110775
110776
110777
110778
110779
110780
110781
110782
110783
110784
110785
110786
110787
110788
110789
110790
110791
110792
110793
110794
110795
110796
110797
110798
110799
110800
110801
110802
110803
110804
110805
110806
110807
110808
110809
110810
110811
110812
110813
110814
110815
110816
110817
110818
110819
110820
110821
110822
110823
110824
110825
110826
110827
110828
110829
110830
110831
110832
110833
110834
110835
110836
110837
110838
110839
110840
110841
110842
110843
110844
110845
110846
110847
110848
110849
110850
110851
110852
110853
110854
110855
110856
110857
110858
110859
110860
110861
110862
110863
110864
110865
110866
110867
110868
110869
110870
110871
110872
110873
110874
110875
110876
110877
110878
110879
110880
110881
110882
110883
110884
110885
110886
110887
110888
110889
110890
110891
110892
110893
110894
110895
110896
110897
110898
110899
110900
110901
110902
110903
110904
110905
110906
110907
110908
110909
110910
110911
110912
110913
110914
110915
110916
110917
110918
110919
110920
110921
110922
110923
110924
110925
110926
110927
110928
110929
110930
110931
110932
110933
110934
110935
110936
110937
110938
110939
110940
110941
110942
110943
110944
110945
110946
110947
110948
110949
110950
110951
110952
110953
110954
110955
110956
110957
110958
110959
110960
110961
110962
110963
110964
110965
110966
110967
110968
110969
110970
110971
110972
110973
110974
110975
110976
110977
110978
110979
110980
110981
110982
110983
110984
110985
110986
110987
110988
110989
110990
110991
110992
110993
110994
110995
110996
110997
110998
110999
111000
111001
111002
111003
111004
111005
111006
111007
111008
111009
111010
111011
111012
111013
111014
111015
111016
111017
111018
111019
111020
111021
111022
111023
111024
111025
111026
111027
111028
111029
111030
111031
111032
111033
111034
111035
111036
111037
111038
111039
111040
111041
111042
111043
111044
111045
111046
111047
111048
111049
111050
111051
111052
111053
111054
111055
111056
111057
111058
111059
111060
111061
111062
111063
111064
111065
111066
111067
111068
111069
111070
111071
111072
111073
111074
111075
111076
111077
111078
111079
111080
111081
111082
111083
111084
111085
111086
111087
111088
111089
111090
111091
111092
111093
111094
111095
111096
111097
111098
111099
111100
111101
111102
111103
111104
111105
111106
111107
111108
111109
111110
111111
111112
111113
111114
111115
111116
111117
111118
111119
111120
111121
111122
111123
111124
111125
111126
111127
111128
111129
111130
111131
111132
111133
111134
111135
111136
111137
111138
111139
111140
111141
111142
111143
111144
111145
111146
111147
111148
111149
111150
111151
111152
111153
111154
111155
111156
111157
111158
111159
111160
111161
111162
111163
111164
111165
111166
111167
111168
111169
111170
111171
111172
111173
111174
111175
111176
111177
111178
111179
111180
111181
111182
111183
111184
111185
111186
111187
111188
111189
111190
111191
111192
111193
111194
111195
111196
111197
111198
111199
111200
111201
111202
111203
111204
111205
111206
111207
111208
111209
111210
111211
111212
111213
111214
111215
111216
111217
111218
111219
111220
111221
111222
111223
111224
111225
111226
111227
111228
111229
111230
111231
111232
111233
111234
111235
111236
111237
111238
111239
111240
111241
111242
111243
111244
111245
111246
111247
111248
111249
111250
111251
111252
111253
111254
111255
111256
111257
111258
111259
111260
111261
111262
111263
111264
111265
111266
111267
111268
111269
111270
111271
111272
111273
111274
111275
111276
111277
111278
111279
111280
111281
111282
111283
111284
111285
111286
111287
111288
111289
111290
111291
111292
111293
111294
111295
111296
111297
111298
111299
111300
111301
111302
111303
111304
111305
111306
111307
111308
111309
111310
111311
111312
111313
111314
111315
111316
111317
111318
111319
111320
111321
111322
111323
111324
111325
111326
111327
111328
111329
111330
111331
111332
111333
111334
111335
111336
111337
111338
111339
111340
111341
111342
111343
111344
111345
111346
111347
111348
111349
111350
111351
111352
111353
111354
111355
111356
111357
111358
111359
111360
111361
111362
111363
111364
111365
111366
111367
111368
111369
111370
111371
111372
111373
111374
111375
111376
111377
111378
111379
111380
111381
111382
111383
111384
111385
111386
111387
111388
111389
111390
111391
111392
111393
111394
111395
111396
111397
111398
111399
111400
111401
111402
111403
111404
111405
111406
111407
111408
111409
111410
111411
111412
111413
111414
111415
111416
111417
111418
111419
111420
111421
111422
111423
111424
111425
111426
111427
111428
111429
111430
111431
111432
111433
111434
111435
111436
111437
111438
111439
111440
111441
111442
111443
111444
111445
111446
111447
111448
111449
111450
111451
111452
111453
111454
111455
111456
111457
111458
111459
111460
111461
111462
111463
111464
111465
111466
111467
111468
111469
111470
111471
111472
111473
111474
111475
111476
111477
111478
111479
111480
111481
111482
111483
111484
111485
111486
111487
111488
111489
111490
111491
111492
111493
111494
111495
111496
111497
111498
111499
111500
111501
111502
111503
111504
111505
111506
111507
111508
111509
111510
111511
111512
111513
111514
111515
111516
111517
111518
111519
111520
111521
111522
111523
111524
111525
111526
111527
111528
111529
111530
111531
111532
111533
111534
111535
111536
111537
111538
111539
111540
111541
111542
111543
111544
111545
111546
111547
111548
111549
111550
111551
111552
111553
111554
111555
111556
111557
111558
111559
111560
111561
111562
111563
111564
111565
111566
111567
111568
111569
111570
111571
111572
111573
111574
111575
111576
111577
111578
111579
111580
111581
111582
111583
111584
111585
111586
111587
111588
111589
111590
111591
111592
111593
111594
111595
111596
111597
111598
111599
111600
111601
111602
111603
111604
111605
111606
111607
111608
111609
111610
111611
111612
111613
111614
111615
111616
111617
111618
111619
111620
111621
111622
111623
111624
111625
111626
111627
111628
111629
111630
111631
111632
111633
111634
111635
111636
111637
111638
111639
111640
111641
111642
111643
111644
111645
111646
111647
111648
111649
111650
111651
111652
111653
111654
111655
111656
111657
111658
111659
111660
111661
111662
111663
111664
111665
111666
111667
111668
111669
111670
111671
111672
111673
111674
111675
111676
111677
111678
111679
111680
111681
111682
111683
111684
111685
111686
111687
111688
111689
111690
111691
111692
111693
111694
111695
111696
111697
111698
111699
111700
111701
111702
111703
111704
111705
111706
111707
111708
111709
111710
111711
111712
111713
111714
111715
111716
111717
111718
111719
111720
111721
111722
111723
111724
111725
111726
111727
111728
111729
111730
111731
111732
111733
111734
111735
111736
111737
111738
111739
111740
111741
111742
111743
111744
111745
111746
111747
111748
111749
111750
111751
111752
111753
111754
111755
111756
111757
111758
111759
111760
111761
111762
111763
111764
111765
111766
111767
111768
111769
111770
111771
111772
111773
111774
111775
111776
111777
111778
111779
111780
111781
111782
111783
111784
111785
111786
111787
111788
111789
111790
111791
111792
111793
111794
111795
111796
111797
111798
111799
111800
111801
111802
111803
111804
111805
111806
111807
111808
111809
111810
111811
111812
111813
111814
111815
111816
111817
111818
111819
111820
111821
111822
111823
111824
111825
111826
111827
111828
111829
111830
111831
111832
111833
111834
111835
111836
111837
111838
111839
111840
111841
111842
111843
111844
111845
111846
111847
111848
111849
111850
111851
111852
111853
111854
111855
111856
111857
111858
111859
111860
111861
111862
111863
111864
111865
111866
111867
111868
111869
111870
111871
111872
111873
111874
111875
111876
111877
111878
111879
111880
111881
111882
111883
111884
111885
111886
111887
111888
111889
111890
111891
111892
111893
111894
111895
111896
111897
111898
111899
111900
111901
111902
111903
111904
111905
111906
111907
111908
111909
111910
111911
111912
111913
111914
111915
111916
111917
111918
111919
111920
111921
111922
111923
111924
111925
111926
111927
111928
111929
111930
111931
111932
111933
111934
111935
111936
111937
111938
111939
111940
111941
111942
111943
111944
111945
111946
111947
111948
111949
111950
111951
111952
111953
111954
111955
111956
111957
111958
111959
111960
111961
111962
111963
111964
111965
111966
111967
111968
111969
111970
111971
111972
111973
111974
111975
111976
111977
111978
111979
111980
111981
111982
111983
111984
111985
111986
111987
111988
111989
111990
111991
111992
111993
111994
111995
111996
111997
111998
111999
112000
112001
112002
112003
112004
112005
112006
112007
112008
112009
112010
112011
112012
112013
112014
112015
112016
112017
112018
112019
112020
112021
112022
112023
112024
112025
112026
112027
112028
112029
112030
112031
112032
112033
112034
112035
112036
112037
112038
112039
112040
112041
112042
112043
112044
112045
112046
112047
112048
112049
112050
112051
112052
112053
112054
112055
112056
112057
112058
112059
112060
112061
112062
112063
112064
112065
112066
112067
112068
112069
112070
112071
112072
112073
112074
112075
112076
112077
112078
112079
112080
112081
112082
112083
112084
112085
112086
112087
112088
112089
112090
112091
112092
112093
112094
112095
112096
112097
112098
112099
112100
112101
112102
112103
112104
112105
112106
112107
112108
112109
112110
112111
112112
112113
112114
112115
112116
112117
112118
112119
112120
112121
112122
112123
112124
112125
112126
112127
112128
112129
112130
112131
112132
112133
112134
112135
112136
112137
112138
112139
112140
112141
112142
112143
112144
112145
112146
112147
112148
112149
112150
112151
112152
112153
112154
112155
112156
112157
112158
112159
112160
112161
112162
112163
112164
112165
112166
112167
112168
112169
112170
112171
112172
112173
112174
112175
112176
112177
112178
112179
112180
112181
112182
112183
112184
112185
112186
112187
112188
112189
112190
112191
112192
112193
112194
112195
112196
112197
112198
112199
112200
112201
112202
112203
112204
112205
112206
112207
112208
112209
112210
112211
112212
112213
112214
112215
112216
112217
112218
112219
112220
112221
112222
112223
112224
112225
112226
112227
112228
112229
112230
112231
112232
112233
112234
112235
112236
112237
112238
112239
112240
112241
112242
112243
112244
112245
112246
112247
112248
112249
112250
112251
112252
112253
112254
112255
112256
112257
112258
112259
112260
112261
112262
112263
112264
112265
112266
112267
112268
112269
112270
112271
112272
112273
112274
112275
112276
112277
112278
112279
112280
112281
112282
112283
112284
112285
112286
112287
112288
112289
112290
112291
112292
112293
112294
112295
112296
112297
112298
112299
112300
112301
112302
112303
112304
112305
112306
112307
112308
112309
112310
112311
112312
112313
112314
112315
112316
112317
112318
112319
112320
112321
112322
112323
112324
112325
112326
112327
112328
112329
112330
112331
112332
112333
112334
112335
112336
112337
112338
112339
112340
112341
112342
112343
112344
112345
112346
112347
112348
112349
112350
112351
112352
112353
112354
112355
112356
112357
112358
112359
112360
112361
112362
112363
112364
112365
112366
112367
112368
112369
112370
112371
112372
112373
112374
112375
112376
112377
112378
112379
112380
112381
112382
112383
112384
112385
112386
112387
112388
112389
112390
112391
112392
112393
112394
112395
112396
112397
112398
112399
112400
112401
112402
112403
112404
112405
112406
112407
112408
112409
112410
112411
112412
112413
112414
112415
112416
112417
112418
112419
112420
112421
112422
112423
112424
112425
112426
112427
112428
112429
112430
112431
112432
112433
112434
112435
112436
112437
112438
112439
112440
112441
112442
112443
112444
112445
112446
112447
112448
112449
112450
112451
112452
112453
112454
112455
112456
112457
112458
112459
112460
112461
112462
112463
112464
112465
112466
112467
112468
112469
112470
112471
112472
112473
112474
112475
112476
112477
112478
112479
112480
112481
112482
112483
112484
112485
112486
112487
112488
112489
112490
112491
112492
112493
112494
112495
112496
112497
112498
112499
112500
112501
112502
112503
112504
112505
112506
112507
112508
112509
112510
112511
112512
112513
112514
112515
112516
112517
112518
112519
112520
112521
112522
112523
112524
112525
112526
112527
112528
112529
112530
112531
112532
112533
112534
112535
112536
112537
112538
112539
112540
112541
112542
112543
112544
112545
112546
112547
112548
112549
112550
112551
112552
112553
112554
112555
112556
112557
112558
112559
112560
112561
112562
112563
112564
112565
112566
112567
112568
112569
112570
112571
112572
112573
112574
112575
112576
112577
112578
112579
112580
112581
112582
112583
112584
112585
112586
112587
112588
112589
112590
112591
112592
112593
112594
112595
112596
112597
112598
112599
112600
112601
112602
112603
112604
112605
112606
112607
112608
112609
112610
112611
112612
112613
112614
112615
112616
112617
112618
112619
112620
112621
112622
112623
112624
112625
112626
112627
112628
112629
112630
112631
112632
112633
112634
112635
112636
112637
112638
112639
112640
112641
112642
112643
112644
112645
112646
112647
112648
112649
112650
112651
112652
112653
112654
112655
112656
112657
112658
112659
112660
112661
112662
112663
112664
112665
112666
112667
112668
112669
112670
112671
112672
112673
112674
112675
112676
112677
112678
112679
112680
112681
112682
112683
112684
112685
112686
112687
112688
112689
112690
112691
112692
112693
112694
112695
112696
112697
112698
112699
112700
112701
112702
112703
112704
112705
112706
112707
112708
112709
112710
112711
112712
112713
112714
112715
112716
112717
112718
112719
112720
112721
112722
112723
112724
112725
112726
112727
112728
112729
112730
112731
112732
112733
112734
112735
112736
112737
112738
112739
112740
112741
112742
112743
112744
112745
112746
112747
112748
112749
112750
112751
112752
112753
112754
112755
112756
112757
112758
112759
112760
112761
112762
112763
112764
112765
112766
112767
112768
112769
112770
112771
112772
112773
112774
112775
112776
112777
112778
112779
112780
112781
112782
112783
112784
112785
112786
112787
112788
112789
112790
112791
112792
112793
112794
112795
112796
112797
112798
112799
112800
112801
112802
112803
112804
112805
112806
112807
112808
112809
112810
112811
112812
112813
112814
112815
112816
112817
112818
112819
112820
112821
112822
112823
112824
112825
112826
112827
112828
112829
112830
112831
112832
112833
112834
112835
112836
112837
112838
112839
112840
112841
112842
112843
112844
112845
112846
112847
112848
112849
112850
112851
112852
112853
112854
112855
112856
112857
112858
112859
112860
112861
112862
112863
112864
112865
112866
112867
112868
112869
112870
112871
112872
112873
112874
112875
112876
112877
112878
112879
112880
112881
112882
112883
112884
112885
112886
112887
112888
112889
112890
112891
112892
112893
112894
112895
112896
112897
112898
112899
112900
112901
112902
112903
112904
112905
112906
112907
112908
112909
112910
112911
112912
112913
112914
112915
112916
112917
112918
112919
112920
112921
112922
112923
112924
112925
112926
112927
112928
112929
112930
112931
112932
112933
112934
112935
112936
112937
112938
112939
112940
112941
112942
112943
112944
112945
112946
112947
112948
112949
112950
112951
112952
112953
112954
112955
112956
112957
112958
112959
112960
112961
112962
112963
112964
112965
112966
112967
112968
112969
112970
112971
112972
112973
112974
112975
112976
112977
112978
112979
112980
112981
112982
112983
112984
112985
112986
112987
112988
112989
112990
112991
112992
112993
112994
112995
112996
112997
112998
112999
113000
113001
113002
113003
113004
113005
113006
113007
113008
113009
113010
113011
113012
113013
113014
113015
113016
113017
113018
113019
113020
113021
113022
113023
113024
113025
113026
113027
113028
113029
113030
113031
113032
113033
113034
113035
113036
113037
113038
113039
113040
113041
113042
113043
113044
113045
113046
113047
113048
113049
113050
113051
113052
113053
113054
113055
113056
113057
113058
113059
113060
113061
113062
113063
113064
113065
113066
113067
113068
113069
113070
113071
113072
113073
113074
113075
113076
113077
113078
113079
113080
113081
113082
113083
113084
113085
113086
113087
113088
113089
113090
113091
113092
113093
113094
113095
113096
113097
113098
113099
113100
113101
113102
113103
113104
113105
113106
113107
113108
113109
113110
113111
113112
113113
113114
113115
113116
113117
113118
113119
113120
113121
113122
113123
113124
113125
113126
113127
113128
113129
113130
113131
113132
113133
113134
113135
113136
113137
113138
113139
113140
113141
113142
113143
113144
113145
113146
113147
113148
113149
113150
113151
113152
113153
113154
113155
113156
113157
113158
113159
113160
113161
113162
113163
113164
113165
113166
113167
113168
113169
113170
113171
113172
113173
113174
113175
113176
113177
113178
113179
113180
113181
113182
113183
113184
113185
113186
113187
113188
113189
113190
113191
113192
113193
113194
113195
113196
113197
113198
113199
113200
113201
113202
113203
113204
113205
113206
113207
113208
113209
113210
113211
113212
113213
113214
113215
113216
113217
113218
113219
113220
113221
113222
113223
113224
113225
113226
113227
113228
113229
113230
113231
113232
113233
113234
113235
113236
113237
113238
113239
113240
113241
113242
113243
113244
113245
113246
113247
113248
113249
113250
113251
113252
113253
113254
113255
113256
113257
113258
113259
113260
113261
113262
113263
113264
113265
113266
113267
113268
113269
113270
113271
113272
113273
113274
113275
113276
113277
113278
113279
113280
113281
113282
113283
113284
113285
113286
113287
113288
113289
113290
113291
113292
113293
113294
113295
113296
113297
113298
113299
113300
113301
113302
113303
113304
113305
113306
113307
113308
113309
113310
113311
113312
113313
113314
113315
113316
113317
113318
113319
113320
113321
113322
113323
113324
113325
113326
113327
113328
113329
113330
113331
113332
113333
113334
113335
113336
113337
113338
113339
113340
113341
113342
113343
113344
113345
113346
113347
113348
113349
113350
113351
113352
113353
113354
113355
113356
113357
113358
113359
113360
113361
113362
113363
113364
113365
113366
113367
113368
113369
113370
113371
113372
113373
113374
113375
113376
113377
113378
113379
113380
113381
113382
113383
113384
113385
113386
113387
113388
113389
113390
113391
113392
113393
113394
113395
113396
113397
113398
113399
113400
113401
113402
113403
113404
113405
113406
113407
113408
113409
113410
113411
113412
113413
113414
113415
113416
113417
113418
113419
113420
113421
113422
113423
113424
113425
113426
113427
113428
113429
113430
113431
113432
113433
113434
113435
113436
113437
113438
113439
113440
113441
113442
113443
113444
113445
113446
113447
113448
113449
113450
113451
113452
113453
113454
113455
113456
113457
113458
113459
113460
113461
113462
113463
113464
113465
113466
113467
113468
113469
113470
113471
113472
113473
113474
113475
113476
113477
113478
113479
113480
113481
113482
113483
113484
113485
113486
113487
113488
113489
113490
113491
113492
113493
113494
113495
113496
113497
113498
113499
113500
113501
113502
113503
113504
113505
113506
113507
113508
113509
113510
113511
113512
113513
113514
113515
113516
113517
113518
113519
113520
113521
113522
113523
113524
113525
113526
113527
113528
113529
113530
113531
113532
113533
113534
113535
113536
113537
113538
113539
113540
113541
113542
113543
113544
113545
113546
113547
113548
113549
113550
113551
113552
113553
113554
113555
113556
113557
113558
113559
113560
113561
113562
113563
113564
113565
113566
113567
113568
113569
113570
113571
113572
113573
113574
113575
113576
113577
113578
113579
113580
113581
113582
113583
113584
113585
113586
113587
113588
113589
113590
113591
113592
113593
113594
113595
113596
113597
113598
113599
113600
113601
113602
113603
113604
113605
113606
113607
113608
113609
113610
113611
113612
113613
113614
113615
113616
113617
113618
113619
113620
113621
113622
113623
113624
113625
113626
113627
113628
113629
113630
113631
113632
113633
113634
113635
113636
113637
113638
113639
113640
113641
113642
113643
113644
113645
113646
113647
113648
113649
113650
113651
113652
113653
113654
113655
113656
113657
113658
113659
113660
113661
113662
113663
113664
113665
113666
113667
113668
113669
113670
113671
113672
113673
113674
113675
113676
113677
113678
113679
113680
113681
113682
113683
113684
113685
113686
113687
113688
113689
113690
113691
113692
113693
113694
113695
113696
113697
113698
113699
113700
113701
113702
113703
113704
113705
113706
113707
113708
113709
113710
113711
113712
113713
113714
113715
113716
113717
113718
113719
113720
113721
113722
113723
113724
113725
113726
113727
113728
113729
113730
113731
113732
113733
113734
113735
113736
113737
113738
113739
113740
113741
113742
113743
113744
113745
113746
113747
113748
113749
113750
113751
113752
113753
113754
113755
113756
113757
113758
113759
113760
113761
113762
113763
113764
113765
113766
113767
113768
113769
113770
113771
113772
113773
113774
113775
113776
113777
113778
113779
113780
113781
113782
113783
113784
113785
113786
113787
113788
113789
113790
113791
113792
113793
113794
113795
113796
113797
113798
113799
113800
113801
113802
113803
113804
113805
113806
113807
113808
113809
113810
113811
113812
113813
113814
113815
113816
113817
113818
113819
113820
113821
113822
113823
113824
113825
113826
113827
113828
113829
113830
113831
113832
113833
113834
113835
113836
113837
113838
113839
113840
113841
113842
113843
113844
113845
113846
113847
113848
113849
113850
113851
113852
113853
113854
113855
113856
113857
113858
113859
113860
113861
113862
113863
113864
113865
113866
113867
113868
113869
113870
113871
113872
113873
113874
113875
113876
113877
113878
113879
113880
113881
113882
113883
113884
113885
113886
113887
113888
113889
113890
113891
113892
113893
113894
113895
113896
113897
113898
113899
113900
113901
113902
113903
113904
113905
113906
113907
113908
113909
113910
113911
113912
113913
113914
113915
113916
113917
113918
113919
113920
113921
113922
113923
113924
113925
113926
113927
113928
113929
113930
113931
113932
113933
113934
113935
113936
113937
113938
113939
113940
113941
113942
113943
113944
113945
113946
113947
113948
113949
113950
113951
113952
113953
113954
113955
113956
113957
113958
113959
113960
113961
113962
113963
113964
113965
113966
113967
113968
113969
113970
113971
113972
113973
113974
113975
113976
113977
113978
113979
113980
113981
113982
113983
113984
113985
113986
113987
113988
113989
113990
113991
113992
113993
113994
113995
113996
113997
113998
113999
114000
114001
114002
114003
114004
114005
114006
114007
114008
114009
114010
114011
114012
114013
114014
114015
114016
114017
114018
114019
114020
114021
114022
114023
114024
114025
114026
114027
114028
114029
114030
114031
114032
114033
114034
114035
114036
114037
114038
114039
114040
114041
114042
114043
114044
114045
114046
114047
114048
114049
114050
114051
114052
114053
114054
114055
114056
114057
114058
114059
114060
114061
114062
114063
114064
114065
114066
114067
114068
114069
114070
114071
114072
114073
114074
114075
114076
114077
114078
114079
114080
114081
114082
114083
114084
114085
114086
114087
114088
114089
114090
114091
114092
114093
114094
114095
114096
114097
114098
114099
114100
114101
114102
114103
114104
114105
114106
114107
114108
114109
114110
114111
114112
114113
114114
114115
114116
114117
114118
114119
114120
114121
114122
114123
114124
114125
114126
114127
114128
114129
114130
114131
114132
114133
114134
114135
114136
114137
114138
114139
114140
114141
114142
114143
114144
114145
114146
114147
114148
114149
114150
114151
114152
114153
114154
114155
114156
114157
114158
114159
114160
114161
114162
114163
114164
114165
114166
114167
114168
114169
114170
114171
114172
114173
114174
114175
114176
114177
114178
114179
114180
114181
114182
114183
114184
114185
114186
114187
114188
114189
114190
114191
114192
114193
114194
114195
114196
114197
114198
114199
114200
114201
114202
114203
114204
114205
114206
114207
114208
114209
114210
114211
114212
114213
114214
114215
114216
114217
114218
114219
114220
114221
114222
114223
114224
114225
114226
114227
114228
114229
114230
114231
114232
114233
114234
114235
114236
114237
114238
114239
114240
114241
114242
114243
114244
114245
114246
114247
114248
114249
114250
114251
114252
114253
114254
114255
114256
114257
114258
114259
114260
114261
114262
114263
114264
114265
114266
114267
114268
114269
114270
114271
114272
114273
114274
114275
114276
114277
114278
114279
114280
114281
114282
114283
114284
114285
114286
114287
114288
114289
114290
114291
114292
114293
114294
114295
114296
114297
114298
114299
114300
114301
114302
114303
114304
114305
114306
114307
114308
114309
114310
114311
114312
114313
114314
114315
114316
114317
114318
114319
114320
114321
114322
114323
114324
114325
114326
114327
114328
114329
114330
114331
114332
114333
114334
114335
114336
114337
114338
114339
114340
114341
114342
114343
114344
114345
114346
114347
114348
114349
114350
114351
114352
114353
114354
114355
114356
114357
114358
114359
114360
114361
114362
114363
114364
114365
114366
114367
114368
114369
114370
114371
114372
114373
114374
114375
114376
114377
114378
114379
114380
114381
114382
114383
114384
114385
114386
114387
114388
114389
114390
114391
114392
114393
114394
114395
114396
114397
114398
114399
114400
114401
114402
114403
114404
114405
114406
114407
114408
114409
114410
114411
114412
114413
114414
114415
114416
114417
114418
114419
114420
114421
114422
114423
114424
114425
114426
114427
114428
114429
114430
114431
114432
114433
114434
114435
114436
114437
114438
114439
114440
114441
114442
114443
114444
114445
114446
114447
114448
114449
114450
114451
114452
114453
114454
114455
114456
114457
114458
114459
114460
114461
114462
114463
114464
114465
114466
114467
114468
114469
114470
114471
114472
114473
114474
114475
114476
114477
114478
114479
114480
114481
114482
114483
114484
114485
114486
114487
114488
114489
114490
114491
114492
114493
114494
114495
114496
114497
114498
114499
114500
114501
114502
114503
114504
114505
114506
114507
114508
114509
114510
114511
114512
114513
114514
114515
114516
114517
114518
114519
114520
114521
114522
114523
114524
114525
114526
114527
114528
114529
114530
114531
114532
114533
114534
114535
114536
114537
114538
114539
114540
114541
114542
114543
114544
114545
114546
114547
114548
114549
114550
114551
114552
114553
114554
114555
114556
114557
114558
114559
114560
114561
114562
114563
114564
114565
114566
114567
114568
114569
114570
114571
114572
114573
114574
114575
114576
114577
114578
114579
114580
114581
114582
114583
114584
114585
114586
114587
114588
114589
114590
114591
114592
114593
114594
114595
114596
114597
114598
114599
114600
114601
114602
114603
114604
114605
114606
114607
114608
114609
114610
114611
114612
114613
114614
114615
114616
114617
114618
114619
114620
114621
114622
114623
114624
114625
114626
114627
114628
114629
114630
114631
114632
114633
114634
114635
114636
114637
114638
114639
114640
114641
114642
114643
114644
114645
114646
114647
114648
114649
114650
114651
114652
114653
114654
114655
114656
114657
114658
114659
114660
114661
114662
114663
114664
114665
114666
114667
114668
114669
114670
114671
114672
114673
114674
114675
114676
114677
114678
114679
114680
114681
114682
114683
114684
114685
114686
114687
114688
114689
114690
114691
114692
114693
114694
114695
114696
114697
114698
114699
114700
114701
114702
114703
114704
114705
114706
114707
114708
114709
114710
114711
114712
114713
114714
114715
114716
114717
114718
114719
114720
114721
114722
114723
114724
114725
114726
114727
114728
114729
114730
114731
114732
114733
114734
114735
114736
114737
114738
114739
114740
114741
114742
114743
114744
114745
114746
114747
114748
114749
114750
114751
114752
114753
114754
114755
114756
114757
114758
114759
114760
114761
114762
114763
114764
114765
114766
114767
114768
114769
114770
114771
114772
114773
114774
114775
114776
114777
114778
114779
114780
114781
114782
114783
114784
114785
114786
114787
114788
114789
114790
114791
114792
114793
114794
114795
114796
114797
114798
114799
114800
114801
114802
114803
114804
114805
114806
114807
114808
114809
114810
114811
114812
114813
114814
114815
114816
114817
114818
114819
114820
114821
114822
114823
114824
114825
114826
114827
114828
114829
114830
114831
114832
114833
114834
114835
114836
114837
114838
114839
114840
114841
114842
114843
114844
114845
114846
114847
114848
114849
114850
114851
114852
114853
114854
114855
114856
114857
114858
114859
114860
114861
114862
114863
114864
114865
114866
114867
114868
114869
114870
114871
114872
114873
114874
114875
114876
114877
114878
114879
114880
114881
114882
114883
114884
114885
114886
114887
114888
114889
114890
114891
114892
114893
114894
114895
114896
114897
114898
114899
114900
114901
114902
114903
114904
114905
114906
114907
114908
114909
114910
114911
114912
114913
114914
114915
114916
114917
114918
114919
114920
114921
114922
114923
114924
114925
114926
114927
114928
114929
114930
114931
114932
114933
114934
114935
114936
114937
114938
114939
114940
114941
114942
114943
114944
114945
114946
114947
114948
114949
114950
114951
114952
114953
114954
114955
114956
114957
114958
114959
114960
114961
114962
114963
114964
114965
114966
114967
114968
114969
114970
114971
114972
114973
114974
114975
114976
114977
114978
114979
114980
114981
114982
114983
114984
114985
114986
114987
114988
114989
114990
114991
114992
114993
114994
114995
114996
114997
114998
114999
115000
115001
115002
115003
115004
115005
115006
115007
115008
115009
115010
115011
115012
115013
115014
115015
115016
115017
115018
115019
115020
115021
115022
115023
115024
115025
115026
115027
115028
115029
115030
115031
115032
115033
115034
115035
115036
115037
115038
115039
115040
115041
115042
115043
115044
115045
115046
115047
115048
115049
115050
115051
115052
115053
115054
115055
115056
115057
115058
115059
115060
115061
115062
115063
115064
115065
115066
115067
115068
115069
115070
115071
115072
115073
115074
115075
115076
115077
115078
115079
115080
115081
115082
115083
115084
115085
115086
115087
115088
115089
115090
115091
115092
115093
115094
115095
115096
115097
115098
115099
115100
115101
115102
115103
115104
115105
115106
115107
115108
115109
115110
115111
115112
115113
115114
115115
115116
115117
115118
115119
115120
115121
115122
115123
115124
115125
115126
115127
115128
115129
115130
115131
115132
115133
115134
115135
115136
115137
115138
115139
115140
115141
115142
115143
115144
115145
115146
115147
115148
115149
115150
115151
115152
115153
115154
115155
115156
115157
115158
115159
115160
115161
115162
115163
115164
115165
115166
115167
115168
115169
115170
115171
115172
115173
115174
115175
115176
115177
115178
115179
115180
115181
115182
115183
115184
115185
115186
115187
115188
115189
115190
115191
115192
115193
115194
115195
115196
115197
115198
115199
115200
115201
115202
115203
115204
115205
115206
115207
115208
115209
115210
115211
115212
115213
115214
115215
115216
115217
115218
115219
115220
115221
115222
115223
115224
115225
115226
115227
115228
115229
115230
115231
115232
115233
115234
115235
115236
115237
115238
115239
115240
115241
115242
115243
115244
115245
115246
115247
115248
115249
115250
115251
115252
115253
115254
115255
115256
115257
115258
115259
115260
115261
115262
115263
115264
115265
115266
115267
115268
115269
115270
115271
115272
115273
115274
115275
115276
115277
115278
115279
115280
115281
115282
115283
115284
115285
115286
115287
115288
115289
115290
115291
115292
115293
115294
115295
115296
115297
115298
115299
115300
115301
115302
115303
115304
115305
115306
115307
115308
115309
115310
115311
115312
115313
115314
115315
115316
115317
115318
115319
115320
115321
115322
115323
115324
115325
115326
115327
115328
115329
115330
115331
115332
115333
115334
115335
115336
115337
115338
115339
115340
115341
115342
115343
115344
115345
115346
115347
115348
115349
115350
115351
115352
115353
115354
115355
115356
115357
115358
115359
115360
115361
115362
115363
115364
115365
115366
115367
115368
115369
115370
115371
115372
115373
115374
115375
115376
115377
115378
115379
115380
115381
115382
115383
115384
115385
115386
115387
115388
115389
115390
115391
115392
115393
115394
115395
115396
115397
115398
115399
115400
115401
115402
115403
115404
115405
115406
115407
115408
115409
115410
115411
115412
115413
115414
115415
115416
115417
115418
115419
115420
115421
115422
115423
115424
115425
115426
115427
115428
115429
115430
115431
115432
115433
115434
115435
115436
115437
115438
115439
115440
115441
115442
115443
115444
115445
115446
115447
115448
115449
115450
115451
115452
115453
115454
115455
115456
115457
115458
115459
115460
115461
115462
115463
115464
115465
115466
115467
115468
115469
115470
115471
115472
115473
115474
115475
115476
115477
115478
115479
115480
115481
115482
115483
115484
115485
115486
115487
115488
115489
115490
115491
115492
115493
115494
115495
115496
115497
115498
115499
115500
115501
115502
115503
115504
115505
115506
115507
115508
115509
115510
115511
115512
115513
115514
115515
115516
115517
115518
115519
115520
115521
115522
115523
115524
115525
115526
115527
115528
115529
115530
115531
115532
115533
115534
115535
115536
115537
115538
115539
115540
115541
115542
115543
115544
115545
115546
115547
115548
115549
115550
115551
115552
115553
115554
115555
115556
115557
115558
115559
115560
115561
115562
115563
115564
115565
115566
115567
115568
115569
115570
115571
115572
115573
115574
115575
115576
115577
115578
115579
115580
115581
115582
115583
115584
115585
115586
115587
115588
115589
115590
115591
115592
115593
115594
115595
115596
115597
115598
115599
115600
115601
115602
115603
115604
115605
115606
115607
115608
115609
115610
115611
115612
115613
115614
115615
115616
115617
115618
115619
115620
115621
115622
115623
115624
115625
115626
115627
115628
115629
115630
115631
115632
115633
115634
115635
115636
115637
115638
115639
115640
115641
115642
115643
115644
115645
115646
115647
115648
115649
115650
115651
115652
115653
115654
115655
115656
115657
115658
115659
115660
115661
115662
115663
115664
115665
115666
115667
115668
115669
115670
115671
115672
115673
115674
115675
115676
115677
115678
115679
115680
115681
115682
115683
115684
115685
115686
115687
115688
115689
115690
115691
115692
115693
115694
115695
115696
115697
115698
115699
115700
115701
115702
115703
115704
115705
115706
115707
115708
115709
115710
115711
115712
115713
115714
115715
115716
115717
115718
115719
115720
115721
115722
115723
115724
115725
115726
115727
115728
115729
115730
115731
115732
115733
115734
115735
115736
115737
115738
115739
115740
115741
115742
115743
115744
115745
115746
115747
115748
115749
115750
115751
115752
115753
115754
115755
115756
115757
115758
115759
115760
115761
115762
115763
115764
115765
115766
115767
115768
115769
115770
115771
115772
115773
115774
115775
115776
115777
115778
115779
115780
115781
115782
115783
115784
115785
115786
115787
115788
115789
115790
115791
115792
115793
115794
115795
115796
115797
115798
115799
115800
115801
115802
115803
115804
115805
115806
115807
115808
115809
115810
115811
115812
115813
115814
115815
115816
115817
115818
115819
115820
115821
115822
115823
115824
115825
115826
115827
115828
115829
115830
115831
115832
115833
115834
115835
115836
115837
115838
115839
115840
115841
115842
115843
115844
115845
115846
115847
115848
115849
115850
115851
115852
115853
115854
115855
115856
115857
115858
115859
115860
115861
115862
115863
115864
115865
115866
115867
115868
115869
115870
115871
115872
115873
115874
115875
115876
115877
115878
115879
115880
115881
115882
115883
115884
115885
115886
115887
115888
115889
115890
115891
115892
115893
115894
115895
115896
115897
115898
115899
115900
115901
115902
115903
115904
115905
115906
115907
115908
115909
115910
115911
115912
115913
115914
115915
115916
115917
115918
115919
115920
115921
115922
115923
115924
115925
115926
115927
115928
115929
115930
115931
115932
115933
115934
115935
115936
115937
115938
115939
115940
115941
115942
115943
115944
115945
115946
115947
115948
115949
115950
115951
115952
115953
115954
115955
115956
115957
115958
115959
115960
115961
115962
115963
115964
115965
115966
115967
115968
115969
115970
115971
115972
115973
115974
115975
115976
115977
115978
115979
115980
115981
115982
115983
115984
115985
115986
115987
115988
115989
115990
115991
115992
115993
115994
115995
115996
115997
115998
115999
116000
116001
116002
116003
116004
116005
116006
116007
116008
116009
116010
116011
116012
116013
116014
116015
116016
116017
116018
116019
116020
116021
116022
116023
116024
116025
116026
116027
116028
116029
116030
116031
116032
116033
116034
116035
116036
116037
116038
116039
116040
116041
116042
116043
116044
116045
116046
116047
116048
116049
116050
116051
116052
116053
116054
116055
116056
116057
116058
116059
116060
116061
116062
116063
116064
116065
116066
116067
116068
116069
116070
116071
116072
116073
116074
116075
116076
116077
116078
116079
116080
116081
116082
116083
116084
116085
116086
116087
116088
116089
116090
116091
116092
116093
116094
116095
116096
116097
116098
116099
116100
116101
116102
116103
116104
116105
116106
116107
116108
116109
116110
116111
116112
116113
116114
116115
116116
116117
116118
116119
116120
116121
116122
116123
116124
116125
116126
116127
116128
116129
116130
116131
116132
116133
116134
116135
116136
116137
116138
116139
116140
116141
116142
116143
116144
116145
116146
116147
116148
116149
116150
116151
116152
116153
116154
116155
116156
116157
116158
116159
116160
116161
116162
116163
116164
116165
116166
116167
116168
116169
116170
116171
116172
116173
116174
116175
116176
116177
116178
116179
116180
116181
116182
116183
116184
116185
116186
116187
116188
116189
116190
116191
116192
116193
116194
116195
116196
116197
116198
116199
116200
116201
116202
116203
116204
116205
116206
116207
116208
116209
116210
116211
116212
116213
116214
116215
116216
116217
116218
116219
116220
116221
116222
116223
116224
116225
116226
116227
116228
116229
116230
116231
116232
116233
116234
116235
116236
116237
116238
116239
116240
116241
116242
116243
116244
116245
116246
116247
116248
116249
116250
116251
116252
116253
116254
116255
116256
116257
116258
116259
116260
116261
116262
116263
116264
116265
116266
116267
116268
116269
116270
116271
116272
116273
116274
116275
116276
116277
116278
116279
116280
116281
116282
116283
116284
116285
116286
116287
116288
116289
116290
116291
116292
116293
116294
116295
116296
116297
116298
116299
116300
116301
116302
116303
116304
116305
116306
116307
116308
116309
116310
116311
116312
116313
116314
116315
116316
116317
116318
116319
116320
116321
116322
116323
116324
116325
116326
116327
116328
116329
116330
116331
116332
116333
116334
116335
116336
116337
116338
116339
116340
116341
116342
116343
116344
116345
116346
116347
116348
116349
116350
116351
116352
116353
116354
116355
116356
116357
116358
116359
116360
116361
116362
116363
116364
116365
116366
116367
116368
116369
116370
116371
116372
116373
116374
116375
116376
116377
116378
116379
116380
116381
116382
116383
116384
116385
116386
116387
116388
116389
116390
116391
116392
116393
116394
116395
116396
116397
116398
116399
116400
116401
116402
116403
116404
116405
116406
116407
116408
116409
116410
116411
116412
116413
116414
116415
116416
116417
116418
116419
116420
116421
116422
116423
116424
116425
116426
116427
116428
116429
116430
116431
116432
116433
116434
116435
116436
116437
116438
116439
116440
116441
116442
116443
116444
116445
116446
116447
116448
116449
116450
116451
116452
116453
116454
116455
116456
116457
116458
116459
116460
116461
116462
116463
116464
116465
116466
116467
116468
116469
116470
116471
116472
116473
116474
116475
116476
116477
116478
116479
116480
116481
116482
116483
116484
116485
116486
116487
116488
116489
116490
116491
116492
116493
116494
116495
116496
116497
116498
116499
116500
116501
116502
116503
116504
116505
116506
116507
116508
116509
116510
116511
116512
116513
116514
116515
116516
116517
116518
116519
116520
116521
116522
116523
116524
116525
116526
116527
116528
116529
116530
116531
116532
116533
116534
116535
116536
116537
116538
116539
116540
116541
116542
116543
116544
116545
116546
116547
116548
116549
116550
116551
116552
116553
116554
116555
116556
116557
116558
116559
116560
116561
116562
116563
116564
116565
116566
116567
116568
116569
116570
116571
116572
116573
116574
116575
116576
116577
116578
116579
116580
116581
116582
116583
116584
116585
116586
116587
116588
116589
116590
116591
116592
116593
116594
116595
116596
116597
116598
116599
116600
116601
116602
116603
116604
116605
116606
116607
116608
116609
116610
116611
116612
116613
116614
116615
116616
116617
116618
116619
116620
116621
116622
116623
116624
116625
116626
116627
116628
116629
116630
116631
116632
116633
116634
116635
116636
116637
116638
116639
116640
116641
116642
116643
116644
116645
116646
116647
116648
116649
116650
116651
116652
116653
116654
116655
116656
116657
116658
116659
116660
116661
116662
116663
116664
116665
116666
116667
116668
116669
116670
116671
116672
116673
116674
116675
116676
116677
116678
116679
116680
116681
116682
116683
116684
116685
116686
116687
116688
116689
116690
116691
116692
116693
116694
116695
116696
116697
116698
116699
116700
116701
116702
116703
116704
116705
116706
116707
116708
116709
116710
116711
116712
116713
116714
116715
116716
116717
116718
116719
116720
116721
116722
116723
116724
116725
116726
116727
116728
116729
116730
116731
116732
116733
116734
116735
116736
116737
116738
116739
116740
116741
116742
116743
116744
116745
116746
116747
116748
116749
116750
116751
116752
116753
116754
116755
116756
116757
116758
116759
116760
116761
116762
116763
116764
116765
116766
116767
116768
116769
116770
116771
116772
116773
116774
116775
116776
116777
116778
116779
116780
116781
116782
116783
116784
116785
116786
116787
116788
116789
116790
116791
116792
116793
116794
116795
116796
116797
116798
116799
116800
116801
116802
116803
116804
116805
116806
116807
116808
116809
116810
116811
116812
116813
116814
116815
116816
116817
116818
116819
116820
116821
116822
116823
116824
116825
116826
116827
116828
116829
116830
116831
116832
116833
116834
116835
116836
116837
116838
116839
116840
116841
116842
116843
116844
116845
116846
116847
116848
116849
116850
116851
116852
116853
116854
116855
116856
116857
116858
116859
116860
116861
116862
116863
116864
116865
116866
116867
116868
116869
116870
116871
116872
116873
116874
116875
116876
116877
116878
116879
116880
116881
116882
116883
116884
116885
116886
116887
116888
116889
116890
116891
116892
116893
116894
116895
116896
116897
116898
116899
116900
116901
116902
116903
116904
116905
116906
116907
116908
116909
116910
116911
116912
116913
116914
116915
116916
116917
116918
116919
116920
116921
116922
116923
116924
116925
116926
116927
116928
116929
116930
116931
116932
116933
116934
116935
116936
116937
116938
116939
116940
116941
116942
116943
116944
116945
116946
116947
116948
116949
116950
116951
116952
116953
116954
116955
116956
116957
116958
116959
116960
116961
116962
116963
116964
116965
116966
116967
116968
116969
116970
116971
116972
116973
116974
116975
116976
116977
116978
116979
116980
116981
116982
116983
116984
116985
116986
116987
116988
116989
116990
116991
116992
116993
116994
116995
116996
116997
116998
116999
117000
117001
117002
117003
117004
117005
117006
117007
117008
117009
117010
117011
117012
117013
117014
117015
117016
117017
117018
117019
117020
117021
117022
117023
117024
117025
117026
117027
117028
117029
117030
117031
117032
117033
117034
117035
117036
117037
117038
117039
117040
117041
117042
117043
117044
117045
117046
117047
117048
117049
117050
117051
117052
117053
117054
117055
117056
117057
117058
117059
117060
117061
117062
117063
117064
117065
117066
117067
117068
117069
117070
117071
117072
117073
117074
117075
117076
117077
117078
117079
117080
117081
117082
117083
117084
117085
117086
117087
117088
117089
117090
117091
117092
117093
117094
117095
117096
117097
117098
117099
117100
117101
117102
117103
117104
117105
117106
117107
117108
117109
117110
117111
117112
117113
117114
117115
117116
117117
117118
117119
117120
117121
117122
117123
117124
117125
117126
117127
117128
117129
117130
117131
117132
117133
117134
117135
117136
117137
117138
117139
117140
117141
117142
117143
117144
117145
117146
117147
117148
117149
117150
117151
117152
117153
117154
117155
117156
117157
117158
117159
117160
117161
117162
117163
117164
117165
117166
117167
117168
117169
117170
117171
117172
117173
117174
117175
117176
117177
117178
117179
117180
117181
117182
117183
117184
117185
117186
117187
117188
117189
117190
117191
117192
117193
117194
117195
117196
117197
117198
117199
117200
117201
117202
117203
117204
117205
117206
117207
117208
117209
117210
117211
117212
117213
117214
117215
117216
117217
117218
117219
117220
117221
117222
117223
117224
117225
117226
117227
117228
117229
117230
117231
117232
117233
117234
117235
117236
117237
117238
117239
117240
117241
117242
117243
117244
117245
117246
117247
117248
117249
117250
117251
117252
117253
117254
117255
117256
117257
117258
117259
117260
117261
117262
117263
117264
117265
117266
117267
117268
117269
117270
117271
117272
117273
117274
117275
117276
117277
117278
117279
117280
117281
117282
117283
117284
117285
117286
117287
117288
117289
117290
117291
117292
117293
117294
117295
117296
117297
117298
117299
117300
117301
117302
117303
117304
117305
117306
117307
117308
117309
117310
117311
117312
117313
117314
117315
117316
117317
117318
117319
117320
117321
117322
117323
117324
117325
117326
117327
117328
117329
117330
117331
117332
117333
117334
117335
117336
117337
117338
117339
117340
117341
117342
117343
117344
117345
117346
117347
117348
117349
117350
117351
117352
117353
117354
117355
117356
117357
117358
117359
117360
117361
117362
117363
117364
117365
117366
117367
117368
117369
117370
117371
117372
117373
117374
117375
117376
117377
117378
117379
117380
117381
117382
117383
117384
117385
117386
117387
117388
117389
117390
117391
117392
117393
117394
117395
117396
117397
117398
117399
117400
117401
117402
117403
117404
117405
117406
117407
117408
117409
117410
117411
117412
117413
117414
117415
117416
117417
117418
117419
117420
117421
117422
117423
117424
117425
117426
117427
117428
117429
117430
117431
117432
117433
117434
117435
117436
117437
117438
117439
117440
117441
117442
117443
117444
117445
117446
117447
117448
117449
117450
117451
117452
117453
117454
117455
117456
117457
117458
117459
117460
117461
117462
117463
117464
117465
117466
117467
117468
117469
117470
117471
117472
117473
117474
117475
117476
117477
117478
117479
117480
117481
117482
117483
117484
117485
117486
117487
117488
117489
117490
117491
117492
117493
117494
117495
117496
117497
117498
117499
117500
117501
117502
117503
117504
117505
117506
117507
117508
117509
117510
117511
117512
117513
117514
117515
117516
117517
117518
117519
117520
117521
117522
117523
117524
117525
117526
117527
117528
117529
117530
117531
117532
117533
117534
117535
117536
117537
117538
117539
117540
117541
117542
117543
117544
117545
117546
117547
117548
117549
117550
117551
117552
117553
117554
117555
117556
117557
117558
117559
117560
117561
117562
117563
117564
117565
117566
117567
117568
117569
117570
117571
117572
117573
117574
117575
117576
117577
117578
117579
117580
117581
117582
117583
117584
117585
117586
117587
117588
117589
117590
117591
117592
117593
117594
117595
117596
117597
117598
117599
117600
117601
117602
117603
117604
117605
117606
117607
117608
117609
117610
117611
117612
117613
117614
117615
117616
117617
117618
117619
117620
117621
117622
117623
117624
117625
117626
117627
117628
117629
117630
117631
117632
117633
117634
117635
117636
117637
117638
117639
117640
117641
117642
117643
117644
117645
117646
117647
117648
117649
117650
117651
117652
117653
117654
117655
117656
117657
117658
117659
117660
117661
117662
117663
117664
117665
117666
117667
117668
117669
117670
117671
117672
117673
117674
117675
117676
117677
117678
117679
117680
117681
117682
117683
117684
117685
117686
117687
117688
117689
117690
117691
117692
117693
117694
117695
117696
117697
117698
117699
117700
117701
117702
117703
117704
117705
117706
117707
117708
117709
117710
117711
117712
117713
117714
117715
117716
117717
117718
117719
117720
117721
117722
117723
117724
117725
117726
117727
117728
117729
117730
117731
117732
117733
117734
117735
117736
117737
117738
117739
117740
117741
117742
117743
117744
117745
117746
117747
117748
117749
117750
117751
117752
117753
117754
117755
117756
117757
117758
117759
117760
117761
117762
117763
117764
117765
117766
117767
117768
117769
117770
117771
117772
117773
117774
117775
117776
117777
117778
117779
117780
117781
117782
117783
117784
117785
117786
117787
117788
117789
117790
117791
117792
117793
117794
117795
117796
117797
117798
117799
117800
117801
117802
117803
117804
117805
117806
117807
117808
117809
117810
117811
117812
117813
117814
117815
117816
117817
117818
117819
117820
117821
117822
117823
117824
117825
117826
117827
117828
117829
117830
117831
117832
117833
117834
117835
117836
117837
117838
117839
117840
117841
117842
117843
117844
117845
117846
117847
117848
117849
117850
117851
117852
117853
117854
117855
117856
117857
117858
117859
117860
117861
117862
117863
117864
117865
117866
117867
117868
117869
117870
117871
117872
117873
117874
117875
117876
117877
117878
117879
117880
117881
117882
117883
117884
117885
117886
117887
117888
117889
117890
117891
117892
117893
117894
117895
117896
117897
117898
117899
117900
117901
117902
117903
117904
117905
117906
117907
117908
117909
117910
117911
117912
117913
117914
117915
117916
117917
117918
117919
117920
117921
117922
117923
117924
117925
117926
117927
117928
117929
117930
117931
117932
117933
117934
117935
117936
117937
117938
117939
117940
117941
117942
117943
117944
117945
117946
117947
117948
117949
117950
117951
117952
117953
117954
117955
117956
117957
117958
117959
117960
117961
117962
117963
117964
117965
117966
117967
117968
117969
117970
117971
117972
117973
117974
117975
117976
117977
117978
117979
117980
117981
117982
117983
117984
117985
117986
117987
117988
117989
117990
117991
117992
117993
117994
117995
117996
117997
117998
117999
118000
118001
118002
118003
118004
118005
118006
118007
118008
118009
118010
118011
118012
118013
118014
118015
118016
118017
118018
118019
118020
118021
118022
118023
118024
118025
118026
118027
118028
118029
118030
118031
118032
118033
118034
118035
118036
118037
118038
118039
118040
118041
118042
118043
118044
118045
118046
118047
118048
118049
118050
118051
118052
118053
118054
118055
118056
118057
118058
118059
118060
118061
118062
118063
118064
118065
118066
118067
118068
118069
118070
118071
118072
118073
118074
118075
118076
118077
118078
118079
118080
118081
118082
118083
118084
118085
118086
118087
118088
118089
118090
118091
118092
118093
118094
118095
118096
118097
118098
118099
118100
118101
118102
118103
118104
118105
118106
118107
118108
118109
118110
118111
118112
118113
118114
118115
118116
118117
118118
118119
118120
118121
118122
118123
118124
118125
118126
118127
118128
118129
118130
118131
118132
118133
118134
118135
118136
118137
118138
118139
118140
118141
118142
118143
118144
118145
118146
118147
118148
118149
118150
118151
118152
118153
118154
118155
118156
118157
118158
118159
118160
118161
118162
118163
118164
118165
118166
118167
118168
118169
118170
118171
118172
118173
118174
118175
118176
118177
118178
118179
118180
118181
118182
118183
118184
118185
118186
118187
118188
118189
118190
118191
118192
118193
118194
118195
118196
118197
118198
118199
118200
118201
118202
118203
118204
118205
118206
118207
118208
118209
118210
118211
118212
118213
118214
118215
118216
118217
118218
118219
118220
118221
118222
118223
118224
118225
118226
118227
118228
118229
118230
118231
118232
118233
118234
118235
118236
118237
118238
118239
118240
118241
118242
118243
118244
118245
118246
118247
118248
118249
118250
118251
118252
118253
118254
118255
118256
118257
118258
118259
118260
118261
118262
118263
118264
118265
118266
118267
118268
118269
118270
118271
118272
118273
118274
118275
118276
118277
118278
118279
118280
118281
118282
118283
118284
118285
118286
118287
118288
118289
118290
118291
118292
118293
118294
118295
118296
118297
118298
118299
118300
118301
118302
118303
118304
118305
118306
118307
118308
118309
118310
118311
118312
118313
118314
118315
118316
118317
118318
118319
118320
118321
118322
118323
118324
118325
118326
118327
118328
118329
118330
118331
118332
118333
118334
118335
118336
118337
118338
118339
118340
118341
118342
118343
118344
118345
118346
118347
118348
118349
118350
118351
118352
118353
118354
118355
118356
118357
118358
118359
118360
118361
118362
118363
118364
118365
118366
118367
118368
118369
118370
118371
118372
118373
118374
118375
118376
118377
118378
118379
118380
118381
118382
118383
118384
118385
118386
118387
118388
118389
118390
118391
118392
118393
118394
118395
118396
118397
118398
118399
118400
118401
118402
118403
118404
118405
118406
118407
118408
118409
118410
118411
118412
118413
118414
118415
118416
118417
118418
118419
118420
118421
118422
118423
118424
118425
118426
118427
118428
118429
118430
118431
118432
118433
118434
118435
118436
118437
118438
118439
118440
118441
118442
118443
118444
118445
118446
118447
118448
118449
118450
118451
118452
118453
118454
118455
118456
118457
118458
118459
118460
118461
118462
118463
118464
118465
118466
118467
118468
118469
118470
118471
118472
118473
118474
118475
118476
118477
118478
118479
118480
118481
118482
118483
118484
118485
118486
118487
118488
118489
118490
118491
118492
118493
118494
118495
118496
118497
118498
118499
118500
118501
118502
118503
118504
118505
118506
118507
118508
118509
118510
118511
118512
118513
118514
118515
118516
118517
118518
118519
118520
118521
118522
118523
118524
118525
118526
118527
118528
118529
118530
118531
118532
118533
118534
118535
118536
118537
118538
118539
118540
118541
118542
118543
118544
118545
118546
118547
118548
118549
118550
118551
118552
118553
118554
118555
118556
118557
118558
118559
118560
118561
118562
118563
118564
118565
118566
118567
118568
118569
118570
118571
118572
118573
118574
118575
118576
118577
118578
118579
118580
118581
118582
118583
118584
118585
118586
118587
118588
118589
118590
118591
118592
118593
118594
118595
118596
118597
118598
118599
118600
118601
118602
118603
118604
118605
118606
118607
118608
118609
118610
118611
118612
118613
118614
118615
118616
118617
118618
118619
118620
118621
118622
118623
118624
118625
118626
118627
118628
118629
118630
118631
118632
118633
118634
118635
118636
118637
118638
118639
118640
118641
118642
118643
118644
118645
118646
118647
118648
118649
118650
118651
118652
118653
118654
118655
118656
118657
118658
118659
118660
118661
118662
118663
118664
118665
118666
118667
118668
118669
118670
118671
118672
118673
118674
118675
118676
118677
118678
118679
118680
118681
118682
118683
118684
118685
118686
118687
118688
118689
118690
118691
118692
118693
118694
118695
118696
118697
118698
118699
118700
118701
118702
118703
118704
118705
118706
118707
118708
118709
118710
118711
118712
118713
118714
118715
118716
118717
118718
118719
118720
118721
118722
118723
118724
118725
118726
118727
118728
118729
118730
118731
118732
118733
118734
118735
118736
118737
118738
118739
118740
118741
118742
118743
118744
118745
118746
118747
118748
118749
118750
118751
118752
118753
118754
118755
118756
118757
118758
118759
118760
118761
118762
118763
118764
118765
118766
118767
118768
118769
118770
118771
118772
118773
118774
118775
118776
118777
118778
118779
118780
118781
118782
118783
118784
118785
118786
118787
118788
118789
118790
118791
118792
118793
118794
118795
118796
118797
118798
118799
118800
118801
118802
118803
118804
118805
118806
118807
118808
118809
118810
118811
118812
118813
118814
118815
118816
118817
118818
118819
118820
118821
118822
118823
118824
118825
118826
118827
118828
118829
118830
118831
118832
118833
118834
118835
118836
118837
118838
118839
118840
118841
118842
118843
118844
118845
118846
118847
118848
118849
118850
118851
118852
118853
118854
118855
118856
118857
118858
118859
118860
118861
118862
118863
118864
118865
118866
118867
118868
118869
118870
118871
118872
118873
118874
118875
118876
118877
118878
118879
118880
118881
118882
118883
118884
118885
118886
118887
118888
118889
118890
118891
118892
118893
118894
118895
118896
118897
118898
118899
118900
118901
118902
118903
118904
118905
118906
118907
118908
118909
118910
118911
118912
118913
118914
118915
118916
118917
118918
118919
118920
118921
118922
118923
118924
118925
118926
118927
118928
118929
118930
118931
118932
118933
118934
118935
118936
118937
118938
118939
118940
118941
118942
118943
118944
118945
118946
118947
118948
118949
118950
118951
118952
118953
118954
118955
118956
118957
118958
118959
118960
118961
118962
118963
118964
118965
118966
118967
118968
118969
118970
118971
118972
118973
118974
118975
118976
118977
118978
118979
118980
118981
118982
118983
118984
118985
118986
118987
118988
118989
118990
118991
118992
118993
118994
118995
118996
118997
118998
118999
119000
119001
119002
119003
119004
119005
119006
119007
119008
119009
119010
119011
119012
119013
119014
119015
119016
119017
119018
119019
119020
119021
119022
119023
119024
119025
119026
119027
119028
119029
119030
119031
119032
119033
119034
119035
119036
119037
119038
119039
119040
119041
119042
119043
119044
119045
119046
119047
119048
119049
119050
119051
119052
119053
119054
119055
119056
119057
119058
119059
119060
119061
119062
119063
119064
119065
119066
119067
119068
119069
119070
119071
119072
119073
119074
119075
119076
119077
119078
119079
119080
119081
119082
119083
119084
119085
119086
119087
119088
119089
119090
119091
119092
119093
119094
119095
119096
119097
119098
119099
119100
119101
119102
119103
119104
119105
119106
119107
119108
119109
119110
119111
119112
119113
119114
119115
119116
119117
119118
119119
119120
119121
119122
119123
119124
119125
119126
119127
119128
119129
119130
119131
119132
119133
119134
119135
119136
119137
119138
119139
119140
119141
119142
119143
119144
119145
119146
119147
119148
119149
119150
119151
119152
119153
119154
119155
119156
119157
119158
119159
119160
119161
119162
119163
119164
119165
119166
119167
119168
119169
119170
119171
119172
119173
119174
119175
119176
119177
119178
119179
119180
119181
119182
119183
119184
119185
119186
119187
119188
119189
119190
119191
119192
119193
119194
119195
119196
119197
119198
119199
119200
119201
119202
119203
119204
119205
119206
119207
119208
119209
119210
119211
119212
119213
119214
119215
119216
119217
119218
119219
119220
119221
119222
119223
119224
119225
119226
119227
119228
119229
119230
119231
119232
119233
119234
119235
119236
119237
119238
119239
119240
119241
119242
119243
119244
119245
119246
119247
119248
119249
119250
119251
119252
119253
119254
119255
119256
119257
119258
119259
119260
119261
119262
119263
119264
119265
119266
119267
119268
119269
119270
119271
119272
119273
119274
119275
119276
119277
119278
119279
119280
119281
119282
119283
119284
119285
119286
119287
119288
119289
119290
119291
119292
119293
119294
119295
119296
119297
119298
119299
119300
119301
119302
119303
119304
119305
119306
119307
119308
119309
119310
119311
119312
119313
119314
119315
119316
119317
119318
119319
119320
119321
119322
119323
119324
119325
119326
119327
119328
119329
119330
119331
119332
119333
119334
119335
119336
119337
119338
119339
119340
119341
119342
119343
119344
119345
119346
119347
119348
119349
119350
119351
119352
119353
119354
119355
119356
119357
119358
119359
119360
119361
119362
119363
119364
119365
119366
119367
119368
119369
119370
119371
119372
119373
119374
119375
119376
119377
119378
119379
119380
119381
119382
119383
119384
119385
119386
119387
119388
119389
119390
119391
119392
119393
119394
119395
119396
119397
119398
119399
119400
119401
119402
119403
119404
119405
119406
119407
119408
119409
119410
119411
119412
119413
119414
119415
119416
119417
119418
119419
119420
119421
119422
119423
119424
119425
119426
119427
119428
119429
119430
119431
119432
119433
119434
119435
119436
119437
119438
119439
119440
119441
119442
119443
119444
119445
119446
119447
119448
119449
119450
119451
119452
119453
119454
119455
119456
119457
119458
119459
119460
119461
119462
119463
119464
119465
119466
119467
119468
119469
119470
119471
119472
119473
119474
119475
119476
119477
119478
119479
119480
119481
119482
119483
119484
119485
119486
119487
119488
119489
119490
119491
119492
119493
119494
119495
119496
119497
119498
119499
119500
119501
119502
119503
119504
119505
119506
119507
119508
119509
119510
119511
119512
119513
119514
119515
119516
119517
119518
119519
119520
119521
119522
119523
119524
119525
119526
119527
119528
119529
119530
119531
119532
119533
119534
119535
119536
119537
119538
119539
119540
119541
119542
119543
119544
119545
119546
119547
119548
119549
119550
119551
119552
119553
119554
119555
119556
119557
119558
119559
119560
119561
119562
119563
119564
119565
119566
119567
119568
119569
119570
119571
119572
119573
119574
119575
119576
119577
119578
119579
119580
119581
119582
119583
119584
119585
119586
119587
119588
119589
119590
119591
119592
119593
119594
119595
119596
119597
119598
119599
119600
119601
119602
119603
119604
119605
119606
119607
119608
119609
119610
119611
119612
119613
119614
119615
119616
119617
119618
119619
119620
119621
119622
119623
119624
119625
119626
119627
119628
119629
119630
119631
119632
119633
119634
119635
119636
119637
119638
119639
119640
119641
119642
119643
119644
119645
119646
119647
119648
119649
119650
119651
119652
119653
119654
119655
119656
119657
119658
119659
119660
119661
119662
119663
119664
119665
119666
119667
119668
119669
119670
119671
119672
119673
119674
119675
119676
119677
119678
119679
119680
119681
119682
119683
119684
119685
119686
119687
119688
119689
119690
119691
119692
119693
119694
119695
119696
119697
119698
119699
119700
119701
119702
119703
119704
119705
119706
119707
119708
119709
119710
119711
119712
119713
119714
119715
119716
119717
119718
119719
119720
119721
119722
119723
119724
119725
119726
119727
119728
119729
119730
119731
119732
119733
119734
119735
119736
119737
119738
119739
119740
119741
119742
119743
119744
119745
119746
119747
119748
119749
119750
119751
119752
119753
119754
119755
119756
119757
119758
119759
119760
119761
119762
119763
119764
119765
119766
119767
119768
119769
119770
119771
119772
119773
119774
119775
119776
119777
119778
119779
119780
119781
119782
119783
119784
119785
119786
119787
119788
119789
119790
119791
119792
119793
119794
119795
119796
119797
119798
119799
119800
119801
119802
119803
119804
119805
119806
119807
119808
119809
119810
119811
119812
119813
119814
119815
119816
119817
119818
119819
119820
119821
119822
119823
119824
119825
119826
119827
119828
119829
119830
119831
119832
119833
119834
119835
119836
119837
119838
119839
119840
119841
119842
119843
119844
119845
119846
119847
119848
119849
119850
119851
119852
119853
119854
119855
119856
119857
119858
119859
119860
119861
119862
119863
119864
119865
119866
119867
119868
119869
119870
119871
119872
119873
119874
119875
119876
119877
119878
119879
119880
119881
119882
119883
119884
119885
119886
119887
119888
119889
119890
119891
119892
119893
119894
119895
119896
119897
119898
119899
119900
119901
119902
119903
119904
119905
119906
119907
119908
119909
119910
119911
119912
119913
119914
119915
119916
119917
119918
119919
119920
119921
119922
119923
119924
119925
119926
119927
119928
119929
119930
119931
119932
119933
119934
119935
119936
119937
119938
119939
119940
119941
119942
119943
119944
119945
119946
119947
119948
119949
119950
119951
119952
119953
119954
119955
119956
119957
119958
119959
119960
119961
119962
119963
119964
119965
119966
119967
119968
119969
119970
119971
119972
119973
119974
119975
119976
119977
119978
119979
119980
119981
119982
119983
119984
119985
119986
119987
119988
119989
119990
119991
119992
119993
119994
119995
119996
119997
119998
119999
120000
120001
120002
120003
120004
120005
120006
120007
120008
120009
120010
120011
120012
120013
120014
120015
120016
120017
120018
120019
120020
120021
120022
120023
120024
120025
120026
120027
120028
120029
120030
120031
120032
120033
120034
120035
120036
120037
120038
120039
120040
120041
120042
120043
120044
120045
120046
120047
120048
120049
120050
120051
120052
120053
120054
120055
120056
120057
120058
120059
120060
120061
120062
120063
120064
120065
120066
120067
120068
120069
120070
120071
120072
120073
120074
120075
120076
120077
120078
120079
120080
120081
120082
120083
120084
120085
120086
120087
120088
120089
120090
120091
120092
120093
120094
120095
120096
120097
120098
120099
120100
120101
120102
120103
120104
120105
120106
120107
120108
120109
120110
120111
120112
120113
120114
120115
120116
120117
120118
120119
120120
120121
120122
120123
120124
120125
120126
120127
120128
120129
120130
120131
120132
120133
120134
120135
120136
120137
120138
120139
120140
120141
120142
120143
120144
120145
120146
120147
120148
120149
120150
120151
120152
120153
120154
120155
120156
120157
120158
120159
120160
120161
120162
120163
120164
120165
120166
120167
120168
120169
120170
120171
120172
120173
120174
120175
120176
120177
120178
120179
120180
120181
120182
120183
120184
120185
120186
120187
120188
120189
120190
120191
120192
120193
120194
120195
120196
120197
120198
120199
120200
120201
120202
120203
120204
120205
120206
120207
120208
120209
120210
120211
120212
120213
120214
120215
120216
120217
120218
120219
120220
120221
120222
120223
120224
120225
120226
120227
120228
120229
120230
120231
120232
120233
120234
120235
120236
120237
120238
120239
120240
120241
120242
120243
120244
120245
120246
120247
120248
120249
120250
120251
120252
120253
120254
120255
120256
120257
120258
120259
120260
120261
120262
120263
120264
120265
120266
120267
120268
120269
120270
120271
120272
120273
120274
120275
120276
120277
120278
120279
120280
120281
120282
120283
120284
120285
120286
120287
120288
120289
120290
120291
120292
120293
120294
120295
120296
120297
120298
120299
120300
120301
120302
120303
120304
120305
120306
120307
120308
120309
120310
120311
120312
120313
120314
120315
120316
120317
120318
120319
120320
120321
120322
120323
120324
120325
120326
120327
120328
120329
120330
120331
120332
120333
120334
120335
120336
120337
120338
120339
120340
120341
120342
120343
120344
120345
120346
120347
120348
120349
120350
120351
120352
120353
120354
120355
120356
120357
120358
120359
120360
120361
120362
120363
120364
120365
120366
120367
120368
120369
120370
120371
120372
120373
120374
120375
120376
120377
120378
120379
120380
120381
120382
120383
120384
120385
120386
120387
120388
120389
120390
120391
120392
120393
120394
120395
120396
120397
120398
120399
120400
120401
120402
120403
120404
120405
120406
120407
120408
120409
120410
120411
120412
120413
120414
120415
120416
120417
120418
120419
120420
120421
120422
120423
120424
120425
120426
120427
120428
120429
120430
120431
120432
120433
120434
120435
120436
120437
120438
120439
120440
120441
120442
120443
120444
120445
120446
120447
120448
120449
120450
120451
120452
120453
120454
120455
120456
120457
120458
120459
120460
120461
120462
120463
120464
120465
120466
120467
120468
120469
120470
120471
120472
120473
120474
120475
120476
120477
120478
120479
120480
120481
120482
120483
120484
120485
120486
120487
120488
120489
120490
120491
120492
120493
120494
120495
120496
120497
120498
120499
120500
120501
120502
120503
120504
120505
120506
120507
120508
120509
120510
120511
120512
120513
120514
120515
120516
120517
120518
120519
120520
120521
120522
120523
120524
120525
120526
120527
120528
120529
120530
120531
120532
120533
120534
120535
120536
120537
120538
120539
120540
120541
120542
120543
120544
120545
120546
120547
120548
120549
120550
120551
120552
120553
120554
120555
120556
120557
120558
120559
120560
120561
120562
120563
120564
120565
120566
120567
120568
120569
120570
120571
120572
120573
120574
120575
120576
120577
120578
120579
120580
120581
120582
120583
120584
120585
120586
120587
120588
120589
120590
120591
120592
120593
120594
120595
120596
120597
120598
120599
120600
120601
120602
120603
120604
120605
120606
120607
120608
120609
120610
120611
120612
120613
120614
120615
120616
120617
120618
120619
120620
120621
120622
120623
120624
120625
120626
120627
120628
120629
120630
120631
120632
120633
120634
120635
120636
120637
120638
120639
120640
120641
120642
120643
120644
120645
120646
120647
120648
120649
120650
120651
120652
120653
120654
120655
120656
120657
120658
120659
120660
120661
120662
120663
120664
120665
120666
120667
120668
120669
120670
120671
120672
120673
120674
120675
120676
120677
120678
120679
120680
120681
120682
120683
120684
120685
120686
120687
120688
120689
120690
120691
120692
120693
120694
120695
120696
120697
120698
120699
120700
120701
120702
120703
120704
120705
120706
120707
120708
120709
120710
120711
120712
120713
120714
120715
120716
120717
120718
120719
120720
120721
120722
120723
120724
120725
120726
120727
120728
120729
120730
120731
120732
120733
120734
120735
120736
120737
120738
120739
120740
120741
120742
120743
120744
120745
120746
120747
120748
120749
120750
120751
120752
120753
120754
120755
120756
120757
120758
120759
120760
120761
120762
120763
120764
120765
120766
120767
120768
120769
120770
120771
120772
120773
120774
120775
120776
120777
120778
120779
120780
120781
120782
120783
120784
120785
120786
120787
120788
120789
120790
120791
120792
120793
120794
120795
120796
120797
120798
120799
120800
120801
120802
120803
120804
120805
120806
120807
120808
120809
120810
120811
120812
120813
120814
120815
120816
120817
120818
120819
120820
120821
120822
120823
120824
120825
120826
120827
120828
120829
120830
120831
120832
120833
120834
120835
120836
120837
120838
120839
120840
120841
120842
120843
120844
120845
120846
120847
120848
120849
120850
120851
120852
120853
120854
120855
120856
120857
120858
120859
120860
120861
120862
120863
120864
120865
120866
120867
120868
120869
120870
120871
120872
120873
120874
120875
120876
120877
120878
120879
120880
120881
120882
120883
120884
120885
120886
120887
120888
120889
120890
120891
120892
120893
120894
120895
120896
120897
120898
120899
120900
120901
120902
120903
120904
120905
120906
120907
120908
120909
120910
120911
120912
120913
120914
120915
120916
120917
120918
120919
120920
120921
120922
120923
120924
120925
120926
120927
120928
120929
120930
120931
120932
120933
120934
120935
120936
120937
120938
120939
120940
120941
120942
120943
120944
120945
120946
120947
120948
120949
120950
120951
120952
120953
120954
120955
120956
120957
120958
120959
120960
120961
120962
120963
120964
120965
120966
120967
120968
120969
120970
120971
120972
120973
120974
120975
120976
120977
120978
120979
120980
120981
120982
120983
120984
120985
120986
120987
120988
120989
120990
120991
120992
120993
120994
120995
120996
120997
120998
120999
121000
121001
121002
121003
121004
121005
121006
121007
121008
121009
121010
121011
121012
121013
121014
121015
121016
121017
121018
121019
121020
121021
121022
121023
121024
121025
121026
121027
121028
121029
121030
121031
121032
121033
121034
121035
121036
121037
121038
121039
121040
121041
121042
121043
121044
121045
121046
121047
121048
121049
121050
121051
121052
121053
121054
121055
121056
121057
121058
121059
121060
121061
121062
121063
121064
121065
121066
121067
121068
121069
121070
121071
121072
121073
121074
121075
121076
121077
121078
121079
121080
121081
121082
121083
121084
121085
121086
121087
121088
121089
121090
121091
121092
121093
121094
121095
121096
121097
121098
121099
121100
121101
121102
121103
121104
121105
121106
121107
121108
121109
121110
121111
121112
121113
121114
121115
121116
121117
121118
121119
121120
121121
121122
121123
121124
121125
121126
121127
121128
121129
121130
121131
121132
121133
121134
121135
121136
121137
121138
121139
121140
121141
121142
121143
121144
121145
121146
121147
121148
121149
121150
121151
121152
121153
121154
121155
121156
121157
121158
121159
121160
121161
121162
121163
121164
121165
121166
121167
121168
121169
121170
121171
121172
121173
121174
121175
121176
121177
121178
121179
121180
121181
121182
121183
121184
121185
121186
121187
121188
121189
121190
121191
121192
121193
121194
121195
121196
121197
121198
121199
121200
121201
121202
121203
121204
121205
121206
121207
121208
121209
121210
121211
121212
121213
121214
121215
121216
121217
121218
121219
121220
121221
121222
121223
121224
121225
121226
121227
121228
121229
121230
121231
121232
121233
121234
121235
121236
121237
121238
121239
121240
121241
121242
121243
121244
121245
121246
121247
121248
121249
121250
121251
121252
121253
121254
121255
121256
121257
121258
121259
121260
121261
121262
121263
121264
121265
121266
121267
121268
121269
121270
121271
121272
121273
121274
121275
121276
121277
121278
121279
121280
121281
121282
121283
121284
121285
121286
121287
121288
121289
121290
121291
121292
121293
121294
121295
121296
121297
121298
121299
121300
121301
121302
121303
121304
121305
121306
121307
121308
121309
121310
121311
121312
121313
121314
121315
121316
121317
121318
121319
121320
121321
121322
121323
121324
121325
121326
121327
121328
121329
121330
121331
121332
121333
121334
121335
121336
121337
121338
121339
121340
121341
121342
121343
121344
121345
121346
121347
121348
121349
121350
121351
121352
121353
121354
121355
121356
121357
121358
121359
121360
121361
121362
121363
121364
121365
121366
121367
121368
121369
121370
121371
121372
121373
121374
121375
121376
121377
121378
121379
121380
121381
121382
121383
121384
121385
121386
121387
121388
121389
121390
121391
121392
121393
121394
121395
121396
121397
121398
121399
121400
121401
121402
121403
121404
121405
121406
121407
121408
121409
121410
121411
121412
121413
121414
121415
121416
121417
121418
121419
121420
121421
121422
121423
121424
121425
121426
121427
121428
121429
121430
121431
121432
121433
121434
121435
121436
121437
121438
121439
121440
121441
121442
121443
121444
121445
121446
121447
121448
121449
121450
121451
121452
121453
121454
121455
121456
121457
121458
121459
121460
121461
121462
121463
121464
121465
121466
121467
121468
121469
121470
121471
121472
121473
121474
121475
121476
121477
121478
121479
121480
121481
121482
121483
121484
121485
121486
121487
121488
121489
121490
121491
121492
121493
121494
121495
121496
121497
121498
121499
121500
121501
121502
121503
121504
121505
121506
121507
121508
121509
121510
121511
121512
121513
121514
121515
121516
121517
121518
121519
121520
121521
121522
121523
121524
121525
121526
121527
121528
121529
121530
121531
121532
121533
121534
121535
121536
121537
121538
121539
121540
121541
121542
121543
121544
121545
121546
121547
121548
121549
121550
121551
121552
121553
121554
121555
121556
121557
121558
121559
121560
121561
121562
121563
121564
121565
121566
121567
121568
121569
121570
121571
121572
121573
121574
121575
121576
121577
121578
121579
121580
121581
121582
121583
121584
121585
121586
121587
121588
121589
121590
121591
121592
121593
121594
121595
121596
121597
121598
121599
121600
121601
121602
121603
121604
121605
121606
121607
121608
121609
121610
121611
121612
121613
121614
121615
121616
121617
121618
121619
121620
121621
121622
121623
121624
121625
121626
121627
121628
121629
121630
121631
121632
121633
121634
121635
121636
121637
121638
121639
121640
121641
121642
121643
121644
121645
121646
121647
121648
121649
121650
121651
121652
121653
121654
121655
121656
121657
121658
121659
121660
121661
121662
121663
121664
121665
121666
121667
121668
121669
121670
121671
121672
121673
121674
121675
121676
121677
121678
121679
121680
121681
121682
121683
121684
121685
121686
121687
121688
121689
121690
121691
121692
121693
121694
121695
121696
121697
121698
121699
121700
121701
121702
121703
121704
121705
121706
121707
121708
121709
121710
121711
121712
121713
121714
121715
121716
121717
121718
121719
121720
121721
121722
121723
121724
121725
121726
121727
121728
121729
121730
121731
121732
121733
121734
121735
121736
121737
121738
121739
121740
121741
121742
121743
121744
121745
121746
121747
121748
121749
121750
121751
121752
121753
121754
121755
121756
121757
121758
121759
121760
121761
121762
121763
121764
121765
121766
121767
121768
121769
121770
121771
121772
121773
121774
121775
121776
121777
121778
121779
121780
121781
121782
121783
121784
121785
121786
121787
121788
121789
121790
121791
121792
121793
121794
121795
121796
121797
121798
121799
121800
121801
121802
121803
121804
121805
121806
121807
121808
121809
121810
121811
121812
121813
121814
121815
121816
121817
121818
121819
121820
121821
121822
121823
121824
121825
121826
121827
121828
121829
121830
121831
121832
121833
121834
121835
121836
121837
121838
121839
121840
121841
121842
121843
121844
121845
121846
121847
121848
121849
121850
121851
121852
121853
121854
121855
121856
121857
121858
121859
121860
121861
121862
121863
121864
121865
121866
121867
121868
121869
121870
121871
121872
121873
121874
121875
121876
121877
121878
121879
121880
121881
121882
121883
121884
121885
121886
121887
121888
121889
121890
121891
121892
121893
121894
121895
121896
121897
121898
121899
121900
121901
121902
121903
121904
121905
121906
121907
121908
121909
121910
121911
121912
121913
121914
121915
121916
121917
121918
121919
121920
121921
121922
121923
121924
121925
121926
121927
121928
121929
121930
121931
121932
121933
121934
121935
121936
121937
121938
121939
121940
121941
121942
121943
121944
121945
121946
121947
121948
121949
121950
121951
121952
121953
121954
121955
121956
121957
121958
121959
121960
121961
121962
121963
121964
121965
121966
121967
121968
121969
121970
121971
121972
121973
121974
121975
121976
121977
121978
121979
121980
121981
121982
121983
121984
121985
121986
121987
121988
121989
121990
121991
121992
121993
121994
121995
121996
121997
121998
121999
122000
122001
122002
122003
122004
122005
122006
122007
122008
122009
122010
122011
122012
122013
122014
122015
122016
122017
122018
122019
122020
122021
122022
122023
122024
122025
122026
122027
122028
122029
122030
122031
122032
122033
122034
122035
122036
122037
122038
122039
122040
122041
122042
122043
122044
122045
122046
122047
122048
122049
122050
122051
122052
122053
122054
122055
122056
122057
122058
122059
122060
122061
122062
122063
122064
122065
122066
122067
122068
122069
122070
122071
122072
122073
122074
122075
122076
122077
122078
122079
122080
122081
122082
122083
122084
122085
122086
122087
122088
122089
122090
122091
122092
122093
122094
122095
122096
122097
122098
122099
122100
122101
122102
122103
122104
122105
122106
122107
122108
122109
122110
122111
122112
122113
122114
122115
122116
122117
122118
122119
122120
122121
122122
122123
122124
122125
122126
122127
122128
122129
122130
122131
122132
122133
122134
122135
122136
122137
122138
122139
122140
122141
122142
122143
122144
122145
122146
122147
122148
122149
122150
122151
122152
122153
122154
122155
122156
122157
122158
122159
122160
122161
122162
122163
122164
122165
122166
122167
122168
122169
122170
122171
122172
122173
122174
122175
122176
122177
122178
122179
122180
122181
122182
122183
122184
122185
122186
122187
122188
122189
122190
122191
122192
122193
122194
122195
122196
122197
122198
122199
122200
122201
122202
122203
122204
122205
122206
122207
122208
122209
122210
122211
122212
122213
122214
122215
122216
122217
122218
122219
122220
122221
122222
122223
122224
122225
122226
122227
122228
122229
122230
122231
122232
122233
122234
122235
122236
122237
122238
122239
122240
122241
122242
122243
122244
122245
122246
122247
122248
122249
122250
122251
122252
122253
122254
122255
122256
122257
122258
122259
122260
122261
122262
122263
122264
122265
122266
122267
122268
122269
122270
122271
122272
122273
122274
122275
122276
122277
122278
122279
122280
122281
122282
122283
122284
122285
122286
122287
122288
122289
122290
122291
122292
122293
122294
122295
122296
122297
122298
122299
122300
122301
122302
122303
122304
122305
122306
122307
122308
122309
122310
122311
122312
122313
122314
122315
122316
122317
122318
122319
122320
122321
122322
122323
122324
122325
122326
122327
122328
122329
122330
122331
122332
122333
122334
122335
122336
122337
122338
122339
122340
122341
122342
122343
122344
122345
122346
122347
122348
122349
122350
122351
122352
122353
122354
122355
122356
122357
122358
122359
122360
122361
122362
122363
122364
122365
122366
122367
122368
122369
122370
122371
122372
122373
122374
122375
122376
122377
122378
122379
122380
122381
122382
122383
122384
122385
122386
122387
122388
122389
122390
122391
122392
122393
122394
122395
122396
122397
122398
122399
122400
122401
122402
122403
122404
122405
122406
122407
122408
122409
122410
122411
122412
122413
122414
122415
122416
122417
122418
122419
122420
122421
122422
122423
122424
122425
122426
122427
122428
122429
122430
122431
122432
122433
122434
122435
122436
122437
122438
122439
122440
122441
122442
122443
122444
122445
122446
122447
122448
122449
122450
122451
122452
122453
122454
122455
122456
122457
122458
122459
122460
122461
122462
122463
122464
122465
122466
122467
122468
122469
122470
122471
122472
122473
122474
122475
122476
122477
122478
122479
122480
122481
122482
122483
122484
122485
122486
122487
122488
122489
122490
122491
122492
122493
122494
122495
122496
122497
122498
122499
122500
122501
122502
122503
122504
122505
122506
122507
122508
122509
122510
122511
122512
122513
122514
122515
122516
122517
122518
122519
122520
122521
122522
122523
122524
122525
122526
122527
122528
122529
122530
122531
122532
122533
122534
122535
122536
122537
122538
122539
122540
122541
122542
122543
122544
122545
122546
122547
122548
122549
122550
122551
122552
122553
122554
122555
122556
122557
122558
122559
122560
122561
122562
122563
122564
122565
122566
122567
122568
122569
122570
122571
122572
122573
122574
122575
122576
122577
122578
122579
122580
122581
122582
122583
122584
122585
122586
122587
122588
122589
122590
122591
122592
122593
122594
122595
122596
122597
122598
122599
122600
122601
122602
122603
122604
122605
122606
122607
122608
122609
122610
122611
122612
122613
122614
122615
122616
122617
122618
122619
122620
122621
122622
122623
122624
122625
122626
122627
122628
122629
122630
122631
122632
122633
122634
122635
122636
122637
122638
122639
122640
122641
122642
122643
122644
122645
122646
122647
122648
122649
122650
122651
122652
122653
122654
122655
122656
122657
122658
122659
122660
122661
122662
122663
122664
122665
122666
122667
122668
122669
122670
122671
122672
122673
122674
122675
122676
122677
122678
122679
122680
122681
122682
122683
122684
122685
122686
122687
122688
122689
122690
122691
122692
122693
122694
122695
122696
122697
122698
122699
122700
122701
122702
122703
122704
122705
122706
122707
122708
122709
122710
122711
122712
122713
122714
122715
122716
122717
122718
122719
122720
122721
122722
122723
122724
122725
122726
122727
122728
122729
122730
122731
122732
122733
122734
122735
122736
122737
122738
122739
122740
122741
122742
122743
122744
122745
122746
122747
122748
122749
122750
122751
122752
122753
122754
122755
122756
122757
122758
122759
122760
122761
122762
122763
122764
122765
122766
122767
122768
122769
122770
122771
122772
122773
122774
122775
122776
122777
122778
122779
122780
122781
122782
122783
122784
122785
122786
122787
122788
122789
122790
122791
122792
122793
122794
122795
122796
122797
122798
122799
122800
122801
122802
122803
122804
122805
122806
122807
122808
122809
122810
122811
122812
122813
122814
122815
122816
122817
122818
122819
122820
122821
122822
122823
122824
122825
122826
122827
122828
122829
122830
122831
122832
122833
122834
122835
122836
122837
122838
122839
122840
122841
122842
122843
122844
122845
122846
122847
122848
122849
122850
122851
122852
122853
122854
122855
122856
122857
122858
122859
122860
122861
122862
122863
122864
122865
122866
122867
122868
122869
122870
122871
122872
122873
122874
122875
122876
122877
122878
122879
122880
122881
122882
122883
122884
122885
122886
122887
122888
122889
122890
122891
122892
122893
122894
122895
122896
122897
122898
122899
122900
122901
122902
122903
122904
122905
122906
122907
122908
122909
122910
122911
122912
122913
122914
122915
122916
122917
122918
122919
122920
122921
122922
122923
122924
122925
122926
122927
122928
122929
122930
122931
122932
122933
122934
122935
122936
122937
122938
122939
122940
122941
122942
122943
122944
122945
122946
122947
122948
122949
122950
122951
122952
122953
122954
122955
122956
122957
122958
122959
122960
122961
122962
122963
122964
122965
122966
122967
122968
122969
122970
122971
122972
122973
122974
122975
122976
122977
122978
122979
122980
122981
122982
122983
122984
122985
122986
122987
122988
122989
122990
122991
122992
122993
122994
122995
122996
122997
122998
122999
123000
123001
123002
123003
123004
123005
123006
123007
123008
123009
123010
123011
123012
123013
123014
123015
123016
123017
123018
123019
123020
123021
123022
123023
123024
123025
123026
123027
123028
123029
123030
123031
123032
123033
123034
123035
123036
123037
123038
123039
123040
123041
123042
123043
123044
123045
123046
123047
123048
123049
123050
123051
123052
123053
123054
123055
123056
123057
123058
123059
123060
123061
123062
123063
123064
123065
123066
123067
123068
123069
123070
123071
123072
123073
123074
123075
123076
123077
123078
123079
123080
123081
123082
123083
123084
123085
123086
123087
123088
123089
123090
123091
123092
123093
123094
123095
123096
123097
123098
123099
123100
123101
123102
123103
123104
123105
123106
123107
123108
123109
123110
123111
123112
123113
123114
123115
123116
123117
123118
123119
123120
123121
123122
123123
123124
123125
123126
123127
123128
123129
123130
123131
123132
123133
123134
123135
123136
123137
123138
123139
123140
123141
123142
123143
123144
123145
123146
123147
123148
123149
123150
123151
123152
123153
123154
123155
123156
123157
123158
123159
123160
123161
123162
123163
123164
123165
123166
123167
123168
123169
123170
123171
123172
123173
123174
123175
123176
123177
123178
123179
123180
123181
123182
123183
123184
123185
123186
123187
123188
123189
123190
123191
123192
123193
123194
123195
123196
123197
123198
123199
123200
123201
123202
123203
123204
123205
123206
123207
123208
123209
123210
123211
123212
123213
123214
123215
123216
123217
123218
123219
123220
123221
123222
123223
123224
123225
123226
123227
123228
123229
123230
123231
123232
123233
123234
123235
123236
123237
123238
123239
123240
123241
123242
123243
123244
123245
123246
123247
123248
123249
123250
123251
123252
123253
123254
123255
123256
123257
123258
123259
123260
123261
123262
123263
123264
123265
123266
123267
123268
123269
123270
123271
123272
123273
123274
123275
123276
123277
123278
123279
123280
123281
123282
123283
123284
123285
123286
123287
123288
123289
123290
123291
123292
123293
123294
123295
123296
123297
123298
123299
123300
123301
123302
123303
123304
123305
123306
123307
123308
123309
123310
123311
123312
123313
123314
123315
123316
123317
123318
123319
123320
123321
123322
123323
123324
123325
123326
123327
123328
123329
123330
123331
123332
123333
123334
123335
123336
123337
123338
123339
123340
123341
123342
123343
123344
123345
123346
123347
123348
123349
123350
123351
123352
123353
123354
123355
123356
123357
123358
123359
123360
123361
123362
123363
123364
123365
123366
123367
123368
123369
123370
123371
123372
123373
123374
123375
123376
123377
123378
123379
123380
123381
123382
123383
123384
123385
123386
123387
123388
123389
123390
123391
123392
123393
123394
123395
123396
123397
123398
123399
123400
123401
123402
123403
123404
123405
123406
123407
123408
123409
123410
123411
123412
123413
123414
123415
123416
123417
123418
123419
123420
123421
123422
123423
123424
123425
123426
123427
123428
123429
123430
123431
123432
123433
123434
123435
123436
123437
123438
123439
123440
123441
123442
123443
123444
123445
123446
123447
123448
123449
123450
123451
123452
123453
123454
123455
123456
123457
123458
123459
123460
123461
123462
123463
123464
123465
123466
123467
123468
123469
123470
123471
123472
123473
123474
123475
123476
123477
123478
123479
123480
123481
123482
123483
123484
123485
123486
123487
123488
123489
123490
123491
123492
123493
123494
123495
123496
123497
123498
123499
123500
123501
123502
123503
123504
123505
123506
123507
123508
123509
123510
123511
123512
123513
123514
123515
123516
123517
123518
123519
123520
123521
123522
123523
123524
123525
123526
123527
123528
123529
123530
123531
123532
123533
123534
123535
123536
123537
123538
123539
123540
123541
123542
123543
123544
123545
123546
123547
123548
123549
123550
123551
123552
123553
123554
123555
123556
123557
123558
123559
123560
123561
123562
123563
123564
123565
123566
123567
123568
123569
123570
123571
123572
123573
123574
123575
123576
123577
123578
123579
123580
123581
123582
123583
123584
123585
123586
123587
123588
123589
123590
123591
123592
123593
123594
123595
123596
123597
123598
123599
123600
123601
123602
123603
123604
123605
123606
123607
123608
123609
123610
123611
123612
123613
123614
123615
123616
123617
123618
123619
123620
123621
123622
123623
123624
123625
123626
123627
123628
123629
123630
123631
123632
123633
123634
123635
123636
123637
123638
123639
123640
123641
123642
123643
123644
123645
123646
123647
123648
123649
123650
123651
123652
123653
123654
123655
123656
123657
123658
123659
123660
123661
123662
123663
123664
123665
123666
123667
123668
123669
123670
123671
123672
123673
123674
123675
123676
123677
123678
123679
123680
123681
123682
123683
123684
123685
123686
123687
123688
123689
123690
123691
123692
123693
123694
123695
123696
123697
123698
123699
123700
123701
123702
123703
123704
123705
123706
123707
123708
123709
123710
123711
123712
123713
123714
123715
123716
123717
123718
123719
123720
123721
123722
123723
123724
123725
123726
123727
123728
123729
123730
123731
123732
123733
123734
123735
123736
123737
123738
123739
123740
123741
123742
123743
123744
123745
123746
123747
123748
123749
123750
123751
123752
123753
123754
123755
123756
123757
123758
123759
123760
123761
123762
123763
123764
123765
123766
123767
123768
123769
123770
123771
123772
123773
123774
123775
123776
123777
123778
123779
123780
123781
123782
123783
123784
123785
123786
123787
123788
123789
123790
123791
123792
123793
123794
123795
123796
123797
123798
123799
123800
123801
123802
123803
123804
123805
123806
123807
123808
123809
123810
123811
123812
123813
123814
123815
123816
123817
123818
123819
123820
123821
123822
123823
123824
123825
123826
123827
123828
123829
123830
123831
123832
123833
123834
123835
123836
123837
123838
123839
123840
123841
123842
123843
123844
123845
123846
123847
123848
123849
123850
123851
123852
123853
123854
123855
123856
123857
123858
123859
123860
123861
123862
123863
123864
123865
123866
123867
123868
123869
123870
123871
123872
123873
123874
123875
123876
123877
123878
123879
123880
123881
123882
123883
123884
123885
123886
123887
123888
123889
123890
123891
123892
123893
123894
123895
123896
123897
123898
123899
123900
123901
123902
123903
123904
123905
123906
123907
123908
123909
123910
123911
123912
123913
123914
123915
123916
123917
123918
123919
123920
123921
123922
123923
123924
123925
123926
123927
123928
123929
123930
123931
123932
123933
123934
123935
123936
123937
123938
123939
123940
123941
123942
123943
123944
123945
123946
123947
123948
123949
123950
123951
123952
123953
123954
123955
123956
123957
123958
123959
123960
123961
123962
123963
123964
123965
123966
123967
123968
123969
123970
123971
123972
123973
123974
123975
123976
123977
123978
123979
123980
123981
123982
123983
123984
123985
123986
123987
123988
123989
123990
123991
123992
123993
123994
123995
123996
123997
123998
123999
124000
124001
124002
124003
124004
124005
124006
124007
124008
124009
124010
124011
124012
124013
124014
124015
124016
124017
124018
124019
124020
124021
124022
124023
124024
124025
124026
124027
124028
124029
124030
124031
124032
124033
124034
124035
124036
124037
124038
124039
124040
124041
124042
124043
124044
124045
124046
124047
124048
124049
124050
124051
124052
124053
124054
124055
124056
124057
124058
124059
124060
124061
124062
124063
124064
124065
124066
124067
124068
124069
124070
124071
124072
124073
124074
124075
124076
124077
124078
124079
124080
124081
124082
124083
124084
124085
124086
124087
124088
124089
124090
124091
124092
124093
124094
124095
124096
124097
124098
124099
124100
124101
124102
124103
124104
124105
124106
124107
124108
124109
124110
124111
124112
124113
124114
124115
124116
124117
124118
124119
124120
124121
124122
124123
124124
124125
124126
124127
124128
124129
124130
124131
124132
124133
124134
124135
124136
124137
124138
124139
124140
124141
124142
124143
124144
124145
124146
124147
124148
124149
124150
124151
124152
124153
124154
124155
124156
124157
124158
124159
124160
124161
124162
124163
124164
124165
124166
124167
124168
124169
124170
124171
124172
124173
124174
124175
124176
124177
124178
124179
124180
124181
124182
124183
124184
124185
124186
124187
124188
124189
124190
124191
124192
124193
124194
124195
124196
124197
124198
124199
124200
124201
124202
124203
124204
124205
124206
124207
124208
124209
124210
124211
124212
124213
124214
124215
124216
124217
124218
124219
124220
124221
124222
124223
124224
124225
124226
124227
124228
124229
124230
124231
124232
124233
124234
124235
124236
124237
124238
124239
124240
124241
124242
124243
124244
124245
124246
124247
124248
124249
124250
124251
124252
124253
124254
124255
124256
124257
124258
124259
124260
124261
124262
124263
124264
124265
124266
124267
124268
124269
124270
124271
124272
124273
124274
124275
124276
124277
124278
124279
124280
124281
124282
124283
124284
124285
124286
124287
124288
124289
124290
124291
124292
124293
124294
124295
124296
124297
124298
124299
124300
124301
124302
124303
124304
124305
124306
124307
124308
124309
124310
124311
124312
124313
124314
124315
124316
124317
124318
124319
124320
124321
124322
124323
124324
124325
124326
124327
124328
124329
124330
124331
124332
124333
124334
124335
124336
124337
124338
124339
124340
124341
124342
124343
124344
124345
124346
124347
124348
124349
124350
124351
124352
124353
124354
124355
124356
124357
124358
124359
124360
124361
124362
124363
124364
124365
124366
124367
124368
124369
124370
124371
124372
124373
124374
124375
124376
124377
124378
124379
124380
124381
124382
124383
124384
124385
124386
124387
124388
124389
124390
124391
124392
124393
124394
124395
124396
124397
124398
124399
124400
124401
124402
124403
124404
124405
124406
124407
124408
124409
124410
124411
124412
124413
124414
124415
124416
124417
124418
124419
124420
124421
124422
124423
124424
124425
124426
124427
124428
124429
124430
124431
124432
124433
124434
124435
124436
124437
124438
124439
124440
124441
124442
124443
124444
124445
124446
124447
124448
124449
124450
124451
124452
124453
124454
124455
124456
124457
124458
124459
124460
124461
124462
124463
124464
124465
124466
124467
124468
124469
124470
124471
124472
124473
124474
124475
124476
124477
124478
124479
124480
124481
124482
124483
124484
124485
124486
124487
124488
124489
124490
124491
124492
124493
124494
124495
124496
124497
124498
124499
124500
124501
124502
124503
124504
124505
124506
124507
124508
124509
124510
124511
124512
124513
124514
124515
124516
124517
124518
124519
124520
124521
124522
124523
124524
124525
124526
124527
124528
124529
124530
124531
124532
124533
124534
124535
124536
124537
124538
124539
124540
124541
124542
124543
124544
124545
124546
124547
124548
124549
124550
124551
124552
124553
124554
124555
124556
124557
124558
124559
124560
124561
124562
124563
124564
124565
124566
124567
124568
124569
124570
124571
124572
124573
124574
124575
124576
124577
124578
124579
124580
124581
124582
124583
124584
124585
124586
124587
124588
124589
124590
124591
124592
124593
124594
124595
124596
124597
124598
124599
124600
124601
124602
124603
124604
124605
124606
124607
124608
124609
124610
124611
124612
124613
124614
124615
124616
124617
124618
124619
124620
124621
124622
124623
124624
124625
124626
124627
124628
124629
124630
124631
124632
124633
124634
124635
124636
124637
124638
124639
124640
124641
124642
124643
124644
124645
124646
124647
124648
124649
124650
124651
124652
124653
124654
124655
124656
124657
124658
124659
124660
124661
124662
124663
124664
124665
124666
124667
124668
124669
124670
124671
124672
124673
124674
124675
124676
124677
124678
124679
124680
124681
124682
124683
124684
124685
124686
124687
124688
124689
124690
124691
124692
124693
124694
124695
124696
124697
124698
124699
124700
124701
124702
124703
124704
124705
124706
124707
124708
124709
124710
124711
124712
124713
124714
124715
124716
124717
124718
124719
124720
124721
124722
124723
124724
124725
124726
124727
124728
124729
124730
124731
124732
124733
124734
124735
124736
124737
124738
124739
124740
124741
124742
124743
124744
124745
124746
124747
124748
124749
124750
124751
124752
124753
124754
124755
124756
124757
124758
124759
124760
124761
124762
124763
124764
124765
124766
124767
124768
124769
124770
124771
124772
124773
124774
124775
124776
124777
124778
124779
124780
124781
124782
124783
124784
124785
124786
124787
124788
124789
124790
124791
124792
124793
124794
124795
124796
124797
124798
124799
124800
124801
124802
124803
124804
124805
124806
124807
124808
124809
124810
124811
124812
124813
124814
124815
124816
124817
124818
124819
124820
124821
124822
124823
124824
124825
124826
124827
124828
124829
124830
124831
124832
124833
124834
124835
124836
124837
124838
124839
124840
124841
124842
124843
124844
124845
124846
124847
124848
124849
124850
124851
124852
124853
124854
124855
124856
124857
124858
124859
124860
124861
124862
124863
124864
124865
124866
124867
124868
124869
124870
124871
124872
124873
124874
124875
124876
124877
124878
124879
124880
124881
124882
124883
124884
124885
124886
124887
124888
124889
124890
124891
124892
124893
124894
124895
124896
124897
124898
124899
124900
124901
124902
124903
124904
124905
124906
124907
124908
124909
124910
124911
124912
124913
124914
124915
124916
124917
124918
124919
124920
124921
124922
124923
124924
124925
124926
124927
124928
124929
124930
124931
124932
124933
124934
124935
124936
124937
124938
124939
124940
124941
124942
124943
124944
124945
124946
124947
124948
124949
124950
124951
124952
124953
124954
124955
124956
124957
124958
124959
124960
124961
124962
124963
124964
124965
124966
124967
124968
124969
124970
124971
124972
124973
124974
124975
124976
124977
124978
124979
124980
124981
124982
124983
124984
124985
124986
124987
124988
124989
124990
124991
124992
124993
124994
124995
124996
124997
124998
124999
125000
125001
125002
125003
125004
125005
125006
125007
125008
125009
125010
125011
125012
125013
125014
125015
125016
125017
125018
125019
125020
125021
125022
125023
125024
125025
125026
125027
125028
125029
125030
125031
125032
125033
125034
125035
125036
125037
125038
125039
125040
125041
125042
125043
125044
125045
125046
125047
125048
125049
125050
125051
125052
125053
125054
125055
125056
125057
125058
125059
125060
125061
125062
125063
125064
125065
125066
125067
125068
125069
125070
125071
125072
125073
125074
125075
125076
125077
125078
125079
125080
125081
125082
125083
125084
125085
125086
125087
125088
125089
125090
125091
125092
125093
125094
125095
125096
125097
125098
125099
125100
125101
125102
125103
125104
125105
125106
125107
125108
125109
125110
125111
125112
125113
125114
125115
125116
125117
125118
125119
125120
125121
125122
125123
125124
125125
125126
125127
125128
125129
125130
125131
125132
125133
125134
125135
125136
125137
125138
125139
125140
125141
125142
125143
125144
125145
125146
125147
125148
125149
125150
125151
125152
125153
125154
125155
125156
125157
125158
125159
125160
125161
125162
125163
125164
125165
125166
125167
125168
125169
125170
125171
125172
125173
125174
125175
125176
125177
125178
125179
125180
125181
125182
125183
125184
125185
125186
125187
125188
125189
125190
125191
125192
125193
125194
125195
125196
125197
125198
125199
125200
125201
125202
125203
125204
125205
125206
125207
125208
125209
125210
125211
125212
125213
125214
125215
125216
125217
125218
125219
125220
125221
125222
125223
125224
125225
125226
125227
125228
125229
125230
125231
125232
125233
125234
125235
125236
125237
125238
125239
125240
125241
125242
125243
125244
125245
125246
125247
125248
125249
125250
125251
125252
125253
125254
125255
125256
125257
125258
125259
125260
125261
125262
125263
125264
125265
125266
125267
125268
125269
125270
125271
125272
125273
125274
125275
125276
125277
125278
125279
125280
125281
125282
125283
125284
125285
125286
125287
125288
125289
125290
125291
125292
125293
125294
125295
125296
125297
125298
125299
125300
125301
125302
125303
125304
125305
125306
125307
125308
125309
125310
125311
125312
125313
125314
125315
125316
125317
125318
125319
125320
125321
125322
125323
125324
125325
125326
125327
125328
125329
125330
125331
125332
125333
125334
125335
125336
125337
125338
125339
125340
125341
125342
125343
125344
125345
125346
125347
125348
125349
125350
125351
125352
125353
125354
125355
125356
125357
125358
125359
125360
125361
125362
125363
125364
125365
125366
125367
125368
125369
125370
125371
125372
125373
125374
125375
125376
125377
125378
125379
125380
125381
125382
125383
125384
125385
125386
125387
125388
125389
125390
125391
125392
125393
125394
125395
125396
125397
125398
125399
125400
125401
125402
125403
125404
125405
125406
125407
125408
125409
125410
125411
125412
125413
125414
125415
125416
125417
125418
125419
125420
125421
125422
125423
125424
125425
125426
125427
125428
125429
125430
125431
125432
125433
125434
125435
125436
125437
125438
125439
125440
125441
125442
125443
125444
125445
125446
125447
125448
125449
125450
125451
125452
125453
125454
125455
125456
125457
125458
125459
125460
125461
125462
125463
125464
125465
125466
125467
125468
125469
125470
125471
125472
125473
125474
125475
125476
125477
125478
125479
125480
125481
125482
125483
125484
125485
125486
125487
125488
125489
125490
125491
125492
125493
125494
125495
125496
125497
125498
125499
125500
125501
125502
125503
125504
125505
125506
125507
125508
125509
125510
125511
125512
125513
125514
125515
125516
125517
125518
125519
125520
125521
125522
125523
125524
125525
125526
125527
125528
125529
125530
125531
125532
125533
125534
125535
125536
125537
125538
125539
125540
125541
125542
125543
125544
125545
125546
125547
125548
125549
125550
125551
125552
125553
125554
125555
125556
125557
125558
125559
125560
125561
125562
125563
125564
125565
125566
125567
125568
125569
125570
125571
125572
125573
125574
125575
125576
125577
125578
125579
125580
125581
125582
125583
125584
125585
125586
125587
125588
125589
125590
125591
125592
125593
125594
125595
125596
125597
125598
125599
125600
125601
125602
125603
125604
125605
125606
125607
125608
125609
125610
125611
125612
125613
125614
125615
125616
125617
125618
125619
125620
125621
125622
125623
125624
125625
125626
125627
125628
125629
125630
125631
125632
125633
125634
125635
125636
125637
125638
125639
125640
125641
125642
125643
125644
125645
125646
125647
125648
125649
125650
125651
125652
125653
125654
125655
125656
125657
125658
125659
125660
125661
125662
125663
125664
125665
125666
125667
125668
125669
125670
125671
125672
125673
125674
125675
125676
125677
125678
125679
125680
125681
125682
125683
125684
125685
125686
125687
125688
125689
125690
125691
125692
125693
125694
125695
125696
125697
125698
125699
125700
125701
125702
125703
125704
125705
125706
125707
125708
125709
125710
125711
125712
125713
125714
125715
125716
125717
125718
125719
125720
125721
125722
125723
125724
125725
125726
125727
125728
125729
125730
125731
125732
125733
125734
125735
125736
125737
125738
125739
125740
125741
125742
125743
125744
125745
125746
125747
125748
125749
125750
125751
125752
125753
125754
125755
125756
125757
125758
125759
125760
125761
125762
125763
125764
125765
125766
125767
125768
125769
125770
125771
125772
125773
125774
125775
125776
125777
125778
125779
125780
125781
125782
125783
125784
125785
125786
125787
125788
125789
125790
125791
125792
125793
125794
125795
125796
125797
125798
125799
125800
125801
125802
125803
125804
125805
125806
125807
125808
125809
125810
125811
125812
125813
125814
125815
125816
125817
125818
125819
125820
125821
125822
125823
125824
125825
125826
125827
125828
125829
125830
125831
125832
125833
125834
125835
125836
125837
125838
125839
125840
125841
125842
125843
125844
125845
125846
125847
125848
125849
125850
125851
125852
125853
125854
125855
125856
125857
125858
125859
125860
125861
125862
125863
125864
125865
125866
125867
125868
125869
125870
125871
125872
125873
125874
125875
125876
125877
125878
125879
125880
125881
125882
125883
125884
125885
125886
125887
125888
125889
125890
125891
125892
125893
125894
125895
125896
125897
125898
125899
125900
125901
125902
125903
125904
125905
125906
125907
125908
125909
125910
125911
125912
125913
125914
125915
125916
125917
125918
125919
125920
125921
125922
125923
125924
125925
125926
125927
125928
125929
125930
125931
125932
125933
125934
125935
125936
125937
125938
125939
125940
125941
125942
125943
125944
125945
125946
125947
125948
125949
125950
125951
125952
125953
125954
125955
125956
125957
125958
125959
125960
125961
125962
125963
125964
125965
125966
125967
125968
125969
125970
125971
125972
125973
125974
125975
125976
125977
125978
125979
125980
125981
125982
125983
125984
125985
125986
125987
125988
125989
125990
125991
125992
125993
125994
125995
125996
125997
125998
125999
126000
126001
126002
126003
126004
126005
126006
126007
126008
126009
126010
126011
126012
126013
126014
126015
126016
126017
126018
126019
126020
126021
126022
126023
126024
126025
126026
126027
126028
126029
126030
126031
126032
126033
126034
126035
126036
126037
126038
126039
126040
126041
126042
126043
126044
126045
126046
126047
126048
126049
126050
126051
126052
126053
126054
126055
126056
126057
126058
126059
126060
126061
126062
126063
126064
126065
126066
126067
126068
126069
126070
126071
126072
126073
126074
126075
126076
126077
126078
126079
126080
126081
126082
126083
126084
126085
126086
126087
126088
126089
126090
126091
126092
126093
126094
126095
126096
126097
126098
126099
126100
126101
126102
126103
126104
126105
126106
126107
126108
126109
126110
126111
126112
126113
126114
126115
126116
126117
126118
126119
126120
126121
126122
126123
126124
126125
126126
126127
126128
126129
126130
126131
126132
126133
126134
126135
126136
126137
126138
126139
126140
126141
126142
126143
126144
126145
126146
126147
126148
126149
126150
126151
126152
126153
126154
126155
126156
126157
126158
126159
126160
126161
126162
126163
126164
126165
126166
126167
126168
126169
126170
126171
126172
126173
126174
126175
126176
126177
126178
126179
126180
126181
126182
126183
126184
126185
126186
126187
126188
126189
126190
126191
126192
126193
126194
126195
126196
126197
126198
126199
126200
126201
126202
126203
126204
126205
126206
126207
126208
126209
126210
126211
126212
126213
126214
126215
126216
126217
126218
126219
126220
126221
126222
126223
126224
126225
126226
126227
126228
126229
126230
126231
126232
126233
126234
126235
126236
126237
126238
126239
126240
126241
126242
126243
126244
126245
126246
126247
126248
126249
126250
126251
126252
126253
126254
126255
126256
126257
126258
126259
126260
126261
126262
126263
126264
126265
126266
126267
126268
126269
126270
126271
126272
126273
126274
126275
126276
126277
126278
126279
126280
126281
126282
126283
126284
126285
126286
126287
126288
126289
126290
126291
126292
126293
126294
126295
126296
126297
126298
126299
126300
126301
126302
126303
126304
126305
126306
126307
126308
126309
126310
126311
126312
126313
126314
126315
126316
126317
126318
126319
126320
126321
126322
126323
126324
126325
126326
126327
126328
126329
126330
126331
126332
126333
126334
126335
126336
126337
126338
126339
126340
126341
126342
126343
126344
126345
126346
126347
126348
126349
126350
126351
126352
126353
126354
126355
126356
126357
126358
126359
126360
126361
126362
126363
126364
126365
126366
126367
126368
126369
126370
126371
126372
126373
126374
126375
126376
126377
126378
126379
126380
126381
126382
126383
126384
126385
126386
126387
126388
126389
126390
126391
126392
126393
126394
126395
126396
126397
126398
126399
126400
126401
126402
126403
126404
126405
126406
126407
126408
126409
126410
126411
126412
126413
126414
126415
126416
126417
126418
126419
126420
126421
126422
126423
126424
126425
126426
126427
126428
126429
126430
126431
126432
126433
126434
126435
126436
126437
126438
126439
126440
126441
126442
126443
126444
126445
126446
126447
126448
126449
126450
126451
126452
126453
126454
126455
126456
126457
126458
126459
126460
126461
126462
126463
126464
126465
126466
126467
126468
126469
126470
126471
126472
126473
126474
126475
126476
126477
126478
126479
126480
126481
126482
126483
126484
126485
126486
126487
126488
126489
126490
126491
126492
126493
126494
126495
126496
126497
126498
126499
126500
126501
126502
126503
126504
126505
126506
126507
126508
126509
126510
126511
126512
126513
126514
126515
126516
126517
126518
126519
126520
126521
126522
126523
126524
126525
126526
126527
126528
126529
126530
126531
126532
126533
126534
126535
126536
126537
126538
126539
126540
126541
126542
126543
126544
126545
126546
126547
126548
126549
126550
126551
126552
126553
126554
126555
126556
126557
126558
126559
126560
126561
126562
126563
126564
126565
126566
126567
126568
126569
126570
126571
126572
126573
126574
126575
126576
126577
126578
126579
126580
126581
126582
126583
126584
126585
126586
126587
126588
126589
126590
126591
126592
126593
126594
126595
126596
126597
126598
126599
126600
126601
126602
126603
126604
126605
126606
126607
126608
126609
126610
126611
126612
126613
126614
126615
126616
126617
126618
126619
126620
126621
126622
126623
126624
126625
126626
126627
126628
126629
126630
126631
126632
126633
126634
126635
126636
126637
126638
126639
126640
126641
126642
126643
126644
126645
126646
126647
126648
126649
126650
126651
126652
126653
126654
126655
126656
126657
126658
126659
126660
126661
126662
126663
126664
126665
126666
126667
126668
126669
126670
126671
126672
126673
126674
126675
126676
126677
126678
126679
126680
126681
126682
126683
126684
126685
126686
126687
126688
126689
126690
126691
126692
126693
126694
126695
126696
126697
126698
126699
126700
126701
126702
126703
126704
126705
126706
126707
126708
126709
126710
126711
126712
126713
126714
126715
126716
126717
126718
126719
126720
126721
126722
126723
126724
126725
126726
126727
126728
126729
126730
126731
126732
126733
126734
126735
126736
126737
126738
126739
126740
126741
126742
126743
126744
126745
126746
126747
126748
126749
126750
126751
126752
126753
126754
126755
126756
126757
126758
126759
126760
126761
126762
126763
126764
126765
126766
126767
126768
126769
126770
126771
126772
126773
126774
126775
126776
126777
126778
126779
126780
126781
126782
126783
126784
126785
126786
126787
126788
126789
126790
126791
126792
126793
126794
126795
126796
126797
126798
126799
126800
126801
126802
126803
126804
126805
126806
126807
126808
126809
126810
126811
126812
126813
126814
126815
126816
126817
126818
126819
126820
126821
126822
126823
126824
126825
126826
126827
126828
126829
126830
126831
126832
126833
126834
126835
126836
126837
126838
126839
126840
126841
126842
126843
126844
126845
126846
126847
126848
126849
126850
126851
126852
126853
126854
126855
126856
126857
126858
126859
126860
126861
126862
126863
126864
126865
126866
126867
126868
126869
126870
126871
126872
126873
126874
126875
126876
126877
126878
126879
126880
126881
126882
126883
126884
126885
126886
126887
126888
126889
126890
126891
126892
126893
126894
126895
126896
126897
126898
126899
126900
126901
126902
126903
126904
126905
126906
126907
126908
126909
126910
126911
126912
126913
126914
126915
126916
126917
126918
126919
126920
126921
126922
126923
126924
126925
126926
126927
126928
126929
126930
126931
126932
126933
126934
126935
126936
126937
126938
126939
126940
126941
126942
126943
126944
126945
126946
126947
126948
126949
126950
126951
126952
126953
126954
126955
126956
126957
126958
126959
126960
126961
126962
126963
126964
126965
126966
126967
126968
126969
126970
126971
126972
126973
126974
126975
126976
126977
126978
126979
126980
126981
126982
126983
126984
126985
126986
126987
126988
126989
126990
126991
126992
126993
126994
126995
126996
126997
126998
126999
127000
127001
127002
127003
127004
127005
127006
127007
127008
127009
127010
127011
127012
127013
127014
127015
127016
127017
127018
127019
127020
127021
127022
127023
127024
127025
127026
127027
127028
127029
127030
127031
127032
127033
127034
127035
127036
127037
127038
127039
127040
127041
127042
127043
127044
127045
127046
127047
127048
127049
127050
127051
127052
127053
127054
127055
127056
127057
127058
127059
127060
127061
127062
127063
127064
127065
127066
127067
127068
127069
127070
127071
127072
127073
127074
127075
127076
127077
127078
127079
127080
127081
127082
127083
127084
127085
127086
127087
127088
127089
127090
127091
127092
127093
127094
127095
127096
127097
127098
127099
127100
127101
127102
127103
127104
127105
127106
127107
127108
127109
127110
127111
127112
127113
127114
127115
127116
127117
127118
127119
127120
127121
127122
127123
127124
127125
127126
127127
127128
127129
127130
127131
127132
127133
127134
127135
127136
127137
127138
127139
127140
127141
127142
127143
127144
127145
127146
127147
127148
127149
127150
127151
127152
127153
127154
127155
127156
127157
127158
127159
127160
127161
127162
127163
127164
127165
127166
127167
127168
127169
127170
127171
127172
127173
127174
127175
127176
127177
127178
127179
127180
127181
127182
127183
127184
127185
127186
127187
127188
127189
127190
127191
127192
127193
127194
127195
127196
127197
127198
127199
127200
127201
127202
127203
127204
127205
127206
127207
127208
127209
127210
127211
127212
127213
127214
127215
127216
127217
127218
127219
127220
127221
127222
127223
127224
127225
127226
127227
127228
127229
127230
127231
127232
127233
127234
127235
127236
127237
127238
127239
127240
127241
127242
127243
127244
127245
127246
127247
127248
127249
127250
127251
127252
127253
127254
127255
127256
127257
127258
127259
127260
127261
127262
127263
127264
127265
127266
127267
127268
127269
127270
127271
127272
127273
127274
127275
127276
127277
127278
127279
127280
127281
127282
127283
127284
127285
127286
127287
127288
127289
127290
127291
127292
127293
127294
127295
127296
127297
127298
127299
127300
127301
127302
127303
127304
127305
127306
127307
127308
127309
127310
127311
127312
127313
127314
127315
127316
127317
127318
127319
127320
127321
127322
127323
127324
127325
127326
127327
127328
127329
127330
127331
127332
127333
127334
127335
127336
127337
127338
127339
127340
127341
127342
127343
127344
127345
127346
127347
127348
127349
127350
127351
127352
127353
127354
127355
127356
127357
127358
127359
127360
127361
127362
127363
127364
127365
127366
127367
127368
127369
127370
127371
127372
127373
127374
127375
127376
127377
127378
127379
127380
127381
127382
127383
127384
127385
127386
127387
127388
127389
127390
127391
127392
127393
127394
127395
127396
127397
127398
127399
127400
127401
127402
127403
127404
127405
127406
127407
127408
127409
127410
127411
127412
127413
127414
127415
127416
127417
127418
127419
127420
127421
127422
127423
127424
127425
127426
127427
127428
127429
127430
127431
127432
127433
127434
127435
127436
127437
127438
127439
127440
127441
127442
127443
127444
127445
127446
127447
127448
127449
127450
127451
127452
127453
127454
127455
127456
127457
127458
127459
127460
127461
127462
127463
127464
127465
127466
127467
127468
127469
127470
127471
127472
127473
127474
127475
127476
127477
127478
127479
127480
127481
127482
127483
127484
127485
127486
127487
127488
127489
127490
127491
127492
127493
127494
127495
127496
127497
127498
127499
127500
127501
127502
127503
127504
127505
127506
127507
127508
127509
127510
127511
127512
127513
127514
127515
127516
127517
127518
127519
127520
127521
127522
127523
127524
127525
127526
127527
127528
127529
127530
127531
127532
127533
127534
127535
127536
127537
127538
127539
127540
127541
127542
127543
127544
127545
127546
127547
127548
127549
127550
127551
127552
127553
127554
127555
127556
127557
127558
127559
127560
127561
127562
127563
127564
127565
127566
127567
127568
127569
127570
127571
127572
127573
127574
127575
127576
127577
127578
127579
127580
127581
127582
127583
127584
127585
127586
127587
127588
127589
127590
127591
127592
127593
127594
127595
127596
127597
127598
127599
127600
127601
127602
127603
127604
127605
127606
127607
127608
127609
127610
127611
127612
127613
127614
127615
127616
127617
127618
127619
127620
127621
127622
127623
127624
127625
127626
127627
127628
127629
127630
127631
127632
127633
127634
127635
127636
127637
127638
127639
127640
127641
127642
127643
127644
127645
127646
127647
127648
127649
127650
127651
127652
127653
127654
127655
127656
127657
127658
127659
127660
127661
127662
127663
127664
127665
127666
127667
127668
127669
127670
127671
127672
127673
127674
127675
127676
127677
127678
127679
127680
127681
127682
127683
127684
127685
127686
127687
127688
127689
127690
127691
127692
127693
127694
127695
127696
127697
127698
127699
127700
127701
127702
127703
127704
127705
127706
127707
127708
127709
127710
127711
127712
127713
127714
127715
127716
127717
127718
127719
127720
127721
127722
127723
127724
127725
127726
127727
127728
127729
127730
127731
127732
127733
127734
127735
127736
127737
127738
127739
127740
127741
127742
127743
127744
127745
127746
127747
127748
127749
127750
127751
127752
127753
127754
127755
127756
127757
127758
127759
127760
127761
127762
127763
127764
127765
127766
127767
127768
127769
127770
127771
127772
127773
127774
127775
127776
127777
127778
127779
127780
127781
127782
127783
127784
127785
127786
127787
127788
127789
127790
127791
127792
127793
127794
127795
127796
127797
127798
127799
127800
127801
127802
127803
127804
127805
127806
127807
127808
127809
127810
127811
127812
127813
127814
127815
127816
127817
127818
127819
127820
127821
127822
127823
127824
127825
127826
127827
127828
127829
127830
127831
127832
127833
127834
127835
127836
127837
127838
127839
127840
127841
127842
127843
127844
127845
127846
127847
127848
127849
127850
127851
127852
127853
127854
127855
127856
127857
127858
127859
127860
127861
127862
127863
127864
127865
127866
127867
127868
127869
127870
127871
127872
127873
127874
127875
127876
127877
127878
127879
127880
127881
127882
127883
127884
127885
127886
127887
127888
127889
127890
127891
127892
127893
127894
127895
127896
127897
127898
127899
127900
127901
127902
127903
127904
127905
127906
127907
127908
127909
127910
127911
127912
127913
127914
127915
127916
127917
127918
127919
127920
127921
127922
127923
127924
127925
127926
127927
127928
127929
127930
127931
127932
127933
127934
127935
127936
127937
127938
127939
127940
127941
127942
127943
127944
127945
127946
127947
127948
127949
127950
127951
127952
127953
127954
127955
127956
127957
127958
127959
127960
127961
127962
127963
127964
127965
127966
127967
127968
127969
127970
127971
127972
127973
127974
127975
127976
127977
127978
127979
127980
127981
127982
127983
127984
127985
127986
127987
127988
127989
127990
127991
127992
127993
127994
127995
127996
127997
127998
127999
128000
128001
128002
128003
128004
128005
128006
128007
128008
128009
128010
128011
128012
128013
128014
128015
128016
128017
128018
128019
128020
128021
128022
128023
128024
128025
128026
128027
128028
128029
128030
128031
128032
128033
128034
128035
128036
128037
128038
128039
128040
128041
128042
128043
128044
128045
128046
128047
128048
128049
128050
128051
128052
128053
128054
128055
128056
128057
128058
128059
128060
128061
128062
128063
128064
128065
128066
128067
128068
128069
128070
128071
128072
128073
128074
128075
128076
128077
128078
128079
128080
128081
128082
128083
128084
128085
128086
128087
128088
128089
128090
128091
128092
128093
128094
128095
128096
128097
128098
128099
128100
128101
128102
128103
128104
128105
128106
128107
128108
128109
128110
128111
128112
128113
128114
128115
128116
128117
128118
128119
128120
128121
128122
128123
128124
128125
128126
128127
128128
128129
128130
128131
128132
128133
128134
128135
128136
128137
128138
128139
128140
128141
128142
128143
128144
128145
128146
128147
128148
128149
128150
128151
128152
128153
128154
128155
128156
128157
128158
128159
128160
128161
128162
128163
128164
128165
128166
128167
128168
128169
128170
128171
128172
128173
128174
128175
128176
128177
128178
128179
128180
128181
128182
128183
128184
128185
128186
128187
128188
128189
128190
128191
128192
128193
128194
128195
128196
128197
128198
128199
128200
128201
128202
128203
128204
128205
128206
128207
128208
128209
128210
128211
128212
128213
128214
128215
128216
128217
128218
128219
128220
128221
128222
128223
128224
128225
128226
128227
128228
128229
128230
128231
128232
128233
128234
128235
128236
128237
128238
128239
128240
128241
128242
128243
128244
128245
128246
128247
128248
128249
128250
128251
128252
128253
128254
128255
128256
128257
128258
128259
128260
128261
128262
128263
128264
128265
128266
128267
128268
128269
128270
128271
128272
128273
128274
128275
128276
128277
128278
128279
128280
128281
128282
128283
128284
128285
128286
128287
128288
128289
128290
128291
128292
128293
128294
128295
128296
128297
128298
128299
128300
128301
128302
128303
128304
128305
128306
128307
128308
128309
128310
128311
128312
128313
128314
128315
128316
128317
128318
128319
128320
128321
128322
128323
128324
128325
128326
128327
128328
128329
128330
128331
128332
128333
128334
128335
128336
128337
128338
128339
128340
128341
128342
128343
128344
128345
128346
128347
128348
128349
128350
128351
128352
128353
128354
128355
128356
128357
128358
128359
128360
128361
128362
128363
128364
128365
128366
128367
128368
128369
128370
128371
128372
128373
128374
128375
128376
128377
128378
128379
128380
128381
128382
128383
128384
128385
128386
128387
128388
128389
128390
128391
128392
128393
128394
128395
128396
128397
128398
128399
128400
128401
128402
128403
128404
128405
128406
128407
128408
128409
128410
128411
128412
128413
128414
128415
128416
128417
128418
128419
128420
128421
128422
128423
128424
128425
128426
128427
128428
128429
128430
128431
128432
128433
128434
128435
128436
128437
128438
128439
128440
128441
128442
128443
128444
128445
128446
128447
128448
128449
128450
128451
128452
128453
128454
128455
128456
128457
128458
128459
128460
128461
128462
128463
128464
128465
128466
128467
128468
128469
128470
128471
128472
128473
128474
128475
128476
128477
128478
128479
128480
128481
128482
128483
128484
128485
128486
128487
128488
128489
128490
128491
128492
128493
128494
128495
128496
128497
128498
128499
128500
128501
128502
128503
128504
128505
128506
128507
128508
128509
128510
128511
128512
128513
128514
128515
128516
128517
128518
128519
128520
128521
128522
128523
128524
128525
128526
128527
128528
128529
128530
128531
128532
128533
128534
128535
128536
128537
128538
128539
128540
128541
128542
128543
128544
128545
128546
128547
128548
128549
128550
128551
128552
128553
128554
128555
128556
128557
128558
128559
128560
128561
128562
128563
128564
128565
128566
128567
128568
128569
128570
128571
128572
128573
128574
128575
128576
128577
128578
128579
128580
128581
128582
128583
128584
128585
128586
128587
128588
128589
128590
128591
128592
128593
128594
128595
128596
128597
128598
128599
128600
128601
128602
128603
128604
128605
128606
128607
128608
128609
128610
128611
128612
128613
128614
128615
128616
128617
128618
128619
128620
128621
128622
128623
128624
128625
128626
128627
128628
128629
128630
128631
128632
128633
128634
128635
128636
128637
128638
128639
128640
128641
128642
128643
128644
128645
128646
128647
128648
128649
128650
128651
128652
128653
128654
128655
128656
128657
128658
128659
128660
128661
128662
128663
128664
128665
128666
128667
128668
128669
128670
128671
128672
128673
128674
128675
128676
128677
128678
128679
128680
128681
128682
128683
128684
128685
128686
128687
128688
128689
128690
128691
128692
128693
128694
128695
128696
128697
128698
128699
128700
128701
128702
128703
128704
128705
128706
128707
128708
128709
128710
128711
128712
128713
128714
128715
128716
128717
128718
128719
128720
128721
128722
128723
128724
128725
128726
128727
128728
128729
128730
128731
128732
128733
128734
128735
128736
128737
128738
128739
128740
128741
128742
128743
128744
128745
128746
128747
128748
128749
128750
128751
128752
128753
128754
128755
128756
128757
128758
128759
128760
128761
128762
128763
128764
128765
128766
128767
128768
128769
128770
128771
128772
128773
128774
128775
128776
128777
128778
128779
128780
128781
128782
128783
128784
128785
128786
128787
128788
128789
128790
128791
128792
128793
128794
128795
128796
128797
128798
128799
128800
128801
128802
128803
128804
128805
128806
128807
128808
128809
128810
128811
128812
128813
128814
128815
128816
128817
128818
128819
128820
128821
128822
128823
128824
128825
128826
128827
128828
128829
128830
128831
128832
128833
128834
128835
128836
128837
128838
128839
128840
128841
128842
128843
128844
128845
128846
128847
128848
128849
128850
128851
128852
128853
128854
128855
128856
128857
128858
128859
128860
128861
128862
128863
128864
128865
128866
128867
128868
128869
128870
128871
128872
128873
128874
128875
128876
128877
128878
128879
128880
128881
128882
128883
128884
128885
128886
128887
128888
128889
128890
128891
128892
128893
128894
128895
128896
128897
128898
128899
128900
128901
128902
128903
128904
128905
128906
128907
128908
128909
128910
128911
128912
128913
128914
128915
128916
128917
128918
128919
128920
128921
128922
128923
128924
128925
128926
128927
128928
128929
128930
128931
128932
128933
128934
128935
128936
128937
128938
128939
128940
128941
128942
128943
128944
128945
128946
128947
128948
128949
128950
128951
128952
128953
128954
128955
128956
128957
128958
128959
128960
128961
128962
128963
128964
128965
128966
128967
128968
128969
128970
128971
128972
128973
128974
128975
128976
128977
128978
128979
128980
128981
128982
128983
128984
128985
128986
128987
128988
128989
128990
128991
128992
128993
128994
128995
128996
128997
128998
128999
129000
129001
129002
129003
129004
129005
129006
129007
129008
129009
129010
129011
129012
129013
129014
129015
129016
129017
129018
129019
129020
129021
129022
129023
129024
129025
129026
129027
129028
129029
129030
129031
129032
129033
129034
129035
129036
129037
129038
129039
129040
129041
129042
129043
129044
129045
129046
129047
129048
129049
129050
129051
129052
129053
129054
129055
129056
129057
129058
129059
129060
129061
129062
129063
129064
129065
129066
129067
129068
129069
129070
129071
129072
129073
129074
129075
129076
129077
129078
129079
129080
129081
129082
129083
129084
129085
129086
129087
129088
129089
129090
129091
129092
129093
129094
129095
129096
129097
129098
129099
129100
129101
129102
129103
129104
129105
129106
129107
129108
129109
129110
129111
129112
129113
129114
129115
129116
129117
129118
129119
129120
129121
129122
129123
129124
129125
129126
129127
129128
129129
129130
129131
129132
129133
129134
129135
129136
129137
129138
129139
129140
129141
129142
129143
129144
129145
129146
129147
129148
129149
129150
129151
129152
129153
129154
129155
129156
129157
129158
129159
129160
129161
129162
129163
129164
129165
129166
129167
129168
129169
129170
129171
129172
129173
129174
129175
129176
129177
129178
129179
129180
129181
129182
129183
129184
129185
129186
129187
129188
129189
129190
129191
129192
129193
129194
129195
129196
129197
129198
129199
129200
129201
129202
129203
129204
129205
129206
129207
129208
129209
129210
129211
129212
129213
129214
129215
129216
129217
129218
129219
129220
129221
129222
129223
129224
129225
129226
129227
129228
129229
129230
129231
129232
129233
129234
129235
129236
129237
129238
129239
129240
129241
129242
129243
129244
129245
129246
129247
129248
129249
129250
129251
129252
129253
129254
129255
129256
129257
129258
129259
129260
129261
129262
129263
129264
129265
129266
129267
129268
129269
129270
129271
129272
129273
129274
129275
129276
129277
129278
129279
129280
129281
129282
129283
129284
129285
129286
129287
129288
129289
129290
129291
129292
129293
129294
129295
129296
129297
129298
129299
129300
129301
129302
129303
129304
129305
129306
129307
129308
129309
129310
129311
129312
129313
129314
129315
129316
129317
129318
129319
129320
129321
129322
129323
129324
129325
129326
129327
129328
129329
129330
129331
129332
129333
129334
129335
129336
129337
129338
129339
129340
129341
129342
129343
129344
129345
129346
129347
129348
129349
129350
129351
129352
129353
129354
129355
129356
129357
129358
129359
129360
129361
129362
129363
129364
129365
129366
129367
129368
129369
129370
129371
129372
129373
129374
129375
129376
129377
129378
129379
129380
129381
129382
129383
129384
129385
129386
129387
129388
129389
129390
129391
129392
129393
129394
129395
129396
129397
129398
129399
129400
129401
129402
129403
129404
129405
129406
129407
129408
129409
129410
129411
129412
129413
129414
129415
129416
129417
129418
129419
129420
129421
129422
129423
129424
129425
129426
129427
129428
129429
129430
129431
129432
129433
129434
129435
129436
129437
129438
129439
129440
129441
129442
129443
129444
129445
129446
129447
129448
129449
129450
129451
129452
129453
129454
129455
129456
129457
129458
129459
129460
129461
129462
129463
129464
129465
129466
129467
129468
129469
129470
129471
129472
129473
129474
129475
129476
129477
129478
129479
129480
129481
129482
129483
129484
129485
129486
129487
129488
129489
129490
129491
129492
129493
129494
129495
129496
129497
129498
129499
129500
129501
129502
129503
129504
129505
129506
129507
129508
129509
129510
129511
129512
129513
129514
129515
129516
129517
129518
129519
129520
129521
129522
129523
129524
129525
129526
129527
129528
129529
129530
129531
129532
129533
129534
129535
129536
129537
129538
129539
129540
129541
129542
129543
129544
129545
129546
129547
129548
129549
129550
129551
129552
129553
129554
129555
129556
129557
129558
129559
129560
129561
129562
129563
129564
129565
129566
129567
129568
129569
129570
129571
129572
129573
129574
129575
129576
129577
129578
129579
129580
129581
129582
129583
129584
129585
129586
129587
129588
129589
129590
129591
129592
129593
129594
129595
129596
129597
129598
129599
129600
129601
129602
129603
129604
129605
129606
129607
129608
129609
129610
129611
129612
129613
129614
129615
129616
129617
129618
129619
129620
129621
129622
129623
129624
129625
129626
129627
129628
129629
129630
129631
129632
129633
129634
129635
129636
129637
129638
129639
129640
129641
129642
129643
129644
129645
129646
129647
129648
129649
129650
129651
129652
129653
129654
129655
129656
129657
129658
129659
129660
129661
129662
129663
129664
129665
129666
129667
129668
129669
129670
129671
129672
129673
129674
129675
129676
129677
129678
129679
129680
129681
129682
129683
129684
129685
129686
129687
129688
129689
129690
129691
129692
129693
129694
129695
129696
129697
129698
129699
129700
129701
129702
129703
129704
129705
129706
129707
129708
129709
129710
129711
129712
129713
129714
129715
129716
129717
129718
129719
129720
129721
129722
129723
129724
129725
129726
129727
129728
129729
129730
129731
129732
129733
129734
129735
129736
129737
129738
129739
129740
129741
129742
129743
129744
129745
129746
129747
129748
129749
129750
129751
129752
129753
129754
129755
129756
129757
129758
129759
129760
129761
129762
129763
129764
129765
129766
129767
129768
129769
129770
129771
129772
129773
129774
129775
129776
129777
129778
129779
129780
129781
129782
129783
129784
129785
129786
129787
129788
129789
129790
129791
129792
129793
129794
129795
129796
129797
129798
129799
129800
129801
129802
129803
129804
129805
129806
129807
129808
129809
129810
129811
129812
129813
129814
129815
129816
129817
129818
129819
129820
129821
129822
129823
129824
129825
129826
129827
129828
129829
129830
129831
129832
129833
129834
129835
129836
129837
129838
129839
129840
129841
129842
129843
129844
129845
129846
129847
129848
129849
129850
129851
129852
129853
129854
129855
129856
129857
129858
129859
129860
129861
129862
129863
129864
129865
129866
129867
129868
129869
129870
129871
129872
129873
129874
129875
129876
129877
129878
129879
129880
129881
129882
129883
129884
129885
129886
129887
129888
129889
129890
129891
129892
129893
129894
129895
129896
129897
129898
129899
129900
129901
129902
129903
129904
129905
129906
129907
129908
129909
129910
129911
129912
129913
129914
129915
129916
129917
129918
129919
129920
129921
129922
129923
129924
129925
129926
129927
129928
129929
129930
129931
129932
129933
129934
129935
129936
129937
129938
129939
129940
129941
129942
129943
129944
129945
129946
129947
129948
129949
129950
129951
129952
129953
129954
129955
129956
129957
129958
129959
129960
129961
129962
129963
129964
129965
129966
129967
129968
129969
129970
129971
129972
129973
129974
129975
129976
129977
129978
129979
129980
129981
129982
129983
129984
129985
129986
129987
129988
129989
129990
129991
129992
129993
129994
129995
129996
129997
129998
129999
130000
130001
130002
130003
130004
130005
130006
130007
130008
130009
130010
130011
130012
130013
130014
130015
130016
130017
130018
130019
130020
130021
130022
130023
130024
130025
130026
130027
130028
130029
130030
130031
130032
130033
130034
130035
130036
130037
130038
130039
130040
130041
130042
130043
130044
130045
130046
130047
130048
130049
130050
130051
130052
130053
130054
130055
130056
130057
130058
130059
130060
130061
130062
130063
130064
130065
130066
130067
130068
130069
130070
130071
130072
130073
130074
130075
130076
130077
130078
130079
130080
130081
130082
130083
130084
130085
130086
130087
130088
130089
130090
130091
130092
130093
130094
130095
130096
130097
130098
130099
130100
130101
130102
130103
130104
130105
130106
130107
130108
130109
130110
130111
130112
130113
130114
130115
130116
130117
130118
130119
130120
130121
130122
130123
130124
130125
130126
130127
130128
130129
130130
130131
130132
130133
130134
130135
130136
130137
130138
130139
130140
130141
130142
130143
130144
130145
130146
130147
130148
130149
130150
130151
130152
130153
130154
130155
130156
130157
130158
130159
130160
130161
130162
130163
130164
130165
130166
130167
130168
130169
130170
130171
130172
130173
130174
130175
130176
130177
130178
130179
130180
130181
130182
130183
130184
130185
130186
130187
130188
130189
130190
130191
130192
130193
130194
130195
130196
130197
130198
130199
130200
130201
130202
130203
130204
130205
130206
130207
130208
130209
130210
130211
130212
130213
130214
130215
130216
130217
130218
130219
130220
130221
130222
130223
130224
130225
130226
130227
130228
130229
130230
130231
130232
130233
130234
130235
130236
130237
130238
130239
130240
130241
130242
130243
130244
130245
130246
130247
130248
130249
130250
130251
130252
130253
130254
130255
130256
130257
130258
130259
130260
130261
130262
130263
130264
130265
130266
130267
130268
130269
130270
130271
130272
130273
130274
130275
130276
130277
130278
130279
130280
130281
130282
130283
130284
130285
130286
130287
130288
130289
130290
130291
130292
130293
130294
130295
130296
130297
130298
130299
130300
130301
130302
130303
130304
130305
130306
130307
130308
130309
130310
130311
130312
130313
130314
130315
130316
130317
130318
130319
130320
130321
130322
130323
130324
130325
130326
130327
130328
130329
130330
130331
130332
130333
130334
130335
130336
130337
130338
130339
130340
130341
130342
130343
130344
130345
130346
130347
130348
130349
130350
130351
130352
130353
130354
130355
130356
130357
130358
130359
130360
130361
130362
130363
130364
130365
130366
130367
130368
130369
130370
130371
130372
130373
130374
130375
130376
130377
130378
130379
130380
130381
130382
130383
130384
130385
130386
130387
130388
130389
130390
130391
130392
130393
130394
130395
130396
130397
130398
130399
130400
130401
130402
130403
130404
130405
130406
130407
130408
130409
130410
130411
130412
130413
130414
130415
130416
130417
130418
130419
130420
130421
130422
130423
130424
130425
130426
130427
130428
130429
130430
130431
130432
130433
130434
130435
130436
130437
130438
130439
130440
130441
130442
130443
130444
130445
130446
130447
130448
130449
130450
130451
130452
130453
130454
130455
130456
130457
130458
130459
130460
130461
130462
130463
130464
130465
130466
130467
130468
130469
130470
130471
130472
130473
130474
130475
130476
130477
130478
130479
130480
130481
130482
130483
130484
130485
130486
130487
130488
130489
130490
130491
130492
130493
130494
130495
130496
130497
130498
130499
130500
130501
130502
130503
130504
130505
130506
130507
130508
130509
130510
130511
130512
130513
130514
130515
130516
130517
130518
130519
130520
130521
130522
130523
130524
130525
130526
130527
130528
130529
130530
130531
130532
130533
130534
130535
130536
130537
130538
130539
130540
130541
130542
130543
130544
130545
130546
130547
130548
130549
130550
130551
130552
130553
130554
130555
130556
130557
130558
130559
130560
130561
130562
130563
130564
130565
130566
130567
130568
130569
130570
130571
130572
130573
130574
130575
130576
130577
130578
130579
130580
130581
130582
130583
130584
130585
130586
130587
130588
130589
130590
130591
130592
130593
130594
130595
130596
130597
130598
130599
130600
130601
130602
130603
130604
130605
130606
130607
130608
130609
130610
130611
130612
130613
130614
130615
130616
130617
130618
130619
130620
130621
130622
130623
130624
130625
130626
130627
130628
130629
130630
130631
130632
130633
130634
130635
130636
130637
130638
130639
130640
130641
130642
130643
130644
130645
130646
130647
130648
130649
130650
130651
130652
130653
130654
130655
130656
130657
130658
130659
130660
130661
130662
130663
130664
130665
130666
130667
130668
130669
130670
130671
130672
130673
130674
130675
130676
130677
130678
130679
130680
130681
130682
130683
130684
130685
130686
130687
130688
130689
130690
130691
130692
130693
130694
130695
130696
130697
130698
130699
130700
130701
130702
130703
130704
130705
130706
130707
130708
130709
130710
130711
130712
130713
130714
130715
130716
130717
130718
130719
130720
130721
130722
130723
130724
130725
130726
130727
130728
130729
130730
130731
130732
130733
130734
130735
130736
130737
130738
130739
130740
130741
130742
130743
130744
130745
130746
130747
130748
130749
130750
130751
130752
130753
130754
130755
130756
130757
130758
130759
130760
130761
130762
130763
130764
130765
130766
130767
130768
130769
130770
130771
130772
130773
130774
130775
130776
130777
130778
130779
130780
130781
130782
130783
130784
130785
130786
130787
130788
130789
130790
130791
130792
130793
130794
130795
130796
130797
130798
130799
130800
130801
130802
130803
130804
130805
130806
130807
130808
130809
130810
130811
130812
130813
130814
130815
130816
130817
130818
130819
130820
130821
130822
130823
130824
130825
130826
130827
130828
130829
130830
130831
130832
130833
130834
130835
130836
130837
130838
130839
130840
130841
130842
130843
130844
130845
130846
130847
130848
130849
130850
130851
130852
130853
130854
130855
130856
130857
130858
130859
130860
130861
130862
130863
130864
130865
130866
130867
130868
130869
130870
130871
130872
130873
130874
130875
130876
130877
130878
130879
130880
130881
130882
130883
130884
130885
130886
130887
130888
130889
130890
130891
130892
130893
130894
130895
130896
130897
130898
130899
130900
130901
130902
130903
130904
130905
130906
130907
130908
130909
130910
130911
130912
130913
130914
130915
130916
130917
130918
130919
130920
130921
130922
130923
130924
130925
130926
130927
130928
130929
130930
130931
130932
130933
130934
130935
130936
130937
130938
130939
130940
130941
130942
130943
130944
130945
130946
130947
130948
130949
130950
130951
130952
130953
130954
130955
130956
130957
130958
130959
130960
130961
130962
130963
130964
130965
130966
130967
130968
130969
130970
130971
130972
130973
130974
130975
130976
130977
130978
130979
130980
130981
130982
130983
130984
130985
130986
130987
130988
130989
130990
130991
130992
130993
130994
130995
130996
130997
130998
130999
131000
131001
131002
131003
131004
131005
131006
131007
131008
131009
131010
131011
131012
131013
131014
131015
131016
131017
131018
131019
131020
131021
131022
131023
131024
131025
131026
131027
131028
131029
131030
131031
131032
131033
131034
131035
131036
131037
131038
131039
131040
131041
131042
131043
131044
131045
131046
131047
131048
131049
131050
131051
131052
131053
131054
131055
131056
131057
131058
131059
131060
131061
131062
131063
131064
131065
131066
131067
131068
131069
131070
131071
131072
131073
131074
131075
131076
131077
131078
131079
131080
131081
131082
131083
131084
131085
131086
131087
131088
131089
131090
131091
131092
131093
131094
131095
131096
131097
131098
131099
131100
131101
131102
131103
131104
131105
131106
131107
131108
131109
131110
131111
131112
131113
131114
131115
131116
131117
131118
131119
131120
131121
131122
131123
131124
131125
131126
131127
131128
131129
131130
131131
131132
131133
131134
131135
131136
131137
131138
131139
131140
131141
131142
131143
131144
131145
131146
131147
131148
131149
131150
131151
131152
131153
131154
131155
131156
131157
131158
131159
131160
131161
131162
131163
131164
131165
131166
131167
131168
131169
131170
131171
131172
131173
131174
131175
131176
131177
131178
131179
131180
131181
131182
131183
131184
131185
131186
131187
131188
131189
131190
131191
131192
131193
131194
131195
131196
131197
131198
131199
131200
131201
131202
131203
131204
131205
131206
131207
131208
131209
131210
131211
131212
131213
131214
131215
131216
131217
131218
131219
131220
131221
131222
131223
131224
131225
131226
131227
131228
131229
131230
131231
131232
131233
131234
131235
131236
131237
131238
131239
131240
131241
131242
131243
131244
131245
131246
131247
131248
131249
131250
131251
131252
131253
131254
131255
131256
131257
131258
131259
131260
131261
131262
131263
131264
131265
131266
131267
131268
131269
131270
131271
131272
131273
131274
131275
131276
131277
131278
131279
131280
131281
131282
131283
131284
131285
131286
131287
131288
131289
131290
131291
131292
131293
131294
131295
131296
131297
131298
131299
131300
131301
131302
131303
131304
131305
131306
131307
131308
131309
131310
131311
131312
131313
131314
131315
131316
131317
131318
131319
131320
131321
131322
131323
131324
131325
131326
131327
131328
131329
131330
131331
131332
131333
131334
131335
131336
131337
131338
131339
131340
131341
131342
131343
131344
131345
131346
131347
131348
131349
131350
131351
131352
131353
131354
131355
131356
131357
131358
131359
131360
131361
131362
131363
131364
131365
131366
131367
131368
131369
131370
131371
131372
131373
131374
131375
131376
131377
131378
131379
131380
131381
131382
131383
131384
131385
131386
131387
131388
131389
131390
131391
131392
131393
131394
131395
131396
131397
131398
131399
131400
131401
131402
131403
131404
131405
131406
131407
131408
131409
131410
131411
131412
131413
131414
131415
131416
131417
131418
131419
131420
131421
131422
131423
131424
131425
131426
131427
131428
131429
131430
131431
131432
131433
131434
131435
131436
131437
131438
131439
131440
131441
131442
131443
131444
131445
131446
131447
131448
131449
131450
131451
131452
131453
131454
131455
131456
131457
131458
131459
131460
131461
131462
131463
131464
131465
131466
131467
131468
131469
131470
131471
131472
131473
131474
131475
131476
131477
131478
131479
131480
131481
131482
131483
131484
131485
131486
131487
131488
131489
131490
131491
131492
131493
131494
131495
131496
131497
131498
131499
131500
131501
131502
131503
131504
131505
131506
131507
131508
131509
131510
131511
131512
131513
131514
131515
131516
131517
131518
131519
131520
131521
131522
131523
131524
131525
131526
131527
131528
131529
131530
131531
131532
131533
131534
131535
131536
131537
131538
131539
131540
131541
131542
131543
131544
131545
131546
131547
131548
131549
131550
131551
131552
131553
131554
131555
131556
131557
131558
131559
131560
131561
131562
131563
131564
131565
131566
131567
131568
131569
131570
131571
131572
131573
131574
131575
131576
131577
131578
131579
131580
131581
131582
131583
131584
131585
131586
131587
131588
131589
131590
131591
131592
131593
131594
131595
131596
131597
131598
131599
131600
131601
131602
131603
131604
131605
131606
131607
131608
131609
131610
131611
131612
131613
131614
131615
131616
131617
131618
131619
131620
131621
131622
131623
131624
131625
131626
131627
131628
131629
131630
131631
131632
131633
131634
131635
131636
131637
131638
131639
131640
131641
131642
131643
131644
131645
131646
131647
131648
131649
131650
131651
131652
131653
131654
131655
131656
131657
131658
131659
131660
131661
131662
131663
131664
131665
131666
131667
131668
131669
131670
131671
131672
131673
131674
131675
131676
131677
131678
131679
131680
131681
131682
131683
131684
131685
131686
131687
131688
131689
131690
131691
131692
131693
131694
131695
131696
131697
131698
131699
131700
131701
131702
131703
131704
131705
131706
131707
131708
131709
131710
131711
131712
131713
131714
131715
131716
131717
131718
131719
131720
131721
131722
131723
131724
131725
131726
131727
131728
131729
131730
131731
131732
131733
131734
131735
131736
131737
131738
131739
131740
131741
131742
131743
131744
131745
131746
131747
131748
131749
131750
131751
131752
131753
131754
131755
131756
131757
131758
131759
131760
131761
131762
131763
131764
131765
131766
131767
131768
131769
131770
131771
131772
131773
131774
131775
131776
131777
131778
131779
131780
131781
131782
131783
131784
131785
131786
131787
131788
131789
131790
131791
131792
131793
131794
131795
131796
131797
131798
131799
131800
131801
131802
131803
131804
131805
131806
131807
131808
131809
131810
131811
131812
131813
131814
131815
131816
131817
131818
131819
131820
131821
131822
131823
131824
131825
131826
131827
131828
131829
131830
131831
131832
131833
131834
131835
131836
131837
131838
131839
131840
131841
131842
131843
131844
131845
131846
131847
131848
131849
131850
131851
131852
131853
131854
131855
131856
131857
131858
131859
131860
131861
131862
131863
131864
131865
131866
131867
131868
131869
131870
131871
131872
131873
131874
131875
131876
131877
131878
131879
131880
131881
131882
131883
131884
131885
131886
131887
131888
131889
131890
131891
131892
131893
131894
131895
131896
131897
131898
131899
131900
131901
131902
131903
131904
131905
131906
131907
131908
131909
131910
131911
131912
131913
131914
131915
131916
131917
131918
131919
131920
131921
131922
131923
131924
131925
131926
131927
131928
131929
131930
131931
131932
131933
131934
131935
131936
131937
131938
131939
131940
131941
131942
131943
131944
131945
131946
131947
131948
131949
131950
131951
131952
131953
131954
131955
131956
131957
131958
131959
131960
131961
131962
131963
131964
131965
131966
131967
131968
131969
131970
131971
131972
131973
131974
131975
131976
131977
131978
131979
131980
131981
131982
131983
131984
131985
131986
131987
131988
131989
131990
131991
131992
131993
131994
131995
131996
131997
131998
131999
132000
132001
132002
132003
132004
132005
132006
132007
132008
132009
132010
132011
132012
132013
132014
132015
132016
132017
132018
132019
132020
132021
132022
132023
132024
132025
132026
132027
132028
132029
132030
132031
132032
132033
132034
132035
132036
132037
132038
132039
132040
132041
132042
132043
132044
132045
132046
132047
132048
132049
132050
132051
132052
132053
132054
132055
132056
132057
132058
132059
132060
132061
132062
132063
132064
132065
132066
132067
132068
132069
132070
132071
132072
132073
132074
132075
132076
132077
132078
132079
132080
132081
132082
132083
132084
132085
132086
132087
132088
132089
132090
132091
132092
132093
132094
132095
132096
132097
132098
132099
132100
132101
132102
132103
132104
132105
132106
132107
132108
132109
132110
132111
132112
132113
132114
132115
132116
132117
132118
132119
132120
132121
132122
132123
132124
132125
132126
132127
132128
132129
132130
132131
132132
132133
132134
132135
132136
132137
132138
132139
132140
132141
132142
132143
132144
132145
132146
132147
132148
132149
132150
132151
132152
132153
132154
132155
132156
132157
132158
132159
132160
132161
132162
132163
132164
132165
132166
132167
132168
132169
132170
132171
132172
132173
132174
132175
132176
132177
132178
132179
132180
132181
132182
132183
132184
132185
132186
132187
132188
132189
132190
132191
132192
132193
132194
132195
132196
132197
132198
132199
132200
132201
132202
132203
132204
132205
132206
132207
132208
132209
132210
132211
132212
132213
132214
132215
132216
132217
132218
132219
132220
132221
132222
132223
132224
132225
132226
132227
132228
132229
132230
132231
132232
132233
132234
132235
132236
132237
132238
132239
132240
132241
132242
132243
132244
132245
132246
132247
132248
132249
132250
132251
132252
132253
132254
132255
132256
132257
132258
132259
132260
132261
132262
132263
132264
132265
132266
132267
132268
132269
132270
132271
132272
132273
132274
132275
132276
132277
132278
132279
132280
132281
132282
132283
132284
132285
132286
132287
132288
132289
132290
132291
132292
132293
132294
132295
132296
132297
132298
132299
132300
132301
132302
132303
132304
132305
132306
132307
132308
132309
132310
132311
132312
132313
132314
132315
132316
132317
132318
132319
132320
132321
132322
132323
132324
132325
132326
132327
132328
132329
132330
132331
132332
132333
132334
132335
132336
132337
132338
132339
132340
132341
132342
132343
132344
132345
132346
132347
132348
132349
132350
132351
132352
132353
132354
132355
132356
132357
132358
|
;;; rnrs exceptions (6) --- R6RS exceptions
;; Copyright (C) 2013 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: ffi struct bytevector bytestructure
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; A clean implementation of (rnrs exceptions (6)). The dynamic environment
;; capturing operations are noteworthy.
;;; Code:
(library
(rnrs exceptions (6))
(export with-exception-handler raise raise-continuable guard)
(import (rnrs base (6))
(srfi 39))
;;; Helpers
;;; Ignores any extra `else' clauses.
;;; Helps to generate cond clauses with a default `else' clause.
(define-syntax cond+
(syntax-rules (else)
((cond+ clause ... (else else1) (else else2))
(cond+ clause ... (else else1)))
((cond+ clause ...)
(cond clause ...))))
;;; Captures the current dynamic environment. It is reified as a procedure that
;;; accepts a thunk and executes it in the captured dynenv.
(define (capture-dynenv)
((call/cc
(lambda (captured-env)
(lambda ()
(lambda (proc)
(call/cc
(lambda (go-back)
(captured-env
(lambda ()
(call-with-values proc go-back)))))))))))
;;; Captures the current dynamic environment and returns a procedure that
;;; accepts as many arguments as PROC and applies PROC to them in that dynenv.
;;; In other words, returns a version of PROC that's tied to the current dynenv.
(define (dynenv-proc proc)
(let ((env (capture-dynenv)))
(lambda args
(env (lambda () (apply proc args))))))
;;; Returns a procedure that's always executed in the current dynamic
;;; environment and not the one from which it's called.
(define-syntax dynenv-lambda
(syntax-rules ()
((_ args body body* ...)
(dynenv-proc (lambda args body body* ...)))))
;;; Main code:
(define handlers (make-parameter '()))
(define &non-continuable '&non-continuable)
(define (with-exception-handler handler thunk)
(parameterize ((handlers (cons handler (handlers))))
(thunk)))
(define (%raise condition continuable?)
(if (null? (handlers))
(error "unhandled exception" condition)
(let ((handler (car (handlers))))
(parameterize ((handlers (cdr (handlers))))
(if continuable?
(handler condition)
(begin
(handler condition)
(%raise &non-continuable #f)))))))
(define (raise-continuable condition)
(%raise condition #t))
(define (raise condition)
(%raise condition #f))
(define-syntax guard
(syntax-rules ()
((guard (var clause clause* ...)
body body* ...)
(call/cc
(lambda (return)
(let ((handler (dynenv-lambda (var re-raise)
(return
(cond+ clause
clause*
...
(else (re-raise)))))))
(with-exception-handler
(lambda (condition)
(let ((re-raise (dynenv-lambda ()
(raise condition))))
(handler condition re-raise)))
(lambda ()
body body* ...))))))))
)
(define-module (test)
#\use-module (bytestructures guile))
(display cstring-pointer)
(newline)
;;; align.scm --- Alignment calculation helpers.
;; Copyright © 2018 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;; Code:
;;; Either remains at 'position' or rounds up to the next multiple of
;;; 'alignment' depending on whether 'size' (if not greater than 'alignment')
;;; would fit. Returns three values: the chosen position, the start of the
;;; alignment boundary of the chosen position, and the bit offset of the chosen
;;; position from the start of the alignment boundary. A bit is represented by
;;; the value 1/8.
(define (align position size alignment)
(let* ((integer (floor position))
(fraction (- position integer)))
(let-values (((prev-boundary-index offset) (floor/ integer alignment)))
(let* ((prev-boundary (* prev-boundary-index alignment))
(next-boundary (+ prev-boundary alignment)))
(if (< next-boundary (+ position (min size alignment)))
(values next-boundary next-boundary 0)
(values position prev-boundary (* 8 (+ offset fraction))))))))
;;; Returns 'position' if it's already a multiple of 'alignment'; otherwise
;;; returns the next multiple.
(define (next-boundary position alignment)
(align position +inf.0 alignment))
;;; align.scm ends here
;;; bytestructures --- Structured access to bytevector contents.
;; Copyright © 2015, 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This is the base of the module, defining the data types and procedures that
;; make up the bytestructures framework.
;;; Code:
;;; Descriptors
(define-record-type <bytestructure-descriptor>
(%make-bytestructure-descriptor size alignment unwrapper getter setter meta)
bytestructure-descriptor?
(size bd-size)
(alignment bd-alignment)
(unwrapper bd-unwrapper)
(getter bd-getter)
(setter bd-setter)
(meta bd-meta))
(define make-bytestructure-descriptor
(case-lambda
((size alignment unwrapper getter setter)
(%make-bytestructure-descriptor
size alignment unwrapper getter setter #f))
((size alignment unwrapper getter setter meta)
(%make-bytestructure-descriptor
size alignment unwrapper getter setter meta))))
(define bytestructure-descriptor-size
(case-lambda
((descriptor) (bytestructure-descriptor-size descriptor #f #f))
((descriptor bytevector offset)
(let ((size (bd-size descriptor)))
(if (procedure? size)
(size #f bytevector offset)
size)))))
(define (bytestructure-descriptor-size/syntax bytevector offset descriptor)
(let ((size (bd-size descriptor)))
(if (procedure? size)
(size #t bytevector offset)
size)))
(define bytestructure-descriptor-alignment bd-alignment)
(define bytestructure-descriptor-unwrapper bd-unwrapper)
(define bytestructure-descriptor-getter bd-getter)
(define bytestructure-descriptor-setter bd-setter)
(define bytestructure-descriptor-metadata bd-meta)
;;; Bytestructures
(define-record-type <bytestructure>
(make-bytestructure bytevector offset descriptor)
bytestructure?
(bytevector bytestructure-bytevector)
(offset bytestructure-offset)
(descriptor bytestructure-descriptor))
(define bytestructure
(case-lambda ((descriptor) (%bytestructure descriptor #f #f))
((descriptor values) (%bytestructure descriptor #t values))))
(define (%bytestructure descriptor init? values)
(let ((bytevector (make-bytevector
(bytestructure-descriptor-size descriptor))))
(when init?
(bytestructure-primitive-set! bytevector 0 descriptor values))
(make-bytestructure bytevector 0 descriptor)))
(define (bytestructure-size bytestructure)
(bytestructure-descriptor-size (bytestructure-descriptor bytestructure)
(bytestructure-bytevector bytestructure)
(bytestructure-offset bytestructure)))
(define-syntax-rule (bytestructure-unwrap <bytestructure> <index> ...)
(let ((bytestructure <bytestructure>))
(let ((bytevector (bytestructure-bytevector bytestructure))
(offset (bytestructure-offset bytestructure))
(descriptor (bytestructure-descriptor bytestructure)))
(bytestructure-unwrap* bytevector offset descriptor <index> ...))))
(define-syntax bytestructure-unwrap*
(syntax-rules ()
((_ <bytevector> <offset> <descriptor>)
(values <bytevector> <offset> <descriptor>))
((_ <bytevector> <offset> <descriptor> <index> <indices> ...)
(let ((bytevector <bytevector>)
(offset <offset>)
(descriptor <descriptor>))
(let ((unwrapper (bd-unwrapper descriptor)))
(when (not unwrapper)
(error "Cannot index through this descriptor." descriptor))
(let-values (((bytevector* offset* descriptor*)
(unwrapper #f bytevector offset <index>)))
(bytestructure-unwrap*
bytevector* offset* descriptor* <indices> ...)))))))
(define-syntax-rule (bytestructure-ref <bytestructure> <index> ...)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap <bytestructure> <index> ...)))
(bytestructure-primitive-ref bytevector offset descriptor)))
(define-syntax-rule (bytestructure-ref*
<bytevector> <offset> <descriptor> <index> ...)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap*
<bytevector> <offset> <descriptor> <index> ...)))
(bytestructure-primitive-ref bytevector offset descriptor)))
(define (bytestructure-primitive-ref bytevector offset descriptor)
(let ((getter (bd-getter descriptor)))
(if getter
(getter #f bytevector offset)
(make-bytestructure bytevector offset descriptor))))
(define-syntax-rule (bytestructure-set! <bytestructure> <index> ... <value>)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap <bytestructure> <index> ...)))
(bytestructure-primitive-set! bytevector offset descriptor <value>)))
(define-syntax-rule (bytestructure-set!*
<bytevector> <offset> <descriptor> <index> ... <value>)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap*
<bytevector> <offset> <descriptor> <index> ...)))
(bytestructure-primitive-set! bytevector offset descriptor <value>)))
(define (bytestructure-primitive-set! bytevector offset descriptor value)
(let ((setter (bd-setter descriptor)))
(if setter
(setter #f bytevector offset value)
(if (bytevector? value)
(bytevector-copy! bytevector offset value 0
(bytestructure-descriptor-size
descriptor bytevector offset))
(error "Cannot write value with this bytestructure descriptor."
value descriptor)))))
(define (bytestructure-ref/dynamic bytestructure . indices)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap bytestructure)))
(let loop ((bytevector bytevector)
(offset offset)
(descriptor descriptor)
(indices indices))
(if (null? indices)
(bytestructure-primitive-ref bytevector offset descriptor)
(let-values (((bytevector* offset* descriptor*)
(bytestructure-unwrap*
bytevector offset descriptor (car indices))))
(loop bytevector*
offset*
descriptor*
(cdr indices)))))))
(define (bytestructure-set!/dynamic bytestructure . args)
(let-values (((bytevector offset descriptor)
(bytestructure-unwrap bytestructure)))
(let loop ((bytevector bytevector)
(offset offset)
(descriptor descriptor)
(args args))
(if (null? (cdr args))
(bytestructure-primitive-set! bytevector offset descriptor (car args))
(let-values (((bytevector* offset* descriptor*)
(bytestructure-unwrap*
bytevector offset descriptor (car args))))
(loop bytevector*
offset*
descriptor*
(cdr args)))))))
(define-syntax-case-stubs
bytestructure-unwrap/syntax
bytestructure-ref/syntax
bytestructure-set!/syntax
define-bytestructure-accessors)
(cond-expand
(guile (include-from-path "bytestructures/body/base.syntactic.scm"))
(syntax-case (include "base.syntactic.scm"))
(else))
;;; base.scm ends here
;;; bytestructures --- Structured access to bytevector contents.
;; Copyright © 2015 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This is an extension to the base of the module which allows using the API
;; purely in the macro-expand phase, which puts some limitations on its use but
;; reduces run-time overhead to zero or nearly zero.
;;; Code:
(define-syntax-rule (syntax-case-lambda <pattern> <body>)
(lambda (stx)
(syntax-case stx ()
(<pattern> <body>))))
(define syntax-car (syntax-case-lambda (car . cdr) #'car))
(define syntax-cdr (syntax-case-lambda (car . cdr) #'cdr))
(define syntax-null? (syntax-case-lambda stx (null? (syntax->datum #'stx))))
(define (syntactic-unwrap bytevector offset descriptor indices)
(let loop ((bytevector bytevector)
(offset offset)
(descriptor descriptor)
(indices indices))
(if (not (syntax-null? indices))
(let ((unwrapper (bd-unwrapper descriptor)))
(when (not unwrapper)
(error "Cannot index through this descriptor." descriptor))
(let-values (((bytevector* offset* descriptor*)
(unwrapper #t bytevector offset (syntax-car indices))))
(loop bytevector* offset* descriptor* (syntax-cdr indices))))
(let ((getter (bd-getter descriptor))
(setter (bd-setter descriptor)))
(values bytevector offset descriptor getter setter)))))
(define (bytestructure-unwrap/syntax bytevector offset descriptor indices)
(let-values (((bytevector* offset* _descriptor _getter _setter)
(syntactic-unwrap bytevector offset descriptor indices)))
#`(values #,bytevector* #,offset*)))
(define (bytestructure-ref/syntax bytevector offset descriptor indices)
(let-values (((bytevector* offset* descriptor* getter _setter)
(syntactic-unwrap bytevector offset descriptor indices)))
(if getter
(getter #t bytevector* offset*)
(error "The indices given to bytestructure-ref/syntax do not lead to a
bytestructure descriptor that can decode values. You must have used the wrong
getter macro, forgot to provide some of the indices, or meant to use the
unwrapper instead of the getter. The given indices follow." indices))))
(define (bytestructure-set!/syntax bytevector offset descriptor indices value)
(let-values (((bytevector* offset* descriptor* _getter setter)
(syntactic-unwrap bytevector offset descriptor indices)))
(if setter
(setter #t bytevector* offset* value)
(error "The indices given to bytestructure-set!/syntax do not lead to a
bytestructure descriptor that can encode values. You must have used the wrong
setter macro, or forgot to provide some of the indices. The given indices
follow." indices))))
(define-syntax-rule (define-bytestructure-unwrapper <name> <descriptor>)
(define-syntax <name>
(let ((descriptor <descriptor>))
(syntax-case-lambda (_ <bytevector> <offset> . <indices>)
(bytestructure-unwrap/syntax
#'<bytevector> #'<offset> descriptor #'<indices>)))))
(define-syntax-rule (define-bytestructure-getter* <name> <descriptor>)
(define-syntax <name>
(let ((descriptor <descriptor>))
(syntax-case-lambda (_ <bytevector> <offset> . <indices>)
(bytestructure-ref/syntax
#'<bytevector> #'<offset> descriptor #'<indices>)))))
(define-syntax-rule (define-bytestructure-setter* <name> <descriptor>)
(define-syntax <name>
(let ((descriptor <descriptor>))
(syntax-case-lambda (_ <bytevector> <offset> <index> (... ...) <value>)
(bytestructure-set!/syntax
#'<bytevector> #'<offset> descriptor #'(<index> (... ...)) #'<value>)))))
(define-syntax-rule (define-bytestructure-getter <name> <descriptor>)
(define-syntax <name>
(let ((descriptor <descriptor>))
(syntax-case-lambda (_ <bytevector> . <indices>)
(bytestructure-ref/syntax #'<bytevector> 0 descriptor #'<indices>)))))
(define-syntax-rule (define-bytestructure-setter <name> <descriptor>)
(define-syntax <name>
(let ((descriptor <descriptor>))
(syntax-case-lambda (_ <bytevector> <index> (... ...) <value>)
(bytestructure-set!/syntax
#'<bytevector> 0 descriptor #'(<index> (... ...)) #'<value>)))))
(define-syntax define-bytestructure-accessors
(syntax-rules ()
((_ <descriptor> <unwrapper> <getter> <setter>)
(begin
(define-bytestructure-unwrapper <unwrapper> <descriptor>)
(define-bytestructure-getter <getter> <descriptor>)
(define-bytestructure-setter <setter> <descriptor>)))
((_ <descriptor> <unwrapper> <getter> <setter> <getter*> <setter*>)
(begin
(define-bytestructure-unwrapper <unwrapper> <descriptor>)
(define-bytestructure-getter <getter> <descriptor>)
(define-bytestructure-setter <setter> <descriptor>)
(define-bytestructure-getter* <getter*> <descriptor>)
(define-bytestructure-setter* <setter*> <descriptor>)))))
;; Local Variables:
;; eval: (put (quote syntax-case-lambda) (quote scheme-indent-function) 1)
;; End:
;;; base.syntactic.scm ends here
;;; bitfields.scm --- Struct bitfield constructor.
;; Copyright © 2015, 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module is complementary to the struct module. It isn't used on its own.
;; This code partly uses rational numbers for byte counts and offsets, to
;; represent granularity down to bits. I.e. 1/8 is a size or offset of one bit.
;;; Code:
;;; Only a macro for efficiency reasons.
(define-syntax bit-field/signed
(syntax-rules ()
((_ <num> <width> <start> <end> <signed?>)
(let ((unsigned-value (bit-field <num> <start> <end>)))
(if (not <signed?>)
unsigned-value
(let ((sign (bit-set? (- <width> 1) unsigned-value)))
(if sign
(- unsigned-value (expt 2 <width>))
unsigned-value)))))))
(define (validate-integer-descriptor descriptor)
(when (not (assq descriptor integer-descriptors))
(error "Invalid descriptor for bitfield." descriptor)))
(define (integer-descriptor-signed? descriptor)
(assq descriptor signed-integer-descriptors))
(define integer-descriptor-signed->unsigned-mapping
(map cons
(map car signed-integer-descriptors)
(map car unsigned-integer-descriptors)))
(define (integer-descriptor-signed->unsigned descriptor)
(cdr (assq descriptor integer-descriptor-signed->unsigned-mapping)))
(define (unsigned-integer-descriptor integer-descriptor)
(if (integer-descriptor-signed? integer-descriptor)
(integer-descriptor-signed->unsigned integer-descriptor)
integer-descriptor))
(define-record-type <bitfield-metadata>
(make-bitfield-metadata int-descriptor width)
bitfield-metadata?
(int-descriptor bitfield-metadata-int-descriptor)
(width bitfield-metadata-width))
(define (bitfield-descriptor int-descriptor bit-offset width)
(validate-integer-descriptor int-descriptor)
(let ((signed? (integer-descriptor-signed? int-descriptor))
(uint-descriptor (unsigned-integer-descriptor int-descriptor)))
(let ((num-getter (bytestructure-descriptor-getter uint-descriptor))
(num-setter (bytestructure-descriptor-setter uint-descriptor)))
(define start bit-offset)
(define end (+ start width))
(define (getter syntax? bytevector offset)
(let ((num (num-getter syntax? bytevector offset)))
(if syntax?
(quasisyntax
(bit-field/signed (unsyntax num) (unsyntax width)
(unsyntax start) (unsyntax end)
(unsyntax signed?)))
(bit-field/signed num width start end signed?))))
(define (setter syntax? bytevector offset value)
(let* ((oldnum (num-getter syntax? bytevector offset))
(newnum (if syntax?
(quasisyntax
(copy-bit-field (unsyntax oldnum) (unsyntax value)
(unsyntax start) (unsyntax end)))
(copy-bit-field oldnum value start end))))
(num-setter syntax? bytevector offset newnum)))
(define meta (make-bitfield-metadata int-descriptor width))
(make-bytestructure-descriptor #f #f #f getter setter meta))))
;;; bitfields.scm ends here
;;; explicit-endianness.scm --- Auxiliary bytevector operations.
;; Copyright © 2015 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; The numeric module requires top-level bindings to bytevector procedures with
;; an explicit endianness, instead of the ones that take an endianness
;; argument. This library provides them.
;;; Code:
(define-syntax define-explicit-endianness-getters
(syntax-rules ()
((_ (original le-name be-name) ...)
(begin
(begin
(define (le-name bytevector index)
(original bytevector index (endianness little)))
(define (be-name bytevector index)
(original bytevector index (endianness big))))
...))))
(define-explicit-endianness-getters
(bytevector-ieee-single-ref bytevector-ieee-single-le-ref
bytevector-ieee-single-be-ref)
(bytevector-ieee-double-ref bytevector-ieee-double-le-ref
bytevector-ieee-double-be-ref)
(bytevector-s16-ref bytevector-s16le-ref
bytevector-s16be-ref)
(bytevector-u16-ref bytevector-u16le-ref
bytevector-u16be-ref)
(bytevector-s32-ref bytevector-s32le-ref
bytevector-s32be-ref)
(bytevector-u32-ref bytevector-u32le-ref
bytevector-u32be-ref)
(bytevector-s64-ref bytevector-s64le-ref
bytevector-s64be-ref)
(bytevector-u64-ref bytevector-u64le-ref
bytevector-u64be-ref))
(define-syntax define-explicit-endianness-setters
(syntax-rules ()
((_ (original le-name be-name) ...)
(begin
(begin
(define (le-name bytevector index value)
(original bytevector index value (endianness little)))
(define (be-name bytevector index value)
(original bytevector index value (endianness big))))
...))))
(define-explicit-endianness-setters
(bytevector-ieee-single-set! bytevector-ieee-single-le-set!
bytevector-ieee-single-be-set!)
(bytevector-ieee-double-set! bytevector-ieee-double-le-set!
bytevector-ieee-double-be-set!)
(bytevector-s16-set! bytevector-s16le-set!
bytevector-s16be-set!)
(bytevector-u16-set! bytevector-u16le-set!
bytevector-u16be-set!)
(bytevector-s32-set! bytevector-s32le-set!
bytevector-s32be-set!)
(bytevector-u32-set! bytevector-u32le-set!
bytevector-u32be-set!)
(bytevector-s64-set! bytevector-s64le-set!
bytevector-s64be-set!)
(bytevector-u64-set! bytevector-u64le-set!
bytevector-u64be-set!))
;;; explicit-endianness.scm ends here
;;; numeric.scm --- Numeric types as supported by (rnrs bytevectors).
;; Copyright © 2015, 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module defines descriptors for numeric types of specific size, and
;; native or specific endianness, as made possible by the bytevector referencing
;; and assigning procedures in the (rnrs bytevectors) module.
;; We use the strange cond-expand/runtime macro to make sure that certain checks
;; for CPU architecture and data model are done at library-load-time and not
;; compile time, since one might cross-compile the library.
;;; Code:
(define base-environment
(cond-expand
(guile-2
(current-module))
(else
(environment '(scheme base)))))
(define-syntax cond-expand/runtime
(syntax-rules ()
((_ (<cond> <expr>) ...)
(let ((const (eval '(cond-expand (<cond> '<expr>) ...)
base-environment)))
(cond
((equal? const '<expr>) <expr>)
...)))))
(define i8align 1)
(define i16align 2)
(define i32align 4)
(define i64align
(cond-expand/runtime
(i386 4)
(else 8)))
(define f32align 4)
(define f64align
(cond-expand/runtime
(i386 4)
(else 8)))
(define-syntax-rule (make-numeric-descriptor <size> <align> <getter> <setter>)
(let ()
(define size <size>)
(define alignment <align>)
(define (getter syntax? bytevector offset)
(if syntax?
(quasisyntax
(<getter> (unsyntax bytevector) (unsyntax offset)))
(<getter> bytevector offset)))
(define (setter syntax? bytevector offset value)
(if syntax?
(quasisyntax
(<setter> (unsyntax bytevector) (unsyntax offset) (unsyntax value)))
(<setter> bytevector offset value)))
(make-bytestructure-descriptor size alignment #f getter setter)))
(define-syntax-rule (define-numeric-descriptors <list>
(<name> <size> <align> <getter> <setter>)
...)
(begin
(define <name>
(make-numeric-descriptor <size> <align> <getter> <setter>))
...
(define <list> (list (list <name> '<name> <getter> <setter>) ...))))
(define-numeric-descriptors
signed-integer-native-descriptors
(int8 1 i8align bytevector-s8-ref bytevector-s8-set!)
(int16 2 i16align bytevector-s16-native-ref bytevector-s16-native-set!)
(int32 4 i32align bytevector-s32-native-ref bytevector-s32-native-set!)
(int64 8 i64align bytevector-s64-native-ref bytevector-s64-native-set!))
(define-numeric-descriptors
unsigned-integer-native-descriptors
(uint8 1 i8align bytevector-u8-ref bytevector-u8-set!)
(uint16 2 i16align bytevector-u16-native-ref bytevector-u16-native-set!)
(uint32 4 i32align bytevector-u32-native-ref bytevector-u32-native-set!)
(uint64 8 i64align bytevector-u64-native-ref bytevector-u64-native-set!))
(define-numeric-descriptors
float-native-descriptors
(float32 4 f32align
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!)
(float64 8 f64align
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!))
(define-syntax-rule (define-with-endianness <list> <endianness>
(<name> <size> <align> <native-name> <getter> <setter>)
...)
(begin
(define <name>
(if (equal? <endianness> (native-endianness))
<native-name>
(make-numeric-descriptor <size> <align> <getter> <setter>)))
...
(define <list> (list (list <name> '<name> <getter> <setter>) ...))))
(define-with-endianness
signed-integer-le-descriptors (endianness little)
(int16le 2 i16align int16 bytevector-s16le-ref bytevector-s16le-set!)
(int32le 4 i32align int32 bytevector-s32le-ref bytevector-s32le-set!)
(int64le 8 i64align int64 bytevector-s64le-ref bytevector-s64le-set!))
(define-with-endianness
signed-integer-be-descriptors (endianness big)
(int16be 2 i16align int16 bytevector-s16be-ref bytevector-s16be-set!)
(int32be 4 i32align int32 bytevector-s32be-ref bytevector-s32be-set!)
(int64be 8 i64align int64 bytevector-s64be-ref bytevector-s64be-set!))
(define-with-endianness
unsigned-integer-le-descriptors (endianness little)
(uint16le 2 i16align uint16 bytevector-u16le-ref bytevector-u16le-set!)
(uint32le 4 i32align uint32 bytevector-u32le-ref bytevector-u32le-set!)
(uint64le 8 i64align uint64 bytevector-u64le-ref bytevector-u64le-set!))
(define-with-endianness
unsigned-integer-be-descriptors (endianness big)
(uint16be 2 i16align uint16 bytevector-u16be-ref bytevector-u16be-set!)
(uint32be 4 i32align uint32 bytevector-u32be-ref bytevector-u32be-set!)
(uint64be 8 i64align uint64 bytevector-u64be-ref bytevector-u64be-set!))
(define-with-endianness
float-le-descriptors (endianness little)
(float32le 4 f32align float32
bytevector-ieee-single-le-ref
bytevector-ieee-single-le-set!)
(float64le 8 f64align float64
bytevector-ieee-double-le-ref
bytevector-ieee-double-le-set!))
(define-with-endianness
float-be-descriptors (endianness big)
(float32be 4 f32align float32
bytevector-ieee-single-be-ref
bytevector-ieee-single-be-set!)
(float64be 8 f64align float64
bytevector-ieee-double-be-ref
bytevector-ieee-double-be-set!))
(define-syntax-rule (make-complex-descriptor
<float-size> <float-align> <float-getter> <float-setter>)
(let ()
(define size (* 2 <float-size>))
(define alignment <float-align>)
(define (getter syntax? bytevector offset)
(if syntax?
(quasisyntax
(let ((real (<float-getter> (unsyntax bytevector)
(unsyntax offset)))
(imag (<float-getter> (unsyntax bytevector)
(+ (unsyntax offset) <float-size>))))
(make-rectangular real imag)))
(let ((real (<float-getter> bytevector offset))
(imag (<float-getter> bytevector (+ offset <float-size>))))
(make-rectangular real imag))))
(define (setter syntax? bytevector offset value)
(if syntax?
(quasisyntax
(let ((val (unsyntax value)))
(let ((real (real-part val))
(imag (imag-part val)))
(<float-setter> (unsyntax bytevector)
(unsyntax offset)
real)
(<float-setter> (unsyntax bytevector)
(+ (unsyntax offset) <float-size>)
imag))))
(let ((real (real-part value))
(imag (imag-part value)))
(<float-setter> bytevector offset real)
(<float-setter> bytevector (+ offset <float-size>) imag))))
(make-bytestructure-descriptor size alignment #f getter setter)))
(define-syntax-rule (define-complex-descriptors <list>
(<name> <float-size> <float-align>
<float-getter> <float-setter>)
...)
(begin
(define <name>
(make-complex-descriptor <float-size> <float-align>
<float-getter> <float-setter>))
...
(define <list> (list (list <name> '<name> <float-getter> <float-setter>)
...))))
(define-complex-descriptors
complex-native-descriptors
(complex64 4 f32align
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!)
(complex128 8 f64align
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!))
(define-syntax-rule (define-complex-with-endianness <list> <endianness>
(<name> <float-size> <float-align> <native-name>
<float-getter> <float-setter>)
...)
(begin
(define <name>
(if (equal? <endianness> (native-endianness))
<native-name>
(make-complex-descriptor <float-size> <float-align>
<float-getter> <float-setter>)))
...
(define <list> (list (list <name> '<name> <float-getter> <float-setter>)
...))))
(define-complex-with-endianness
complex-le-descriptors (endianness little)
(complex64le 4 f32align complex64
bytevector-ieee-single-le-ref
bytevector-ieee-single-le-set!)
(complex128le 8 f64align complex128
bytevector-ieee-double-le-ref
bytevector-ieee-double-le-set!))
(define-complex-with-endianness
complex-be-descriptors (endianness big)
(complex64be 4 f32align complex64
bytevector-ieee-single-be-ref
bytevector-ieee-single-be-set!)
(complex128be 8 f64align complex128
bytevector-ieee-double-be-ref
bytevector-ieee-double-be-set!))
(define signed-integer-descriptors
(append signed-integer-native-descriptors
signed-integer-le-descriptors
signed-integer-be-descriptors))
(define unsigned-integer-descriptors
(append unsigned-integer-native-descriptors
unsigned-integer-le-descriptors
unsigned-integer-be-descriptors))
(define integer-descriptors
(append signed-integer-descriptors unsigned-integer-descriptors))
(define float-descriptors
(append float-native-descriptors
float-le-descriptors
float-be-descriptors))
(define complex-descriptors
(append complex-native-descriptors
complex-le-descriptors
complex-be-descriptors))
(define numeric-descriptors
(append integer-descriptors float-descriptors complex-descriptors))
(define short int16)
(define unsigned-short uint16)
(define int (cond-expand/runtime
(lp32 int16)
(ilp64 int64)
(else int32)))
(define unsigned-int (cond-expand/runtime
(lp32 uint16)
(ilp64 uint64)
(else uint32)))
(define long (cond-expand/runtime
(ilp64 int64)
(lp64 int64)
(else int32)))
(define unsigned-long (cond-expand/runtime
(ilp64 uint64)
(lp64 uint64)
(else uint32)))
(define long-long int64)
(define unsigned-long-long uint64)
(define arch32bit? (cond-expand/runtime
(lp32 #t)
(ilp32 #t)
(else #f)))
(define intptr_t (if arch32bit?
int32
int64))
(define uintptr_t (if arch32bit?
uint32
uint64))
(define size_t uintptr_t)
(define ssize_t intptr_t)
(define ptrdiff_t intptr_t)
(define float float32)
(define double float64)
;;; numeric.scm ends here
;;; string.scm --- Strings in encodings supported by (rnrs bytevectors).
;; Copyright © 2017 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module defines descriptors for strings encoded in various encodings, as
;; supported by (rnrs bytevectors).
;;; Code:
(define (ascii->string bytevector start end)
(let ((string (utf8->string bytevector start end)))
(when (not (= (string-length string) (bytevector-length bytevector)))
(error "Bytevector contains non-ASCII characters." bytevector))
string))
(define (string->ascii string)
(let ((bytevector (string->utf8 string)))
(when (not (= (string-length string) (bytevector-length bytevector)))
(error "String contains non-ASCII characters." string))
bytevector))
(define (bytevector->string bytevector offset size encoding)
(case encoding
((ascii) (ascii->string bytevector offset (+ offset size)))
((utf8) (utf8->string bytevector offset (+ offset size)))
(else
(let ((bytevector (bytevector-copy bytevector offset (+ offset size))))
(case encoding
((utf16le) (utf16->string bytevector 'little #t))
((utf16be) (utf16->string bytevector 'big #t))
((utf32le) (utf32->string bytevector 'little #t))
((utf32be) (utf32->string bytevector 'big #t))
(else (error "Unknown string encoding." encoding)))))))
(define (string->bytevector string encoding)
(case encoding
((ascii) (string->ascii string))
((utf8) (string->utf8 string))
((utf16le) (string->utf16 string 'little))
((utf16be) (string->utf16 string 'big))
((utf32le) (string->utf32 string 'little))
((utf32be) (string->utf32 string 'big))))
;;; Note: because macro output may not contain raw symbols, we cannot output
;;; (quote foo) for raw symbol foo either, so there's no way to inject symbol
;;; literals into macro output. Hence we inject references to the following
;;; variables instead.
(define ascii 'ascii)
(define utf8 'utf8)
(define utf16le 'utf16le)
(define utf16be 'utf16be)
(define utf32le 'utf32le)
(define utf32be 'utf32be)
;;; Make sure this returns a boolean and not any other type of value, as the
;;; output will be part of macro output.
(define (fixed-width-encoding? encoding)
(not (not (memq encoding '(ascii utf32le utf32be)))))
(define (bytevector-zero! bv start end)
(do ((i start (+ i 1)))
((= i end))
(bytevector-u8-set! bv i #x00)))
(define (bs:string size encoding)
(define alignment 1)
(define (getter syntax? bytevector offset)
(if syntax?
(quasisyntax
(bytevector->string (unsyntax bytevector)
(unsyntax offset)
(unsyntax size)
(unsyntax
(datum->syntax (syntax utf8) encoding))))
(bytevector->string bytevector offset size encoding)))
(define (setter syntax? bytevector offset string)
(if syntax?
(quasisyntax
(let* ((bv (string->bytevector
(unsyntax string)
(unsyntax
(datum->syntax (syntax utf8) encoding))))
(length (bytevector-length bv)))
(when (> length (unsyntax size))
(error "String too long." (unsyntax string)))
(when (and (unsyntax (fixed-width-encoding? encoding))
(< length (unsyntax size)))
(error "String too short." (unsyntax string)))
(bytevector-copy! (unsyntax bytevector)
(unsyntax offset)
bv)
(when (not (unsyntax (fixed-width-encoding? encoding)))
(bytevector-zero! (unsyntax bytevector)
(+ (unsyntax offset) (bytevector-length bv))
(+ (unsyntax offset) (unsyntax size))))))
(let* ((bv (string->bytevector string encoding))
(length (bytevector-length bv)))
(when (> length size)
(error "String too long." string))
(when (and (fixed-width-encoding? encoding) (< length size))
(error "String too short." string))
(bytevector-copy! bytevector offset bv)
(when (not (fixed-width-encoding? encoding))
(bytevector-zero! bytevector
(+ offset (bytevector-length bv))
(+ offset size))))))
(make-bytestructure-descriptor size alignment #f getter setter))
;;; string.scm ends here
;;; struct.scm --- Struct descriptor constructor.
;; Copyright © 2015, 2016, 2021 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This constructor allows the creation of struct descriptors with named and
;; ordered fields with a specific content descriptor.
;; This code partly uses rational numbers for byte counts and offsets, to
;; represent granularity down to bits. I.e. 1/8 is a size or offset of one bit.
;;; Code:
(define (pack-alignment pack alignment)
(case pack
((#t) 1)
((#f) alignment)
(else (min pack alignment))))
(define-record-type <field>
(make-field name descriptor size alignment position)
field?
(name field-name)
(descriptor field-descriptor)
(size field-size)
(alignment field-alignment)
(position field-position))
(define (construct-normal-field pack position name descriptor)
(let*-values
(((size)
(bytestructure-descriptor-size descriptor))
((alignment)
(pack-alignment pack (bytestructure-descriptor-alignment descriptor)))
((position _boundary _bit-offset)
(align position size alignment)))
(values (make-field name descriptor size alignment position)
(+ position size))))
(define (construct-bit-field pack position name descriptor width)
(if (zero? width)
(let* ((alignment (bytestructure-descriptor-alignment descriptor))
(position (next-boundary position alignment)))
(values (make-field #f descriptor 0 1 position)
position))
(let*-values
(((int-size)
(bytestructure-descriptor-size descriptor))
((size)
(* 1/8 width))
((int-alignment)
(bytestructure-descriptor-alignment descriptor))
((alignment)
(pack-alignment pack int-alignment))
((position boundary offset)
(align position size alignment))
((descriptor)
(bitfield-descriptor descriptor offset width)))
(values (make-field name descriptor int-size alignment boundary)
(+ position size)))))
(define (construct-fields pack field-specs)
(let loop ((field-specs field-specs)
(position 0)
(fields '()))
(if (null? field-specs)
(reverse fields)
(let* ((field-spec (car field-specs))
(field-specs (cdr field-specs))
(name-or-type (car field-spec)))
(if (and (eq? name-or-type 'union)
(pair? (cadr field-spec)))
(let-values (((next-position fields)
(add-union-fields pack
position
(cadr field-spec)
fields)))
(loop field-specs
next-position
fields))
(let-values (((field next-position)
(construct-field pack position field-spec)))
(loop field-specs
next-position
(cons field fields))))))))
(define (add-union-fields pack position field-specs fields)
(define (field-spec-alignment field-spec)
(let ((descriptor (cadr field-spec)))
(bytestructure-descriptor-alignment descriptor)))
(define (field-spec-size field-spec)
(let ((descriptor (cadr field-spec)))
(bytestructure-descriptor-size descriptor)))
(let* ((alignment (apply max (map field-spec-alignment field-specs)))
(alignment (pack-alignment pack alignment))
(size (apply max (map field-spec-size field-specs)))
(position (align position size alignment)))
(let loop ((field-specs field-specs)
(next-position position)
(fields fields))
(if (null? field-specs)
(values next-position fields)
(let ((field-spec (car field-specs))
(field-specs (cdr field-specs)))
(let-values (((field next-position)
(construct-field pack position field-spec)))
(loop field-specs
(max position next-position)
(cons field fields))))))))
(define (construct-field pack position field-spec)
(let* ((name (car field-spec))
(descriptor (cadr field-spec))
(bitfield? (not (null? (cddr field-spec))))
(width (if bitfield?
(car (cddr field-spec))
#f)))
(if bitfield?
(construct-bit-field pack position name descriptor width)
(construct-normal-field pack position name descriptor))))
(define-record-type <struct-metadata>
(make-struct-metadata field-alist)
struct-metadata?
(field-alist struct-metadata-field-alist))
(define bs:struct
(case-lambda
((field-specs)
(bs:struct #f field-specs))
((pack field-specs)
(define %fields (construct-fields pack field-specs))
(define fields (filter field-name %fields))
(define field-alist (map (lambda (field)
(cons (field-name field) field))
fields))
(define alignment (apply max (map field-alignment fields)))
(define (field-end field)
(+ (field-position field) (field-size field)))
(define size (let ((end (apply max (map field-end %fields))))
(let-values (((size . _) (next-boundary end alignment)))
size)))
(define (unwrapper syntax? bytevector offset index)
(let* ((index (if syntax? (syntax->datum index) index))
(field-entry (assq index field-alist))
(field (if field-entry
(cdr field-entry)
(error "No such struct field." index))))
(let* ((descriptor (field-descriptor field))
(position (field-position field))
(offset (if syntax?
(quasisyntax
(+ (unsyntax offset) (unsyntax position)))
(+ offset position))))
(values bytevector offset descriptor))))
(define (setter syntax? bytevector offset value)
(define (count-error fields values)
(error "Mismatch between number of struct fields and given values."
fields values))
(when syntax?
(error "Writing into struct not supported with macro API."))
(cond
((bytevector? value)
(bytevector-copy! bytevector offset value 0 size))
((vector? value)
(let loop ((fields fields)
(values (vector->list value)))
(if (null? values)
(when (not (null? fields))
(count-error fields value))
(begin
(when (null? fields)
(count-error fields value))
(let* ((field (car fields))
(value (car values))
(descriptor (field-descriptor field))
(position (field-position field))
(offset (+ offset position)))
(bytestructure-set!* bytevector offset descriptor value)
(loop (cdr fields) (cdr values)))))))
((pair? value)
;; Assumed to be a pseudo-alist like ((k1 v1) (k2 v2) ...).
(for-each
(lambda (pair)
(let ((key (car pair))
(value (cadr pair)))
(let-values (((bytevector offset descriptor)
(unwrapper #f bytevector offset key)))
(bytestructure-set!* bytevector offset descriptor value))))
value))
(else
(error "Invalid value for writing into struct." value))))
(define meta
(let ((simple-field-alist (map (lambda (field)
(cons (field-name field)
(field-descriptor field)))
fields)))
(make-struct-metadata simple-field-alist)))
(make-bytestructure-descriptor size alignment unwrapper #f setter meta))))
(define debug-alignment
(case-lambda
((fields) (debug-alignment #f fields))
((pack fields)
(let* ((fields (construct-fields pack fields))
(alignment (apply max (map field-alignment fields)))
(size (let* ((field (last fields))
(end (+ (field-position field) (field-size field))))
(let-values (((size . _) (next-boundary end alignment)))
size))))
(format #t "{\n")
(for-each (lambda (field)
(let ((name (field-name field))
(pos (* 8 (field-position field)))
(size (* 8 (field-size field)))
(align (* 8 (field-alignment field))))
(format #t " ~a - ~a: ~a (~a, ~a)\n"
pos (+ pos size) name size align)))
fields)
(format #t "} = ~a\n" (* 8 size))
(values)))))
;;; struct.scm ends here
;;; union.scm --- Union descriptor constructor.
;; Copyright © 2015, 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This constructor allows the creation of union descriptors with named fields
;; with a specific content descriptor.
;;; Code:
(define make-field cons)
(define field-name car)
(define field-content cdr)
(define find-field assq)
(define (construct-fields fields)
(map (lambda (field)
(make-field (car field) (cadr field)))
fields))
(define-record-type <union-metadata>
(make-union-metadata field-alist)
union-metadata?
(field-alist union-metadata-field-alist))
(define (bs:union %fields)
(define fields (construct-fields %fields))
(define alignment (apply max (map (lambda (field)
(bytestructure-descriptor-alignment
(field-content field)))
fields)))
(define size (let ((max-element
(apply max (map (lambda (field)
(bytestructure-descriptor-size
(field-content field)))
fields))))
(let-values (((size . _) (next-boundary max-element alignment)))
size)))
(define (unwrapper syntax? bytevector offset index)
(let ((index (if syntax? (syntax->datum index) index)))
(values bytevector
offset
(field-content (find-field index fields)))))
(define (setter syntax? bytevector offset value)
(when syntax?
(error "Writing into union not supported with macro API."))
(cond
((bytevector? value)
(bytevector-copy! bytevector offset value 0 size))
((and (list? value) (= 2 (length value)))
(let-values (((bytevector* offset* descriptor)
(unwrapper #f bytevector offset (car value))))
(bytestructure-set!* bytevector* offset* descriptor (cadr value))))
(else
(error "Invalid value for writing into union." value))))
(define meta (make-union-metadata fields))
(make-bytestructure-descriptor size alignment unwrapper #f setter meta))
;;; union.scm ends here
;;; utils.scm --- Utility library for bytestructures.
;; Copyright © 2015 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Just some utility procedures and macros.
;;; Code:
(define-syntax define-syntax-rule
(syntax-rules ()
((_ (<name> . <args>) <expr>)
(define-syntax <name>
(syntax-rules ()
((_ . <args>)
<expr>))))))
(cond-expand
((or guile syntax-case)
(define-syntax-rule (if-syntax-case <then> <else>)
<then>))
(else
(define-syntax-rule (if-syntax-case <then> <else>)
<else>)))
(define-syntax-rule (define-syntax-case-stubs <name> ...)
(if-syntax-case
(begin)
(begin
(define (<name> . rest)
(error "Not supported. You need syntax-case."))
...)))
(define-syntax-case-stubs
syntax
quasisyntax
unsyntax
unsyntax-splicing
syntax->datum
datum->syntax)
;;; utils.scm ends here
;;; vector.scm --- Vector descriptor constructor.
;; Copyright © 2015, 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This constructor allows the creation of vector descriptors with a specific
;; length and element descriptor.
;; Be careful with identifier names here; don't confuse vector descriptor and
;; Scheme vector APIs and variables.
;;; Code:
(define-record-type <vector-metadata>
(make-vector-metadata length element-descriptor)
vector-metadata?
(length vector-metadata-length)
(element-descriptor vector-metadata-element-descriptor))
(define (bs:vector length descriptor)
(define element-size (bytestructure-descriptor-size descriptor))
(define size (* length element-size))
(define alignment (bytestructure-descriptor-alignment descriptor))
(define (unwrapper syntax? bytevector offset index)
(values bytevector
(if syntax?
(quasisyntax
(+ (unsyntax offset)
(* (unsyntax index) (unsyntax element-size))))
(+ offset (* index element-size)))
descriptor))
(define (setter syntax? bytevector offset value)
(when syntax?
(error "Writing into vector not supported with macro API."))
(cond
((bytevector? value)
(bytevector-copy! bytevector offset value 0 size))
((vector? value)
(do ((i 0 (+ i 1))
(offset offset (+ offset element-size)))
((= i (vector-length value)))
(bytestructure-set!*
bytevector offset descriptor (vector-ref value i))))
(else
(error "Invalid value for writing into vector." value))))
(define meta (make-vector-metadata length descriptor))
(make-bytestructure-descriptor size alignment unwrapper #f setter meta))
;;; vector.scm ends here
(define-module (bytestructures guile base))
(import
(srfi 9)
(srfi 11)
(ice-9 format)
(bytestructures guile bytevectors)
(bytestructures guile utils))
(include-from-path "bytestructures/body/base.scm")
(include-from-path "bytestructures/r7/base.exports.sld")
(import (srfi srfi-9 gnu))
(set-record-type-printer!
<bytestructure-descriptor>
(lambda (record port)
(format port "#<bytestructure-descriptor 0x~x>" (object-address record))))
(set-record-type-printer!
<bytestructure>
(lambda (record port)
(format port "#<bytestructure 0x~x>" (object-address record))))
(define-module (bytestructures guile bitfields))
(import
(srfi 9)
(srfi 60)
(bytestructures guile utils)
(bytestructures guile base)
(bytestructures guile numeric-metadata))
(include-from-path "bytestructures/body/bitfields.scm")
(include-from-path "bytestructures/r7/bitfields.exports.sld")
;;; Compatibility shim for Guile, because its implementation of utf16->string
;;; and utf32->string doesn't conform to R6RS.
(define-module (bytestructures guile bytevectors))
(import
(rnrs base)
(rnrs control)
(bytestructures r6 bytevectors))
(re-export
endianness native-endianness bytevector?
make-bytevector bytevector-length bytevector=? bytevector-fill!
bytevector-copy!
bytevector-copy
bytevector-u8-ref bytevector-s8-ref
bytevector-u8-set! bytevector-s8-set! bytevector->u8-list
u8-list->bytevector
bytevector-uint-ref bytevector-uint-set!
bytevector-sint-ref bytevector-sint-set!
bytevector->sint-list bytevector->uint-list
uint-list->bytevector sint-list->bytevector
bytevector-u16-ref bytevector-s16-ref
bytevector-u16-set! bytevector-s16-set!
bytevector-u16-native-ref bytevector-s16-native-ref
bytevector-u16-native-set! bytevector-s16-native-set!
bytevector-u32-ref bytevector-s32-ref
bytevector-u32-set! bytevector-s32-set!
bytevector-u32-native-ref bytevector-s32-native-ref
bytevector-u32-native-set! bytevector-s32-native-set!
bytevector-u64-ref bytevector-s64-ref
bytevector-u64-set! bytevector-s64-set!
bytevector-u64-native-ref bytevector-s64-native-ref
bytevector-u64-native-set! bytevector-s64-native-set!
bytevector-ieee-single-ref
bytevector-ieee-single-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!
bytevector-ieee-double-ref
bytevector-ieee-double-set!
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!
string->utf8
utf8->string
string->utf16 string->utf32)
(export
(r6rs-utf16->string . utf16->string)
(r6rs-utf32->string . utf32->string))
(define (read-bom16 bv)
(let ((c0 (bytevector-u8-ref bv 0))
(c1 (bytevector-u8-ref bv 1)))
(cond
((and (= c0 #xFE) (= c1 #xFF))
'big)
((and (= c0 #xFF) (= c1 #xFE))
'little)
(else
#f))))
(define r6rs-utf16->string
(case-lambda
((bv default-endianness)
(let ((bom-endianness (read-bom16 bv)))
(if (not bom-endianness)
(utf16->string bv default-endianness)
(substring/shared (utf16->string bv bom-endianness) 1))))
((bv endianness endianness-mandatory?)
(if endianness-mandatory?
(utf16->string bv endianness)
(r6rs-utf16->string bv endianness)))))
(define (read-bom32 bv)
(let ((c0 (bytevector-u8-ref bv 0))
(c1 (bytevector-u8-ref bv 1))
(c2 (bytevector-u8-ref bv 2))
(c3 (bytevector-u8-ref bv 3)))
(cond
((and (= c0 #x00) (= c1 #x00) (= c2 #xFE) (= c3 #xFF))
'big)
((and (= c0 #xFF) (= c1 #xFE) (= c2 #x00) (= c3 #x00))
'little)
(else
#f))))
(define r6rs-utf32->string
(case-lambda
((bv default-endianness)
(let ((bom-endianness (read-bom32 bv)))
(if (not bom-endianness)
(utf32->string bv default-endianness)
(substring/shared (utf32->string bv bom-endianness) 1))))
((bv endianness endianness-mandatory?)
(if endianness-mandatory?
(utf32->string bv endianness)
(r6rs-utf32->string bv endianness)))))
;;; cstring-pointer.scm --- Pointers to null-terminated strings.
;; Copyright © 2017 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; The cstring-pointer descriptor represents a pointer to a null-terminated
;; string, and will return the string as a Scheme string upon a reference
;; operation. Its setter however does not take Scheme strings, only addresses
;; to existing strings in memory. The reason is: Guile's string->pointer
;; creates a new C string in memory, returning an FFI pointer object holding its
;; address; the string is freed when the pointer object is garbage collected.
;; We have no means of holding a reference to the FFI pointer object; we can
;; only write the address it holds into our bytevector, which won't protect the
;; pointer object from GC.
;;; Code:
(define-module (bytestructures guile cstring-pointer))
(import
(bytestructures guile base)
(bytestructures guile numeric)
(prefix (system foreign) ffi-))
(export cstring-pointer)
(define (bytevector-address-ref bv offset)
(bytestructure-ref* bv offset uintptr_t))
(define (bytevector-address-set! bv offset address)
(bytestructure-set!* bv offset uintptr_t address))
(define cstring-pointer
(let ()
(define size (bytestructure-descriptor-size intptr_t))
(define alignment (bytestructure-descriptor-alignment intptr_t))
(define unwrapper #f)
(define (getter syntax? bv offset)
(if syntax?
#`(let* ((address (bytevector-address-ref #,bv #,offset))
(pointer (ffi-make-pointer address)))
(ffi-pointer->string pointer))
(let* ((address (bytevector-address-ref bv offset))
(pointer (ffi-make-pointer address)))
(ffi-pointer->string pointer))))
(define (setter syntax? bv offset address)
(if syntax?
#`(bytevector-address-set! #,bv #,offset #,address)
(bytevector-address-set! bv offset address)))
(make-bytestructure-descriptor size alignment unwrapper getter setter)))
(define-module (bytestructures guile explicit-endianness))
(import
(bytestructures guile bytevectors)
(bytestructures guile utils))
(include-from-path "bytestructures/body/explicit-endianness.scm")
(include-from-path "bytestructures/r7/explicit-endianness.exports.sld")
;;; ffi.scm --- Convert bytestructure descriptors to Guile/libffi types.
;; Copyright © 2016 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module offers a way to convert bytestructure descriptors to Guile/libffi
;; type objects. For instance, the bytestructure descriptor created with
;; (bs:struct `((x ,uint8) (y ,uint16))) gets converted into a two-element list
;; containing the libffi codes for uint8 and uint16.
;;; Code:
(define-module (bytestructures guile ffi))
(import
(ice-9 match)
(prefix (system foreign) ffi-)
(bytestructures guile base)
(bytestructures guile numeric)
(bytestructures guile vector)
(bytestructures guile struct)
(bytestructures guile union)
(bytestructures guile pointer)
(bytestructures guile bitfields))
(export
bytestructure-descriptor->ffi-descriptor
bs:pointer->proc
)
(define numeric-type-mapping
`((,int8 . ,ffi-int8)
(,uint8 . ,ffi-uint8)
(,int16 . ,ffi-int16)
(,uint16 . ,ffi-uint16)
(,int32 . ,ffi-int32)
(,uint32 . ,ffi-uint32)
(,int64 . ,ffi-int64)
(,uint64 . ,ffi-uint64)
(,float32 . ,ffi-float)
(,float64 . ,ffi-double)))
(define (bytestructure-descriptor->ffi-descriptor descriptor)
(define (convert descriptor)
(cond
((assq descriptor numeric-type-mapping)
=> (match-lambda ((key . val) val)))
(else
(let ((metadata (bytestructure-descriptor-metadata descriptor)))
(cond
((vector-metadata? metadata)
(make-list
(vector-metadata-length metadata)
(convert (vector-metadata-element-descriptor metadata))))
((struct-metadata? metadata)
(map convert (map cdr (struct-metadata-field-alist metadata))))
((union-metadata? metadata)
;; TODO: Add support once Guile/libffi supports this.
(error "Unions not supported." descriptor))
((pointer-metadata? metadata)
'*)
((bitfield-metadata? metadata)
;; TODO: Add support once Guile/libffi supports this.
(error "Bitfields not supported." descriptor))
(else
(error "Unsupported bytestructure descriptor." descriptor)))))))
(cond
((eq? descriptor 'void)
ffi-void)
((vector-metadata? (bytestructure-descriptor-metadata descriptor))
'*)
(else
(convert descriptor))))
(define (bs:pointer->proc ret-type func-ptr arg-types)
(define (type->raw-type type)
(if (bytestructure-descriptor? type)
(bytestructure-descriptor->ffi-descriptor type)
type))
(define (value->raw-value value)
(if (bytestructure? value)
(ffi-bytevector->pointer (bytestructure-bytevector value))
value))
(define (raw-value->value raw-value type)
(if (bytestructure-descriptor? type)
(make-bytestructure (ffi-pointer->bytevector
raw-value
(bytestructure-descriptor-size type))
0
type)
raw-value))
(let* ((raw-ret-type (type->raw-type ret-type))
(raw-arg-types (map type->raw-type arg-types))
(raw-proc (ffi-pointer->procedure
raw-ret-type func-ptr raw-arg-types)))
(lambda args
(let* ((raw-args (map value->raw-value args))
(raw-ret-val (apply raw-proc raw-args)))
(raw-value->value raw-ret-val ret-type)))))
(define-module (bytestructures guile numeric-all))
(import
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base)
(bytestructures guile explicit-endianness)
(bytestructures guile numeric-data-model))
(include-from-path "bytestructures/body/numeric.scm")
(include-from-path "bytestructures/r7/numeric.exports.sld")
(include-from-path "bytestructures/r7/numeric-metadata.exports.sld")
(define-module (bytestructures guile numeric-data-model))
(import (system foreign))
(import (system base target))
(define architecture
(let ((cpu (target-cpu)))
(cond
((member cpu '("i386" "i486" "i586" "i686"))
'i386)
((string=? "x86_64" cpu)
'x86-64)
((string-prefix? "arm" cpu)
'arm)
((string-prefix? "aarch64" cpu)
'aarch64))))
(define data-model
(if (= 4 (sizeof '*))
(if (= 2 (sizeof int))
'lp32
'ilp32)
(cond
((= 8 (sizeof int)) 'ilp64)
((= 4 (sizeof long)) 'llp64)
(else 'lp64))))
(cond-expand-provide
(current-module)
(list architecture data-model))
(define-module (bytestructures guile numeric-metadata))
(import (bytestructures guile numeric-all))
(re-export
signed-integer-native-descriptors
signed-integer-le-descriptors
signed-integer-be-descriptors
signed-integer-descriptors
unsigned-integer-native-descriptors
unsigned-integer-le-descriptors
unsigned-integer-be-descriptors
unsigned-integer-descriptors
float-native-descriptors
float-le-descriptors
float-be-descriptors
integer-descriptors
float-descriptors
numeric-descriptors
)
(define-module (bytestructures guile numeric))
(import (bytestructures guile numeric-all))
(re-export
int8 uint8 int16 uint16 int32 uint32 int64 uint64
int16le uint16le int32le uint32le int64le uint64le
int16be uint16be int32be uint32be int64be uint64be
float32 float64 float32le float64le float32be float64be
short unsigned-short
int unsigned-int
long unsigned-long
long-long unsigned-long-long
intptr_t uintptr_t
size_t ssize_t ptrdiff_t
float double
complex64 complex128
complex64le complex128le
complex64be complex128be
)
;;; pointer.scm --- Pointer descriptor constructor.
;; Copyright © 2015 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This constructor allows the creation of pointer descriptors with a specific
;; pointed-to descriptor.
;;; Code:
(define-module (bytestructures guile pointer))
(import
(srfi 9)
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base)
(prefix (system foreign) ffi-))
(export
bs:pointer
pointer-metadata? pointer-metadata-content-descriptor
)
(define pointer-size (ffi-sizeof '*))
(define bytevector-address-ref
(case pointer-size
((1) bytevector-u8-ref)
((2) bytevector-u16-native-ref)
((4) bytevector-u32-native-ref)
((8) bytevector-u64-native-ref)))
(define bytevector-address-set!
(case pointer-size
((1) bytevector-u8-set!)
((2) bytevector-u16-native-set!)
((4) bytevector-u32-native-set!)
((8) bytevector-u64-native-set!)))
(define (pointer-ref bytevector offset index content-size)
(let* ((base-address (bytevector-address-ref bytevector offset))
(address (+ base-address (* index content-size))))
(if (zero? base-address)
(error "Tried to dereference null-pointer.")
(ffi-pointer->bytevector (ffi-make-pointer address) content-size))))
(define (pointer-set! bytevector offset value)
(cond
((exact-integer? value)
(bytevector-address-set! bytevector offset value))
((bytevector? value)
(bytevector-address-set! bytevector offset
(ffi-pointer-address
(ffi-bytevector->pointer value))))
((bytestructure? value)
(bytevector-address-set! bytevector offset
(ffi-pointer-address
(ffi-bytevector->pointer
(bytestructure-bytevector value)))))))
(define-record-type <pointer-metadata>
(make-pointer-metadata content-descriptor)
pointer-metadata?
(content-descriptor pointer-metadata-content-descriptor))
(define (bs:pointer %descriptor)
(define (get-descriptor)
(if (promise? %descriptor)
(force %descriptor)
%descriptor))
(define size pointer-size)
(define alignment size)
(define (unwrapper syntax? bytevector offset index)
(define (syntax-list id . elements)
(datum->syntax id (map syntax->datum elements)))
(let ((descriptor (get-descriptor)))
(when (eq? 'void descriptor)
(error "Tried to follow void pointer."))
(let* ((size (bytestructure-descriptor-size descriptor))
(index-datum (if syntax? (syntax->datum index) index))
(index (if (eq? '* index-datum) 0 index-datum))
(bytevector*
(if syntax?
#`(pointer-ref #,bytevector #,offset #,index #,size)
(pointer-ref bytevector offset index size))))
(values bytevector* 0 descriptor))))
(define (getter syntax? bytevector offset)
(if syntax?
#`(bytevector-address-ref #,bytevector #,offset)
(bytevector-address-ref bytevector offset)))
(define (setter syntax? bytevector offset value)
(if syntax?
#`(pointer-set! #,bytevector #,offset #,value)
(pointer-set! bytevector offset value)))
(define meta (make-pointer-metadata %descriptor))
(make-bytestructure-descriptor size alignment unwrapper getter setter meta))
;;; pointer.scm ends here
(define-module (bytestructures guile string))
(import
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base))
(include-from-path "bytestructures/body/string.scm")
(include-from-path "bytestructures/r7/string.exports.sld")
(define-module (bytestructures guile struct))
(import
(srfi 1)
(srfi 9)
(srfi 11)
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base)
(bytestructures guile bitfields))
(include-from-path "bytestructures/body/align.scm")
(include-from-path "bytestructures/body/struct.scm")
(include-from-path "bytestructures/r7/struct.exports.sld")
(define-module (bytestructures guile union))
(import
(srfi 9)
(srfi 11)
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base))
(include-from-path "bytestructures/body/align.scm")
(include-from-path "bytestructures/body/union.scm")
(include-from-path "bytestructures/r7/union.exports.sld")
(define-module (bytestructures guile utils))
(include-from-path "bytestructures/body/utils.scm")
(export
if-syntax-case
define-syntax-case-stubs
)
(define-module (bytestructures guile vector))
(import
(srfi 9)
(bytestructures guile bytevectors)
(bytestructures guile utils)
(bytestructures guile base))
(include-from-path "bytestructures/body/vector.scm")
(include-from-path "bytestructures/r7/vector.exports.sld")
;;; Compatibility shim for R6RS systems, because R6RS and R7RS have different
;;; semantics for some procedures of the same name. We use R7RS semantics
;;; everywhere, so implement them in terms of R6RS.
(library (bytestructures r6 bytevectors)
(export
endianness native-endianness bytevector?
make-bytevector bytevector-length bytevector=? bytevector-fill!
(rename (r7rs-bytevector-copy! bytevector-copy!))
(rename (r7rs-bytevector-copy bytevector-copy))
bytevector-u8-ref bytevector-s8-ref
bytevector-u8-set! bytevector-s8-set! bytevector->u8-list
u8-list->bytevector
bytevector-uint-ref bytevector-uint-set!
bytevector-sint-ref bytevector-sint-set!
bytevector->sint-list bytevector->uint-list
uint-list->bytevector sint-list->bytevector
bytevector-u16-ref bytevector-s16-ref
bytevector-u16-set! bytevector-s16-set!
bytevector-u16-native-ref bytevector-s16-native-ref
bytevector-u16-native-set! bytevector-s16-native-set!
bytevector-u32-ref bytevector-s32-ref
bytevector-u32-set! bytevector-s32-set!
bytevector-u32-native-ref bytevector-s32-native-ref
bytevector-u32-native-set! bytevector-s32-native-set!
bytevector-u64-ref bytevector-s64-ref
bytevector-u64-set! bytevector-s64-set!
bytevector-u64-native-ref bytevector-s64-native-ref
bytevector-u64-native-set! bytevector-s64-native-set!
bytevector-ieee-single-ref
bytevector-ieee-single-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!
bytevector-ieee-double-ref
bytevector-ieee-double-set!
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!
(rename (r7rs-string->utf8 string->utf8))
(rename (r7rs-utf8->string utf8->string))
string->utf16 string->utf32
utf16->string utf32->string
)
(import
(rnrs base)
(rnrs control)
(rnrs bytevectors))
(define r7rs-bytevector-copy!
(case-lambda
((to at from)
(bytevector-copy! from 0 to at (bytevector-length from)))
((to at from start)
(bytevector-copy! from start to at (- (bytevector-length from) start)))
((to at from start end)
(bytevector-copy! from start to at (- end start)))))
(define r7rs-bytevector-copy
(case-lambda
((bytevector)
(bytevector-copy bytevector))
((bytevector start)
(r7rs-bytevector-copy bytevector start (bytevector-length bytevector)))
((bytevector start end)
(let* ((size (- end start))
(bytevector* (make-bytevector size)))
(bytevector-copy! bytevector start bytevector* 0 size)
bytevector*))))
(define r7rs-string->utf8
(case-lambda
((string)
(string->utf8 string))
((string start)
(string->utf8 (substring string start (string-length string))))
((string start end)
(string->utf8 (substring string start end)))))
(define r7rs-utf8->string
(case-lambda
((bytevector)
(utf8->string bytevector))
((bytevector start)
(utf8->string (r7rs-bytevector-copy bytevector start)))
((bytevector start end)
(utf8->string (r7rs-bytevector-copy bytevector start end))))))
(export
make-bytestructure-descriptor
bytestructure-descriptor?
bytestructure-descriptor-size
bytestructure-descriptor-size/syntax
bytestructure-descriptor-alignment
bytestructure-descriptor-unwrapper
bytestructure-descriptor-getter
bytestructure-descriptor-setter
bytestructure-descriptor-metadata
make-bytestructure
bytestructure?
bytestructure-bytevector
bytestructure-offset
bytestructure-descriptor
bytestructure-size
bytestructure
bytestructure-unwrap
bytestructure-unwrap*
bytestructure-ref
bytestructure-ref*
bytestructure-set!
bytestructure-set!*
bytestructure-ref/dynamic
bytestructure-set!/dynamic
bytestructure-unwrap/syntax
bytestructure-ref/syntax
bytestructure-set!/syntax
define-bytestructure-accessors
)
(define-library (bytestructures r7 base)
(import
(scheme base)
(scheme case-lambda)
(bytestructures r7 utils))
(cond-expand
((library (rnrs syntax-case))
(import (rnrs syntax-case)))
(else))
(include-library-declarations "base.exports.sld")
(include "body/base.scm"))
(export
bitfield-descriptor
bitfield-metadata?
bitfield-metadata-int-descriptor
bitfield-metadata-width
)
(define-library (bytestructures r7 bitfields)
(import
(scheme base)
(srfi 60)
(bytestructures r7 utils)
(bytestructures r7 base)
(bytestructures r7 numeric-metadata))
(include-library-declarations "bitfields.exports.sld")
(include "body/bitfields.scm"))
(define-library (bytestructures r7 bytevectors)
(cond-expand
((library (rnrs bytevectors))
(import (except (rnrs bytevectors)
bytevector?
make-bytevector
bytevector-length
bytevector-u8-ref
bytevector-u8-set!
bytevector-copy
bytevector-copy!
string->utf8
utf8->string)))
(else
(import (except (r6rs bytevectors)
bytevector?
make-bytevector
bytevector-length
bytevector-u8-ref
bytevector-u8-set!
bytevector-copy
bytevector-copy!
string->utf8
utf8->string))))
(export
endianness
native-endianness
bytevector=?
bytevector-fill!
bytevector-s8-ref
bytevector-s8-set!
bytevector->u8-list u8-list->bytevector
bytevector-uint-ref bytevector-sint-ref
bytevector-uint-set! bytevector-sint-set!
bytevector->uint-list bytevector->sint-list
uint-list->bytevector sint-list->bytevector
bytevector-u16-ref bytevector-s16-ref
bytevector-u16-native-ref bytevector-s16-native-ref
bytevector-u16-set! bytevector-s16-set!
bytevector-u16-native-set! bytevector-s16-native-set!
bytevector-u32-ref bytevector-s32-ref
bytevector-u32-native-ref bytevector-s32-native-ref
bytevector-u32-set! bytevector-s32-set!
bytevector-u32-native-set! bytevector-s32-native-set!
bytevector-u64-ref bytevector-s64-ref
bytevector-u64-native-ref bytevector-s64-native-ref
bytevector-u64-set! bytevector-s64-set!
bytevector-u64-native-set! bytevector-s64-native-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-ref
bytevector-ieee-double-native-ref
bytevector-ieee-double-ref
bytevector-ieee-single-native-set!
bytevector-ieee-single-set!
bytevector-ieee-double-native-set!
bytevector-ieee-double-set!
string->utf16 string->utf32
utf16->string utf32->string
))
(export
bytevector-ieee-single-le-ref bytevector-ieee-single-be-ref
bytevector-ieee-single-le-set! bytevector-ieee-single-be-set!
bytevector-ieee-double-le-ref bytevector-ieee-double-be-ref
bytevector-ieee-double-le-set! bytevector-ieee-double-be-set!
bytevector-s16le-ref bytevector-s16be-ref
bytevector-s16le-set! bytevector-s16be-set!
bytevector-u16le-ref bytevector-u16be-ref
bytevector-u16le-set! bytevector-u16be-set!
bytevector-s32le-ref bytevector-s32be-ref
bytevector-s32le-set! bytevector-s32be-set!
bytevector-u32le-ref bytevector-u32be-ref
bytevector-u32le-set! bytevector-u32be-set!
bytevector-s64le-ref bytevector-s64be-ref
bytevector-s64le-set! bytevector-s64be-set!
bytevector-u64le-ref bytevector-u64be-ref
bytevector-u64le-set! bytevector-u64be-set!
)
(define-library (bytestructures r7 explicit-endianness)
(import
(scheme base)
(bytestructures r7 utils)
(bytestructures r7 bytevectors))
(include-library-declarations "explicit-endianness.exports.sld")
(include "body/explicit-endianness.scm"))
(define-library (bytestructures r7 numeric-all)
(import
(scheme base)
(scheme complex)
(scheme eval)
(bytestructures r7 utils)
(bytestructures r7 base)
(bytestructures r7 bytevectors)
(bytestructures r7 explicit-endianness))
(include-library-declarations "numeric.exports.sld")
(include-library-declarations "numeric-metadata.exports.sld")
(include "body/numeric.scm"))
(export
signed-integer-native-descriptors
signed-integer-le-descriptors
signed-integer-be-descriptors
signed-integer-descriptors
unsigned-integer-native-descriptors
unsigned-integer-le-descriptors
unsigned-integer-be-descriptors
unsigned-integer-descriptors
float-native-descriptors
float-le-descriptors
float-be-descriptors
complex-native-descriptors
complex-le-descriptors
complex-be-descriptors
integer-descriptors
float-descriptors
complex-descriptors
numeric-descriptors
)
(define-library (bytestructures r7 numeric-metadata)
(import (bytestructures r7 numeric-all))
(include-library-declarations "numeric-metadata.exports.sld"))
(export
int8 int16 int32 int64
uint8 uint16 uint32 uint64
int16le int32le int64le
uint16le uint32le uint64le
int16be int32be int64be
uint16be uint32be uint64be
float32 float64
float32le float64le
float32be float64be
short unsigned-short
int unsigned-int
long unsigned-long
long-long unsigned-long-long
intptr_t uintptr_t
size_t ssize_t ptrdiff_t
float double
complex64 complex128
complex64le complex128le
complex64be complex128be
)
(define-library (bytestructures r7 numeric)
(import (bytestructures r7 numeric-all))
(include-library-declarations "numeric.exports.sld"))
(export bs:string)
(cond-expand
(r6rs
(export bytevector->string string->bytevector
ascii utf8 utf16le utf16be utf32le utf32be
bytevector-zero!))
(else))
(define-library (bytestructures r7 string)
(import
(scheme base)
(bytestructures r7 bytevectors)
(bytestructures r7 utils)
(bytestructures r7 base))
(cond-expand
((library (rnrs syntax-case))
(import (rnrs syntax-case)))
(else))
(include-library-declarations "string.exports.sld")
(include "body/string.scm"))
(export
bs:struct
struct-metadata?
struct-metadata-field-alist
)
(define-library (bytestructures r7 struct)
(import
(scheme base)
(scheme case-lambda)
(srfi 1)
(srfi 28)
(bytestructures r7 utils)
(bytestructures r7 base)
(bytestructures r7 bitfields))
(include-library-declarations "struct.exports.sld")
(include "body/align.scm")
(include "body/struct.scm"))
(export
bs:union
union-metadata?
union-metadata-field-alist
)
(define-library (bytestructures r7 union)
(import
(scheme base)
(bytestructures r7 utils)
(bytestructures r7 base))
(include-library-declarations "union.exports.sld")
(include "body/align.scm")
(include "body/union.scm"))
(define-library (bytestructures r7 utils)
(import (scheme base))
(cond-expand
((library (rnrs syntax-case))
(import (rnrs syntax-case)))
(else))
(export
define-syntax-rule
if-syntax-case
define-syntax-case-stubs
quasisyntax
unsyntax
unsyntax-splicing
syntax->datum
datum->syntax
)
(include "body/utils.scm"))
(export
bs:vector
vector-metadata?
vector-metadata-length
vector-metadata-element-descriptor
)
(define-library (bytestructures r7 vector)
(import
(scheme base)
(bytestructures r7 utils)
(bytestructures r7 base))
(include-library-declarations "vector.exports.sld")
(include "body/vector.scm"))
(define-module (bytestructures guile))
;;; Note: cstring-pointer import/export hack: Guile 2.0.x has a problem when a
;;; module has the same name as an identifier defined in it, and the identifier
;;; is imported and re-exported. To work around it, we import `cstring-pointer'
;;; with a rename to `_cstring-pointer', define `cstring-pointer' explicitly in
;;; this module, and export that.
(import
(bytestructures guile base)
(bytestructures guile vector)
(bytestructures guile struct)
(bytestructures guile union)
(bytestructures guile pointer)
(bytestructures guile numeric)
(bytestructures guile string)
(rename (bytestructures guile cstring-pointer)
(cstring-pointer _cstring-pointer)))
(re-export
make-bytestructure-descriptor
bytestructure-descriptor?
bytestructure-descriptor-size
bytestructure-descriptor-size/syntax
bytestructure-descriptor-alignment
bytestructure-descriptor-unwrapper
bytestructure-descriptor-getter
bytestructure-descriptor-setter
bytestructure-descriptor-metadata
make-bytestructure
bytestructure?
bytestructure-bytevector
bytestructure-offset
bytestructure-descriptor
bytestructure-size
bytestructure
bytestructure-unwrap
bytestructure-unwrap*
bytestructure-ref
bytestructure-ref*
bytestructure-set!
bytestructure-set!*
bytestructure-ref/dynamic
bytestructure-set!/dynamic
bytestructure-unwrap/syntax
bytestructure-ref/syntax
bytestructure-set!/syntax
define-bytestructure-accessors
bs:vector
vector-metadata? vector-metadata-length vector-metadata-element-descriptor
bs:struct
struct-metadata? struct-metadata-field-alist
bs:union
union-metadata? union-metadata-field-alist
bs:pointer
pointer-metadata? pointer-metadata-content-descriptor
int8 int16 int32 int64
int16le int32le int64le
int16be int32be int64be
uint8 uint16 uint32 uint64
uint16le uint32le uint64le
uint16be uint32be uint64be
float32 float64
float32le float64le
float32be float64be
short unsigned-short
int unsigned-int
long unsigned-long
long-long unsigned-long-long
intptr_t uintptr_t
size_t ssize_t ptrdiff_t
float double
complex64 complex128
complex64le complex128le
complex64be complex128be
bs:string
)
(define cstring-pointer _cstring-pointer)
(export cstring-pointer)
(define-library (bytestructures r7)
(import
(bytestructures r7 base)
(bytestructures r7 vector)
(bytestructures r7 struct)
(bytestructures r7 union)
(bytestructures r7 numeric)
(bytestructures r7 string))
(include-library-declarations "r7/base.exports.sld")
(include-library-declarations "r7/vector.exports.sld")
(include-library-declarations "r7/struct.exports.sld")
(include-library-declarations "r7/union.exports.sld")
(include-library-declarations "r7/numeric.exports.sld")
(include-library-declarations "r7/string.exports.sld"))
;;; Warning: nasal demons.
;;;
;;; Will output differences between GCC's behavior and our behavior, but not in
;;; a very nice format. Zero output is good. The C code and Scheme procedure
;;; we generate are fairly straightforward so read the code to understand.
(define-module (bytestructures bitfield-tests))
(export run-bitfield-tests)
(use-modules (srfi srfi-1)
(srfi srfi-9)
(ice-9 rdelim)
(bytestructures r6 bytevectors)
(bytestructures guile))
(define-record-type <struct>
(make-struct name fields)
struct?
(name struct-name)
(fields struct-fields))
(define-record-type <field>
(make-field name int-size bit-size signed? value)
struct?
(name field-name)
(int-size field-int-size)
(bit-size field-bit-size)
(signed? field-signed?)
(value field-value))
(define *keep-files* (make-parameter #f))
(define (run-bitfield-tests count random-seed-string keep-files)
(set! *random-state* (seed->random-state random-seed-string))
(parameterize ((*keep-files* keep-files))
(test-structs (generate-structs count))))
(define (generate-structs n)
(remove-bad-structs (map random-struct (iota n))))
(define (remove-bad-structs structs)
(filter (lambda (struct)
(find (lambda (field)
(not (zero? (field-bit-size field))))
(struct-fields struct)))
structs))
(define (random-struct i)
(let ((field-count (+ 1 (random 50))))
(make-struct (format #f "s~a" i)
(map random-field (iota field-count)))))
(define (random-field i)
(let* ((name (format #f "f~a" i))
(int-size (* 8 (expt 2 (random 4))))
(bit-size (random (+ 1 int-size)))
(signed? (= 0 (random 2)))
(value (random (expt 2 bit-size)))
(value (if (and signed? (> value (+ -1 (expt 2 (- bit-size 1)))))
(- value (expt 2 bit-size))
value)))
(make-field name int-size bit-size signed? value)))
(define (test-structs structs)
(let* ((c-code (c-code-for-structs structs))
(c-output (get-c-output c-code))
(scm-code (scm-code-for-structs structs))
(scm-output (get-scm-output scm-code)))
(diff-outputs c-output scm-output)))
(define (c-code-for-structs structs)
(string-concatenate
(append
(list "#include <stdio.h>\n"
"#include <stdint.h>\n"
"#include <strings.h>\n"
"int main(){\n")
(map c-code-for-struct structs)
(list "return 0;}"))))
(define (c-code-for-struct struct)
(let ((name (struct-name struct))
(fields (struct-fields struct)))
(string-concatenate
(append
(list (format #f "struct ~a {\n" name))
(map c-decl-for-field fields)
(list "};\n"
(format #f "{ struct ~a foo;\n" name)
(format #f " bzero((void*)&foo, sizeof(foo));\n"))
(map c-assignment-for-field fields)
(list (format #f " printf(\"struct ~a:\\n\");\n" name)
" uint8_t *ptr = (void*)&foo;\n"
" for (int i = 0; i < sizeof(foo); ++i) {\n"
" printf(\"%d \", *(ptr+i));\n"
" }\n"
" printf(\"\\n\");\n"
"}\n")))))
(define (c-decl-for-field field)
(let ((name (field-name field))
(int-size (field-int-size field))
(bit-size (field-bit-size field))
(signed? (field-signed? field)))
(format #f " ~aint~a_t ~a:~a;\n"
(if signed? "" "u")
int-size
(if (zero? bit-size) "" name)
bit-size)))
(define (c-assignment-for-field field)
(let ((name (field-name field))
(bit-size (field-bit-size field))
(signed? (field-signed? field))
(value (field-value field)))
(if (zero? bit-size)
""
(format #f " foo.~a = ~a~a;\n" name value (if signed? "" "u")))))
(define (get-c-output code)
(let* ((port (mkstemp! (string-copy "/tmp/bitfield-XXXXXX")))
(file (port-filename port))
(exe-port (mkstemp! (string-copy "/tmp/bitfield-compiled-XXXXXX")))
(exe-file (port-filename exe-port))
(output-port (mkstemp! (string-copy "/tmp/bitfield-output-XXXXXX")))
(output-file (port-filename output-port)))
(close-port exe-port)
(close-port output-port)
(display code port)
(force-output port)
(unless (zero? (system* "gcc" "-x" "c" "-std=c11" file "-o" exe-file))
(error "gcc failed"))
(unless (zero? (system (format #f "~a > ~a" exe-file output-file)))
(error "exe failed"))
(let ((out (read-string (open output-file O_RDONLY))))
(unless (*keep-files*)
(for-each delete-file (list file exe-file output-file)))
out)))
(define (scm-code-for-structs structs)
(lambda ()
(string-concatenate
(map scm-code-for-struct structs))))
(define (scm-code-for-struct struct)
(let* ((name (struct-name struct))
(fields (struct-fields struct))
(descriptor (struct->descriptor struct))
(values (map field-value (filter-nonzero-fields fields)))
(bs (bytestructure descriptor (list->vector values))))
(string-concatenate
(append
(list (format #f "struct ~a:\n" name))
(let ((bv (bytestructure-bytevector bs)))
(map (lambda (i)
(format #f "~a " (bytevector-u8-ref bv i)))
(iota (bytevector-length bv))))
(list "\n")))))
(define (struct->descriptor struct)
(let ((fields (struct-fields struct)))
(bs:struct (map field->struct-descriptor-field fields))))
(define (field->struct-descriptor-field field)
(let ((name (field-name field))
(int-size (field-int-size field))
(bit-size (field-bit-size field))
(signed? (field-signed? field)))
(list name
(module-ref (resolve-module
'(bytestructures bitfield-tests))
(string->symbol
(format #f "~aint~a"
(if signed? "" "u")
int-size)))
bit-size)))
(define (filter-nonzero-fields fields)
(filter (lambda (field)
(not (zero? (field-bit-size field))))
fields))
(define (get-scm-output code)
(code))
(define (diff-outputs o1 o2)
(let* ((p1 (mkstemp! (string-copy "/tmp/bitfield-out1-XXXXXX")))
(f1 (port-filename p1))
(p2 (mkstemp! (string-copy "/tmp/bitfield-out2-XXXXXX")))
(f2 (port-filename p2)))
(display o1 p1)
(display o2 p2)
(flush-all-ports)
(close-port p1)
(close-port p2)
(let ((retval (system* "diff" "-y" "--suppress-common" f1 f2)))
(unless (*keep-files*)
(for-each delete-file (list f1 f2)))
retval)))
;;; Use this in the REPL. It produces wrong results when ran as a script.
(use-modules (system vm coverage)
(system vm vm)
(srfi srfi-11))
(let ((output-directory
(string-append
(getenv "HOME") "/srv/http/htdocs/lcov/scheme-bytestructures")))
(let-values (((data . values)
(with-code-coverage (the-vm)
(lambda ()
(load "run-tests.guile.scm")))))
(let* ((port (mkstemp! (string-copy "/tmp/bytestructures-coverage-XXXXXX")))
(file (port-filename port)))
(coverage-data->lcov data port)
(close port)
(when (not (zero? (system* "genhtml" file "-o" output-directory)))
(error "genhtml failed"))
(delete-file file))))
;;; run-tests.body.scm --- Bytestructures test suite.
;; Copyright © 2015, 2021 Taylan Kammer <taylan.kammer@gmail.com>
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; A relatively simple SRFI-64 test suite.
;;; Code:
(define-syntax-rule (test-= name expected expr)
(test-approximate name expected expr 0))
(define-syntax-rule (maybe-skip-syntax . <body>)
(if-syntax-case
(begin . <body>)
(begin)))
(test-begin "bytestructures")
(test-group "numeric"
(define-syntax test-numeric-descriptors
(syntax-rules ()
((_ <descriptor-id> ...)
(let ()
(define (destructure-numeric-descriptor-entry descriptor-entry proc)
(define descriptor (list-ref descriptor-entry 0))
(define name (list-ref descriptor-entry 1))
(define getter (list-ref descriptor-entry 2))
(define setter (list-ref descriptor-entry 3))
(define size (bytestructure-descriptor-size descriptor))
(define float? (assq descriptor float-descriptors))
(define signed? (or float? (assq descriptor signed-integer-descriptors)))
(proc descriptor name getter setter size float? signed?))
(define (get-min/max float? signed? size)
(cond
(float? (inexact (expt 2 (case size ((4) 24) ((8) 53)))))
(signed? (- (expt 256 (- size 1))))
(else (- (expt 256 size) 1))))
(destructure-numeric-descriptor-entry
(assq <descriptor-id> numeric-descriptors)
(lambda (descriptor name getter setter size float? signed?)
(test-group (symbol->string name)
(let ((test-value-1 (if float? 1.0 1))
(test-value-2 (if float? 2.0 1)))
(test-group "procedural"
(define min/max (get-min/max float? signed? size))
(define bs (bytestructure descriptor))
(test-eqv "size" size (bytevector-length
(bytestructure-bytevector bs)))
(test-= "ref" test-value-1
(begin
(setter (bytestructure-bytevector bs) 0 test-value-1)
(bytestructure-ref bs)))
(test-= "set" test-value-2
(begin
(bytestructure-set! bs test-value-2)
(getter (bytestructure-bytevector bs) 0)))
(test-= "min/max" min/max
(begin
(bytestructure-set! bs min/max)
(bytestructure-ref bs))))
(maybe-skip-syntax
(test-group "syntactic"
(define min/max (get-min/max float? signed? size))
;; Must insert the top-level reference <descriptor-id> here.
(define-bytestructure-accessors <descriptor-id>
bs-unwrapper bs-getter bs-setter)
(define bv (make-bytevector size))
(test-= "ref" test-value-1
(begin
(setter bv 0 test-value-1)
(bs-getter bv)))
(test-= "set" test-value-2
(begin
(bs-setter bv test-value-2)
(getter bv 0)))
(test-= "min/max" min/max
(begin
(bs-setter bv min/max)
(bs-getter bv)))))))))
...))))
(test-numeric-descriptors
float32 float32le float32be
float64 float64le float64be
int8 int16 int32 int64
int16le int32le int64le
int16be int32be int64be
uint8 uint16 uint32 uint64
uint16le uint32le uint64le
uint16be uint32be uint64be))
(test-group "vector"
(test-assert "create" (bs:vector 3 uint16))
(test-group "procedural"
(define bs (bytestructure (bs:vector 3 uint16)))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 2 321)
(test-eqv "ref" 321 (bytestructure-ref bs 1))
(test-eqv "set" 456 (begin (bytestructure-set! bs 1 456)
(bytestructure-ref bs 1)))
(test-eqv "init" 321
(let ((bs (bytestructure (bs:vector 3 uint16) '#(321 123 321))))
(bytestructure-ref bs 2))))
(maybe-skip-syntax
(test-group "syntactic"
(define-bytestructure-accessors (bs:vector 3 uint16)
unwrapper getter setter)
(define bv (make-bytevector 6))
(bytevector-u16-native-set! bv 2 321)
(test-eqv "ref" 321 (getter bv 1))
(test-eqv "set" 456 (begin (setter bv 1 456)
(getter bv 1))))))
(test-group "struct"
(test-group "aligned"
(test-assert "create" (bs:struct `((x ,uint8) (y ,uint16))))
(test-group "procedural"
(define bs (bytestructure (bs:struct `((x ,uint8) (y ,uint16)))))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 2 321)
(test-eqv "ref" 321 (bytestructure-ref bs 'y))
(test-eqv "set" 456 (begin (bytestructure-set! bs 'y 456)
(bytestructure-ref bs 'y)))
(test-eqv "init" 321
(let ((bs (bytestructure (bs:struct `((x ,uint8) (y ,uint16)))
'#(123 321))))
(bytestructure-ref bs 'y))))
(maybe-skip-syntax
(test-group "syntactic"
(define-bytestructure-accessors (bs:struct `((x ,uint8) (y ,uint16)))
unwrapper getter setter)
(define bv (make-bytevector 4))
(bytevector-u16-native-set! bv 2 321)
(test-eqv "ref" 321 (getter bv y))
(test-eqv "set" 456 (begin (setter bv y 456)
(getter bv y))))))
(test-group "packed"
(test-assert "create" (bs:struct #t `((x ,uint8) (y ,uint16))))
(test-group "procedural"
(define bs (bytestructure (bs:struct #t `((x ,uint8) (y ,uint16)))))
;; u16-native-set! may error on non-aligned access.
(guard (err (else (test-skip 3)))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 1 321))
(test-eqv "ref" 321 (bytestructure-ref bs 'y))
(test-eqv "set" 456 (begin (bytestructure-set! bs 'y 456)
(bytestructure-ref bs 'y)))
(test-eqv "init" 321
(let ((bs (bytestructure (bs:struct #t `((x ,uint8) (y ,uint16)))
'#(123 321))))
(bytestructure-ref bs 'y))))
(maybe-skip-syntax
(test-group "syntactic"
(define-bytestructure-accessors (bs:struct #t `((x ,uint8) (y ,uint16)))
unwrapper getter setter)
(define bv (make-bytevector 4))
;; u16-native-set! may error on non-aligned access.
(guard (err (else (test-skip 2)))
(bytevector-u16-native-set! bv 1 321))
(test-eqv "ref" 321 (getter bv y))
(test-eqv "set" 456 (begin (setter bv y 456)
(getter bv y))))))
(test-group "anonymous-union"
(test-assert "create"
(bs:struct
`((x ,uint8)
(union
((a ,uint16)
(b ,uint32))))))
;; Don't use 64-bit ints; their alignment differs between platforms.
(test-group "aligned"
(define bs
(bytestructure
(bs:struct
`((union
((x ,uint8)
(y ,uint16)))
(union
((a ,uint16)
(b ,uint32)))))))
(test-eqv "size" 8 (bytevector-length (bytestructure-bytevector bs)))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 4 321)
(test-eqv "ref1" 321 (bytestructure-ref bs 'a))
(bytevector-u32-native-set! (bytestructure-bytevector bs) 4 456)
(test-eqv "ref2" 456 (bytestructure-ref bs 'b))
(test-eqv "set1" 789 (begin (bytestructure-set! bs 'a 789)
(bytestructure-ref bs 'a)))
(test-eqv "set2" 987 (begin (bytestructure-set! bs 'b 987)
(bytestructure-ref bs 'b))))
(test-group "packed"
(define bs
(bytestructure
(bs:struct
#t
`((union
((x ,uint8)
(y ,uint16)))
(union
((a ,uint16)
(b ,uint32)))))))
(test-eqv "size" 6 (bytevector-length (bytestructure-bytevector bs)))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 2 321)
(test-eqv "ref1" 321 (bytestructure-ref bs 'a))
(bytevector-u32-native-set! (bytestructure-bytevector bs) 2 456)
(test-eqv "ref2" 456 (bytestructure-ref bs 'b))
(test-eqv "set1" 789 (begin (bytestructure-set! bs 'a 789)
(bytestructure-ref bs 'a)))
(test-eqv "set2" 987 (begin (bytestructure-set! bs 'b 987)
(bytestructure-ref bs 'b))))))
(test-group "union"
(test-assert "create" (bs:union `((x ,uint8) (y ,uint16))))
(test-group "procedural"
(define bs (bytestructure (bs:union `((x ,uint8) (y ,uint16)))))
(bytevector-u16-native-set! (bytestructure-bytevector bs) 0 321)
(test-eqv "ref" 321 (bytestructure-ref bs 'y))
(test-eqv "set" 456 (begin (bytestructure-set! bs 'y 456)
(bytestructure-ref bs 'y))))
(maybe-skip-syntax
(test-group "syntactic"
(define-bytestructure-accessors (bs:union `((x ,uint8) (y ,uint16)))
unwrapper getter setter)
(define bv (make-bytevector 2))
(bytevector-u16-native-set! bv 0 321)
(test-eqv "ref" 321 (getter bv y))
(test-eqv "set" 456 (begin (setter bv y 456)
(getter bv y))))))
(test-group "string"
(test-group "ascii"
(test-assert "create" (bs:string 4 'ascii))
(test-group "procedural"
(define bsd (bs:string 4 'ascii))
(define bs (make-bytestructure (string->utf8 "1234") 0 bsd))
(test-equal "ref" "1234" (bytestructure-ref bs))
(test-equal "set" "4321" (begin
(bytestructure-set! bs "4321")
(bytestructure-ref bs)))
(test-error "too-long" #t (bytestructure-set! bs "12345"))
(test-error "too-short" #t (bytestructure-set! bs "123"))
(set! bs (make-bytestructure (string->utf8 "äåãø") 0 bsd))
(test-error "decoding-error" #t (bytestructure-ref bs))
(test-error "encoding-error" #t (bytestructure-set! bs "øãåä")))
(test-group "syntactic"
(define-bytestructure-accessors (bs:string 4 'ascii)
unwrapper getter setter)
(define bv (string->utf8 "1234"))
(test-equal "ref" "1234" (getter bv))
(test-equal "set" "4321" (begin
(setter bv "4321")
(getter bv)))
(test-error "too-long" #t (setter bv "12345"))
(test-error "too-short" #t (setter bv "123"))
(set! bv (string->utf8 "äåãø"))
(test-error "ref-error" #t (getter bv))
(test-error "set-error" #t (setter bv "øãåä"))))
(test-group "utf8"
(test-assert "create" (bs:string 4 'utf8))
(test-group "procedural"
(define bsd (bs:string 4 'utf8))
(define bs (make-bytestructure (string->utf8 "1234") 0 bsd))
(test-equal "ref" "1234" (bytestructure-ref bs))
(test-equal "set" "4321" (begin
(bytestructure-set! bs "4321")
(bytestructure-ref bs)))
(test-error "too-long" #t (bytestructure-set! bs "äåãø"))
(test-equal (string-append "123" (string #\nul))
(begin
(bytestructure-set! bs "123")
(bytestructure-ref bs))))
(test-group "syntactic"
(define-bytestructure-accessors (bs:string 4 'utf8)
unwrapper getter setter)
(define bv (string->utf8 "1234"))
(test-equal "ref" "1234" (getter bv))
(test-equal "set" "4321" (begin
(setter bv "4321")
(getter bv)))
(test-error "too-long" #t (setter bv "äåãø"))
(test-equal (string-append "123" (string #\nul))
(begin
(setter bv "123")
(getter bv)))))
(let ()
(define-syntax-rule
(test-string-encodings
(<name> <encoding> <endianness> <size> <fixed-width?> <string->utf>)
...)
(begin
(test-group <name>
(test-assert "create" (bs:string <size> '<encoding>))
(test-group "procedural"
(define bs (make-bytestructure (<string->utf> "1234" '<endianness>)
0
(bs:string <size> '<encoding>)))
(test-equal "ref" "1234" (bytestructure-ref bs))
(test-equal "set" "4321" (begin
(bytestructure-set! bs "4321")
(bytestructure-ref bs)))
(test-error "too-long" #t (bytestructure-set! bs "12345"))
(if <fixed-width?>
(test-error "too-short" #t (bytestructure-set! bs "123"))
(test-equal (string-append "123" (string #\nul))
(begin
(bytestructure-set! bs "123")
(bytestructure-ref bs)))))
(test-group "syntactic"
(define-bytestructure-accessors (bs:string <size> '<encoding>)
unwrapper getter setter)
(define bv (<string->utf> "1234" '<endianness>))
(test-equal "ref" "1234" (getter bv))
(test-equal "set" "4321" (begin
(setter bv "4321")
(getter bv)))
(test-error "too-long" #t (setter bv "12345"))
(if <fixed-width?>
(test-error "too-short" #t (setter bv "123"))
(test-equal (string-append "123" (string #\nul))
(begin
(setter bv "123")
(getter bv))))))
...))
(test-string-encodings
("utf16le" utf16le little 8 #f string->utf16)
("utf16be" utf16be big 8 #f string->utf16)
("utf32le" utf32le little 16 #t string->utf32)
("utf32be" utf32be big 16 #t string->utf32))))
(cond-expand
(guile
(let ()
(define (protect-from-gc-upto-here obj)
(with-output-to-file *null-device*
(lambda ()
(display (eq? #f obj)))))
(define pointer-size (ffi-sizeof '*))
(define bytevector-address-set!
(case pointer-size
((1) bytevector-u8-set!)
((2) bytevector-u16-native-set!)
((4) bytevector-u32-native-set!)
((8) bytevector-u64-native-set!)))
(test-group "pointer"
(test-assert "create" (bs:pointer uint16))
(test-group "procedural"
(define bs (bytestructure (bs:pointer uint16)))
(define bv1 (make-bytevector 2))
(define bv2 (make-bytevector 4))
(define address1 (ffi-pointer-address (ffi-bytevector->pointer bv1)))
(define address2 (ffi-pointer-address (ffi-bytevector->pointer bv2)))
(bytevector-address-set! (bytestructure-bytevector bs) 0 address1)
(bytevector-u16-native-set! bv1 0 321)
(test-eqv "ref1" 321 (bytestructure-ref bs '*))
(test-eqv "set1" 456 (begin (bytestructure-set! bs '* 456)
(bytestructure-ref bs '*)))
(test-eqv "ref2" address1 (bytestructure-ref bs))
(test-eqv "set2" address2 (begin (bytestructure-set! bs address2)
(bytestructure-ref bs)))
(bytevector-address-set! (bytestructure-bytevector bs) 0 address2)
(bytevector-u16-native-set! bv2 2 456)
(test-eqv "ref3" 456 (bytestructure-ref bs 1))
(test-eqv "set3" 789 (begin (bytestructure-set! bs 1 789)
(bytestructure-ref bs 1)))
(protect-from-gc-upto-here bv1)
(protect-from-gc-upto-here bv2))
(test-group "syntactic"
(define-bytestructure-accessors (bs:pointer uint16)
unwrapper getter setter)
(define bv (make-bytevector pointer-size))
(define bv1 (make-bytevector 2))
(define bv2 (make-bytevector 4))
(define address1 (ffi-pointer-address (ffi-bytevector->pointer bv1)))
(define address2 (ffi-pointer-address (ffi-bytevector->pointer bv2)))
(bytevector-address-set! bv 0 address1)
(bytevector-u16-native-set! bv1 0 321)
(test-eqv "ref" 321 (getter bv *))
(test-eqv "set" 456 (begin (setter bv * 456)
(getter bv *)))
(test-eqv "ref2" address1 (getter bv))
(test-eqv "set2" address1 (begin (setter bv address1)
(getter bv)))
(bytevector-address-set! bv 0 address2)
(bytevector-u16-native-set! bv2 2 456)
(test-eqv "ref3" 456 (getter bv 1))
(test-eqv "set3" 789 (begin (setter bv 1 789)
(getter bv 1)))
(protect-from-gc-upto-here bv1)
(protect-from-gc-upto-here bv2)))
(test-group "cstring-pointer"
(let* ((cstr1-ptr (ffi-string->pointer "abc"))
(cstr2-ptr (ffi-string->pointer "cba"))
(cstr1-addr (ffi-pointer-address cstr1-ptr))
(cstr2-addr (ffi-pointer-address cstr2-ptr)))
(test-group "procedural"
(define bs (bytestructure cstring-pointer))
(bytevector-address-set! (bytestructure-bytevector bs) 0 cstr1-addr)
(test-equal "ref" "abc" (bytestructure-ref bs))
(test-equal "set" "cba" (begin (bytestructure-set! bs cstr2-addr)
(bytestructure-ref bs))))
(test-group "syntactic"
(define-bytestructure-accessors cstring-pointer
unwrapper getter setter)
(define bv (make-bytevector pointer-size))
(bytevector-address-set! bv 0 cstr1-addr)
(test-equal "ref" "abc" (getter bv))
(test-equal "set" "cba" (begin (setter bv cstr2-addr)
(getter bv))))))))
(else
))
;; Do this before test-end since it removes the auto-inserted test runner.
(define success
(let ((runner (test-runner-current)))
(and (zero? (test-runner-xpass-count runner))
(zero? (test-runner-fail-count runner)))))
(test-end "bytestructures")
(exit (if success 0 1))
;; Local Variables:
;; eval: (put (quote test-group) (quote scheme-indent-function) 1)
;; eval: (put (quote test-=) (quote scheme-indent-function) 2)
;; End:
(use-modules
(srfi srfi-11)
(srfi srfi-64)
((rnrs exceptions) #\select (guard))
((system foreign) #\prefix ffi-)
(bytestructures r6 bytevectors)
(bytestructures guile utils)
(bytestructures guile)
(bytestructures guile numeric-metadata))
(define inexact exact->inexact)
(include-from-path "run-tests.body.scm")
(import
(scheme base)
(srfi 64)
(bytestructures r7 utils)
(bytestructures r7)
(bytestructures r7 numeric-metadata)
(bytestructures r7 bytevectors)
(bytestructures r7 explicit-endianness))
(include "run-tests.body.scm")
;;; commonmark.scm --- An implementation of CommonMark markdown
;; Copyright (C) 2014 Taylan Ulrich Bayirli/Kammer
;; Author: Taylan Ulrich Bayirli/Kammer <taylanbayirli@gmail.com>
;; Keywords:
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;;
;;; Code:
(define (parse port)
(let* ((lines (preprocess port))
(blocks (parse-blocks lines)))
blocks))
(define (preprocess port)
(do ((line (read-line port) (read-line port))
(lines '() (cons (preprocess-line line) lines)))
((eof-object? line) (reverse lines))))
(define (preprocess-line line)
(do ((chars (string->list line) (cdr chars))
(processed-chars '() (let ((char (car chars)))
(if (char=? char #\tab)
(append (make-list 4 #\space)
processed-chars)
(cons char processed-chars)))))
((null? chars) (apply string (reverse processed-chars)))))
(define (parse-blocks lines)
(do ((lines lines (cdr lines))
(blocks '() (let ((blocks* (add-line blocks (car lines))))
(if blocks*
blocks*
(begin (close-block! (car blocks))
blocks))))))
((null? lines) (reverse blocks)))
;;; BLOCKS is in reverse here.
(define (add-line blocks line)
(if (null? blocks)
(cons (new-block line) blocks)
(let ((last-block (car blocks)))
(cond
((and (open-text-block? last-block)
(plain-text-line? line))
(add-line-to-text-block last-block line))
((and (open-container-block? last-block)
()))))))
;;; commonmark.scm ends here
(export
)
(define-library (commonmark r7rs)
(import (scheme base))
(include-library-declarations "r7rs-exports.scm")
(include "commonmark.scm"))
;;; generic-ref-set --- Generic accessor and modifier operators.
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;;; Helpers
(define-syntax push!
(syntax-rules ()
((_ <list-var> <x>)
(set! <list-var> (cons <x> <list-var>)))))
(define (alist->hashtable alist)
(let ((table (make-eqv-hashtable 100)))
(for-each (lambda (entry)
(hashtable-set! table (car entry) (cdr entry)))
alist)
table))
;;; Main
(define ref
(case-lambda
((object field)
(let ((getter (lookup-getter object))
(sparse? (sparse-type? object)))
(if sparse?
(let* ((not-found (cons #f #f))
(result (getter object field not-found)))
(if (eqv? result not-found)
(error "Object has no entry for field." object field)
result))
(getter object field))))
((object field default)
(let ((getter (lookup-getter object)))
(getter object field default)))))
(define-syntax set!
(syntax-rules ()
((set! <place> <expression>)
(%set! <place> <expression>))
((set! <object> <field> <value>)
(let* ((object <object>)
(setter (lookup-setter object)))
(setter object <field> <value>)))))
(set! (setter ref) (lambda (object field value) (set! object field value)))
(define (lookup-getter object)
(or (hashtable-ref getter-table (type-of object) #f)
(error "No generic getter for object's type." object)))
(define (lookup-setter object)
(or (hashtable-ref setter-table (type-of object) #f)
(error "No generic setter for object's type." object)))
(define (sparse-type? object)
(memv (type-of object) sparse-types))
(define (type-of object)
(find (lambda (pred) (pred object)) type-list))
(define getter-table
(alist->hashtable
(list (cons bytevector? bytevector-u8-ref)
(cons hashtable? hashtable-ref)
(cons pair? list-ref)
(cons string? string-ref)
(cons vector? vector-ref))))
(define setter-table
(alist->hashtable
(list (cons bytevector? bytevector-u8-set!)
(cons hashtable? hashtable-set!)
(cons pair? list-set!)
(cons string? string-set!)
(cons vector? vector-set!))))
(define sparse-types
(list hashtable?))
(define type-list
(list boolean? bytevector? char? eof-object? hashtable? null? number? pair?
port? procedure? string? symbol? vector?))
(define-syntax define-record-type
(syntax-rules ()
((_ <name> <constructor> <pred> <field> ...)
(begin
(%define-record-type <name> <constructor> <pred> <field> ...)
(push! type-list <pred>)
(register-record-getter <pred> <field> ...)
(register-record-setter <pred> <field> ...)))))
(define-syntax register-record-getter
(syntax-rules ()
((_ <pred> (<field> <getter> . <rest>) ...)
(let ((getters (alist->hashtable (list (cons '<field> <getter>) ...))))
(define (getter record field)
(let ((getter (or (ref getters field #f)
(error "No such field of record." record field))))
(getter record field)))
(set! getter-table <pred> getter)))))
(define-syntax register-record-setter
(syntax-rules ()
((_ . <rest>)
(%register-record-setter () . <rest>))))
(define-syntax %register-record-setter
(syntax-rules ()
((_ <setters> <pred> (<field> <getter>) . <rest>)
(%register-record-setter <setters> <pred> . <rest>))
((_ <setters> <pred> (<field> <getter> <setter>) . <rest>)
(%register-record-setter ((<field> <setter>) . <setters>) <pred> . <rest>))
((_ ((<field> <setter>) ...) <pred>)
(let ((setters (alist->hashtable (list (cons '<field> <setter>) ...))))
(define (setter record field value)
(let ((setter (or (ref setters field #f)
(error "No such assignable field of record."
record field))))
(setter record value)))
(set! setter-table <pred> setter)))))
;;; generic-ref-set.body.scm ends here
(define-library (generic-ref-set)
(export
ref set! define-record-type (rename ref $bracket-apply$))
(import
(rename (except (scheme base) set!)
(define-record-type %define-record-type))
(scheme case-lambda)
(r6rs hashtables)
(srfi 1)
(rename (srfi 17) (set! %set!)))
(include "generic-ref-set.body.scm"))
(define-module (ie-reader cre))
(use-modules
(bytestructures guile))
(define cre-header
(bs:struct
`((signature ,(bs:string 4 'ascii))
(version ,(bs:string 4 'ascii))
(long-name ))))
;; One advantage of dlists is that they allow you to write more
;; efficient programs, while keeping the lucidity of the less
;; efficient version. Take the naïve version of 'reverse'
(define (reverse l)
(if (null? l)
'()
(append (reverse (cdr l))
(list (car l)))))
;; The definition is obviously correct, however it isn't very
;; efficient. For a given step, the cost of the non-trivial case is
;; dependant on the size of the list we have gotten from the recursive
;; call. That is, it takes time proportional to the square of its
;; input list.
;; Of course, no self respecting functional programmer would write
;; reverse in this manner, as the trick of using an accumulating
;; parameter is so well established. Instead we would write
(define (reverse l)
(define (reverse-helper from to)
(if (null? from)
to
(reverse-helper (cdr from)
(cons (car from) to))))
(reverse-helper l '()))
;; By introducing this additional parameter, we have reclaimed a more
;; reasonable complexity of constant time at each recursive call,
;; giving us linear complexity overall.
;; This is a big improvement, and with a little practice, it becomes
;; easy to convince yourself of the correctness of code written in
;; this manner.
;; However, why should you have to practice? Why can't there be a
;; definition as obviously correct as the former, with the efficiency
;; of the latter?
;; Turns out, it is possible to do this, by using a different
;; representation for lists.
(define (reverse* l)
(if (null? l)
(dlist)
(dlist-append (reverse* (cdr l))
(dlist (car l)))))
(define (reverse l)
(dlist->list (reverse* l)))
;; Difference lists, or representing lists as functions, gives us a
;; constant time version of append, thus reducing the complexity of
;; reverse* to O(n), and the definition differs from the original,
;; only in the names we use for the append and list procedures. The
;; final result of this function, however, is a dlist rather than a
;; list, so we must convert back. This also has linear complexity, so
;; the overall complexity is still linear.
;; How does this work? Well, let's replace dlist and dlist-append with
;; their definitions
(define (reverse* l)
(if (null? l)
(lambda (x) (append '() x))
(compose (reverse* (cdr l))
(lambda (x) (append (list (car l)) x)))))
(define (reverse l)
((reverse* l) '()))
;; Now, we replace compose with its definition
(define (reverse* l)
(if (null? l)
(lambda (x) (append '() x))
(lambda (x)
((reverse* (cdr l))
((lambda (x) (append (list (car l)) x)) x)))))
(define (reverse l)
((reverse* l) '()))
;; With a few simplifications: substituting x for its definition,
;; x for (append '() x), and (cons x y) for (append (list x) y)
(define (reverse* l)
(if (null? l)
(lambda (x) x)
(lambda (x)
((reverse* (cdr l))
(cons (car l) x)))))
(define (reverse l)
((reverse* l) '()))
;; Now, if we uncurry reverse*
(define (reverse* l x)
(if (null? l)
x
(reverse* (cdr l) (cons (car l) x))))
(define (reverse l)
(reverse* l '()))
;; Then, it turns out the dlist version is the traditional O(n)
;; implementation in disguise.
;; As an exercise, you can try doing the same thing for the flatten
;; function
(define (flatten xs)
(cond ((null? xs) '())
((pair? xs)
(append (flatten (car xs))
(flatten (cdr xs))))
(else (list xs))))
;;; Functional Breadth First Search
(import (rnrs)
(pfds queues))
;; This is the traditional solution using Queues, for a more
;; interesting solution, see "The Under-Appreciated Unfold" by Jeremy
;; Gibbons and Geraint Jones.
;; We'll need a tree type, we'll use #f for an empty child.
(define-record-type tree
(fields value left right))
;; A small section of the Stern-Brocot Tree
;; https://en.wikipedia.org/wiki/Stern%E2%80%93Brocot_tree
(define stern-brocot
(make-tree 1
(make-tree 1/2
(make-tree 1/3
(make-tree 1/4 #f #f)
(make-tree 2/5 #f #f))
(make-tree 2/3
(make-tree 3/5 #f #f)
(make-tree 3/4 #f #f)))
(make-tree 2
(make-tree 3/2
(make-tree 4/3 #f #f)
(make-tree 5/3 #f #f))
(make-tree 3
(make-tree 5/2 #f #f)
(make-tree 4 #f #f)))))
;; We'll search it breadth-first for the first fraction expressed in
;; fifths.
(define (fifth? f)
(= 5 (denominator f)))
;; The queue search
(define (bfs p? tree)
(define (step queue)
(if (queue-empty? queue)
#f
(let-values ([(head queue*) (dequeue queue)])
(cond ((not head) ; empty-tree, skip
(step queue*))
((p? (tree-value head)) (tree-value head))
(else
(step (enqueue (enqueue queue* (tree-left head))
(tree-right head))))))))
(step (enqueue (make-queue) tree)))
(equal? 2/5 (bfs fifth? stern-brocot))
(define-library (pfds assert)
(export assert assertion-violation)
(import (scheme base))
(begin
()))
;;; bbtrees.sls --- Bounded Balance trees
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Copyright (C) 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;; Documentation:
;;
;; Note: For all procedures which take a key as an argument, the key
;; must be comparable with the ordering procedure of the bbtree.
;;
;; make-bbtree : (any -> any -> boolean) -> bbtree
;; returns an empty bbtree. bbtrees derived from this one will use the
;; procedure argument for ordering keys.
;;
;; bbtree? : any -> bool
;; returns #t if the argument is a bbtree, #f otherwise
;;
;; bbtree-size : bbtree -> non-negative integer
;; returns the number of elements in a bbtree
;;
;; bbtree-ref : bbtree any [any] -> any
;; returns the value associated with the key in the bbtree. If the
;; value is not in the tree, then, if the optional third argument is
;; passed, it is returned, otherwise an &assertion-violation condition
;; is raised.
;;
;; bbtree-set : bbtree any any -> bbtree
;; returns a new bbtree with the key associated with the value. If the
;; key is already in the bbtree, its associated value is replaced with
;; the new value in the returned bbtree.
;;
;; bbtree-update : bbtree any (any -> any) any -> bbtree
;; returns a new bbtree with the value associated with the key updated
;; according to the update procedure. If the key was not already in
;; the bbtree, the update procedure is called on the default value,
;; and the association is added to the bbtree.
;;
;; bbtree-delete : bbtree any -> bbtree
;; returns a new bbtree with the key and its associated value
;; removed. If the key is not in the bbtree, the returned bbtree is a
;; copy of the original
;;
;; bbtree-contains? : bbtree any -> boolean
;; returns #t if there is association for key in the bbtree, false
;; otherwise
;;
;; bbtree-traverse : (any any (any -> any) (any -> any) any) any bbtree -> any
;; A general tree traversal procedure. Returns the value of applying
;; the traverser procedure to the current node's key, value, a
;; procedure to traverse the left subtree, a procedure to traverse the
;; right subtree, and a base value. The subtree traversal procedures
;; both take a base argument, and call bbtree-traverse recursively on
;; the appropriate subtree. It is mostly useful for implementing
;; other, more specific tree traversal procedures. For example,
;; (define (l-to-r-pre-order cons base bbtree)
;; (bbtree-traverse (lambda (key value left right base)
;; (right (left (cons key value base))))
;; base
;; bbtree))
;; implements a left-to-right pre-order traversal variant of bbtree-fold
;;
;; bbtree-fold : (any any any -> any) any bbtree -> any
;; returns the value obtained by the iterating the combine procedure
;; over each node in the tree. The combine procedure takes three
;; arguments, the key and value of the current node, and an
;; accumulator value, and its return value is used as the accumulator
;; value for the next node. The initial accumulator value is provided
;; by the base argument. bbtree-fold performs an left-to-right
;; in-order traversal or "minimum key to maximum key".
;;
;; bbtree-fold-right : (any any any -> any) any bbtree -> any
;; like bbtree-fold, but it performs a right-to-left in-order
;; traversal instead (i.e. maximum to minimum).
;;
;; bbtree-map : (any -> any) bbtree -> bbtree
;; returns the tree obtained by updating the value of each node with
;; the result of applying the procedure to its value.
;;
;; bbtree->alist : bbtree -> Listof(Pairs)
;; returns the key value associations of the bbtree as a list of
;; pairs. The list returned is in sorted order according to the
;; ordering procedure of the bbtree. A consequence of this is that one
;; could write a sort procedure for lists of pairs as
;; (define (alist-sort alist <)
;; (bbtree->alist (alist->bbtree alist <)))
;;
;; alist->bbtree : Listof(Pairs) -> (any any -> boolean) -> bbtree
;; returns the bbtree containing each of the key value pairs in the
;; alist, using the < argument as the ordering procedure.
;;
;; bbtree-keys : bbtree -> Listof(any)
;; returns a list containing all the keys of the bbtree. The keys are
;; sorted according to the bbtree's ordering procedure.
;;
;; bbtree-union : bbtree bbtree -> bbtree
;; returns a bbtree containing the union of the associations in
;; bbtree1 and bbtree2. Where the same key occurs in both, the value
;; in bbtree1 is preferred.
;;
;; bbtree-difference : bbtree bbtree -> bbtree
;; returns a bbtree containing the all the associations in bbtree1,
;; which do not occur in bbtree2.
;;
;; bbtree-intersection : bbtree bbtree -> bbtree
;; returns a bbtree containing all the associations which appear in
;; both bbtree1 and bbtree2. The value in bbtree1 are preferred over
;; those in bbtree2.
;;
;; bbtree-index bbtree any -> non-negative integer
;; returns the index of the key in the bbtree. Index is an integer
;; between 0 and size - 1, with the a key having a lower index than
;; another if first-key < second-key, according to the bbtree ordering
;; procedure.
;;
;; bbtree-ref/index bbtree non-negative-integer -> any any
;; returns the key and value of the association in the bbtree at the
;; given index.
;;
;; bbtree-ordering-procedure : bbtree -> (any any -> bool)
;; returns the ordering procedure used internally to order the
;; bbtree.
(define-library (pfds bbtrees)
(export make-bbtree
bbtree?
bbtree-size
bbtree-ref
bbtree-set
bbtree-update
bbtree-delete
bbtree-contains?
bbtree-ordering-procedure
bbtree-traverse
bbtree-fold
bbtree-fold-right
bbtree-map
bbtree->alist
alist->bbtree
bbtree-keys
bbtree-union
bbtree-difference
bbtree-intersection
bbtree-index
bbtree-ref/index
)
(import (except (scheme base) min member))
(begin
(define weight 4)
;;; bbtree is the wrapper that you interact with from outside the
;;; module, so there is no need to deal with empty and node record types
(define-record-type (bbtree %make-bbtree bbtree?)
(fields tree ordering-procedure))
(define (update-tree bbtree new-tree)
(%make-bbtree new-tree (bbtree-ordering-procedure bbtree)))
;;; inner representation of trees
;;; all non exposed methods can assume a valid tree
(define-record-type empty)
(define-record-type node
(fields key value length left right))
;;; smart constructor for nodes, automatically fills in size field
(define (node* key value left right)
(make-node key value (+ 1 (size left) (size right)) left right))
(define (size tree)
(if (empty? tree)
0
(node-length tree)))
;; looks key up in the tree, and applies proc to the value if it finds
;; it, and calls failure otherwise
(define (lookup tree key proc failure <)
(define (search tree)
(cond ((empty? tree) (failure))
((< (node-key tree) key)
(search (node-right tree)))
((< key (node-key tree))
(search (node-left tree)))
(else (proc tree))))
(search tree))
;; returns the key and value of the minimum element in the tree
(define (min tree)
(cond ((empty? tree)
(assertion-violation 'min "Can't take the minimum value of an empty tree"))
((empty? (node-left tree))
(values (node-key tree)
(node-value tree)))
(else
(min (node-left tree)))))
;;; rotations
(define (rotate-left key value left right)
(let ((r-key (node-key right))
(r-value (node-value right))
(r-left (node-left right))
(r-right (node-right right)))
(node* r-key
r-value
(node* key value left r-left)
r-right)))
(define (rotate-right key value left right)
(let ((l-key (node-key left))
(l-value (node-value left))
(l-left (node-left left))
(l-right (node-right left)))
(node* l-key
l-value
l-left
(node* key value l-right right))))
(define (rotate-left/double key value left right)
(let ((r-key (node-key right))
(r-value (node-value right))
(r-left (node-left right))
(r-right (node-right right)))
(let ((rl-key (node-key r-left))
(rl-value (node-value r-left))
(rl-left (node-left r-left))
(rl-right (node-right r-left)))
(node* rl-key
rl-value
(node* key value left rl-left)
(node* r-key r-value rl-right r-right)))))
(define (rotate-right/double key value left right)
(let ((l-key (node-key left))
(l-value (node-value left))
(l-left (node-left left))
(l-right (node-right left)))
(let ((lr-key (node-key l-right))
(lr-value (node-value l-right))
(lr-left (node-left l-right))
(lr-right (node-right l-right)))
(node* lr-key
lr-value
(node* l-key l-value l-left lr-left)
(node* key value lr-right right)))))
;;; smart constructor for after adding/removing a node
(define (T key value left right)
(let ((l-size (size left))
(r-size (size right)))
(cond ((< (+ l-size r-size) 2)
(node* key value left right))
((> r-size (* weight l-size))
(let ((r-left (node-left right))
(r-right (node-right right)))
(if (< (size r-left) (size r-right))
(rotate-left key value left right)
(rotate-left/double key value left right))))
((> l-size (* weight r-size))
(let ((l-left (node-left left))
(l-right (node-right left)))
(if (< (size l-right) (size l-left))
(rotate-right key value left right)
(rotate-right/double key value left right))))
(else
(node* key value left right)))))
(define (update tree key proc default <)
(define (add-to tree)
(if (empty? tree)
(make-node key (proc default) 1 (make-empty) (make-empty))
(let ((k (node-key tree))
(v (node-value tree))
(l (node-left tree))
(r (node-right tree)))
(cond ((< key k)
(T k v (add-to l) r))
((< k key)
(T k v l (add-to r)))
(else
(node* key (proc v) l r))))))
(add-to tree))
(define (add tree key value <)
(define (replace _) value)
(update tree key replace #f <))
(define (delete tree key <)
(define (delete-from tree)
(if (empty? tree)
tree
(let ((k (node-key tree))
(v (node-value tree))
(l (node-left tree))
(r (node-right tree)))
(cond ((< key k)
(T k v (delete-from l) r))
((< k key)
(T k v l (delete-from r)))
(else
(delete* l r))))))
(delete-from tree))
(define (delete* left right)
(cond ((empty? left) right)
((empty? right) left)
(else
(let-values (((k v) (min right)))
(T k v left (delete-min right))))))
(define (delete-min tree)
(cond ((empty? tree)
(assertion-violation 'delete-min
"Can't delete the minimum value of an empty tree"))
((empty? (node-left tree))
(node-right tree))
(else
(T (node-key tree)
(node-value tree)
(delete-min (node-left tree))
(node-right tree)))))
(define (concat3 key value left right lt)
(cond ((empty? left)
(add right key value lt))
((empty? right)
(add left key value lt))
((< (* weight (size left)) (size right))
(T (node-key right)
(node-value right)
(concat3 key value left (node-left right) lt)
(node-right right)))
((< (* weight (size right)) (size left))
(T (node-key left)
(node-value left)
(node-left left)
(concat3 key value (node-right left) right lt)))
(else
(node* key value left right))))
(define (split-lt tree key <)
(cond ((empty? tree) tree)
((< key (node-key tree))
(split-lt (node-left tree) key <))
((< (node-key tree) key)
(concat3 (node-key tree)
(node-value tree)
(node-left tree)
(split-lt (node-right tree) key <)
<))
(else (node-left tree))))
(define (split-gt tree key <)
(cond ((empty? tree) tree)
((< key (node-key tree))
(concat3 (node-key tree)
(node-value tree)
(split-gt (node-left tree) key <)
(node-right tree)
<))
((< (node-key tree) key)
(split-gt (node-right tree) key <))
(else (node-right tree))))
(define (difference tree1 tree2 <)
(cond ((empty? tree1) tree1)
((empty? tree2) tree1)
(else
(let ((l* (split-lt tree1 (node-key tree2) <))
(r* (split-gt tree1 (node-key tree2) <)))
(concat (difference l* (node-left tree2) <)
(difference r* (node-right tree2) <))))))
(define (concat left right)
(cond ((empty? left) right)
((empty? right) left)
((< (* weight (size left)) (size right))
(T (node-key right)
(node-value right)
(concat left (node-left right))
(node-right right)))
((< (* weight (size right)) (size left))
(T (node-key left)
(node-value left)
(node-left left)
(concat (node-right left) right)))
(else
(let-values (((k v) (min right)))
(T k v left (delete-min right))))))
(define (member key tree <)
(define (yes x) #t)
(define (no) #f)
(lookup tree key yes no <))
(define (intersection t1 t2 <)
(cond ((empty? t1) t1)
((empty? t2) t2)
(else
(let ((l* (split-lt t2 (node-key t1) <))
(r* (split-gt t2 (node-key t1) <)))
(if (member (node-key t1) t2 <)
(concat3 (node-key t1)
(node-value t1)
(intersection (node-left t1) l* <)
(intersection (node-right t1) r* <)
<)
(concat (intersection (node-left t1) l* <)
(intersection (node-right t1) r* <)))))))
;;; hedge union
;; ensures that tree is either empty, or root lies in range low--high
(define (trim low high tree <)
(cond ((empty? tree) tree)
((< low (node-key tree))
(if (< (node-key tree) high)
tree
(trim low high (node-left tree) <)))
(else
(trim low high (node-right tree) <))))
(define (uni-bd tree1 tree2 low high <)
(cond ((empty? tree2) tree1)
((empty? tree1)
(concat3 (node-key tree2)
(node-value tree2)
(split-gt (node-left tree2) low <)
(split-lt (node-right tree2) high <)
<))
(else
(let ((key (node-key tree1)))
(concat3 key
(node-value tree1)
(uni-bd (node-left tree1) (trim low key tree2 <) low key <)
(uni-bd (node-right tree1) (trim key high tree2 <) key high <)
<)))))
;; specialisation of trim for high=+infinity
(define (trim-low low tree <)
(cond ((empty? tree) tree)
((< low (node-key tree)) tree)
(else
(trim-low low (node-right tree) <))))
;; trim for low=-infinity
(define (trim-high high tree <)
(cond ((empty? tree) tree)
((< (node-key tree) high) tree)
(else
(trim-high high (node-left tree) <))))
;; uni-bd for low=-infinity
(define (uni-high tree1 tree2 high <)
(cond ((empty? tree2) tree1)
((empty? tree1)
(concat3 (node-key tree2)
(node-value tree2)
(node-left tree2)
(split-lt (node-right tree2) high <)
<))
(else
(let ((key (node-key tree1)))
(concat3 key
(node-value tree1)
(uni-high (node-left tree1) (trim-high key tree2 <) key <)
(uni-bd (node-right tree1) (trim key high tree2 <) key high <)
<)))))
;; uni-bd for high=+infinity
(define (uni-low tree1 tree2 low <)
(cond ((empty? tree2) tree1)
((empty? tree1)
(concat3 (node-key tree2)
(node-value tree2)
(split-gt (node-left tree2) low <)
(node-right tree2)
<))
(else
(let ((key (node-key tree1)))
(concat3 key
(node-value tree1)
(uni-bd (node-left tree1) (trim low key tree2 <) low key <)
(uni-low (node-right tree1) (trim-low key tree2 <) key <)
<)))))
(define (hedge-union tree1 tree2 <)
(cond ((empty? tree2) tree1)
((empty? tree1) tree2)
(else
(let ((key (node-key tree1)))
(concat3 key
(node-value tree1)
(uni-high (node-left tree1) (trim-high key tree2 <) key <)
(uni-low (node-right tree1) (trim-low key tree2 <) key <)
<)))))
;;; rank and indexing
(define (rank tree key <)
(cond ((empty? tree);; error
(assertion-violation 'rank "Key is not in the tree" key))
((< key (node-key tree))
(rank (node-left tree) key <))
((< (node-key tree) key)
(+ (rank (node-right tree) key <)
(size (node-left tree))
1))
(else
(size (node-left tree)))))
(define (index tree idx)
(if (empty? tree)
(assertion-violation 'index "No value at index" idx)
(let ((l-size (size (node-left tree))))
(cond ((< idx l-size)
(index (node-left tree) idx))
((< l-size idx)
(index (node-right tree)
(- idx l-size 1)))
(else
(values (node-key tree)
(node-value tree)))))))
;;; External procedures
(define (make-bbtree <)
(assert (procedure? <))
(%make-bbtree (make-empty) <))
(define (bbtree-size bbtree)
(assert (bbtree? bbtree))
(size (bbtree-tree bbtree)))
(define bbtree-ref
(let ((ref (lambda (bbtree key failure)
(assert (bbtree? bbtree))
(lookup (bbtree-tree bbtree)
key
node-value
failure
(bbtree-ordering-procedure bbtree)))))
(case-lambda
((bbtree key)
(define (fail)
(assertion-violation 'bbtree-ref "Key is not in the tree" key))
(ref bbtree key fail))
((bbtree key ret)
(ref bbtree key (lambda () ret))))))
(define (bbtree-set bbtree key value)
(assert (bbtree? bbtree))
(update-tree bbtree
(add (bbtree-tree bbtree)
key
value
(bbtree-ordering-procedure bbtree))))
(define (bbtree-update bbtree key proc default)
(assert (bbtree? bbtree))
(update-tree bbtree
(update (bbtree-tree bbtree)
key
proc
default
(bbtree-ordering-procedure bbtree))))
(define (bbtree-delete bbtree key)
(assert (bbtree? bbtree))
(update-tree bbtree
(delete (bbtree-tree bbtree)
key
(bbtree-ordering-procedure bbtree))))
(define (bbtree-contains? bbtree key)
(assert (bbtree? bbtree))
(lookup (bbtree-tree bbtree)
key
(lambda (_) #t)
(lambda () #f)
(bbtree-ordering-procedure bbtree)))
;; iterators
(define (traverse traverser base tree)
(define (left base)
(traverse traverser base (node-left tree)))
(define (right base)
(traverse traverser base (node-right tree)))
(if (empty? tree)
base
(traverser (node-key tree)
(node-value tree)
left
right
base)))
(define (bbtree-traverse traverser base bbtree)
(assert (bbtree? bbtree))
(traverse traverser base (bbtree-tree bbtree)))
(define (bbtree-fold combine base bbtree)
(assert (bbtree? bbtree))
(traverse (lambda (k v l r n)
(r (combine k v (l n))))
base
(bbtree-tree bbtree)))
(define (bbtree-fold-right combine base bbtree)
(assert (bbtree? bbtree))
(traverse (lambda (k v l r n)
(l (combine k v (r n))))
base
(bbtree-tree bbtree)))
;; I could do this more efficiently, but is it worth it?
(define (bbtree-map mapper bbtree)
(bbtree-fold (lambda (key value tree)
(bbtree-set tree key (mapper value)))
(make-bbtree (bbtree-ordering-procedure bbtree))
bbtree))
(define (alist-cons a b c)
(cons (cons a b) c))
(define (bbtree->alist bbtree)
(bbtree-fold-right alist-cons '() bbtree))
(define (alist->bbtree list <)
(fold-left (lambda (tree kv-pair)
(bbtree-set tree (car kv-pair) (cdr kv-pair)))
(make-bbtree <)
list))
(define (bbtree-keys bbtree)
(bbtree-fold-right (lambda (key value base)
(cons key base))
'()
bbtree))
(define (bbtree-union bbtree1 bbtree2)
(update-tree bbtree1
(hedge-union (bbtree-tree bbtree1)
(bbtree-tree bbtree2)
(bbtree-ordering-procedure bbtree1))))
(define (bbtree-difference bbtree1 bbtree2)
(update-tree bbtree1
(difference (bbtree-tree bbtree1)
(bbtree-tree bbtree2)
(bbtree-ordering-procedure bbtree1))))
(define (bbtree-intersection bbtree1 bbtree2)
(update-tree bbtree1
(intersection (bbtree-tree bbtree1)
(bbtree-tree bbtree2)
(bbtree-ordering-procedure bbtree1))))
(define (bbtree-index bbtree key)
;; maybe this should return #f instead of throwing an exception?
(assert (bbtree? bbtree))
(rank (bbtree-tree bbtree)
key
(bbtree-ordering-procedure bbtree)))
(define (bbtree-ref/index bbtree idx)
(assert (bbtree? bbtree))
(let ((tree (bbtree-tree bbtree)))
(unless (and (integer? idx)
(<= 0 idx (- (size tree) 1)))
(assertion-violation 'bbtree-ref/index
"Not a valid index into the bbtree"
idx))
(index tree idx)))
))
;;; deques.sls --- Purely functional deques
;; Copyright (C) 2011,2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;; Documentation:
;;
;; make-deque : () -> deque
;; returns a deque containing to items
;;
;; deque? : any -> boolean
;; tests if an object is a deque
;;
;; deque-length : deque -> non-negative integer
;; returns the number of items in the deque
;;
;; deque-empty? : deque -> boolean
;; returns true if there are no items in the deque, false otherwise
;;
;; enqueue-front : deque any -> deque
;; returns a new deque with the inserted item at the front
;;
;; enqueue-rear : deque any -> deque
;; returns a new deque with the inserted item at the rear
;;
;; dequeue-front : deque -> any queue
;; returns two values, the item at the front of the deque, and a new
;; deque containing all the other items
;; raises a &deque-empty condition if the deque is empty
;;
;; dequeue-rear : deque -> any queue
;; returns two values, the item at the rear of the deque, and a new
;; deque containing all the other items
;; raises a &deque-empty condition if the deque is empty
;;
;; deque-empty-condition? : object -> boolean
;; tests if an object is a &deque-empty condition
;;
;; deque->list : deque -> listof(any)
;; returns a list containing all the elements of the deque. The order
;; of the elements in the list is the same as the order they would be
;; dequeued from the front of the deque.
;;
;; list->deque : listof(any) -> deque
;; returns a deque containing all of the elements in the list. The
;; order of the elements in the deque is the same as the order of the
;; elements in the list.
;;
(library (pfds deques)
(export make-deque
deque?
deque-length
deque-empty?
enqueue-front
enqueue-rear
dequeue-front
dequeue-rear
deque-empty-condition?
deque->list
list->deque
)
(import (except (rnrs) cons*)
(pfds deques private condition)
(pfds private lazy-lists))
(define c 2)
(define (rot1 n l r)
(if (>= n c)
(cons* (head l)
(rot1 (- n c) (tail l) (drop c r)))
(rot2 l (drop n r) '())))
(define (rot2 l r a)
(if (empty? l)
(append* (rev r) a)
(cons* (head l)
(rot2 (tail l)
(drop c r)
(append* (rev (take c r)) a)))))
(define-record-type (deque %make-deque deque?)
(fields
(immutable length)
(immutable lenL)
(immutable lenR)
(immutable l)
(immutable r)
(immutable l^)
(immutable r^)))
(define (make-deque)
(%make-deque 0 0 0 '() '() '() '()))
(define (deque-empty? deque)
(zero? (deque-length deque)))
(define (enqueue-front deque item)
(let ((len (deque-length deque))
(l (deque-l deque))
(r (deque-r deque))
(lenL (deque-lenL deque))
(lenR (deque-lenR deque))
(l^ (deque-l^ deque))
(r^ (deque-r^ deque)))
(makedq (+ 1 len) (+ 1 lenL) lenR (cons* item l) r (tail l^) (tail r^))))
(define (enqueue-rear deque item)
(let ((len (deque-length deque))
(l (deque-l deque))
(r (deque-r deque))
(lenL (deque-lenL deque))
(lenR (deque-lenR deque))
(l^ (deque-l^ deque))
(r^ (deque-r^ deque)))
(makedq (+ 1 len) lenL (+ 1 lenR) l (cons* item r) (tail l^) (tail r^))))
(define (dequeue-front deque)
(when (deque-empty? deque)
(raise (condition
(make-deque-empty-condition)
(make-who-condition 'dequeue-front)
(make-message-condition "There are no elements to remove")
(make-irritants-condition (list deque)))))
(let ((len (deque-length deque))
(lenL (deque-lenL deque))
(lenR (deque-lenR deque))
(l (deque-l deque))
(r (deque-r deque))
(l^ (deque-l^ deque))
(r^ (deque-r^ deque)))
(if (empty? l)
(values (head r) (make-deque))
(values (head l)
(makedq (- len 1)
(- lenL 1)
lenR
(tail l)
r
(tail (tail l^))
(tail (tail r^)))))))
(define (dequeue-rear deque)
(when (deque-empty? deque)
(raise (condition
(make-deque-empty-condition)
(make-who-condition 'dequeue-rear)
(make-message-condition "There are no elements to remove")
(make-irritants-condition (list deque)))))
(let ((len (deque-length deque))
(lenL (deque-lenL deque))
(lenR (deque-lenR deque))
(l (deque-l deque))
(r (deque-r deque))
(l^ (deque-l^ deque))
(r^ (deque-r^ deque)))
(if (empty? r)
(values (head l) (make-deque))
(values (head r)
(makedq (- len 1)
lenL
(- lenR 1)
l
(tail r)
(tail (tail l^))
(tail (tail r^)))))))
(define (makedq len lenL lenR l r l^ r^)
(cond ((> lenL (+ 1 (* c lenR)))
(let* ((n (floor (/ (+ lenL lenR) 2)))
(l* (take n l))
(r* (rot1 n r l)))
(%make-deque len n (- len n) l* r* l* r*)))
((> lenR (+ 1 (* c lenL)))
(let* ((n (floor (/ (+ lenL lenR) 2)))
(l* (rot1 n l r))
(r* (take n r)))
(%make-deque len (- len n) n l* r* l* r*)))
(else
(%make-deque len lenL lenR l r l^ r^))))
(define (list->deque l)
(fold-left enqueue-rear (make-deque) l))
(define (deque->list deq)
(define (recur deq l)
(if (deque-empty? deq)
l
(let-values ([(last deq*) (dequeue-rear deq)])
(recur deq* (cons last l)))))
(recur deq '()))
)
;;; dlists.sls --- Difference Lists
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Commentary:
;;
;; Repeatedly appending to a list is a common, if inefficient pattern
;; in functional programs. Usually the trick we use is to build up the
;; list in reverse, and then to reverse it as the last action of a
;; function.
;;
;; Dlists are a representation of lists as functions that provide for
;; constant time append to either the front or end of a dlist that may
;; be used instead.
;;; Documentation:
;;
;; dlist : any ... -> dlist
;; returns a dlist containing all its arguments.
;;
;; dlist? : any -> boolean
;; returns #t if its argument is a dlist, #f otherwise.
;;
;; dlist-cons : any dlist -> dlist
;; returns a new dlist created by prepending the element to the head
;; of the dlist argument.
;;
;; dlist-snoc : dlist any -> dlist
;; returns a new dlist created by appending the element to the tail of
;; the dlist argument.
;;
;; dlist-append : dlist dlist -> dlist
;; returns a new dlist consisting of all the elements of the first
;; dlist, followed by all the items of the second dlist.
;;
;; dlist->list : dlist -> listof(any)
;; returns a list consisting of all the elements of the dlist.
;;
;; list->dlist : listof(any) -> dlist
;; returns a dlist consisting of all the elements of the list.
(library (pfds dlists)
(export (rename (%dlist dlist))
dlist?
dlist-cons
dlist-snoc
dlist-append
dlist->list
list->dlist
)
(import (rnrs))
(define-record-type dlist
(fields
(immutable proc undl)))
(define (%dlist . args)
(list->dlist args))
(define (compose f g)
(lambda (x)
(f (g x))))
(define (singleton x)
(list->dlist (list x)))
(define (dlist-append dl1 dl2)
(make-dlist (compose (undl dl1) (undl dl2))))
(define (dlist-cons element dlist)
(dlist-append (singleton element) dlist))
(define (dlist-snoc dlist element)
(dlist-append dlist (singleton element)))
(define (dlist->list dlist)
((undl dlist) '()))
(define (list->dlist list)
(make-dlist
(lambda (rest)
(append list rest))))
)
;;; fingertrees.sls --- A Simple General-Purpose Data Structure
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Commentary:
;;
;; Fingertrees are a generalised form of deque, that you can parameterise
;; to compute a value, called the "measure" of a fingertree. This measure
;; will be updated incrementally as you add and remove elements from the
;; fingertree. Among other things, this allows fingertrees to be used
;; where you otherwise might have written a custom data structure.
;;
;; To compute the measure, fingertrees require pieces of information: a
;; converter, a combiner, and an identity.
;;
;; The converter is a procedure of one argument, that maps values in the
;; fingertree to other values which are used for computing the measure.
;;
;; The combiner is a procedure of two arguments, and combines these into
;; one value representing them both. A combiner must be associative
;; i.e. (combine A (combine B C)) must be equivalent to (combine (combine
;; A B) C) for all values A, B and C.
;;
;; An identity is a value that represents the measure of an empty
;; fingertree. It must obey the rule that (combine X identity), (combine
;; identity X) and X are always the same.
;;
;; To make things more concrete, a simple use of a fingertree is as a
;; deque that keeps a running total. In this case, the converter can
;; simply be the function (lambda (x) x) if it is a deque of integers,
;; the combiner would be +, and the identity 0.
;;
;; (define l '(3 1 4 1 5 9))
;;
;; (define ft (list->fingertree l 0 + (lambda (x) x)))
;;
;; (fingertree-measure ft)
;; ; => 23
;; (fingertree-measure (fingertree-snoc ft 2))
;; ; => 25
;; (let-values (((head tail) (fingertree-uncons ft)))
;; (fingertree-measure tail))
;; ; => 20
;;
;; Mathematically speaking, the _return type_ of the converter, the
;; combiner and the identity element are expected to form a
;; monoid.
;;
;; Below, I use the slightly incorrect terminology of referring to the
;; combiner, the converter, and the identity, together as a
;; monoid. Mathematicians, please forgive me. Programmers please forgive
;; me even more. If you can provide a better name (from a programmers,
;; not a mathematicians, point of view) that works in most circumstances,
;; I will be happy to use it.
;;
;; (FWIW the Haskell Data.Fingertree package uses odd name of Measured
;; (which are expected to be instances of Monoid))
;;
;; fingertree? : any -> bool
;; returns #t if argument is a fingertree, #f otherwise.
;;
;; fingertree-empty? : fingertree -> bool
;; returns #t if there are no items in the fingertree, #f otherwise.
;;
;; make-fingertree : id combine measure -> fingertree
;; returns a new fingertree, parameterised by the given monoid.
;;
;; fingertree-cons : any fingertree -> fingertree
;; returns the new fingertree created by adding the element to the front
;; of the argument fingertree.
;;
;; fingertree-snoc : fingertree any -> fingertree
;; returns the new fingertree created by adding the element to the end of
;; the fingertree.
;;
;; fingertree-uncons : fingertree -> any + fingertree
;; returns two values: the element at the front of the fingertree, and a
;; new fingertree containing all but the front element. If the fingertree
;; is empty, a &fingertree-empty condition is raised.
;;
;; fingertree-unsnoc : fingertree -> fingertree + any
;; returns two values: a new fingertree containing all but the rear
;; element of the argument fingertree, and the rear element itself. If
;; the fingertree is empty, a &fingertree-empty-condition is raised.
;;
;; fingertree-append : fingertree fingertree -> fingertree
;; returns a new fingertree which contains all of the elements of the
;; first fingertree argument, followed by all the elements of the
;; second. The argument fingertrees are assumed to be parameterised by
;; the same monoid.
;;
;; list->fingertree : (list->fingertree l id append convert)
;; returns a fingertree containing all of the elements of the argument
;; list, in the same order.
;;
;; fingertree->list : fingertree -> Listof(Any)
;; returns a list of all the elements in the fingertree, in the order
;; they would be unconsed.
;;
;; fingertree-measure : fingertree -> any
;; returns the measure of the fingertree, as defined by the fingertree's
;; monoid.
;;
;; fingertree-split : (any -> bool) fingertree -> fingertree + fingertree
;; returns two values: the first is the largest prefix of the fingertree for
;; which applying the predicate to it's accumulated measure returns
;; #f. The second values is a fingertree containing all those elements
;; not in the first fingertree.
;;
;; fingertree-split3: (any -> bool) fingertree -> fingertree + value + fingertree
;; similar to fingertree-split, however, instead of returning the
;; remainder as the second argument, it returns the head of the remainder
;; as the second argument, and tail of the remainder as the third
;; argument.
;; TODO: what error should I give if the remainder was empty?
;;
;; fingertree-fold : (any -> any -> any) any fingertree
;; returns the value obtained by iterating the combiner procedure over
;; the fingertree in left-to-right order. This procedure takes two
;; arguments, the current value from the fingertree, and an accumulator,
;; and it's return value is used as the accumulator for the next
;; iteration. The initial value for the accumulator is given by the base
;; argument.
;;
;; fingertree-fold-right : (any -> any -> any) any fingertree
;; similar to fingertree-fold, but iterates in right-to-left order.
;;
;; fingertree-reverse : fingertree -> fingertree
;; returns a new fingertree in which the elements are in the opposite
;; order from the argument fingertree.
;;
;; fingertree-empty-condition? : condition -> bool
;; returns #t if the argument is a &fingertree-empty condition, #f otherwise.
;;
(library (pfds fingertrees)
(export fingertree?
fingertree-empty?
make-fingertree
fingertree-cons
fingertree-snoc
fingertree-uncons
fingertree-unsnoc
fingertree-append
list->fingertree
fingertree->list
fingertree-measure
fingertree-split
fingertree-split3
fingertree-fold
fingertree-fold-right
fingertree-reverse
fingertree-empty-condition?
)
(import (rnrs))
;;; List helpers
(define (snoc l val)
(append l (list val)))
(define (take l n)
(if (or (null? l) (zero? n))
'()
(cons (car l)
(take (cdr l) (- n 1)))))
(define (last list)
(if (null? (cdr list))
(car list)
(last (cdr list))))
(define (but-last list)
(if (null? (cdr list))
'()
(cons (car list)
(but-last (cdr list)))))
(define (map-reverse f l)
(fold-left (lambda (o n) (cons (f n) o)) '() l))
;;; Node type
(define-record-type node2
(protocol
(lambda (new)
(lambda (monoid a b)
(define app (mappend monoid))
(new (app (measure-nodetree a monoid)
(measure-nodetree b monoid))
a
b))))
(fields measure a b))
(define-record-type node3
(protocol
(lambda (new)
(lambda (monoid a b c)
(define app (mappend monoid))
(new (app (app (measure-nodetree a monoid)
(measure-nodetree b monoid))
(measure-nodetree c monoid))
a
b
c))))
(fields measure a b c))
(define (node-case node k2 k3)
(if (node2? node)
(k2 (node2-a node) (node2-b node))
(k3 (node3-a node) (node3-b node) (node3-c node))))
(define (node-fold-right f base node)
(node-case node
(lambda (a b)
(f a (f b base)))
(lambda (a b c)
(f a (f b (f c base))))))
(define (node->list node)
(node-fold-right cons '() node))
(define (nodetree-fold-right f base nodetree)
(define (foldr node base)
(cond ((node2? node)
(foldr (node2-a node)
(foldr (node2-b node) base)))
((node3? node)
(foldr (node3-a node)
(foldr (node3-b node)
(foldr (node3-c node) base))))
(else (f node base))))
(foldr nodetree base))
(define (nodetree-fold-left f base nodetree)
(define (foldl node base)
(cond ((node2? node)
(foldl (node2-b node)
(foldl (node2-a node) base)))
((node3? node)
(foldl (node3-c node)
(foldl (node3-b node)
(foldl (node3-a node) base))))
(else (f node base))))
(foldl nodetree base))
;;; Tree type
(define-record-type empty)
(define-record-type single
(fields value))
(define-record-type rib
(protocol
(lambda (new)
(lambda (monoid left middle right)
(define app (mappend monoid))
(new (app (app (measure-digit left monoid)
(measure-ftree middle monoid))
(measure-digit right monoid))
left
middle
right)
)))
;; left and right expected to be lists of length 0 < l < 5
(fields measure left middle right))
(define (ftree-case ftree empty-k single-k rib-k)
(cond ((empty? ftree) (empty-k))
((single? ftree)
(single-k (single-value ftree)))
(else
(rib-k (rib-left ftree)
(rib-middle ftree)
(rib-right ftree)))))
(define (digits-fold-right f b d)
(fold-right (lambda (ntree base)
(nodetree-fold-right f base ntree))
b
d))
(define (digits-fold-left f b d)
(fold-left (lambda (base ntree)
(nodetree-fold-left f base ntree))
b
d))
(define (ftree-fold-right proc base ftree)
(ftree-case ftree
(lambda () base)
(lambda (x) (nodetree-fold-right proc base x))
(lambda (l x r)
(define base* (digits-fold-right proc base r))
(define base** (ftree-fold-right proc base* x))
(digits-fold-right proc base** l))))
(define (ftree-fold-left proc base ftree)
(ftree-case ftree
(lambda () base)
(lambda (x) (nodetree-fold-left proc base x))
(lambda (l x r)
(define base* (digits-fold-left proc base l))
(define base** (ftree-fold-left proc base* x))
(digits-fold-left proc base** r))))
(define (insert-front ftree val monoid)
(ftree-case ftree
(lambda ()
(make-single val))
(lambda (a)
(make-rib monoid (list val) (make-empty) (list a)))
(lambda (l m r)
(if (= (length l) 4)
(make-rib monoid
(list val (car l))
(insert-front m (apply make-node3 monoid (cdr l)) monoid)
r)
(make-rib monoid (cons val l) m r)))))
(define (view-front ftree empty-k cons-k monoid)
(ftree-case ftree
empty-k
(lambda (a)
(cons-k a (make-empty)))
(lambda (l r m)
(cons-k (car l)
(rib-l (cdr l) r m monoid)))))
(define (list->tree l monoid)
(fold-right (lambda (val tree)
(insert-front tree val monoid))
(make-empty)
l))
(define (rib-l l m r monoid)
(if (null? l)
(view-front m
(lambda ()
(list->tree r monoid))
(lambda (x xs)
(make-rib monoid
(node->list x)
xs
r))
monoid)
(make-rib monoid l m r)))
(define (remove-front ftree monoid)
(view-front ftree
(lambda ()
(error 'remove-front "can't remove from an empty tree"))
values
monoid))
(define (insert-rear ftree val monoid)
(ftree-case ftree
(lambda ()
(make-single val))
(lambda (a)
(make-rib monoid (list a) (make-empty) (list val)))
(lambda (l m r)
;; TODO: should r be maintained in reverse order, rather than
;; normal?
;; yes! it will make concatenation slightly slower, but will
;; speed up inserts and removals
(if (= (length r) 4)
(make-rib monoid
l
(insert-rear m (apply make-node3 monoid (take r 3)) monoid)
(list (list-ref r 3) val))
(make-rib monoid l m (snoc r val))))))
(define (remove-rear ftree monoid)
(view-rear ftree
(lambda ()
(error 'remove-rear "can't remove from an empty tree"))
values
monoid))
(define (view-rear ftree empty-k snoc-k monoid)
(ftree-case ftree
empty-k
(lambda (a)
(snoc-k (make-empty) a))
(lambda (l r m)
(snoc-k (rib-r l r (but-last m) monoid)
(last m)))))
(define (rib-r l m r monoid)
(if (null? r)
(view-rear m
(lambda ()
(list->tree l monoid))
(lambda (m* r*)
(make-rib monoid l m* (node->list r*)))
monoid)
(make-rib monoid l m r)))
(define (insert-front/list tree l monoid)
(fold-right (lambda (val tree)
(insert-front tree val monoid))
tree
l))
(define (insert-rear/list tree l monoid)
(fold-left (lambda (tree val)
(insert-rear tree val monoid))
tree
l))
(define (app3 ftree1 ts ftree2 monoid)
(cond ((empty? ftree1)
(insert-front/list ftree2 ts monoid))
((empty? ftree2)
(insert-rear/list ftree1 ts monoid))
((single? ftree1)
(insert-front (insert-front/list ftree2 ts monoid)
(single-value ftree1)
monoid))
((single? ftree2)
(insert-rear (insert-rear/list ftree1 ts monoid)
(single-value ftree2)
monoid))
(else
(let ((l1 (rib-left ftree1))
(m1 (rib-middle ftree1))
(r1 (rib-right ftree1))
(l2 (rib-left ftree2))
(m2 (rib-middle ftree2))
(r2 (rib-right ftree2)))
(make-rib monoid
l1
(app3 m1
(nodes (append r1 ts l2) monoid)
m2
monoid)
r2)))))
(define (nodes lst monoid)
;; *sigh*
(let ((a (car lst))
(b (cadr lst)))
(cond ((null? (cddr lst))
(list (make-node2 monoid a b)))
((null? (cdddr lst))
(list (make-node3 monoid a b (caddr lst))))
((null? (cddddr lst))
(list (make-node2 monoid a b)
(make-node2 monoid (caddr lst) (cadddr lst))))
(else
(cons (make-node3 monoid a b (caddr lst))
(nodes (cdddr lst) monoid))))))
(define (reverse-tree tree monoid)
(ftree-case tree
(lambda () (make-empty))
(lambda (x) (make-single (reverse-nodetree x monoid)))
(lambda (l x r)
(make-rib monoid
(reverse-digit r monoid)
(reverse-tree x monoid)
(reverse-digit l monoid)))))
(define (reverse-digit l monoid)
(map-reverse (lambda (a) (reverse-nodetree a monoid)) l))
(define (reverse-nodetree l monoid)
(cond ((node2? l)
(make-node2 monoid
(reverse-nodetree (node2-b l) monoid)
(reverse-nodetree (node2-a l) monoid)))
((node3? l)
(make-node3 monoid
(reverse-nodetree (node3-c l) monoid)
(reverse-nodetree (node3-b l) monoid)
(reverse-nodetree (node3-a l) monoid)))
(else l)))
;; generalising fingertrees with monoids
;; I think I'm going to need a "configuration" type and pass it around
;; in order to generalize over arbitrary monoids
;; call the type iMeasured or something
(define-record-type monoid*
;; a monoid, but augmented with a procedure to convert objects into the
;; monoid type
(fields (immutable empty mempty)
(immutable append mappend)
(immutable convert mconvert)))
(define (measure-digit obj monoid)
(fold-left (lambda (i a)
((mappend monoid) i (measure-nodetree a monoid)))
(mempty monoid)
obj))
(define (measure-ftree obj monoid)
(cond ((empty? obj)
(mempty monoid))
((single? obj)
(measure-nodetree (single-value obj) monoid))
(else
(rib-measure obj))))
(define (measure-nodetree obj monoid)
(cond ((node2? obj) (node2-measure obj))
((node3? obj) (node3-measure obj))
(else ((mconvert monoid) obj))))
(define (split proc tree monoid)
(if (empty? tree)
(values (make-empty) (make-empty))
(if (proc (measure-ftree tree monoid))
(let-values (((l x r) (split-tree proc (mempty monoid) tree monoid)))
(values l (insert-front r x monoid)))
(values tree (make-empty)))))
(define (split-tree proc i tree monoid)
(ftree-case tree
(lambda ()
(error 'split-tree "shouldn't happen?"))
(lambda (a)
(values (make-empty) a (make-empty)))
(lambda (l m r)
(define app (mappend monoid))
(define vpr (app i (measure-digit l monoid)))
(define vm (app vpr (measure-ftree m monoid)))
(cond ((proc vpr)
(let-values (((l* x* r*) (split-digit proc i l monoid)))
(values (list->tree l* monoid)
x*
(rib-l r* m r monoid))))
((proc vm)
(let*-values (((ml xs mr) (split-tree proc vpr m monoid))
((l* x* r*)
(split-digit proc
(app vpr (measure-ftree ml monoid))
(node->list xs)
monoid)))
(values (rib-r l ml l* monoid)
x*
(rib-l r* mr r monoid))))
(else
(let-values (((l* x* r*) (split-digit proc vm r monoid)))
(values (rib-r l m l* monoid)
x*
(list->tree r* monoid))))))))
(define (split-digit proc i xs monoid)
(if (null? (cdr xs))
(values '() (car xs) '())
(let ((i* ((mappend monoid) i (measure-nodetree (car xs) monoid))))
(if (proc i*)
(values '() (car xs) (cdr xs))
(let-values (((l x r)
(split-digit proc i* (cdr xs) monoid)))
(values (cons (car xs) l) x r))))))
;; exported interface
(define-condition-type &fingertree-empty
&assertion
make-fingertree-empty-condition
fingertree-empty-condition?)
(define-record-type (fingertree %make-fingertree fingertree?)
(fields tree monoid))
(define (%wrap fingertree tree)
(%make-fingertree tree
(fingertree-monoid fingertree)))
(define (make-fingertree id append convert)
(%make-fingertree (make-empty)
(make-monoid* id append convert)))
(define (fingertree-cons a fingertree)
;; TODO: should it obey normal cons interface, or have fingertree
;; first?
(%wrap fingertree
(insert-front (fingertree-tree fingertree)
a
(fingertree-monoid fingertree))))
(define (fingertree-snoc fingertree a)
(%wrap fingertree
(insert-rear (fingertree-tree fingertree)
a
(fingertree-monoid fingertree))))
(define (fingertree-uncons fingertree)
(call-with-values
(lambda ()
(define t (fingertree-tree fingertree))
(when (empty? t)
(raise
(condition
(make-fingertree-empty-condition)
(make-who-condition 'fingertree-uncons)
(make-message-condition "There are no elements to uncons")
(make-irritants-condition (list fingertree)))))
(remove-front t (fingertree-monoid fingertree)))
(lambda (val rest)
(values val
(%wrap fingertree rest)))))
(define (fingertree-unsnoc fingertree)
(call-with-values
(lambda ()
(define t (fingertree-tree fingertree))
(when (empty? t)
(raise
(condition
(make-fingertree-empty-condition)
(make-who-condition 'fingertree-unsnoc)
(make-message-condition "There are no elements to unsnoc")
(make-irritants-condition (list fingertree)))))
(remove-rear t (fingertree-monoid fingertree)))
(lambda (rest val)
(values (%wrap fingertree rest) val))))
(define (fingertree-empty? fingertree)
(empty? (fingertree-tree fingertree)))
(define (fingertree-append fingertree1 fingertree2)
(%wrap fingertree1
(app3 (fingertree-tree fingertree1)
'()
(fingertree-tree fingertree2)
(fingertree-monoid fingertree1))))
;; TODO: fix this
(define (list->fingertree l id append convert)
(define monoid (make-monoid* id append convert))
(%make-fingertree (list->tree l monoid) monoid))
(define (fingertree->list t)
(fingertree-fold-right cons '() t))
(define (fingertree-measure fingertree)
(measure-ftree (fingertree-tree fingertree)
(fingertree-monoid fingertree)))
(define (fingertree-split p fingertree)
(call-with-values
(lambda ()
(split p
(fingertree-tree fingertree)
(fingertree-monoid fingertree)))
(lambda (a b)
(values (%wrap fingertree a)
(%wrap fingertree b)))))
(define (fingertree-split3 p fingertree)
(call-with-values
(lambda ()
(define monoid (fingertree-monoid fingertree))
(split-tree p
(mempty monoid)
(fingertree-tree fingertree)
monoid))
(lambda (a b c)
(values (%wrap fingertree a)
b
(%wrap fingertree c)))))
(define (fingertree-fold f b fingertree)
(ftree-fold-left f b (fingertree-tree fingertree)))
(define (fingertree-fold-right f b fingertree)
(ftree-fold-right f b (fingertree-tree fingertree)))
(define (fingertree-reverse fingertree)
(%wrap fingertree
(reverse-tree (fingertree-tree fingertree)
(fingertree-monoid fingertree))))
)
;;; hamts.sls --- Hash Array Mapped Tries
;; Copyright (C) 2014 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;; Documentation:
;;
;; Note: For all procedures which take a key as an argument, the key
;; must be hashable with the hamt hash function, and comparable with
;; the hamt equivalence predicate.
;;
;; make-hamt : (any -> non-negative integer) (any -> any -> boolean) -> hamt
;; returns a new empty hamt using the given hash and equivalence functions.
;;
;; hamt? : any -> boolean
;; returns #t if argument is a hamt, #f otherwise.
;;
;; hamt-size : hamt -> non-negative integer
;; returns the number of associations in the hamt.
;;
;; hamt-ref : hamt any [any] -> any
;; returns the value associated with the key in the hamt. If there is
;; no value associated with the key, it returns the default value if
;; provided, or raises an &assertion-violation if it isn't.
;;
;; hamt-contains? : hamt any -> boolean
;; returns #t if there is an association for the key in the hamt, #f
;; otherwise.
;;
;; hamt-set : hamt any any -> hamt
;; returns a new hamt with the key associated to the value. If the key
;; is already associated with a value, it is replaced.
;;
;; hamt-update : hamt any (any -> any) any -> hamt
;; returns a new hamt with the valued associated with the key updated
;; by the update procedure. If the hamt does not already have a value
;; associated with the key, then it applies the update procedure to
;; the default value, and associates the key with that.
;;
;; hamt-delete : hamt any -> hamt
;; returns a hamt with the key and its associated value removed. If
;; the key is not in the hamt, a copy of the original hamt is
;; returned.
;;
;; hamt-fold : (any any any -> any) any hamt -> hamt
;; returns the value obtained by iterating the combine procedure over
;; each key value pair in the hamt. The combine procedure takes three
;; arguments, the key and value of an association, and an accumulator,
;; and returns a new accumulator value. The initial value of the
;; accumulator is provided by the base argument. The order in which
;; the hamt is traversed is not guaranteed.
;;
;; hamt-map : (any -> any) hamt -> hamt
;; returns the hamt obtained by applying the update procedure to each
;; of the values in the hamt.
;;
;; hamt->alist : hamt -> Listof(Pairs)
;; returns the key/value associations of the hamt as a list of pairs.
;; The order of the list is not guaranteed.
;;
;; alist->hamt : Listof(Pairs) (any -> non-negative integer) (any -> any -> boolean) -> hamt
;; returns the hamt containing the associations specified by the pairs
;; in the alist. If the same key appears in the alist multiple times,
;; its leftmost value is the one that is used.
;;
;; hamt-equivalence-predicate : hamt -> (any -> any -> boolean)
;; returns the procedure used internally by the hamt to compare keys.
;;
;; hamt-hash-function : hamt -> (any -> non-negative integer)
;; returns the hash procedure used internally by the hamt.
;;
(library (pfds hamts)
(export make-hamt
hamt?
hamt-size
hamt-ref
hamt-set
hamt-update
hamt-delete
hamt-contains?
hamt-equivalence-predicate
hamt-hash-function
hamt-fold
hamt-map
hamt->alist
alist->hamt
)
(import (rnrs)
(pfds private vectors)
(pfds private alists)
(pfds private bitwise))
;;; Helpers
(define cardinality 32) ; 64
(define (mask key level)
(bitwise-arithmetic-shift-right (bitwise-and key (- (expt 2 5) 1)) level))
(define (level-up level)
(+ level 5))
(define (ctpop key index)
(bitwise-bit-count (bitwise-arithmetic-shift-right key (+ 1 index))))
;;; Node types
(define-record-type (subtrie %make-subtrie subtrie?)
(fields size bitmap vector))
(define (make-subtrie bitmap vector)
(define vecsize
(vector-fold (lambda (val accum)
(+ (size val) accum))
0
vector))
(%make-subtrie vecsize bitmap vector))
(define-record-type leaf
(fields key value))
(define-record-type (collision %make-collision collision?)
(fields size hash alist))
(define (make-collision hash alist)
(%make-collision (length alist) hash alist))
;;; Main
(define (lookup vector key default hash eqv?)
(define (handle-subtrie node level)
(define bitmap (subtrie-bitmap node))
(define vector (subtrie-vector node))
(define index (mask h level))
(if (not (bitwise-bit-set? bitmap index))
default
(let ((node (vector-ref vector (ctpop bitmap index))))
(cond ((leaf? node)
(handle-leaf node))
((collision? node)
(handle-collision node))
(else
(handle-subtrie node (level-up level)))))))
(define (handle-leaf node)
(if (eqv? key (leaf-key node))
(leaf-value node)
default))
(define (handle-collision node)
(alist-ref (collision-alist node) key default eqv?))
(define h (hash key))
(define node (vector-ref vector (mask h 0)))
(cond ((not node) default)
((leaf? node) (handle-leaf node))
((collision? node) (handle-collision node))
(else
(handle-subtrie node (level-up 0)))))
(define (insert hvector key update base hash eqv?)
(define (handle-subtrie subtrie level)
(define bitmap (subtrie-bitmap subtrie))
(define vector (subtrie-vector subtrie))
(define index (mask h level))
(define (fixup node)
(make-subtrie bitmap (vector-set vector index node)))
(if (not (bitwise-bit-set? bitmap index))
(make-subtrie (bitwise-bit-set bitmap index)
(vector-insert vector
(ctpop bitmap index)
(make-leaf key (update base))))
(let ((node (vector-ref vector (ctpop bitmap index))))
(cond ((leaf? node)
(fixup (handle-leaf node level)))
((collision? node)
(fixup (handle-collision node level)))
(else
(fixup (handle-subtrie node (level-up level))))))))
(define (handle-leaf node level)
(define lkey (leaf-key node))
(define khash (bitwise-arithmetic-shift-right h level))
(define lhash (bitwise-arithmetic-shift-right (hash lkey) level))
(cond ((eqv? key lkey)
(make-leaf key (update (leaf-value node))))
((equal? khash lhash)
(make-collision lhash
(list (cons lkey (leaf-value node))
(cons key (update base)))))
(else
(handle-subtrie (wrap-subtrie node lhash) (level-up level)))))
(define (handle-collision node level)
(define khash (bitwise-arithmetic-shift-right h level))
(define chash (bitwise-arithmetic-shift-right (collision-hash node) level))
(if (equal? khash chash)
(make-collision (collision-hash node)
(alist-update (collision-alist node) key update base eqv?))
;; TODO: there may be a better (more efficient) way to do this
;; but simple is better for now (see also handle-leaf)
(handle-subtrie (wrap-subtrie node chash) (level-up level))))
(define (wrap-subtrie node chash)
(make-subtrie (bitwise-bit-set 0 (mask chash 0)) (vector node)))
(define h (hash key))
(define idx (mask h 0))
(define node (vector-ref hvector idx))
(define initial-level (level-up 0))
(cond ((not node)
(vector-set hvector idx (make-leaf key (update base))))
((leaf? node)
(vector-set hvector idx (handle-leaf node initial-level)))
((collision? node)
(vector-set hvector idx (handle-collision node initial-level)))
(else
(vector-set hvector idx (handle-subtrie node initial-level)))))
(define (delete vector key hash eqv?)
(define (handle-subtrie subtrie level)
(define bitmap (subtrie-bitmap subtrie))
(define vector (subtrie-vector subtrie))
(define index (mask h level))
(define (fixup node)
(update bitmap vector index node))
(if (not (bitwise-bit-set? bitmap index))
subtrie
(let ((node (vector-ref vector (ctpop bitmap index))))
(cond ((leaf? node)
(fixup (handle-leaf node)))
((collision? node)
(fixup (handle-collision node)))
(else
(fixup (handle-subtrie node (level-up level))))))))
(define (update bitmap vector index value)
(if value
(make-subtrie bitmap (vector-set vector index value))
(let ((vector* (vector-remove vector index)))
(if (equal? '#() vector)
#f
(make-subtrie (bitwise-bit-unset bitmap index)
vector*)))))
(define (handle-leaf node)
(if (eqv? key (leaf-key node))
#f
node))
(define (handle-collision node)
(let ((al (alist-delete (collision-alist node) key eqv?)))
(cond ((null? (cdr al))
(make-leaf (car (car al)) (cdr (car al))))
(else
(make-collision (collision-hash node) al)))))
(define h (hash key))
(define idx (mask h 0))
(define node (vector-ref vector idx))
(cond ((not node) vector)
((leaf? node)
(vector-set vector idx (handle-leaf node)))
((collision? node)
(vector-set vector idx (handle-collision node)))
(else
(vector-set vector idx (handle-subtrie node (level-up 0))))))
(define (vec-map mapper vector)
(define (handle-subtrie trie)
(make-subtrie (subtrie-bitmap trie)
(vector-map dispatch (subtrie-vector vector))))
(define (handle-leaf leaf)
(make-leaf (leaf-key leaf)
(mapper (leaf-value leaf))))
(define (handle-collision collision)
(make-collision (collision-hash collision)
(map (lambda (pair)
(cons (car pair) (mapper (cdr pair))))
(collision-alist collision))))
(define (dispatch val)
(cond ((leaf? val)
(handle-leaf val))
((collision? val)
(handle-collision val))
(else
(handle-subtrie val))))
(vector-map (lambda (val)
;; top can have #f values
(and val (dispatch val)))
vector))
(define (fold combine initial vector)
(define (handle-subtrie trie accum)
(vector-fold dispatch accum (subtrie-vector vector)))
(define (handle-leaf leaf accum)
(combine (leaf-key leaf) (leaf-value leaf) accum))
(define (handle-collision collision accum)
(fold-right (lambda (pair acc)
(combine (car pair) (cdr pair) acc))
accum
(collision-alist collision)))
(define (dispatch val accum)
(cond ((leaf? val)
(handle-leaf val accum))
((collision? val)
(handle-collision val accum))
(else
(handle-subtrie val accum))))
(vector-fold (lambda (val accum)
;; top level can have false values
(if (not val) accum (dispatch val accum)))
initial
vector))
(define (size node)
(cond ((not node) 0)
((leaf? node) 1)
((collision? node) (collision-size node))
(else (subtrie-size node))))
;;; Exported Interface
(define-record-type (hamt %make-hamt hamt?)
(fields size root hash-function equivalence-predicate))
(define (wrap-root root hamt)
(define vecsize
(vector-fold (lambda (val accum)
(+ (size val) accum))
0
root))
(%make-hamt vecsize
root
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))
(define (make-hamt hash eqv?)
(%make-hamt 0 (make-vector cardinality #f) hash eqv?))
(define hamt-ref
(case-lambda
((hamt key)
(define token (cons #f #f))
(define return-val (hamt-ref hamt key token))
(when (eqv? token return-val)
(assertion-violation 'hamt-ref "Key is not in the hamt" key))
return-val)
((hamt key default)
;; assert hamt?
(lookup (hamt-root hamt)
key
default
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))))
(define (hamt-set hamt key value)
(define root
(insert (hamt-root hamt)
key
(lambda (old) value)
'dummy
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))
(wrap-root root hamt))
(define (hamt-update hamt key proc default)
(define root
(insert (hamt-root hamt)
key
proc
default
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))
(wrap-root root hamt))
(define (hamt-delete hamt key)
(define root
(delete (hamt-root hamt)
key
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))
(wrap-root root hamt))
(define (hamt-contains? hamt key)
(define token (cons #f #f))
(if (eqv? token (hamt-ref hamt key token))
#f
#t))
(define (hamt-map mapper hamt)
(%make-hamt (hamt-size hamt)
(vec-map mapper (hamt-root hamt))
(hamt-hash-function hamt)
(hamt-equivalence-predicate hamt)))
(define (hamt-fold combine initial hamt)
(fold combine initial (hamt-root hamt)))
(define (hamt->alist hamt)
(hamt-fold (lambda (key value accumulator)
(cons (cons key value) accumulator))
'()
hamt))
(define (alist->hamt alist hash eqv?)
(fold-right (lambda (kv-pair hamt)
(hamt-set hamt (car kv-pair) (cdr kv-pair)))
(make-hamt hash eqv?)
alist))
)
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;; Documentation:
;;
;; make-heap : (any any -> bool) -> heap
;; returns a new empty heap which uses the ordering procedure.
;;
;; heap : (any any -> bool) any ... -> heap
;; return a new heap, ordered by the procedure argument, that contains
;; all the other arguments as elements.
;;
;; heap? : any -> bool
;; returns #t if the argument is a heap, #f otherwise.
;;
;; heap-size : heap -> non-negative integer
;; returns the number of elements in the heap.
;;
;; heap-empty? : heap -> bool
;; returns #t if the heap contains no elements, #f otherwise.
;;
;; heap-min : heap -> any
;; returns the minimum element in the heap, according the heap's
;; ordering procedure. If there are no elements, a
;; &heap-empty-condition is raised.
;;
;; heap-delete-min : heap -> heap
;; returns a new heap containing all the elements of the heap
;; argument, except for the minimum argument, as determined by the
;; heap's ordering procedure. If there are no elements, a
;; &heap-empty-condition is raised.
;;
;; heap-pop : any + heap
;; returns two values: the the minimum value, and a heap obtained by
;; removing the minimum value from the original heap. If the heap is
;; empty, a &heap-empty-condition is raised.
;;
;; heap-insert : heap any -> heap
;; returns the new heap obtained by adding the element to those in the
;; argument heap.
;;
;; heap->list : heap -> Listof(any)
;; returns the heap containing all the elements of the heap. The
;; elements of the list are ordered according to the heap's ordering
;; procedure.
;;
;; list->heap : Listof(any) (any any -> boolean) -> heap
;; returns the heap containing all the elements of the list, and using
;; the procedure argument to order the elements.
;;
;; heap-merge : heap heap -> heap
;; returns the heap containing all the elements of the argument
;; heaps. The argument heaps are assumed to be using the same ordering
;; procedure.
;;
;; heap-sort : (any any -> bool) list -> list
;; returns a new list that is a permutation of the argument list, such
;; that all the elements are ordered by the given procedure.
;;
;; heap-ordering-procedure : heap -> (any any -> boolean)
;; returns the ordering procedure used internally by the heap.
;;
;; heap-empty-condition? : any -> bool
;; returns #t if argument is a &heap-empty condition, #f otherwise.
;;
(library (pfds heaps)
(export make-heap
(rename (%heap heap))
heap?
heap-size
heap-empty?
heap-min
heap-delete-min
heap-insert
heap-pop
heap->list
list->heap
heap-merge
heap-sort
(rename (heap-ordering-predicate heap-ordering-procedure))
heap-empty-condition?
)
(import (rnrs))
(define-record-type (node %make-node node?)
(fields size height value left right))
(define-record-type leaf)
(define (height x)
(if (leaf? x)
0
(node-height x)))
(define (size x)
(if (leaf? x)
0
(node-size x)))
(define (make-node v l r)
(define sl (height l))
(define sr (height r))
(define m (+ 1 (min sl sr)))
(define sz (+ 1 (size l) (size r)))
(if (< sl sr)
(%make-node sz m v r l)
(%make-node sz m v l r)))
(define (singleton v)
(%make-node 1 0 v (make-leaf) (make-leaf)))
(define (insert tree value prio<?)
(merge-trees tree (singleton value) prio<?))
(define (delete-min tree prio<?)
(merge-trees (node-left tree)
(node-right tree)
prio<?))
(define (merge-trees tree1 tree2 prio<?)
(cond ((leaf? tree1) tree2)
((leaf? tree2) tree1)
((prio<? (node-value tree2)
(node-value tree1))
(make-node (node-value tree2)
(node-left tree2)
(merge-trees tree1
(node-right tree2)
prio<?)))
(else
(make-node (node-value tree1)
(node-left tree1)
(merge-trees (node-right tree1)
tree2
prio<?)))))
;; outside interface
(define-record-type (heap %make-heap heap?)
(fields tree ordering-predicate))
(define (make-heap priority<?)
(%make-heap (make-leaf) priority<?))
(define (%heap < . vals)
(list->heap vals <))
(define (heap-size heap)
(size (heap-tree heap)))
(define (heap-empty? heap)
(leaf? (heap-tree heap)))
(define (heap-min heap)
(when (heap-empty? heap)
(raise (condition
(make-heap-empty-condition)
(make-who-condition 'heap-min)
(make-message-condition "There is no minimum element.")
(make-irritants-condition (list heap)))))
(node-value (heap-tree heap)))
(define (heap-delete-min heap)
(when (heap-empty? heap)
(raise (condition
(make-heap-empty-condition)
(make-who-condition 'heap-delete-min)
(make-message-condition "There is no minimum element.")
(make-irritants-condition (list heap)))))
(let ((< (heap-ordering-predicate heap)))
(%make-heap (delete-min (heap-tree heap) <) <)))
(define (heap-pop heap)
(when (heap-empty? heap)
(raise (condition
(make-heap-empty-condition)
(make-who-condition 'heap-pop)
(make-message-condition "There is no minimum element.")
(make-irritants-condition (list heap)))))
(let* ((tree (heap-tree heap))
(top (node-value tree))
(< (heap-ordering-predicate heap))
(rest (delete-min tree <)))
(values top
(%make-heap rest <))))
(define (heap-insert heap value)
(assert (heap? heap))
(let ((< (heap-ordering-predicate heap)))
(%make-heap (insert (heap-tree heap) value <) <)))
(define (heap->list heap)
(assert (heap? heap))
(let ((< (heap-ordering-predicate heap)))
(let loop ((tree (heap-tree heap)) (list '()))
(if (leaf? tree)
(reverse list)
(loop (delete-min tree <)
(cons (node-value tree) list))))))
(define (list->heap list <)
(%make-heap
(fold-left (lambda (h item)
(insert h item <))
(make-leaf)
list)
<))
(define (heap-merge heap1 heap2)
(define < (heap-ordering-predicate heap1))
(%make-heap
(merge-trees (heap-tree heap1)
(heap-tree heap2)
<)
<))
(define (heap-sort < list)
(heap->list (list->heap list <)))
(define-condition-type &heap-empty
&assertion
make-heap-empty-condition
heap-empty-condition?)
)
(package (pfds (0 3))
(depends (wak-trc-testing))
(synopsis "Purely Functional Data Structures")
(description
"A library of data structures for functional programmers."
"It contains implementations of:"
"- queues"
"- deques"
"- bbtrees"
"- sets"
"- dlists"
"- priority search queues"
"- heaps"
"- hamts"
"- finger trees"
"- sequences")
(homepage "http://github.com/ijp/pfds")
(documentation
"README.org"
"LICENSE")
(libraries
(sls -> "pfds")
("queues" -> ("pdfs" "queues"))
("deques" -> ("pdfs" "deques"))
("private" -> ("pfds" "private"))))
;;; psqs.sls --- Priority Search Queues
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;;; Documentation
;;
;; Priority search queues are a combination of two common abstract
;; data types: finite maps, and priority queues. As such, it provides
;; for access, insertion, removal and update on arbitrary keys, as
;; well as for easy removal of the element with the lowest priority.
;;
;; Note: where a procedure takes a key or priority these are expected
;; to be compatible with the relevant ordering procedures on the psq.
;;
;;;; Basic operations
;;
;; make-psq : < < -> psq
;; takes a two ordering procedures, one for keys, and another for
;; priorities, and returns an empty priority search queue
;;
;; psq? : obj -> boolean
;; returns #t if the object is a priority search queue, #f otherwise.
;;
;; psq-empty? : psq -> boolean
;; returns #t if the priority search queue contains no elements, #f
;; otherwise.
;;
;; psq-size : psq -> non-negative integer
;; returns the number of associations in the priority search queue
;;
;;;; Finite map operations
;;
;; psq-ref : psq key -> priority
;; returns the priority of a key if it is in the priority search
;; queue. If the key is not in the priority queue an
;; assertion-violation is raised.
;;
;; psq-set : psq key priority -> psq
;; returns the priority search queue obtained from inserting a key
;; with a given priority. If the key is already in the priority search
;; queue, it updates the priority to the new value.
;;
;; psq-update : psq key (priority -> priority) priority -> psq
;; returns the priority search queue obtained by modifying the
;; priority of key, by the given function. If the key is not in the
;; priority search queue, it is inserted with the priority obtained by
;; calling the function on the default value.
;;
;; psq-delete : psq key -> psq
;; returns the priority search queue obtained by removing the
;; key-priority association from the priority search queue. If the key
;; is not in the queue, then the returned search queue will be the
;; same as the original.
;;
;; psq-contains? : psq key -> boolean
;; returns #t if there is an association for the given key in the
;; priority search queue, #f otherwise.
;;
;;;; Priority queue operations
;;
;; psq-min : psq -> key
;;
;; returns the key of the minimum association in the priority search
;; queue. If the queue is empty, an assertion violation is raised.
;;
;; psq-delete-min : psq -> psq
;; returns the priority search queue obtained by removing the minimum
;; association in the priority search queue. If the queue is empty, an
;; assertion violation is raised.
;;
;; psq-pop : psq -> key + psq
;; returns two values: the minimum key and the priority search queue
;; obtained by removing the minimum association from the original
;; queue. If the queue is empty, an assertion violation is raised.
;;
;;;; Ranged query functions
;;
;; psq-at-most : psq priority -> ListOf(key . priority)
;; returns an alist containing all the associations in the priority
;; search queue with priority less than or equal to a given value. The
;; alist returned is ordered by key according to the predicate for the
;; psq.
;;
;; psq-at-most-range : psq priority key key -> ListOf(key . priority)
;; Similar to psq-at-most, but it also takes an upper and lower bound,
;; for the keys it will return. These bounds are inclusive.
;;
(library (pfds psqs)
(export make-psq
psq?
psq-empty?
psq-size
;; map operations
psq-ref
psq-set
psq-update
psq-delete
psq-contains?
;; priority queue operations
psq-min
psq-delete-min
psq-pop
;; ranged query operations
psq-at-most
psq-at-most-range
)
(import (except (rnrs) min))
;;; record types
(define-record-type void)
(define-record-type winner
(fields key priority loser-tree maximum-key))
(define-record-type start)
(define-record-type (loser %make-loser loser?)
(fields size key priority left split-key right))
(define (make-loser key priority left split-key right)
(%make-loser (+ (size left) (size right) 1)
key
priority
left
split-key
right))
;;; functions
(define (maximum-key psq)
(winner-maximum-key psq))
(define max-key maximum-key)
(define empty (make-void))
(define (singleton key priority)
(make-winner key priority (make-start) key))
(define (play-match psq1 psq2 key<? prio<?)
(cond ((void? psq1) psq2)
((void? psq2) psq1)
((not (prio<? (winner-priority psq2)
(winner-priority psq1)))
(let ((k1 (winner-key psq1))
(p1 (winner-priority psq1))
(t1 (winner-loser-tree psq1))
(m1 (winner-maximum-key psq1))
(k2 (winner-key psq2))
(p2 (winner-priority psq2))
(t2 (winner-loser-tree psq2))
(m2 (winner-maximum-key psq2)))
(make-winner k1
p1
(balance k2 p2 t1 m1 t2 key<? prio<?)
m2)))
(else
(let ((k1 (winner-key psq1))
(p1 (winner-priority psq1))
(t1 (winner-loser-tree psq1))
(m1 (winner-maximum-key psq1))
(k2 (winner-key psq2))
(p2 (winner-priority psq2))
(t2 (winner-loser-tree psq2))
(m2 (winner-maximum-key psq2)))
(make-winner k2
p2
(balance k1 p1 t1 m1 t2 key<? prio<?)
m2)))))
(define (second-best ltree key key<? prio<?)
(if (start? ltree)
(make-void)
(let ((k (loser-key ltree))
(p (loser-priority ltree))
(l (loser-left ltree))
(m (loser-split-key ltree))
(r (loser-right ltree)))
(if (not (key<? m k))
(play-match (make-winner k p l m)
(second-best r key key<? prio<?)
key<?
prio<?)
(play-match (second-best l m key<? prio<?)
(make-winner k p r key)
key<?
prio<?)))))
(define (delete-min psq key<? prio<?)
;; maybe void psqs should return void?
(second-best (winner-loser-tree psq) (winner-maximum-key psq) key<? prio<?))
(define (psq-case psq empty-k singleton-k match-k key<?)
(if (void? psq)
(empty-k)
(let ((k1 (winner-key psq))
(p1 (winner-priority psq))
(t (winner-loser-tree psq))
(m (winner-maximum-key psq)))
(if (start? t)
(singleton-k k1 p1)
(let ((k2 (loser-key t))
(p2 (loser-priority t))
(l (loser-left t))
(s (loser-split-key t))
(r (loser-right t)))
(if (not (key<? s k2))
(match-k (make-winner k2 p2 l s)
(make-winner k1 p1 r m))
(match-k (make-winner k1 p1 l s)
(make-winner k2 p2 r m))))))))
(define (lookup psq key default key<?)
(psq-case psq
(lambda () default)
(lambda (k p)
(if (or (key<? k key) (key<? key k))
default
p))
(lambda (w1 w2)
(if (not (key<? (max-key w1) key))
(lookup w1 key default key<?)
(lookup w2 key default key<?)))
key<?))
(define (update psq key f default key<? prio<?)
(psq-case psq
(lambda () (singleton key (f default)))
(lambda (k p)
(cond ((key<? key k)
(play-match (singleton key (f default))
(singleton k p)
key<?
prio<?))
((key<? k key)
(play-match (singleton k p)
(singleton key (f default))
key<?
prio<?))
(else
(singleton key (f p)))))
(lambda (w1 w2)
(if (not (key<? (max-key w1) key))
(play-match (update w1 key f default key<? prio<?)
w2
key<?
prio<?)
(play-match w1
(update w2 key f default key<? prio<?)
key<?
prio<?)))
key<?))
(define (insert psq key val key<? prio<?)
(psq-case psq
(lambda () (singleton key val))
(lambda (k p)
(cond ((key<? key k)
(play-match (singleton key val)
(singleton k p)
key<?
prio<?))
((key<? k key)
(play-match (singleton k p)
(singleton key val)
key<?
prio<?))
(else
(singleton key val))))
(lambda (w1 w2)
(if (not (key<? (max-key w1) key))
(play-match (insert w1 key val key<? prio<?) w2 key<? prio<?)
(play-match w1 (insert w2 key val key<? prio<?) key<? prio<?)))
key<?))
(define (delete psq key key<? prio<?)
(psq-case psq
(lambda () empty)
(lambda (k p)
(if (or (key<? k key)
(key<? key k))
(singleton k p)
empty))
(lambda (w1 w2)
(if (not (key<? (max-key w1) key))
(play-match (delete w1 key key<? prio<?) w2 key<? prio<?)
(play-match w1 (delete w2 key key<? prio<?) key<? prio<?)))
key<?))
(define (min tree)
(when (void? tree)
(assertion-violation 'psq-min
"Can't take the minimum of an empty priority search queue"))
(winner-key tree))
(define (pop tree key<? prio<?)
(when (void? tree)
(assertion-violation 'psq-pop
"Can't pop from an empty priority search queue"))
(values (winner-key tree)
(delete-min tree key<? prio<?)))
;; at-most and at-most-range are perfect examples of when to use
;; dlists, but we do not do that here
(define (at-most psq p key<? prio<?)
(define (at-most psq accum)
(if (and (winner? psq)
(prio<? p (winner-priority psq)))
accum
(psq-case psq
(lambda () accum)
(lambda (k p) (cons (cons k p) accum))
(lambda (m1 m2)
(at-most m1 (at-most m2 accum)))
key<?)))
(at-most psq '()))
(define (at-most-range psq p lower upper key<? prio<?)
(define (within-range? key)
;; lower <= k <= upper
(not (or (key<? key lower) (key<? upper key))))
(define (at-most psq accum)
(if (and (winner? psq)
(prio<? p (winner-priority psq)))
accum
(psq-case psq
(lambda () accum)
(lambda (k p)
(if (within-range? k)
(cons (cons k p) accum)
accum))
(lambda (m1 m2)
(let ((accum* (if (key<? upper (max-key m1))
accum
(at-most m2 accum))))
(if (key<? (max-key m1) lower)
accum*
(at-most m1 accum*))))
key<?)))
(at-most psq '()))
;;; Maintaining balance
(define weight 4) ; balancing constant
(define (size ltree)
(if (start? ltree)
0
(loser-size ltree)))
(define (balance key priority left split-key right key<? prio<?)
(let ((l-size (size left))
(r-size (size right)))
(cond ((< (+ l-size r-size) 2)
(make-loser key priority left split-key right))
((> r-size (* weight l-size))
(balance-left key priority left split-key right key<? prio<?))
((> l-size (* weight r-size))
(balance-right key priority left split-key right key<? prio<?))
(else
(make-loser key priority left split-key right)))))
(define (balance-left key priority left split-key right key<? prio<?)
(if (< (size (loser-left right))
(size (loser-right right)))
(single-left key priority left split-key right key<? prio<?)
(double-left key priority left split-key right key<? prio<?)))
(define (balance-right key priority left split-key right key<? prio<?)
(if (< (size (loser-right left))
(size (loser-left left)))
(single-right key priority left split-key right key<? prio<?)
(double-right key priority left split-key right key<? prio<?)))
(define (single-left key priority left split-key right key<? prio<?)
(let ((right-key (loser-key right))
(right-priority (loser-priority right))
(right-left (loser-left right))
(right-split-key (loser-split-key right))
(right-right (loser-right right)))
;; test
(if (and (not (key<? right-split-key right-key))
(not (prio<? right-priority priority)))
(make-loser key
priority
(make-loser right-key right-priority left split-key right-left)
right-split-key
right-right
)
(make-loser right-key
right-priority
(make-loser key priority left split-key right-left)
right-split-key
right-right))))
(define (double-left key priority left split-key right key<? prio<?)
(let ((right-key (loser-key right))
(right-priority (loser-priority right))
(right-left (loser-left right))
(right-split-key (loser-split-key right))
(right-right (loser-right right)))
(single-left key
priority
left
split-key
(single-right right-key
right-priority
right-left
right-split-key
right-right
key<?
prio<?)
key<?
prio<?)))
(define (single-right key priority left split-key right key<? prio<?)
(let ((left-key (loser-key left))
(left-priority (loser-priority left))
(left-left (loser-left left))
(left-split-key (loser-split-key left))
(left-right (loser-right left)))
(if (and (key<? left-split-key left-key)
(not (prio<? left-priority priority)))
(make-loser key
priority
left-left
left-split-key
(make-loser left-key left-priority left-right split-key right))
(make-loser left-key
left-priority
left-left
left-split-key
(make-loser key priority left-right split-key right)))))
(define (double-right key priority left split-key right key<? prio<?)
(let ((left-key (loser-key left))
(left-priority (loser-priority left))
(left-left (loser-left left))
(left-split-key (loser-split-key left))
(left-right (loser-right left)))
(single-right key
priority
(single-left left-key
left-priority
left-left
left-split-key
left-right
key<?
prio<?)
split-key
right
key<?
prio<?)))
;;; Exported Type
(define-record-type (psq %make-psq psq?)
(fields key<? priority<? tree))
(define (%update-psq psq new-tree)
(%make-psq (psq-key<? psq)
(psq-priority<? psq)
new-tree))
;;; Exported Procedures
(define (make-psq key<? priority<?)
(%make-psq key<? priority<? (make-void)))
(define (psq-empty? psq)
(assert (psq? psq))
(void? (psq-tree psq)))
(define (psq-ref psq key)
(define cookie (cons #f #f))
(assert (psq? psq))
(let ((val (lookup (psq-tree psq) key cookie (psq-key<? psq))))
(if (eq? val cookie)
(assertion-violation 'psq-ref "not in tree")
val)))
(define (psq-set psq key priority)
(assert (psq? psq))
(%update-psq psq
(insert (psq-tree psq) key priority (psq-key<? psq) (psq-priority<? psq))))
(define (psq-update psq key f default)
(assert (psq? psq))
(%update-psq psq (update (psq-tree psq) key f default (psq-key<? psq) (psq-priority<? psq))))
(define (psq-delete psq key)
(assert (psq? psq))
(%update-psq psq (delete (psq-tree psq) key (psq-key<? psq) (psq-priority<? psq))))
(define (psq-contains? psq key)
(define cookie (cons #f #f))
(assert (psq? psq))
(let ((val (lookup (psq-tree psq) key cookie (psq-key<? psq))))
(not (eq? val cookie))))
(define (psq-min psq)
(assert (psq? psq))
(min (psq-tree psq)))
(define (psq-delete-min psq)
(assert (and (psq? psq)
(not (psq-empty? psq))))
(%update-psq psq (delete-min (psq-tree psq) (psq-key<? psq) (psq-priority<? psq))))
(define (psq-pop psq)
(assert (psq? psq))
(let-values (((min rest) (pop (psq-tree psq) (psq-key<? psq) (psq-priority<? psq))))
(values min (%update-psq psq rest))))
(define (psq-at-most psq max-priority)
(assert (psq? psq))
(let ((tree (psq-tree psq))
(key<? (psq-key<? psq))
(prio<? (psq-priority<? psq)))
(at-most tree max-priority key<? prio<?)))
(define (psq-at-most-range psq max-priority min-key max-key)
(assert (psq? psq))
(let ((tree (psq-tree psq))
(key<? (psq-key<? psq))
(prio<? (psq-priority<? psq)))
(at-most-range tree max-priority min-key max-key key<? prio<?)))
(define (psq-size psq)
(assert (psq? psq))
(let ((tree (psq-tree psq)))
(if (winner? tree)
(+ 1 (size (winner-loser-tree tree)))
0)))
)
;;; queues.sls --- Purely functional queues
;; Copyright (C) 2011,2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Commentary:
;;
;; A scheme translation of "Simple and Efficient Purely Functional
;; Queues and Deques" by Chris Okazaki
;;
;;
;;; Documentation:
;;
;; make-queue : () -> queue
;; returns a queue containing no items
;;
;; queue? : any -> boolean
;; tests if an object is a queue
;;
;; queue-length : queue -> non-negative integer
;; returns the number of items in the queue
;;
;; queue-empty? : queue -> boolean
;; returns true if there are no items in the queue, false otherwise
;;
;; enqueue : queue any -> queue
;; returns a new queue with the enqueued item at the end
;;
;; dequeue : queue -> value queue
;; returns two values, the item at the front of the queue, and a new
;; queue containing the all the other items
;; raises a &queue-empty condition if the queue is empty
;;
;; queue-empty-condition? : object -> boolean
;; tests if an object is a &queue-empty condition
;;
;; queue->list : queue -> listof(any)
;; returns a queue containing all the items in the list. The order of
;; the elements in the queue is the same as the order of the elements
;; in the list.
;;
;; list->queue : listof(any) -> queue
;; returns a list containing all the items in the queue. The order of
;; the items in the list is the same as the order in the queue.
;; For any list l, (equal? (queue->list (list->queue l)) l) is #t.
;;
(library (pfds queues)
(export make-queue
queue?
queue-length
queue-empty?
enqueue
dequeue
queue-empty-condition?
list->queue
queue->list
)
(import (except (rnrs) cons*)
(pfds private lazy-lists)
(pfds queues private condition)
(rnrs r5rs))
(define (rotate l r a)
(if (empty? l)
(cons* (head r) a)
(cons* (head l)
(rotate (tail l)
(tail r)
(cons* (head r) a)))))
;;; Implementation
(define-record-type (queue %make-queue queue?)
(fields
(immutable length)
(immutable l)
(immutable r)
(immutable l^)))
(define (make-queue)
(%make-queue 0 '() '() '()))
(define (enqueue queue item)
(let ((len (queue-length queue))
(l (queue-l queue))
(r (queue-r queue))
(l^ (queue-l^ queue)))
(makeq (+ len 1) l (cons* item r) l^)))
(define (dequeue queue)
(when (queue-empty? queue)
;; (error 'dequeue "Can't dequeue empty queue")
(raise (condition
(make-queue-empty-condition)
(make-who-condition 'dequeue)
(make-message-condition "There are no elements to dequeue")
(make-irritants-condition (list queue)))))
(let ((len (queue-length queue))
(l (queue-l queue))
(r (queue-r queue))
(l^ (queue-l^ queue)))
(values (head l)
(makeq (- len 1) (tail l) r l^))))
(define (makeq length l r l^)
(if (empty? l^)
(let ((l* (rotate l r '())))
(%make-queue length l* '() l*))
(%make-queue length l r (tail l^))))
(define (queue-empty? queue)
(zero? (queue-length queue)))
(define (list->queue list)
(fold-left enqueue (make-queue) list))
(define (queue->list queue)
(let loop ((rev-list '()) (queue queue))
(if (queue-empty? queue)
(reverse rev-list)
(let-values (((val queue) (dequeue queue)))
(loop (cons val rev-list)
queue)))))
)
;;; sequences.sls --- Purely Functional Sequences
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Commentary:
;; Sequences are a general-purpose, variable-length collection,
;; similar to lists, however they support efficient addition and
;; removal from both ends, and random-access. Like other Scheme
;; collections, sequences are zero-indexed.
;;
;; make-sequence : () -> sequence
;; returns a new empty sequence
;;
;; sequence any ... -> sequence
;; returns a new sequence containing all of the argument elements, in the
;; same order.
;;
;; sequence? : any -> bool
;; returns #t if the argument is a sequence, #f otherwise.
;;
;; sequence-empty? : sequence -> bool
;; returns #t if the argument sequence contains no elements, #f otherwise.
;;
;; sequence-size : sequence -> non-negative integer
;; returns the number of elements in the sequence
;;
;; sequence-cons : any sequence -> sequence
;; return the new sequence created by adding the element to the front of
;; the sequence.
;;
;; sequence-uncons : sequence -> any sequence
;; returns two values: the first element of the sequence, and a new
;; sequence containing all but the first element. If the sequence is
;; empty, a &sequence-empty condition is raised.
;;
;; sequence-snoc : sequence any -> sequence
;; return the new sequence created by adding the element to the end of
;; the sequence.
;;
;; sequence-unsnoc : sequence -> sequence any
;; returns two values: a new sequence containing all but the last
;; element of the sequence, and the last element itself. If the
;; sequence is empty, a &sequence-empty condition is raised.
;;
;; sequence-append : sequence sequence -> sequence
;; returns a new sequence containing all the elements of the first
;; sequence, followed by all the elements of the second sequence.
;;
;; list->sequence : Listof(Any) -> sequence
;; returns a new sequence containing all the elements of the argument
;; list, in the same order.
;;
;; sequence->list : sequence -> Listof(Any)
;; returns a new list containing all the elements of the sequence, in the
;; same order.
;;
;; sequence-split-at sequence integer -> sequence + sequence
;; returns two new sequences, the first containing the first N elements
;; of the sequence, the second containing the remaining elements. If N is
;; negative, it returns the empty sequence as the first argument, and the
;; original sequence as the second argument. Similarly, if N is greater
;; than the length of the list, it returns the original sequence as the
;; first argument, and the empty sequence as the second argument.
;;
;; Consequently, (let-values (((a b) (sequence-split-at s i)))
;; (sequence-append a b)) is equivalent to s for all sequences s, and
;; integers i.
;;
;; sequence-take sequence integer -> sequence
;; returns a new sequence containing the first N elements of the
;; argument sequence. If N is negative, the empty sequence is
;; returned. If N is larger than the length of the sequence, the whole
;; sequence is returned.
;;
;; sequence-drop sequence integer -> sequence
;; returns a new sequence containing all but the first N elements of the
;; argument sequence. If N is negative, the whole sequence is
;; returned. If N is larger than the length of the sequence, the empty
;; sequence is returned.
;;
;; sequence-ref : sequence non-negative-integer -> any
;; returns the element at the specified index in the sequence. If the
;; index is outside the range 0 <= i < (sequence-size sequence), an
;; assertion violation is raised.
;;
;; sequence-set : sequence non-negative-integer any -> sequence
;; returns the new sequence obtained by replacing the element at the
;; specified index in the sequence with the given value. If the index
;; is outside the range 0 <= i < (sequence-size sequence), an
;; assertion violation is raised.
;;
;; sequence-fold (any -> any -> any) any sequence
;; returns the value obtained by iterating the combiner procedure over
;; the sequence in left-to-right order. The combiner procedure takes two
;; arguments, the value of the position in the sequence, and an
;; accumulator, and its return value is used as the value of the
;; accumulator for the next call. The initial accumulator value is given
;; by the base argument.
;;
;; sequence-fold-right (any -> any -> any) any sequence
;; Like sequence-fold, but the sequence is traversed in right-to-left
;; order, rather than left-to-right.
;;
;; sequence-reverse : sequence -> sequence
;; returns a new sequence containing all the arguments of the argument
;; list, in reverse order.
;;
;; sequence-map : (any -> any) sequence -> sequence
;; returns a new sequence obtained by applying the procedure to each
;; element of the argument sequence in turn.
;;
;; sequence-filter : (any -> bool) sequence -> sequence
;; returns a new sequence containing all the elements of the argument
;; sequence for which the predicate is true.
;;
;; sequence-empty-condition? : any -> bool
;; returns #t if an object is a &sequence-empty condition, #f otherwise.
;;
(library (pfds sequences)
(export make-sequence
sequence?
sequence-empty?
sequence-size
sequence-cons
sequence-uncons
sequence-snoc
sequence-unsnoc
sequence-append
list->sequence
sequence->list
(rename (%sequence sequence))
sequence-split-at
sequence-take
sequence-drop
sequence-ref
sequence-set
sequence-fold
sequence-fold-right
sequence-reverse
sequence-map
sequence-filter
sequence-empty-condition?
)
(import (rnrs)
(pfds fingertrees))
;; Note: as sequences are not a subtype of fingertrees, but rather a
;; particular instantiation of them, &sequence-empty is not a subtype
;; of &fingertree-empty
(define-condition-type &sequence-empty
&assertion
make-sequence-empty-condition
sequence-empty-condition?)
(define-record-type (sequence %make-sequence sequence?)
(fields fingertree))
(define (make-sequence)
(%make-sequence (make-fingertree 0 + (lambda (x) 1))))
(define (sequence-empty? seq)
(fingertree-empty? (sequence-fingertree seq)))
(define (sequence-size seq)
(fingertree-measure (sequence-fingertree seq)))
(define (sequence-cons value seq)
(%make-sequence
(fingertree-cons value (sequence-fingertree seq))))
(define (sequence-snoc seq value)
(%make-sequence
(fingertree-snoc (sequence-fingertree seq) value)))
(define (sequence-uncons seq)
(call-with-values
(lambda ()
(define ft (sequence-fingertree seq))
(when (fingertree-empty? ft)
(raise
(condition
(make-sequence-empty-condition)
(make-who-condition 'sequence-uncons)
(make-message-condition "There are no elements to uncons")
(make-irritants-condition (list seq)))))
(fingertree-uncons ft))
(lambda (head tree)
(values head (%make-sequence tree)))))
(define (sequence-unsnoc seq)
(call-with-values
(lambda ()
(define ft (sequence-fingertree seq))
(when (fingertree-empty? ft)
(raise
(condition
(make-sequence-empty-condition)
(make-who-condition 'sequence-unsnoc)
(make-message-condition "There are no elements to unsnoc")
(make-irritants-condition (list seq)))))
(fingertree-unsnoc ft))
(lambda (tree last)
(values (%make-sequence tree) last))))
(define (sequence-append seq1 seq2)
(%make-sequence
(fingertree-append (sequence-fingertree seq1)
(sequence-fingertree seq2))))
(define (list->sequence list)
(fold-left sequence-snoc
(make-sequence)
list))
(define (sequence->list seq)
(fingertree->list (sequence-fingertree seq)))
(define (%sequence . args)
(list->sequence args))
(define (sequence-split-at seq i)
(let-values (((l r)
(fingertree-split (lambda (x) (< i x))
(sequence-fingertree seq))))
(values (%make-sequence l)
(%make-sequence r))))
(define (sequence-take seq i)
(let-values (((head tail)
(sequence-split-at seq i)))
head))
(define (sequence-drop seq i)
(let-values (((head tail)
(sequence-split-at seq i)))
tail))
(define (sequence-ref seq i)
(define size (sequence-size seq))
(unless (and (<= 0 i) (< i size))
(assertion-violation 'sequence-ref "Index out of range" i))
(let-values (((_l x _r)
(fingertree-split3 (lambda (x) (< i x))
(sequence-fingertree seq))))
x))
(define (sequence-set seq i val)
(define size (sequence-size seq))
(unless (and (<= 0 i) (< i size))
(assertion-violation 'sequence-set "Index out of range" i))
(let-values (((l x r)
(fingertree-split3 (lambda (x) (< i x))
(sequence-fingertree seq))))
(%make-sequence
(fingertree-append l (fingertree-cons val r)))))
(define (sequence-fold proc base seq)
(fingertree-fold proc base (sequence-fingertree seq)))
(define (sequence-fold-right proc base seq)
(fingertree-fold-right proc base (sequence-fingertree seq)))
(define (sequence-reverse seq)
(%make-sequence (fingertree-reverse (sequence-fingertree seq))))
(define (sequence-map proc seq)
(define (combine element seq)
(sequence-cons (proc element) seq))
(sequence-fold-right combine (make-sequence) seq))
(define (sequence-filter pred? seq)
(define (combine element seq)
(if (pred? element)
(sequence-cons element seq)
seq))
(sequence-fold-right combine (make-sequence) seq))
)
;;; sets.sls --- Purely Functional Sets
;; Copyright (C) 2012 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;; Documentation:
;;
;; set? : any -> boolean
;; returns #t if the object is a set, #f otherwise
;;
;; make-set : (any any -> boolean) -> set
;; returns a new empty set ordered by the < procedure
;;
;; set-member? : set any -> boolean
;; returns true if element is in the set
;;
;; set-insert : set any -> set
;; returns a new set created by inserting element into the set argument
;;
;; set-remove : set element -> set
;; returns a new set created by removing element from the set
;;
;; set-size : set -> non-negative integer
;; returns the number of elements in the set
;;
;; set<? : set set -> boolean
;; returns #t if set1 is a proper subset of set2, #f otherwise. That
;; is, if all elements of set1 are in set2, and there is at least one
;; element of set2 not in set1.
;;
;; set<=? : set set -> boolean
;; returns #t if set1 is a subset of set2, #f otherwise, i.e. if all
;; elements of set1 are in set2.
;;
;; set=? : set set -> boolean
;; returns #t if every element of set1 is in set2, and vice versa, #f
;; otherwise.
;;
;; set>=? : set set -> boolean
;; returns #t if set2 is a subset of set1, #f otherwise.
;;
;; set>? : set set -> boolean
;; returns #t if set2 is a proper subset of set1, #f otherwise.
;;
;; subset? : set set -> boolean
;; same as set<=?
;;
;; proper-subset? : set set -> boolean
;; same as set<?
;;
;; set-map : (any -> any) set -> set
;; returns the new set created by applying proc to each element of the set
;;
;; set-fold : (any any -> any) any set -> any
;; returns the value obtained by iterating the procedure over each
;; element of the set and an accumulator value. The value of the
;; accumulator is initially base, and the return value of proc is used
;; as the accumulator for the next iteration.
;;
;; list->set : Listof(any) (any any -> any) -> set
;; returns the set containing all the elements of the list, ordered by <.
;;
;; set->list : set -> Listof(any)
;; returns all the elements of the set as a list
;;
;; set-union : set set -> set
;; returns the union of set1 and set2, i.e. contains all elements of
;; set1 and set2.
;;
;; set-intersection : set set -> set
;; returns the intersection of set1 and set2, i.e. the set of all
;; items that are in both set1 and set2.
;;
;; set-difference : set set -> set
;; returns the difference of set1 and set2, i.e. the set of all items
;; in set1 that are not in set2.
;;
;; set-ordering-procedure : set -> (any any -> boolean)
;; returns the ordering procedure used internall by the set.
(library (pfds sets)
(export set?
make-set
set-member?
set-insert
set-remove
set-size
set<?
set<=?
set=?
set>=?
set>?
subset?
proper-subset?
set-map
set-fold
list->set
set->list
set-union
set-intersection
set-difference
set-ordering-procedure
)
(import (rnrs)
(pfds bbtrees))
(define dummy #f)
;;; basic sets
(define-record-type (set %make-set set?)
(fields tree))
(define (set-ordering-procedure set)
(bbtree-ordering-procedure (set-tree set)))
(define (make-set <)
(%make-set (make-bbtree <)))
;; provide a (make-equal-set) function?
(define (set-member? set element)
(bbtree-contains? (set-tree set) element))
(define (set-insert set element)
(%make-set (bbtree-set (set-tree set) element dummy)))
(define (set-remove set element)
(%make-set (bbtree-delete (set-tree set) element)))
(define (set-size set)
(bbtree-size (set-tree set)))
;;; set equality
(define (set<=? set1 set2)
(let ((t (set-tree set2)))
(bbtree-traverse (lambda (k _ l r b)
(and (bbtree-contains? t k)
(l #t)
(r #t)))
#t
(set-tree set1))))
(define (set<? set1 set2)
(and (< (set-size set1)
(set-size set2))
(set<=? set1 set2)))
(define (set>=? set1 set2)
(set<=? set2 set1))
(define (set>? set1 set2)
(set<? set2 set1))
(define (set=? set1 set2)
(and (set<=? set1 set2)
(set>=? set1 set2)))
(define subset? set<=?)
(define proper-subset? set<?)
;;; iterators
(define (set-map proc set)
;; currently restricted to returning a set with the same ordering, I
;; could weaken this to, say, comparing with < on the object-hash,
;; or I make it take a < argument for the result set.
(let ((tree (set-tree set)))
(%make-set
(bbtree-fold (lambda (key _ tree)
(bbtree-set tree (proc key) dummy))
(make-bbtree (bbtree-ordering-procedure tree))
tree))))
(define (set-fold proc base set)
(bbtree-fold (lambda (key value base)
(proc key base))
base
(set-tree set)))
;;; conversion
(define (list->set list <)
(fold-left (lambda (tree element)
(set-insert tree element))
(make-set <)
list))
(define (set->list set)
(set-fold cons '() set))
;;; set operations
(define (set-union set1 set2)
(%make-set (bbtree-union (set-tree set1) (set-tree set2))))
(define (set-intersection set1 set2)
(%make-set (bbtree-intersection (set-tree set1) (set-tree set2))))
(define (set-difference set1 set2)
(%make-set (bbtree-difference (set-tree set1) (set-tree set2))))
)
;; Copyright (C) 2011-2014 Ian Price <ianprice90@googlemail.com>
;; Author: Ian Price <ianprice90@googlemail.com>
;; This program is free software, you can redistribute it and/or
;; modify it under the terms of the new-style BSD license.
;; You should have received a copy of the BSD license along with this
;; program. If not, see <http://www.debian.org/misc/bsd.license>.
;;; Code:
(import (rnrs)
(pfds tests queues)
(pfds tests deques)
(pfds tests bbtrees)
(pfds tests sets)
(pfds tests psqs)
(pfds tests heaps)
(pfds tests fingertrees)
(pfds tests sequences)
(pfds tests hamts)
(pfds tests utils)
(wak trc-testing))
;; Some schemes use lazy loading of modules, and so I can't just use
;; (run-test pfds) and rely on the side effects in the other modules
;; to add them to the pfds parent suite.
(define-syntax add-tests!
(syntax-rules ()
((add-tests! suite ...)
(begin (add-test! pfds 'suite suite) ...))))
(add-tests! queues deques bbtrees sets psqs
heaps fingertrees sequences hamts)
(run-test pfds)
(define-library (r7rs-extras all)
(import (r7rs-extras higher-order))
(include-library-declarations "higher-order.exports.sld")
(import (r7rs-extras io))
(include-library-declarations "io.exports.sld")
(import (r7rs-extras partition))
(include-library-declarations "partition.exports.sld")
(import (r7rs-extras arithmetic))
(include-library-declarations "arithmetic.exports.sld")
(import (r7rs-extras pushpop))
(include-library-declarations "pushpop.exports.sld")
)
;;; arithmetic.body.scm --- Extra arithmetic operations
;; Copyright © 2014 Taylan Ulrich Bayırlı/Kammer
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: extensions arithmetic number
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; If you're desperate for performance, you might benefit from implementing the
;; euclidean variants in terms of the floor and ceiling variants for positive
;; and negative values of `y' respectively. The floor variants are in the
;; (scheme base) library and might be more efficient in your implementation.
;; These might also otherwise have significantly more efficient implementations.
;; Let me know.
;;; Code:
(define-syntax define-divisions
(syntax-rules ()
((_ div div-doc quotient quotient-doc remainder remainder-doc x y
quotient-expr)
(begin
(define (div x y)
div-doc
(let* ((q quotient-expr)
(r (- x (* y quotient-expr))))
(values q r)))
(define (quotient x y)
quotient-doc
quotient-expr)
(define (remainder x y)
remainder-doc
(- x (* y quotient-expr)))))))
(define-divisions
euclidean/
"Return Q and R in X = Q*Y + R where 0 <= R < |Y|."
euclidean-quotient
"Return Q in X = Q*Y + R where 0 <= R < |Y|."
euclidean-remainder
"Return R in X = Q*Y + R where 0 <= R < |Y|."
x y
(cond ((positive? y)
(floor (/ x y)))
((negative? y)
(ceiling (/ x y)))
((zero? y)
(error "division by zero"))
(else +nan.0)))
(define-divisions
ceiling/
"Return Q and R in X = Q*Y + R where Q = ceiling(X/Y)."
ceiling-quotient
"Return Q in X = Q*Y + R where Q = ceiling(X/Y)."
ceiling-remainder
"Return R in X = Q*Y + R where Q = ceiling(X/Y)."
x y
(ceiling (/ x y)))
(define-divisions
centered/
"Return Q and R in X = Q*Y + R where -|Y/2| <= R < |Y/2|."
centered-quotient
"Return Q in X = Q*Y + R where -|Y/2| <= R < |Y/2|."
centered-remainder
"Return R in X = Q*Y + R where -|Y/2| <= R < |Y/2|."
x y
(cond ((positive? y)
(floor (+ 1/2 (/ x y))))
((negative? y)
(ceiling (+ -1/2 (/ x y))))
((zero? y)
(error "division by zero"))
(else +nan.0)))
(define-divisions
round/
"Return Q and R in X = Q*Y + R where Q = round(X/Y)."
round-quotient
"Return Q in X = Q*Y + R where Q = round(X/Y)."
round-remainder
"Return R in X = Q*Y + R where Q = round(X/Y)."
x y
(round (/ x y)))
;;; arithmetic.body.scm ends here
(export
euclidean/
euclidean-quotient
euclidean-remainder
ceiling/
ceiling-quotient
ceiling-remainder
centered/
centered-quotient
centered-remainder
round/
round-quotient
round-remainder
)
(define-library (r7rs-extras arithmetic)
(import (scheme base))
(include-library-declarations "arithmetic.exports.sld")
(include "arithmetic.body.scm"))
;;; higher-order.body.scm --- Auxiliary higher-oder procedures
;; Copyright © 2014 Taylan Ulrich Bayırlı/Kammer
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: extensions higher-order
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Miscellaneous higher-oder procedures for creating constant functions,
;; negating functions, etc.
;;; Code:
(define (const value)
"Make a nullary procedure always returning VALUE."
(lambda () value))
(define (negate proc)
"Make a procedure negating the application of PROC to its arguments."
(lambda x (not (apply proc x))))
(define (compose proc . rest)
"Functional composition; e.g. ((compose x y) a) = (x (y a))."
(if (null? rest)
proc
(let ((rest-proc (apply compose rest)))
(lambda x
(let-values ((x (apply rest-proc x)))
(apply proc x))))))
(define (pipeline proc . rest)
"Reverse functional composition; e.g. ((pipeline x y) a) = (y (x a))."
(if (null? rest)
proc
(let ((rest-proc (apply pipeline rest)))
(lambda x
(let-values ((x (apply proc x)))
(apply rest-proc x))))))
(define (identity . x)
"Returns values given to it as-is."
(apply values x))
(define (and=> value proc)
"If VALUE is true, call PROC on it, else return false."
(if value (proc value) value))
;;; higher-order.body.scm ends here
(export
const
negate
compose
pipeline
identity
and=>
)
(define-library (r7rs-extras higher-order)
(import (scheme base))
(include-library-declarations "higher-order.exports.sld")
(include "higher-order.body.scm"))
;;; io.body.scm --- Input/Output extensions for R7RS
;; Copyright © 2014 Taylan Ulrich Bayırlı/Kammer
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: extensions io i/o input output input/output
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; R7RS leaves out some conceivable combinations of:
;;
;; [call-]with-(input|output|error)[-(from|to)]-port
;;
;; Some of these are nontrivial and annoying to redefine every time one needs
;; them. Others are actually so trivial that their body could be inlined at any
;; place of usage, but it's nevertheless distracting having to remember which
;; ones are or aren't in the base library, so we just define them all.
;;; Code:
(define (call-with-input-string string proc)
"Applies PROC to an input port fed with STRING."
(call-with-port (open-input-string string) proc))
(define (call-with-output-string proc)
"Applies PROC to a port feeding a string which is then returned."
(let ((port (open-output-string)))
(call-with-port port proc)
(get-output-string port)))
(define-syntax with-port
(syntax-rules ()
((with-port port-param port thunk closer)
(parameterize ((port-param port))
(call-with-values thunk
(lambda vals
(closer port)
(apply values vals)))))))
(define (with-input-port port thunk)
"Closes PORT after calling THUNK with it as the `current-input-port'."
(with-port current-input-port port thunk close-input-port))
(define (with-output-port port thunk)
"Closes PORT after calling THUNK with it as the `current-output-port'."
(with-port current-output-port port thunk close-output-port))
(define (with-error-port port thunk)
"Closes PORT after calling THUNK with it as the `current-error-port'."
(with-port current-error-port port thunk close-output-port))
(define (with-input-from-port port thunk)
"Calls THUNK with PORT as the `current-input-port'. Doesn't close PORT."
(parameterize ((current-input-port port))
(thunk)))
(define (with-output-to-port port thunk)
"Calls THUNK with PORT as the `current-output-port'. Doesn't close PORT."
(parameterize ((current-output-port port))
(thunk)))
(define (with-error-to-port port thunk)
"Calls THUNK with PORT as the `current-error-port'. Doesn't close PORT."
(parameterize ((current-error-port port))
(thunk)))
(define (with-error-to-file file thunk)
"Calls THUNK with `current-error-port' bound to FILE."
(with-error-port (open-output-file file) thunk))
(define (with-input-from-string string thunk)
"Calls THUNK with `current-input-port' bound to a port fed with STRING."
(with-input-port (open-input-string string) thunk))
(define (with-output-to-string thunk)
"Calls THUNK with `current-output-port' bound to a port feeding a string which
is then returned."
(let ((port (open-output-string)))
(with-output-port port thunk)
(get-output-string port)))
(define (with-error-to-string thunk)
"Calls THUNK with `current-error-port' bound to a port feeding a string which
is then returned."
(let ((port (open-output-string)))
(with-error-port port thunk)
(get-output-string port)))
;;; io.body.scm ends here
(export
call-with-input-string
call-with-output-string
with-input-port
with-output-port
with-error-port
with-input-from-port
with-output-to-port
with-error-to-port
with-error-to-file
with-input-from-string
with-output-to-string
with-error-to-string
)
(define-library (r7rs-extras io)
(import (scheme base)
(scheme file))
(include-library-declarations "io.exports.sld")
(include "io.body.scm"))
;;; partition.body.scm --- Variable-arity partition procedures
;; Copyright © 2014 Taylan Ulrich Bayırlı/Kammer
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: extensions lists partition partitioning
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; `partition' proper is in SRFI-1; we define alternative versions only.
;;; Code:
(define (%partition exclusive? list . procs)
(if (null? procs)
list
(let ((lists (make-list (+ 1 (length procs)) '())))
(for-each
(lambda (elt)
(let loop ((procs procs)
(lists lists)
(match? #f))
(if (null? procs)
(when (not match?)
(set-car! lists (cons elt (car lists))))
(if ((car procs) elt)
(begin (set-car! lists (cons elt (car lists)))
(when (not exclusive?)
(loop (cdr procs) (cdr lists) #t)))
(loop (cdr procs) (cdr lists) match?)))))
list)
(apply values (map reverse lists)))))
(define (partition* list . procs)
"Partitions LIST via PROCS, returning PROCS + 1 many lists; the last list
containing elements that didn't match any procedure. The ordering of each list
obeys that of LIST. If there are elements matching multiple PROCS, it's
unspecified in which one of the matching lists they appear."
(apply %partition #t list procs))
(define (partition+ list . procs)
"This is like the `partition*' procedure, but elements matching multiple
procedures appear in every corresponding list."
(apply %partition #f list procs))
;;; partition.body.scm ends here
(export
partition*
partition+
)
(define-library (r7rs-extras partition)
(import (scheme base))
(include-library-declarations "partition.exports.sld")
(include "partition.body.scm"))
;;; pushpop.body.scm --- push! and pop!
;; Copyright © 2014 Taylan Ulrich Bayırlı/Kammer
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer
;; Author: Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Keywords: extensions push pop
;; 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 3 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, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Dead simple push! and pop!.
;;; Code:
(define-syntax push!
(syntax-rules ()
((push! pair value)
(set! pair (cons value pair)))))
(define-syntax pop!
(syntax-rules ()
((pop! pair)
(let ((value (car pair)))
(set! pair (cdr pair))
value))))
;;; pushpop.body.scm ends here
(export
push!
pop!
)
(define-library (r7rs-extras pushpop)
(import (scheme base))
(include-library-declarations "pushpop.exports.sld")
(include "pushpop.body.scm"))
;;; generic-ref-set --- Generic accessor and modifier operators.
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;;; Helpers
(define-syntax push!
(syntax-rules ()
((_ <list-var> <x>)
(set! <list-var> (cons <x> <list-var>)))))
(define (alist->hashtable alist)
(let ((table (make-eqv-hashtable 100)))
(for-each (lambda (entry)
(hashtable-set! table (car entry) (cdr entry)))
alist)
table))
(define (pair-ref pair key)
(cond
((eqv? 'car key)
(car pair))
((eqv? 'cdr key)
(cdr pair))
(else
(list-ref pair key))))
(define (pair-set! pair key value)
(cond
((eqv? 'car key)
(set-car! pair value))
((eqv? 'cdr key)
(set-cdr! pair value))
(else
(list-set! pair key value))))
;;; Record inspection support
(cond-expand
((or (library (srfi 99))
(library (rnrs records inspection))
(library (r6rs records inspection)))
(cond-expand
((not (library (srfi 99)))
(define rtd-accessor record-accessor)
(define rtd-mutator record-mutator))
(else))
(define (record-ref record field)
(let* ((rtd (record-rtd record))
(accessor (rtd-accessor rtd field)))
(accessor record)))
(define (record-set! record field value)
(let* ((rtd (record-rtd record))
(mutator (rtd-mutator rtd field)))
(mutator record value)))
(define record-getter
(list (cons record? record-ref)))
(define record-setter
(list (cons record? record-set!)))
(define record-type
(list record?)))
(else
(define record-getter '())
(define record-setter '())
(define record-type '())))
;;; SRFI-4 support
;;; In some implementations, SRFI-4 vectors are also bytevectors. We accomodate
;;; for those implementations by using generic bytevector-ref/set! procedures
;;; which possibly dispatch to an SRFI-4 type's getter/setter, but also
;;; inserting the SRFI-4 getters/setters into the top-level dispatch tables.
(cond-expand
((library (srfi 4))
(define srfi-4-getters
(list (cons s8vector? s8vector-ref)
(cons u8vector? u8vector-ref)
(cons s16vector? s16vector-ref)
(cons u16vector? u16vector-ref)
(cons s32vector? s32vector-ref)
(cons u32vector? u32vector-ref)
(cons s64vector? s64vector-ref)
(cons u64vector? u64vector-ref)))
(define srfi-4-setters
(list (cons s8vector? s8vector-set!)
(cons u8vector? u8vector-set!)
(cons s16vector? s16vector-set!)
(cons u16vector? u16vector-set!)
(cons s32vector? s32vector-set!)
(cons u32vector? u32vector-set!)
(cons s64vector? s64vector-set!)
(cons u64vector? u64vector-set!)))
(define srfi-4-types
(list s8vector? u8vector? s16vector? u16vector? s32vector? u32vector?
s64vector? u64vector?))
(define srfi-4-getters-table (alist->hashtable srfi-4-getters))
(define srfi-4-setters-table (alist->hashtable srfi-4-setters))
(define (bytevector-ref bytevector index)
(let* ((type (find (lambda (pred) (pred bytevector))) srfi-4-types)
(getter (if type
(ref srfi-4-getters-table type)
bytevector-u8-ref)))
(getter bytevector index)))
(define (bytevector-set! bytevector index value)
(let* ((type (find (lambda (pred) (pred bytevector))) srfi-4-types)
(setter (if type
(ref srfi-4-setters-table type)
bytevector-u8-set!)))
(setter bytevector index value))))
(else
(define srfi-4-getters '())
(define srfi-4-setters '())
(define srfi-4-types '())
(define bytevector-ref bytevector-u8-ref)
(define bytevector-set! bytevector-u8-set!)))
;;; SRFI-111 boxes support
(cond-expand
((library (srfi 111))
(define (box-ref box _field)
(unbox box))
(define (box-set! box _field value)
(set-box! box value))
(define box-getter (list (cons box? box-ref)))
(define box-setter (list (cons box? box-set!)))
(define box-type (list box?)))
(else
(define box-getter '())
(define box-setter '())
(define box-type '())))
;;; Main
(define %ref
(case-lambda
((object field)
(let ((getter (lookup-getter object))
(sparse? (sparse-type? object)))
(if sparse?
(let* ((not-found (cons #f #f))
(result (getter object field not-found)))
(if (eqv? result not-found)
(error "Object has no entry for field." object field)
result))
(getter object field))))
((object field default)
(let ((getter (lookup-getter object)))
(getter object field default)))))
(define (%ref* object field . fields)
(if (null? fields)
(%ref object field)
(apply %ref* (%ref object field) fields)))
(define (%set! object field value)
(let ((setter (lookup-setter object)))
(setter object field value)))
(define ref
(getter-with-setter
%ref
(lambda (object field value)
(%set! object field value))))
(define ref*
(getter-with-setter
%ref*
(rec (set!* object field rest0 . rest)
(if (null? rest)
(%set! object field rest0)
(apply set!* (ref object field) rest0 rest)))))
(define ~ ref*)
(define $bracket-apply$ ref*)
(define (lookup-getter object)
(or (hashtable-ref getter-table (type-of object) #f)
(error "No generic getter for object's type." object)))
(define (lookup-setter object)
(or (hashtable-ref setter-table (type-of object) #f)
(error "No generic setter for object's type." object)))
(define (sparse-type? object)
(memv (type-of object) sparse-types))
(define (type-of object)
(find (lambda (pred) (pred object)) type-list))
(define getter-table
(alist->hashtable
(append
(list (cons bytevector? bytevector-ref)
(cons hashtable? hashtable-ref)
(cons pair? pair-ref)
(cons string? string-ref)
(cons vector? vector-ref))
record-getter
srfi-4-getters
box-getter)))
(define setter-table
(alist->hashtable
(append
(list (cons bytevector? bytevector-set!)
(cons hashtable? hashtable-set!)
(cons pair? pair-set!)
(cons string? string-set!)
(cons vector? vector-set!))
record-setter
srfi-4-setters
box-setter)))
(define sparse-types
(list hashtable?))
(define type-list
;; Although the whole SRFI intrinsically neglects performance, we still use
;; the micro-optimization of ordering this list roughly according to most
;; likely match.
(append
(list hashtable? vector? pair? bytevector? string?)
srfi-4-types
box-type
;; The record type must be placed last so specific record types (e.g. box)
;; take precedence.
record-type
;; Place those types we don't support really last.
(list boolean? char? eof-object? null? number? port? procedure? symbol?)))
(define (register-getter-with-setter! type getter sparse?)
(push! type-list type)
(set! (~ getter-table type) getter)
(set! (~ setter-table type) (setter getter))
(when sparse?
(push! sparse-types type)))
(cond-expand
((not (or (library (srfi 99))
(library (rnrs records inspection))
(library (r6rs records inspection))))
(define-syntax define-record-type
(syntax-rules ()
((_ <name> <constructor> <pred> <field> ...)
(begin
(%define-record-type <name> <constructor> <pred> <field> ...)
;; Throw-away definition to not disturb an internal definitions
;; sequence.
(define __throwaway
(begin
(register-getter-with-setter!
<pred>
(getter-with-setter (record-getter <field> ...)
(record-setter <field> ...))
#f)
;; Return the implementation's preferred "unspecified" value.
(if #f #f)))))))
(define-syntax record-getter
(syntax-rules ()
((_ (<field> <getter> . <rest>) ...)
(let ((getters (alist->hashtable (list (cons '<field> <getter>) ...))))
(lambda (record field)
(let ((getter (or (ref getters field #f)
(error "No such field of record." record field))))
(getter record)))))))
(define-syntax record-setter
(syntax-rules ()
((_ . <rest>)
(%record-setter () . <rest>))))
(define-syntax %record-setter
(syntax-rules ()
((_ <setters> (<field> <getter>) . <rest>)
(%record-setter <setters> . <rest>))
((_ <setters> (<field> <getter> <setter>) . <rest>)
(%record-setter ((<field> <setter>) . <setters>) . <rest>))
((_ ((<field> <setter>) ...))
(let ((setters (alist->hashtable (list (cons '<field> <setter>) ...))))
(lambda (record field value)
(let ((setter (or (ref setters field #f)
(error "No such assignable field of record."
record field))))
(setter record value)))))))))
;;; generic-ref-set.body.scm ends here
(define-library (srfi 123)
(export
ref ref* ~ register-getter-with-setter!
$bracket-apply$
set! setter getter-with-setter)
(import
(except (scheme base) set! define-record-type)
(scheme case-lambda)
(r6rs hashtables)
(srfi 1)
(srfi 17)
(srfi 31))
(cond-expand
;; Favor SRFI-99.
((library (srfi 99))
(import (srfi 99)))
;; We assume that if there's the inspection library, there's also the
;; syntactic and procedural libraries.
((library (rnrs records inspection))
(import (rnrs records syntactic))
(import (rnrs records procedural))
(import (rnrs records inspection)))
((library (r6rs records inspection))
(import (r6rs records syntactic))
(import (r6rs records procedural))
(import (r6rs records inspection)))
(else
(import (rename (only (scheme base) define-record-type)
(define-record-type %define-record-type)))
(export define-record-type)))
(cond-expand
((library (srfi 4))
(import (srfi 4)))
(else))
(cond-expand
((library (srfi 111))
(import (srfi 111)))
(else))
(include "123.body.scm"))
;;; generic-ref-set --- Generic accessor and modifier operators.
;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(define-library (tests srfi-123)
(export run-tests)
(import (except (scheme base) define-record-type set!)
(r6rs hashtables)
(srfi 64)
(srfi 123))
(cond-expand
((library (srfi 99))
(import (srfi 99)))
((library (rnrs records inspection))
(import (rnrs records syntactic))
(import (rnrs records procedural)))
(import (rnrs records inspection))
((library (r6rs records inspection))
(import (r6rs records syntactic))
(import (r6rs records procedural)))
(import (r6rs records inspection))
(else))
(cond-expand
((library (srfi 4))
(import (srfi 4)))
(else
(begin
;; Stub to silence compilers.
(define s16vector #f))))
(cond-expand
((library (srfi 111))
(import (srfi 111)))
(else
(begin
;; Stub to silence compilers.
(define box #f))))
(begin
(define-record-type <foo> (make-foo a b) foo?
(a foo-a set-foo-a!)
(b foo-b))
;; The SRFI-99 sample implementation contains a bug where immutable fields
;; are nevertheless mutable through the procedural API. Test whether we are
;; on that implementation.
(cond-expand
((library (srfi 99))
(define using-broken-srfi99
(guard (err (else #f))
(rtd-mutator <foo> 'b))))
(else
(define using-broken-srfi99 #f)))
(define (run-tests)
(let ((runner (test-runner-create)))
(parameterize ((test-runner-current runner))
(test-begin "SRFI-123")
(test-begin "ref")
(test-assert "bytevector" (= 1 (ref (bytevector 0 1 2) 1)))
(test-assert "hashtable" (let ((table (make-eqv-hashtable)))
(hashtable-set! table 'foo 0)
(= 0 (ref table 'foo))))
(test-assert "hashtable default" (let ((table (make-eqv-hashtable)))
(= 1 (ref table 0 1))))
(test-assert "pair" (= 1 (ref (cons 0 1) 'cdr)))
(test-assert "list" (= 1 (ref (list 0 1 2) 1)))
(test-assert "string" (char=? #\b (ref "abc" 1)))
(test-assert "vector" (= 1 (ref (vector 0 1 2) 1)))
(test-assert "record" (= 1 (ref (make-foo 0 1) 'b)))
(cond-expand
((library (srfi 4)) (values))
(else (test-skip 1)))
(test-assert "srfi-4" (= 1 (ref (s16vector 0 1 2) 1)))
(cond-expand
((library (srfi 111)) (values))
(else (test-skip 1)))
(test-assert "srfi-111" (= 1 (ref (box 1) '*)))
(test-end "ref")
(test-assert "ref*" (= 1 (ref* '(_ #(_ (0 . 1) _) _) 1 1 'cdr)))
(test-begin "ref setter")
(test-assert "bytevector" (let ((bv (bytevector 0 1 2)))
(set! (ref bv 1) 3)
(= 3 (ref bv 1))))
(test-assert "hashtable" (let ((ht (make-eqv-hashtable)))
(set! (ref ht 'foo) 0)
(= 0 (ref ht 'foo))))
(test-assert "pair" (let ((p (cons 0 1)))
(set! (ref p 'cdr) 2)
(= 2 (ref p 'cdr))))
(test-assert "list" (let ((l (list 0 1 2)))
(set! (ref l 1) 3)
(= 3 (ref l 1))))
(test-assert "string" (let ((s (string #\a #\b #\c)))
(set! (ref s 1) #\d)
(char=? #\d (ref s 1))))
(test-assert "vector" (let ((v (vector 0 1 2)))
(set! (ref v 1) 3)
(= 3 (ref v 1))))
(test-assert "record" (let ((r (make-foo 0 1)))
(set! (ref r 'a) 2)
(= 2 (ref r 'a))))
(when using-broken-srfi99
(test-expect-fail 1))
(test-assert "bad record assignment"
(not (guard (err (else #f)) (set! (ref (make-foo 0 1) 'b) 2) #t)))
(cond-expand
((library (srfi 4)) (values))
(else (test-skip 1)))
(test-assert "srfi-4" (let ((s16v (s16vector 0 1 2)))
(set! (ref s16v 1) 3)
(= 3 (ref s16v 1))))
(cond-expand
((library (srfi 111)) (values))
(else (test-skip 1)))
(test-assert "srfi-111" (let ((b (box 0)))
(set! (ref b '*) 1)
(= 1 (ref b '*))))
(test-end "ref setter")
(test-assert "ref* setter"
(let ((obj (list '_ (vector '_ (cons 0 1) '_) '_)))
(set! (ref* obj 1 1 'cdr) 2)
(= 2 (ref* obj 1 1 'cdr))))
(test-end "SRFI-123")
(and (= 0 (test-runner-xpass-count runner))
(= 0 (test-runner-fail-count runner))))))
))
(import (scheme base)
(scheme eval)
(scheme process-context))
(if (eval '(run-tests) (environment '(tests srfi-123)))
(exit 0)
(exit 1))
;;; Copyright 2015 William D Clinger.
;;;
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright and permission notice in full.
;;;
;;; I also request that you send me a copy of any improvements that you
;;; make to this software so that they may be incorporated within it to
;;; the benefit of the Scheme community.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This R7RS code implements (rnrs hashtables) on top of SRFI 69.
;;; Private stuff.
;;; Although SRFI 69 is mostly written as though hash functions take
;;; just one argument, its reference implementation routinely passes
;;; a second argument to hash functions, and that arguably incorrect
;;; behavior has undoubtedly found its way into many implementations
;;; of SRFI 69.
;;;
;;; A unary hash function passed to R6RS make-hashtable is therefore
;;; unlikely to work when passed to SRFI 69 make-hash-table. We need
;;; to convert the unary hash function so it will accept a second
;;; optional argument, and we also need to arrange for the original
;;; unary hash function to be returned by hashtable-hash-function.
;;;
;;; We'd like to accomplish this while preserving interoperability
;;; between R6RS hashtables and SRFI 69 hash tables. That argues
;;; against implementing R6RS hashtables by records that encapsulate
;;; a SRFI 69 hash table, which would otherwise be the easy way to
;;; go about this.
;;;
;;; This association list implements a bidirectional mapping between
;;; one-argument hash functions of R6RS and their representations as
;;; two-argument hash functions that will work with SRFI 69.
(define table-of-hash-functions '())
;;; Given a unary hash function, returns a hash function that will
;;; be acceptable to SRFI 69.
(define (make-srfi-69-hash-function hash-function)
(lambda (x . rest)
(if (null? rest)
(hash-function x)
(modulo (hash-function x) (car rest)))))
(define (r6rs->srfi69 hash-function)
(let ((probe (assoc hash-function table-of-hash-functions)))
(if probe
(cdr probe)
(let ((hasher (make-srfi-69-hash-function hash-function)))
(set! table-of-hash-functions
(cons (cons hash-function hasher)
table-of-hash-functions))
hasher))))
(define (srfi69->r6rs hasher)
(define (loop table)
(cond ((null? table)
hasher)
((equal? hasher (cdr (car table)))
(car (car table)))
(else
(loop (cdr table)))))
(loop table-of-hash-functions))
;;; SRFI 69 doesn't define a hash function that's suitable for use
;;; with the eqv? predicate, and we need one for make-eqv-hashtable.
;;;
;;; The R7RS eqv? predicate behaves the same as eq? for these types:
;;;
;;; symbols
;;; booleans
;;; empty list
;;; pairs
;;; records
;;; non-empty strings
;;; non-empty vectors
;;; non-empty bytevectors
;;;
;;; eqv? might behave differently when its arguments are:
;;;
;;; procedures that behave the same but have equal location tags
;;; numbers
;;; characters
;;; empty strings
;;; empty vectors
;;; empty bytevectors
;;;
;;; If eqv? and eq? behave differently on two arguments x and y,
;;; eqv? returns true and eq? returns false.
;;;
;;; FIXME: There is no portable way to define a good hash function
;;; that's compatible with eqv? on procedures and also runs in
;;; constant time. This one is compatible with eqv? and runs in
;;; constant time (on procedures), but isn't any good.
;;; The main thing these numerical constants have in common is that
;;; they're positive and fit in 24 bits.
(define hash:procedure 9445898)
(define hash:character 13048478)
(define hash:empty-string 14079236)
(define hash:empty-vector 1288342)
(define hash:empty-bytevector 11753202)
(define hash:inexact 1134643)
(define hash:infinity+ 2725891)
(define hash:infinity- 5984233)
(define hash:nan 7537847)
(define hash:complex 9999245)
(define (hash-for-eqv x)
(cond ((procedure? x)
hash:procedure)
((number? x)
(cond ((exact-integer? x)
x)
((not (real? x))
(+ hash:complex (complex-hash x)))
((exact? x)
(+ (numerator x) (denominator x)))
(else
(+ hash:inexact (inexact-hash x)))))
((char? x)
(+ hash:character (char->integer x)))
((eqv? x "")
hash:empty-string)
((eqv? x '#())
hash:empty-vector)
((eqv? x '#u8())
hash:empty-bytevector)
(else
(hash-by-identity x))))
;;; The R6RS distinguishes mutable from immutable hashtables,
;;; so we have to keep track of that somehow. Here we remember
;;; all of the immutable hashtables within a SRFI 69 hash-table.
;;;
;;; FIXME: That means the storage occupied by an immutable
;;; hashtable won't be reclaimed if it becomes otherwise
;;; inaccessible.
(define immutable-hashtables
(make-hash-table eqv? (r6rs->srfi69 hash-table-size)))
(define (complain-if-immutable ht complainant)
(if (hash-table-ref/default immutable-hashtables ht #f)
(error (string-append (symbol->string complainant)
": hashtable is immutable")
ht)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Exported procedures.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The R6RS make-eq-hashtable procedure is normally called with
;;; no arguments, but an optional argument specifies the initial
;;; capacity of the table. That optional argument, if present,
;;; will be ignored by this implementation because it has no
;;; counterpart in SRFI 69.
(define (make-eq-hashtable . rest)
(make-hash-table eq? hash-by-identity))
(define (make-eqv-hashtable . rest)
(make-hash-table eqv? (r6rs->srfi69 hash-for-eqv)))
;;; As with make-eq-hashtable and make-eqv-hashtable, the optional
;;; initial capacity will be ignored.
(define (make-hashtable hash-function equiv . rest)
(make-hash-table equiv (r6rs->srfi69 hash-function)))
(define (hashtable? x)
(hash-table? x))
(define (hashtable-size ht)
(hash-table-size ht))
(define (hashtable-ref ht key default)
(hash-table-ref/default ht key default))
(define (hashtable-set! ht key obj)
(complain-if-immutable ht 'hashtable-set!)
(hash-table-set! ht key obj))
(define (hashtable-delete! ht key)
(complain-if-immutable ht 'hashtable-delete!)
(hash-table-delete! ht key))
(define (hashtable-contains? ht key)
(hash-table-exists? ht key))
(define (hashtable-update! ht key proc default)
(complain-if-immutable ht 'hashtable-update!)
(hash-table-set! ht
key
(proc (hash-table-ref/default ht key default))))
;;; By default, hashtable-copy returns an immutable hashtable.
;;; The copy is mutable only if a second argument is passed and
;;; that second argument is true.
(define (hashtable-copy ht . rest)
(let ((mutable? (and (pair? rest) (car rest)))
(the-copy (hash-table-copy ht)))
(if (not mutable?)
(hash-table-set! immutable-hashtables the-copy #t))
the-copy))
;;; As usual, the optional "initial" capacity is ignored.
(define (hashtable-clear! ht . rest)
(complain-if-immutable ht 'hashtable-update!)
(hash-table-walk ht
(lambda (key value)
(hash-table-delete! ht key))))
(define (hashtable-keys ht)
(list->vector (hash-table-keys ht)))
(define (hashtable-entries ht)
(let* ((keys (hashtable-keys ht))
(vals (vector-map (lambda (key)
(hash-table-ref ht key))
keys)))
(values keys vals)))
(define (hashtable-equivalence-function ht)
(hash-table-equivalence-function ht))
(define (hashtable-hash-function ht)
(srfi69->r6rs (hash-table-hash-function ht)))
(define (hashtable-mutable? ht)
(not (hash-table-ref/default immutable-hashtables ht #f)))
(define (equal-hash obj)
(hash obj))
;;; string-hash is exported by SRFI 69.
;;; string-ci-hash is exported by SRFI 69.
(define (r6rs:symbol-hash sym)
(hash-by-identity sym))
;;; Reference implementation of SRFI 69, from
;;; http://srfi.schemers.org/srfi-69/srfi-69.html
;;; Copyright © Panu Kalliokoski (2005). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use,
;;; copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom
;;; the Software is furnished to do so, subject to the following
;;; conditions:
;;;
;;; The above copyright notice and this permission notice shall
;;; be included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
;;; KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
;;; WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
;;; PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
;;; OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
;;; OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
;;; OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;;; Modification history:
;;;
;;; In May 2015, William D Clinger modified this code for use in
;;; R7RS systems, mainly so it could be used as a last resort in
;;; the (r6rs hashtables) approximation to (rnrs hashtables).
;;;
;;; string-ci-hash was changed to use R7RS string-foldcase
;;;
;;; string-hash, symbol-hash, and %string-hash were changed
;;; to eliminate a now-useless procedure call for each character
;;;
;;; whitespace was adjusted because it got messed up during
;;; conversion from HTML to Scheme code
(define *default-bound* (- (expt 2 29) 3))
(define (%string-hash s bound)
(let ((hash 31)
(len (string-length s)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hash bound))
(set! hash (modulo (+ (* 37 hash)
(char->integer (string-ref s index)))
*default-bound*)))))
(define (string-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash s bound)))
(define (string-ci-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash (string-foldcase s) bound)))
(define (symbol-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash (symbol->string s) bound)))
(define (hash obj . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(cond ((integer? obj) (modulo obj bound))
((string? obj) (string-hash obj bound))
((symbol? obj) (symbol-hash obj bound))
((real? obj) (modulo (+ (numerator obj) (denominator obj)) bound))
((number? obj)
(modulo (+ (hash (real-part obj)) (* 3 (hash (imag-part obj))))
bound))
((char? obj) (modulo (char->integer obj) bound))
((vector? obj) (vector-hash obj bound))
((pair? obj) (modulo (+ (hash (car obj)) (* 3 (hash (cdr obj))))
bound))
((null? obj) 0)
((not obj) 0)
((procedure? obj) (error "hash: procedures cannot be hashed" obj))
(else 1))))
(define hash-by-identity hash)
(define (vector-hash v bound)
(let ((hashvalue 571)
(len (vector-length v)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hashvalue bound))
(set! hashvalue (modulo (+ (* 257 hashvalue) (hash (vector-ref v index)))
*default-bound*)))))
(define %make-hash-node cons)
(define %hash-node-set-value! set-cdr!)
(define %hash-node-key car)
(define %hash-node-value cdr)
(define-record-type <srfi-hash-table>
(%make-hash-table size hash compare associate entries)
hash-table?
(size hash-table-size hash-table-set-size!)
(hash hash-table-hash-function)
(compare hash-table-equivalence-function)
(associate hash-table-association-function)
(entries hash-table-entries hash-table-set-entries!))
(define *default-table-size* 64)
(define (appropriate-hash-function-for comparison)
(or (and (eq? comparison eq?) hash-by-identity)
(and (eq? comparison string=?) string-hash)
(and (eq? comparison string-ci=?) string-ci-hash)
hash))
(define (make-hash-table . args)
(let* ((comparison (if (null? args) equal? (car args)))
(hash
(if (or (null? args) (null? (cdr args)))
(appropriate-hash-function-for comparison) (cadr args)))
(size
(if (or (null? args) (null? (cdr args)) (null? (cddr args)))
*default-table-size* (caddr args)))
(association
(or (and (eq? comparison eq?) assq)
(and (eq? comparison eqv?) assv)
(and (eq? comparison equal?) assoc)
(letrec
((associate
(lambda (val alist)
(cond ((null? alist) #f)
((comparison val (caar alist)) (car alist))
(else (associate val (cdr alist)))))))
associate))))
(%make-hash-table 0 hash comparison association (make-vector size '()))))
(define (make-hash-table-maker comp hash)
(lambda args (apply make-hash-table (cons comp (cons hash args)))))
(define make-symbol-hash-table
(make-hash-table-maker eq? symbol-hash))
(define make-string-hash-table
(make-hash-table-maker string=? string-hash))
(define make-string-ci-hash-table
(make-hash-table-maker string-ci=? string-ci-hash))
(define make-integer-hash-table
(make-hash-table-maker = modulo))
(define (%hash-table-hash hash-table key)
((hash-table-hash-function hash-table)
key (vector-length (hash-table-entries hash-table))))
(define (%hash-table-find entries associate hash key)
(associate key (vector-ref entries hash)))
(define (%hash-table-add! entries hash key value)
(vector-set! entries hash
(cons (%make-hash-node key value)
(vector-ref entries hash))))
(define (%hash-table-delete! entries compare hash key)
(let ((entrylist (vector-ref entries hash)))
(cond ((null? entrylist) #f)
((compare key (caar entrylist))
(vector-set! entries hash (cdr entrylist)) #t)
(else
(let loop ((current (cdr entrylist)) (previous entrylist))
(cond ((null? current) #f)
((compare key (caar current))
(set-cdr! previous (cdr current)) #t)
(else (loop (cdr current) current))))))))
(define (%hash-table-walk proc entries)
(do ((index (- (vector-length entries) 1) (- index 1)))
((< index 0)) (for-each proc (vector-ref entries index))))
(define (%hash-table-maybe-resize! hash-table)
(let* ((old-entries (hash-table-entries hash-table))
(hash-length (vector-length old-entries)))
(if (> (hash-table-size hash-table) hash-length)
(let* ((new-length (* 2 hash-length))
(new-entries (make-vector new-length '()))
(hash (hash-table-hash-function hash-table)))
(%hash-table-walk
(lambda (node)
(%hash-table-add! new-entries
(hash (%hash-node-key node) new-length)
(%hash-node-key node) (%hash-node-value node)))
old-entries)
(hash-table-set-entries! hash-table new-entries)))))
(define (hash-table-ref hash-table key . maybe-default)
(cond ((%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key)
=> %hash-node-value)
((null? maybe-default)
(error "hash-table-ref: no value associated with" key))
(else ((car maybe-default)))))
(define (hash-table-ref/default hash-table key default)
(hash-table-ref hash-table key (lambda () default)))
(define (hash-table-set! hash-table key value)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node) (%hash-node-set-value! node value)))
(else (%hash-table-add! entries hash key value)
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))
(define (hash-table-update! hash-table key function . maybe-default)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node)
(%hash-node-set-value!
node (function (%hash-node-value node)))))
((null? maybe-default)
(error "hash-table-update!: no value exists for key" key))
(else (%hash-table-add! entries hash key
(function ((car maybe-default))))
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))
(define (hash-table-update!/default hash-table key function default)
(hash-table-update! hash-table key function (lambda () default)))
(define (hash-table-delete! hash-table key)
(if (%hash-table-delete! (hash-table-entries hash-table)
(hash-table-equivalence-function hash-table)
(%hash-table-hash hash-table key) key)
(hash-table-set-size! hash-table (- (hash-table-size hash-table) 1))))
(define (hash-table-exists? hash-table key)
(and (%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key) #t))
(define (hash-table-walk hash-table proc)
(%hash-table-walk
(lambda (node) (proc (%hash-node-key node) (%hash-node-value node)))
(hash-table-entries hash-table)))
(define (hash-table-fold hash-table f acc)
(hash-table-walk hash-table
(lambda (key value) (set! acc (f key value acc))))
acc)
(define (alist->hash-table alist . args)
(let* ((comparison (if (null? args) equal? (car args)))
(hash
(if (or (null? args) (null? (cdr args)))
(appropriate-hash-function-for comparison) (cadr args)))
(size
(if (or (null? args) (null? (cdr args)) (null? (cddr args)))
(max *default-table-size* (* 2 (length alist))) (caddr args)))
(hash-table (make-hash-table comparison hash size)))
(for-each
(lambda (elem)
(hash-table-update!/default
hash-table (car elem) (lambda (x) x) (cdr elem)))
alist)
hash-table))
(define (hash-table->alist hash-table)
(hash-table-fold hash-table
(lambda (key val acc) (cons (cons key val) acc)) '()))
(define (hash-table-copy hash-table)
(let ((new (make-hash-table (hash-table-equivalence-function hash-table)
(hash-table-hash-function hash-table)
(max *default-table-size*
(* 2 (hash-table-size hash-table))))))
(hash-table-walk hash-table
(lambda (key value) (hash-table-set! new key value)))
new))
(define (hash-table-merge! hash-table1 hash-table2)
(hash-table-walk
hash-table2
(lambda (key value) (hash-table-set! hash-table1 key value)))
hash-table1)
(define (hash-table-keys hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons key acc)) '()))
(define (hash-table-values hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons val acc)) '()))
; eof
;; Copyright 1991, 1994, 1998 William D Clinger
;; Copyright 1998 Lars T Hansen
;; Copyright 1984 - 1993 Lightship Software, Incorporated
;; Permission to copy this software, in whole or in part, to use this
;; software for any lawful purpose, and to redistribute this software
;; is granted subject to the following restriction: Any publication
;; or redistribution of this software, whether on its own or
;; incorporated into other software, must bear the above copyright
;; notices and the following legend:
;; The Twobit compiler and the Larceny runtime system were
;; developed by William Clinger and Lars Hansen with the
;; assistance of Lightship Software and the College of Computer
;; Science of Northeastern University. This acknowledges that
;; Clinger et al remain the sole copyright holders to Twobit
;; and Larceny and that no rights pursuant to that status are
;; waived or conveyed.
;; Twobit and Larceny are provided as is. The user specifically
;; acknowledges that Northeastern University, William Clinger, Lars
;; Hansen, and Lightship Software have not made any representations
;; or warranty with regard to performance of Twobit and Larceny,
;; their merchantability, or fitness for a particular purpose. Users
;; further acknowledge that they have had the opportunity to inspect
;; Twobit and Larceny and will hold harmless Northeastern University,
;; William Clinger, Lars Hansen, and Lightship Software from any cost,
;; liability, or expense arising from, or in any way related to the
;; use of this software.
(define-library (r6rs hashtables)
(export
make-eq-hashtable
make-eqv-hashtable
make-hashtable
hashtable?
hashtable-size
hashtable-ref
hashtable-set!
hashtable-delete!
hashtable-contains?
hashtable-update!
hashtable-copy
hashtable-clear!
hashtable-keys
hashtable-entries
hashtable-equivalence-function
hashtable-hash-function
hashtable-mutable?
equal-hash
string-hash
string-ci-hash
(rename r6rs:symbol-hash symbol-hash) ; see explanation below
)
(import (scheme base)
(scheme cxr))
;; Hashing on inexact and complex numbers depends on whether the
;; (scheme inexact) and (scheme complex) libraries are available.
(cond-expand
((library (rnrs hashtables))) ; nothing to do
((library (scheme inexact))
(import (scheme inexact))
(begin
(define (inexact-hash x)
(cond ((finite? x)
(hash-for-eqv (exact x)))
((infinite? x)
(if (> x 0.0)
hash:infinity+
hash:infinity-))
(else
hash:nan)))))
(else
(begin
(define (inexact-hash x) 0))))
(cond-expand
((and (library (rnrs hashtables))
(not (library (r6rs no-rnrs))))
;; nothing to do
)
((library (scheme complex))
(import (scheme complex))
(begin
(define (complex-hash z)
(+ (hash-for-eqv (real-part z))
(hash-for-eqv (imag-part z))))))
(else
(begin
(define (complex-hash z) 0))))
;; If the (rnrs hashtables) library is available, import it.
;; Otherwise use SRFI 69 if it's available.
;; If SRFI 69 isn't available, use its reference implementation.
;;
;; The (r6rs hashtables) library must export symbol-hash, which
;; has no equivalent among the procedures specified by SRFI 69.
;; The SRFI 69 reference implementation does define symbol-hash,
;; however, which has led to the current situation in which some
;; implementations of (srfi 69) export symbol-hash but others
;; don't. The R7RS says it's an error to import symbol-hash
;; more than once with different bindings, or to redefine it
;; if it's been imported, so this (r6rs hashtables) library
;; defines r6rs:symbol-hash and renames it to symbol-hash only
;; when it's exported.
(cond-expand
((and (library (rnrs hashtables))
(not (library (r6rs no-rnrs))))
(import (rnrs hashtables))
(begin (define r6rs:symbol-hash symbol-hash)))
((library (srfi 69 basic-hash-tables))
(import (srfi 69 basic-hash-tables))
(include "hashtables.atop69.scm"))
((library (srfi 69))
(import (srfi 69))
(include "hashtables.atop69.scm"))
((library (srfi 69 basic-hash-tables))
(import (srfi 69 basic-hash-tables))
(include "hashtables.atop69.scm"))
((library (srfi 69))
(import (srfi 69))
(include "hashtables.atop69.scm"))
((library (scheme char))
(import (scheme char))
(include "hashtables.body69.scm")
(include "hashtables.atop69.scm"))
(else
(begin (define (string-foldcase s) s)
(define (string-ci=? s1 s2)
(string=? s1 s2)))
(include "hashtables.body69.scm")
(include "hashtables.atop69.scm")))
)
(define make-eq-hashtable
(case-lambda
(() (make-eq-hashtable #f #f))
((capacity) (make-eq-hashtable capacity #f))
((capacity weakness)
(when weakness
(error "No weak or ephemeral hashtables supported."))
(if capacity
(rnrs-make-eq-hashtable capacity)
(rnrs-make-eq-hashtable)))))
(define make-eqv-hashtable
(case-lambda
(() (make-eqv-hashtable #f #f))
((capacity) (make-eqv-hashtable capacity #f))
((capacity weakness)
(when weakness
(error "No weak or ephemeral hashtables supported."))
(if capacity
(rnrs-make-eqv-hashtable capacity)
(rnrs-make-eqv-hashtable)))))
(define make-hashtable
(case-lambda
((hash equiv) (make-hashtable hash equiv #f #f))
((hash equiv capacity) (make-hashtable hash equiv capacity #f))
((hash equiv capacity weakness)
(cond
((and (not hash) (eq? equiv eq?))
(make-eq-hashtable capacity weakness))
((and (not hash) (eq? equiv eqv?))
(make-eqv-hashtable capacity weakness))
(else
(when weakness
(error "No weak or ephemeral hashtables supported."))
(let ((hash (if (pair? hash)
(car hash)
hash)))
(if capacity
(rnrs-make-hashtable hash equiv capacity)
(rnrs-make-hashtable hash equiv))))))))
(define (alist->eq-hashtable . args)
(apply alist->hashtable #f eq? args))
(define (alist->eqv-hashtable . args)
(apply alist->hashtable #f eqv? args))
(define alist->hashtable
(case-lambda
((hash equiv alist)
(alist->hashtable hash equiv #f #f alist))
((hash equiv capacity alist)
(alist->hashtable hash equiv capacity #f alist))
((hash equiv capacity weakness alist)
(let ((hashtable (make-hashtable hash equiv capacity weakness)))
(for-each (lambda (entry)
(hashtable-set! hashtable (car entry) (cdr entry)))
(reverse alist))
hashtable))))
(define-enumeration weakness
(weak-key
weak-value
weak-key-and-value
ephemeral-key
ephemeral-value
ephemeral-key-and-value)
weakness-set)
(define hashtable? rnrs-hashtable?)
(define hashtable-size rnrs-hashtable-size)
(define nil (cons #f #f))
(define (nil? obj) (eq? obj nil))
(define hashtable-ref
(case-lambda
((hashtable key)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(error "No such key in hashtable." hashtable key)
value)))
((hashtable key default)
(rnrs-hashtable-ref hashtable key default))))
(define hashtable-set! rnrs-hashtable-set!)
(define hashtable-delete! rnrs-hashtable-delete!)
(define hashtable-contains? rnrs-hashtable-contains?)
(define (hashtable-lookup hashtable key)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(values #f #f)
(values value #t))))
(define hashtable-update!
(case-lambda
((hashtable key proc) (hashtable-update! hashtable key proc nil))
((hashtable key proc default)
(rnrs-hashtable-update!
hashtable key
(lambda (value)
(if (nil? value)
(error "No such key in hashtable." hashtable key)
(proc value)))
default))))
;;; XXX This could be implemented at the platform level to eliminate the second
;;; lookup for the key.
(define (hashtable-intern! hashtable key default-proc)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(let ((value (default-proc)))
(hashtable-set! hashtable key value)
value)
value)))
(define hashtable-copy
(case-lambda
((hashtable) (hashtable-copy hashtable #f #f))
((hashtable mutable) (hashtable-copy hashtable mutable #f))
((hashtable mutable weakness)
(when weakness
(error "No weak or ephemeral tables supported."))
(rnrs-hashtable-copy hashtable mutable))))
(define hashtable-clear!
(case-lambda
((hashtable) (rnrs-hashtable-clear! hashtable))
((hashtable capacity)
(if capacity
(rnrs-hashtable-clear! hashtable capacity)
(rnrs-hashtable-clear! hashtable)))))
(define hashtable-empty-copy
(case-lambda
((hashtable) (hashtable-empty-copy hashtable #f))
((hashtable capacity)
(make-hashtable (hashtable-hash-function hashtable)
(hashtable-equivalence-function hashtable)
(if (eq? #t capacity)
(hashtable-size hashtable)
capacity)
(hashtable-weakness hashtable)))))
(define hashtable-keys rnrs-hashtable-keys)
(define (hashtable-values hashtable)
(let-values (((keys values) (rnrs-hashtable-entries hashtable)))
values))
(define hashtable-entries rnrs-hashtable-entries)
(define (hashtable-key-list hashtable)
(hashtable-map->lset hashtable (lambda (key value) key)))
(define (hashtable-value-list hashtable)
(hashtable-map->lset hashtable (lambda (key value) value)))
(define (hashtable-entry-lists hashtable)
(let ((keys '())
(vals '()))
(hashtable-walk hashtable
(lambda (key val)
(set! keys (cons key keys))
(set! vals (cons val vals))))
(values keys vals)))
;;; XXX The procedures hashtable-walk, hashtable-update-all!, hashtable-prune!,
;;; and hashtable-sum should be implemented more efficiently at the platform
;;; level. In particular, they should not allocate intermediate vectors or
;;; lists to hold the keys or values that are being operated on.
(define (hashtable-walk hashtable proc)
(let-values (((keys values) (rnrs-hashtable-entries hashtable)))
(vector-for-each proc keys values)))
(define (hashtable-update-all! hashtable proc)
(let-values (((keys values) (hashtable-entries hashtable)))
(vector-for-each (lambda (key value)
(hashtable-set! hashtable key (proc key value)))
keys values)))
(define (hashtable-prune! hashtable proc)
(let-values (((keys values) (hashtable-entries hashtable)))
(vector-for-each (lambda (key value)
(when (proc key value)
(hashtable-delete! hashtable key)))
keys values)))
(define (hashtable-merge! hashtable-dest hashtable-source)
(hashtable-walk hashtable-source
(lambda (key value)
(hashtable-set! hashtable-dest key value)))
hashtable-dest)
(define (hashtable-sum hashtable init proc)
(let-values (((keys vals) (hashtable-entry-lists hashtable)))
(fold proc init keys vals)))
(define (hashtable-map->lset hashtable proc)
(hashtable-sum hashtable '()
(lambda (key value accumulator)
(cons (proc key value) accumulator))))
;;; XXX If available, let-escape-continuation might be more efficient than
;;; call/cc here.
(define (hashtable-find hashtable proc)
(call/cc
(lambda (return)
(hashtable-walk hashtable
(lambda (key value)
(when (proc key value)
(return key value #t))))
(return #f #f #f))))
(define (hashtable-empty? hashtable)
(zero? (hashtable-size hashtable)))
;;; XXX A platform-level implementation could avoid allocating the constant true
;;; function and the lookup for the key in the delete operation.
(define (hashtable-pop! hashtable)
(if (hashtable-empty? hashtable)
(error "Cannot pop from empty hashtable." hashtable)
(let-values (((key value found?)
(hashtable-find hashtable (lambda (k v) #t))))
(hashtable-delete! hashtable key)
(values key value))))
(define hashtable-inc!
(case-lambda
((hashtable key) (hashtable-inc! hashtable key 1))
((hashtable key number)
(hashtable-update! hashtable key (lambda (v) (+ v number)) 0))))
(define hashtable-dec!
(case-lambda
((hashtable key) (hashtable-dec! hashtable key 1))
((hashtable key number)
(hashtable-update! hashtable key (lambda (v) (- v number)) 0))))
(define hashtable-equivalence-function rnrs-hashtable-equivalence-function)
(define hashtable-hash-function rnrs-hashtable-hash-function)
(define (hashtable-weakness hashtable) #f)
(define hashtable-mutable? rnrs-hashtable-mutable?)
(define *hash-salt*
(let ((seed (get-environment-variable "SRFI_126_HASH_SEED")))
(if (or (not seed) (string=? seed ""))
(random-integer (greatest-fixnum))
(modulo
(fold (lambda (char result)
(+ (char->integer char) result))
0
(string->list seed))
(greatest-fixnum)))))
(define (hash-salt) *hash-salt*)
(define equal-hash rnrs-equal-hash)
(define string-hash rnrs-string-hash)
(define string-ci-hash rnrs-string-ci-hash)
(define symbol-hash rnrs-symbol-hash)
;; Local Variables:
;; eval: (put 'hashtable-walk 'scheme-indent-function 1)
;; eval: (put 'hashtable-update-all! 'scheme-indent-function 1)
;; eval: (put 'hashtable-prune! 'scheme-indent-function 1)
;; eval: (put 'hashtable-sum 'scheme-indent-function 2)
;; eval: (put 'hashtable-map->lset 'scheme-indent-function 1)
;; eval: (put 'hashtable-find 'scheme-indent-function 1)
;; End:
(define-library (srfi 126)
(export
make-eq-hashtable make-eqv-hashtable make-hashtable
alist->eq-hashtable alist->eqv-hashtable alist->hashtable
weakness
hashtable?
hashtable-size
hashtable-ref hashtable-set! hashtable-delete!
hashtable-contains?
hashtable-lookup hashtable-update! hashtable-intern!
hashtable-copy hashtable-clear! hashtable-empty-copy
hashtable-keys hashtable-values hashtable-entries
hashtable-key-list hashtable-value-list hashtable-entry-lists
hashtable-walk hashtable-update-all! hashtable-prune! hashtable-merge!
hashtable-sum hashtable-map->lset hashtable-find
hashtable-empty? hashtable-pop! hashtable-inc! hashtable-dec!
hashtable-equivalence-function hashtable-hash-function hashtable-weakness
hashtable-mutable?
hash-salt equal-hash string-hash string-ci-hash symbol-hash)
(import
(scheme base)
(scheme case-lambda)
(scheme process-context)
(r6rs enums)
(prefix (r6rs hashtables) rnrs-)
(srfi 1)
(srfi 27))
(begin
;; Smallest allowed in R6RS.
(define (greatest-fixnum) (expt 23 2))
;; INCLUDE 126.body.scm
(define make-eq-hashtable
(case-lambda
(() (make-eq-hashtable #f #f))
((capacity) (make-eq-hashtable capacity #f))
((capacity weakness)
(when weakness
(error "No weak or ephemeral hashtables supported."))
(if capacity
(rnrs-make-eq-hashtable capacity)
(rnrs-make-eq-hashtable)))))
(define make-eqv-hashtable
(case-lambda
(() (make-eqv-hashtable #f #f))
((capacity) (make-eqv-hashtable capacity #f))
((capacity weakness)
(when weakness
(error "No weak or ephemeral hashtables supported."))
(if capacity
(rnrs-make-eqv-hashtable capacity)
(rnrs-make-eqv-hashtable)))))
(define make-hashtable
(case-lambda
((hash equiv) (make-hashtable hash equiv #f #f))
((hash equiv capacity) (make-hashtable hash equiv capacity #f))
((hash equiv capacity weakness)
(cond
((and (not hash) (eq? equiv eq?))
(make-eq-hashtable capacity weakness))
((and (not hash) (eq? equiv eqv?))
(make-eqv-hashtable capacity weakness))
(else
(when weakness
(error "No weak or ephemeral hashtables supported."))
(let ((hash (if (pair? hash)
(car hash)
hash)))
(if capacity
(rnrs-make-hashtable hash equiv capacity)
(rnrs-make-hashtable hash equiv))))))))
(define (alist->eq-hashtable . args)
(apply alist->hashtable #f eq? args))
(define (alist->eqv-hashtable . args)
(apply alist->hashtable #f eqv? args))
(define alist->hashtable
(case-lambda
((hash equiv alist)
(alist->hashtable hash equiv #f #f alist))
((hash equiv capacity alist)
(alist->hashtable hash equiv capacity #f alist))
((hash equiv capacity weakness alist)
(let ((hashtable (make-hashtable hash equiv capacity weakness)))
(for-each (lambda (entry)
(hashtable-set! hashtable (car entry) (cdr entry)))
(reverse alist))
hashtable))))
(define-enumeration weakness
(weak-key
weak-value
weak-key-and-value
ephemeral-key
ephemeral-value
ephemeral-key-and-value)
weakness-set)
(define hashtable? rnrs-hashtable?)
(define hashtable-size rnrs-hashtable-size)
(define nil (cons #f #f))
(define (nil? obj) (eq? obj nil))
(define hashtable-ref
(case-lambda
((hashtable key)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(error "No such key in hashtable." hashtable key)
value)))
((hashtable key default)
(rnrs-hashtable-ref hashtable key default))))
(define hashtable-set! rnrs-hashtable-set!)
(define hashtable-delete! rnrs-hashtable-delete!)
(define hashtable-contains? rnrs-hashtable-contains?)
(define (hashtable-lookup hashtable key)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(values #f #f)
(values value #t))))
(define hashtable-update!
(case-lambda
((hashtable key proc) (hashtable-update! hashtable key proc nil))
((hashtable key proc default)
(rnrs-hashtable-update!
hashtable key
(lambda (value)
(if (nil? value)
(error "No such key in hashtable." hashtable key)
(proc value)))
default))))
;;; XXX This could be implemented at the platform level to eliminate the second
;;; lookup for the key.
(define (hashtable-intern! hashtable key default-proc)
(let ((value (rnrs-hashtable-ref hashtable key nil)))
(if (nil? value)
(let ((value (default-proc)))
(hashtable-set! hashtable key value)
value)
value)))
(define hashtable-copy
(case-lambda
((hashtable) (hashtable-copy hashtable #f #f))
((hashtable mutable) (hashtable-copy hashtable mutable #f))
((hashtable mutable weakness)
(when weakness
(error "No weak or ephemeral tables supported."))
(rnrs-hashtable-copy hashtable mutable))))
(define hashtable-clear!
(case-lambda
((hashtable) (rnrs-hashtable-clear! hashtable))
((hashtable capacity)
(if capacity
(rnrs-hashtable-clear! hashtable capacity)
(rnrs-hashtable-clear! hashtable)))))
(define hashtable-empty-copy
(case-lambda
((hashtable) (hashtable-empty-copy hashtable #f))
((hashtable capacity)
(make-hashtable (hashtable-hash-function hashtable)
(hashtable-equivalence-function hashtable)
(if (eq? #t capacity)
(hashtable-size hashtable)
capacity)
(hashtable-weakness hashtable)))))
(define hashtable-keys rnrs-hashtable-keys)
(define (hashtable-values hashtable)
(let-values (((keys values) (rnrs-hashtable-entries hashtable)))
values))
(define hashtable-entries rnrs-hashtable-entries)
(define (hashtable-key-list hashtable)
(hashtable-map->lset hashtable (lambda (key value) key)))
(define (hashtable-value-list hashtable)
(hashtable-map->lset hashtable (lambda (key value) value)))
(define (hashtable-entry-lists hashtable)
(let ((keys '())
(vals '()))
(hashtable-walk hashtable
(lambda (key val)
(set! keys (cons key keys))
(set! vals (cons val vals))))
(values keys vals)))
;;; XXX The procedures hashtable-walk, hashtable-update-all!, hashtable-prune!,
;;; and hashtable-sum should be implemented more efficiently at the platform
;;; level. In particular, they should not allocate intermediate vectors or
;;; lists to hold the keys or values that are being operated on.
(define (hashtable-walk hashtable proc)
(let-values (((keys values) (rnrs-hashtable-entries hashtable)))
(vector-for-each proc keys values)))
(define (hashtable-update-all! hashtable proc)
(let-values (((keys values) (hashtable-entries hashtable)))
(vector-for-each (lambda (key value)
(hashtable-set! hashtable key (proc key value)))
keys values)))
(define (hashtable-prune! hashtable proc)
(let-values (((keys values) (hashtable-entries hashtable)))
(vector-for-each (lambda (key value)
(when (proc key value)
(hashtable-delete! hashtable key)))
keys values)))
(define (hashtable-merge! hashtable-dest hashtable-source)
(hashtable-walk hashtable-source
(lambda (key value)
(hashtable-set! hashtable-dest key value)))
hashtable-dest)
(define (hashtable-sum hashtable init proc)
(let-values (((keys vals) (hashtable-entry-lists hashtable)))
(fold proc init keys vals)))
(define (hashtable-map->lset hashtable proc)
(hashtable-sum hashtable '()
(lambda (key value accumulator)
(cons (proc key value) accumulator))))
;;; XXX If available, let-escape-continuation might be more efficient than
;;; call/cc here.
(define (hashtable-find hashtable proc)
(call/cc
(lambda (return)
(hashtable-walk hashtable
(lambda (key value)
(when (proc key value)
(return key value #t))))
(return #f #f #f))))
(define (hashtable-empty? hashtable)
(zero? (hashtable-size hashtable)))
;;; XXX A platform-level implementation could avoid allocating the constant true
;;; function and the lookup for the key in the delete operation.
(define (hashtable-pop! hashtable)
(if (hashtable-empty? hashtable)
(error "Cannot pop from empty hashtable." hashtable)
(let-values (((key value found?)
(hashtable-find hashtable (lambda (k v) #t))))
(hashtable-delete! hashtable key)
(values key value))))
(define hashtable-inc!
(case-lambda
((hashtable key) (hashtable-inc! hashtable key 1))
((hashtable key number)
(hashtable-update! hashtable key (lambda (v) (+ v number)) 0))))
(define hashtable-dec!
(case-lambda
((hashtable key) (hashtable-dec! hashtable key 1))
((hashtable key number)
(hashtable-update! hashtable key (lambda (v) (- v number)) 0))))
(define hashtable-equivalence-function rnrs-hashtable-equivalence-function)
(define hashtable-hash-function rnrs-hashtable-hash-function)
(define (hashtable-weakness hashtable) #f)
(define hashtable-mutable? rnrs-hashtable-mutable?)
(define *hash-salt*
(let ((seed (get-environment-variable "SRFI_126_HASH_SEED")))
(if (or (not seed) (string=? seed ""))
(random-integer (greatest-fixnum))
(modulo
(fold (lambda (char result)
(+ (char->integer char) result))
0
(string->list seed))
(greatest-fixnum)))))
(define (hash-salt) *hash-salt*)
(define equal-hash rnrs-equal-hash)
(define string-hash rnrs-string-hash)
(define string-ci-hash rnrs-string-ci-hash)
(define symbol-hash rnrs-symbol-hash)
;; Local Variables:
;; eval: (put 'hashtable-walk 'scheme-indent-function 1)
;; eval: (put 'hashtable-update-all! 'scheme-indent-function 1)
;; eval: (put 'hashtable-prune! 'scheme-indent-function 1)
;; eval: (put 'hashtable-sum 'scheme-indent-function 2)
;; eval: (put 'hashtable-map->lset 'scheme-indent-function 1)
;; eval: (put 'hashtable-find 'scheme-indent-function 1)
;; End:
))
;;; Guile implementation.
(define-module (srfi srfi-126))
(use-modules
(srfi srfi-1)
(srfi srfi-9)
(srfi srfi-9 gnu)
(srfi srfi-11)
(ice-9 hash-table)
(ice-9 control)
((rnrs hashtables) #\select
(equal-hash string-hash string-ci-hash symbol-hash)))
(export
make-eq-hashtable make-eqv-hashtable make-hashtable
alist->eq-hashtable alist->eqv-hashtable alist->hashtable
weakness
hashtable? hashtable-size
hashtable-ref hashtable-set! hashtable-delete! hashtable-contains?
hashtable-lookup hashtable-update! hashtable-intern!
hashtable-copy hashtable-clear! hashtable-empty-copy
hashtable-keys hashtable-values hashtable-entries
hashtable-key-list hashtable-value-list hashtable-entry-lists
hashtable-walk hashtable-update-all! hashtable-prune! hashtable-merge!
hashtable-sum hashtable-map->lset hashtable-find
hashtable-empty? hashtable-pop! hashtable-inc! hashtable-dec!
hashtable-equivalence-function hashtable-hash-function
hashtable-weakness hashtable-mutable?
hash-salt
)
(re-export equal-hash string-hash string-ci-hash symbol-hash)
(define-record-type <hashtable>
(%make-hashtable %table %hash %assoc hash equiv weakness mutable)
hashtable?
(%table %hashtable-table)
(%hash %hashtable-hash)
(%assoc %hashtable-assoc)
(hash hashtable-hash-function)
(equiv hashtable-equivalence-function)
(weakness hashtable-weakness)
(mutable hashtable-mutable? %hashtable-set-mutable!))
(define nil (cons #f #f))
(define (nil? obj) (eq? obj nil))
(define (make-table capacity weakness)
(let ((capacity (or capacity 32)))
(case weakness
((#f) (make-hash-table capacity))
((weak-key) (make-weak-key-hash-table capacity))
((weak-value) (make-weak-value-hash-table capacity))
((weak-key-and-value) (make-doubly-weak-hash-table capacity))
(else (error "Hashtable weakness not supported." weakness)))))
(define* (make-eq-hashtable #\optional capacity weakness)
(let ((table (make-table capacity weakness)))
(%make-hashtable table hashq assq #f eq? weakness #t)))
(define* (make-eqv-hashtable #\optional capacity weakness)
(let ((table (make-table capacity weakness)))
(%make-hashtable table hashv assv #f eqv? weakness #t)))
(define* (make-hashtable hash equiv #\optional capacity weakness)
(cond
((and (not hash) (eq? equiv eq?))
(make-eq-hashtable capacity weakness))
((and (not hash) (eq? equiv eqv?))
(make-eqv-hashtable capacity weakness))
(else
(let* ((table (make-table capacity weakness))
(hash (if (pair? hash)
(car hash)
hash))
(%hash (lambda (obj bound)
(modulo (hash obj) bound)))
(assoc (lambda (key alist)
(find (lambda (entry)
(equiv (car entry) key))
alist))))
(%make-hashtable table %hash assoc hash equiv weakness #t)))))
(define (alist->eq-hashtable . args)
(apply alist->hashtable #f eq? args))
(define (alist->eqv-hashtable . args)
(apply alist->hashtable #f eqv? args))
(define alist->hashtable
(case-lambda
((hash equiv alist)
(alist->hashtable hash equiv #f #f alist))
((hash equiv capacity alist)
(alist->hashtable hash equiv capacity #f alist))
((hash equiv capacity weakness alist)
(let ((ht (make-hashtable hash equiv capacity weakness)))
(for-each (lambda (entry)
(hashtable-set! ht (car entry) (cdr entry)))
(reverse alist))
ht))))
(define-syntax weakness
(lambda (stx)
(syntax-case stx ()
((_ <sym>)
(let ((sym (syntax->datum #'<sym>)))
(case sym
((weak-key weak-value weak-key-and-value ephemeral-key
ephemeral-value ephemeral-key-and-value)
#''sym)
(else
(error "Bad weakness symbol." sym))))))))
(define (hashtable-size ht)
(hash-count (const #t) (%hashtable-table ht)))
(define* (%hashtable-ref ht key default)
(hashx-ref (%hashtable-hash ht) (%hashtable-assoc ht)
(%hashtable-table ht) key default))
(define* (hashtable-ref ht key #\optional (default nil))
(let ((val (%hashtable-ref ht key default)))
(if (nil? val)
(error "No association for key in hashtable." key ht)
val)))
(define (assert-mutable ht)
(when (not (hashtable-mutable? ht))
(error "Hashtable is immutable." ht)))
(define (hashtable-set! ht key value)
(assert-mutable ht)
(hashx-set! (%hashtable-hash ht) (%hashtable-assoc ht)
(%hashtable-table ht) key value)
*unspecified*)
(define (hashtable-delete! ht key)
(assert-mutable ht)
(hashx-remove! (%hashtable-hash ht) (%hashtable-assoc ht)
(%hashtable-table ht) key)
*unspecified*)
(define (hashtable-contains? ht key)
(not (nil? (%hashtable-ref ht key nil))))
(define (hashtable-lookup ht key)
(let ((val (%hashtable-ref ht key nil)))
(if (nil? val)
(values #f #f)
(values val #t))))
(define* (hashtable-update! ht key updater #\optional (default nil))
(assert-mutable ht)
(let ((handle (hashx-create-handle!
(%hashtable-hash ht) (%hashtable-assoc ht)
(%hashtable-table ht) key nil)))
(if (eq? nil (cdr handle))
(if (nil? default)
(error "No association for key in hashtable." key ht)
(set-cdr! handle (updater default)))
(set-cdr! handle (updater (cdr handle))))
(cdr handle)))
(define (hashtable-intern! ht key default-proc)
(assert-mutable ht)
(let ((handle (hashx-create-handle!
(%hashtable-hash ht) (%hashtable-assoc ht)
(%hashtable-table ht) key nil)))
(when (nil? (cdr handle))
(set-cdr! handle (default-proc)))
(cdr handle)))
(define* (hashtable-copy ht #\optional mutable weakness)
(let ((copy (hashtable-empty-copy ht (hashtable-size ht) weakness)))
(hashtable-walk ht
(lambda (k v)
(hashtable-set! copy k v)))
(%hashtable-set-mutable! copy mutable)
copy))
(define* (hashtable-clear! ht #\optional _capacity)
(assert-mutable ht)
(hash-clear! (%hashtable-table ht))
*unspecified*)
(define* (hashtable-empty-copy ht #\optional capacity weakness)
(make-hashtable (hashtable-hash-function ht)
(hashtable-equivalence-function ht)
(case capacity
((#f) #f)
((#t) (hashtable-size ht))
(else capacity))
(or weakness (hashtable-weakness ht))))
(define (hashtable-keys ht)
(let ((keys (make-vector (hashtable-size ht))))
(hashtable-sum ht 0
(lambda (k v i)
(vector-set! keys i k)
(+ i 1)))
keys))
(define (hashtable-values ht)
(let ((vals (make-vector (hashtable-size ht))))
(hashtable-sum ht 0
(lambda (k v i)
(vector-set! vals i v)
(+ i 1)))
vals))
(define (hashtable-entries ht)
(let ((keys (make-vector (hashtable-size ht)))
(vals (make-vector (hashtable-size ht))))
(hashtable-sum ht 0
(lambda (k v i)
(vector-set! keys i k)
(vector-set! vals i v)
(+ i 1)))
(values keys vals)))
(define (hashtable-key-list ht)
(hashtable-map->lset ht (lambda (k v) k)))
(define (hashtable-value-list ht)
(hashtable-map->lset ht (lambda (k v) v)))
(define (hashtable-entry-lists ht)
(let ((keys&vals (cons '() '())))
(hashtable-walk ht
(lambda (k v)
(set-car! keys&vals (cons k (car keys&vals)))
(set-cdr! keys&vals (cons v (cdr keys&vals)))))
(car+cdr keys&vals)))
(define (hashtable-walk ht proc)
(hash-for-each proc (%hashtable-table ht)))
(define (hashtable-update-all! ht proc)
(assert-mutable ht)
(hash-for-each-handle
(lambda (handle)
(set-cdr! handle (proc (car handle) (cdr handle))))
(%hashtable-table ht)))
(define (hashtable-prune! ht pred)
(assert-mutable ht)
(let ((keys (hashtable-sum ht '()
(lambda (k v keys-to-delete)
(if (pred k v)
(cons k keys-to-delete)
keys-to-delete)))))
(for-each (lambda (k)
(hashtable-delete! ht k))
keys)))
(define (hashtable-merge! ht-dest ht-src)
(assert-mutable ht-dest)
(hashtable-walk ht-src
(lambda (k v)
(hashtable-set! ht-dest k v)))
ht-dest)
(define (hashtable-sum ht init proc)
(hash-fold proc init (%hashtable-table ht)))
(define (hashtable-map->lset ht proc)
(hash-map->list proc (%hashtable-table ht)))
(define (hashtable-find ht pred)
(let/ec return
(hashtable-walk ht
(lambda (k v)
(when (pred k v)
(return k v #t))))
(return #f #f #f)))
(define (hashtable-empty? ht)
(zero? (hashtable-size ht)))
(define (hashtable-pop! ht)
(assert-mutable ht)
(when (hashtable-empty? ht)
(error "Cannot pop from empty hashtable." ht))
(let-values (((k v found?) (hashtable-find ht (const #t))))
(hashtable-delete! ht k)
(values k v)))
(define* (hashtable-inc! ht k #\optional (x 1))
(assert-mutable ht)
(hashtable-update! ht k (lambda (v) (+ v x)) 0))
(define* (hashtable-dec! ht k #\optional (x 1))
(assert-mutable ht)
(hashtable-update! ht k (lambda (v) (- v x)) 0))
(define (hash-salt) 0)
(set-record-type-printer!
<hashtable>
(lambda (ht port)
(with-output-to-port port
(lambda ()
(let ((equal-hash (@ (rnrs hashtables) equal-hash))
(string-hash (@ (rnrs hashtables) string-hash))
(string-ci-hash (@ (rnrs hashtables) string-ci-hash))
(symbol-hash (@ (rnrs hashtables) symbol-hash))
(hash (hashtable-hash-function ht))
(equiv (hashtable-equivalence-function ht))
(alist (hashtable-map->lset ht cons)))
(cond
((and (not hash) (eq? equiv eq?))
(display "#hasheq")
(display alist))
((and (not hash) (eq? equiv eqv?))
(display "#hasheqv")
(display alist))
(else
(display "#hash")
(cond
((and (eq? hash (@ (rnrs hashtables) equal-hash)) (eq? equiv equal?))
(display alist))
((and (eq? hash (@ (rnrs hashtables) string-hash)) (eq? equiv string=?))
(display (cons 'string alist)))
((and (eq? hash string-ci-hash) (eq? equiv string-ci=?))
(display (cons 'string-ci alist)))
((and (eq? hash symbol-hash) (eq? equiv eq?))
(display (cons 'symbol alist)))
(else
(display (cons 'custom alist)))))))))))
(read-hash-extend
#\h
(lambda (char port)
(with-input-from-port port
(lambda ()
(let ((equal-hash (@ (rnrs hashtables) equal-hash))
(string-hash (@ (rnrs hashtables) string-hash))
(string-ci-hash (@ (rnrs hashtables) string-ci-hash))
(symbol-hash (@ (rnrs hashtables) symbol-hash))
(type (string-append "h" (symbol->string (read))))
(alist (read)))
(cond
((string=? type "hasheq")
(alist->eq-hashtable alist))
((string=? type "hasheqv")
(alist->eqv-hashtable alist))
(else
(when (not (string=? type "hash"))
(error "Unrecognized hash type." type))
(let* ((has-tag? (symbol? (car alist)))
(subtype (if has-tag?
(car alist)
"equal"))
(alist (if has-tag?
(cdr alist)
alist)))
(cond
((string=? subtype "equal")
(alist->hashtable equal-hash equal? alist))
((string=? subtype "string")
(alist->hashtable string-hash string=? alist))
((string=? subtype "string-ci")
(alist->hashtable string-ci-hash string-ci=? alist))
((string=? subtype "symbol")
(alist->hashtable symbol-hash eq? alist))
(else
(error "Unrecognized hash subtype." subtype)))))))))))
;; Local Variables:
;; eval: (put 'hashtable-walk 'scheme-indent-function 1)
;; eval: (put 'hashtable-update-all! 'scheme-indent-function 1)
;; eval: (put 'hashtable-prune! 'scheme-indent-function 1)
;; eval: (put 'hashtable-sum 'scheme-indent-function 2)
;; eval: (put 'hashtable-map->lset 'scheme-indent-function 1)
;; eval: (put 'hashtable-find 'scheme-indent-function 1)
;; End:
;;; This doesn't test weakness, external representation, and quasiquote.
(test-begin "SRFI-126")
(test-group "constructors & inspection"
(test-group "eq"
(let ((tables (list (make-eq-hashtable)
(make-eq-hashtable 10)
(make-eq-hashtable #f #f)
(make-hashtable #f eq?)
(alist->eq-hashtable '((a . b) (c . d)))
(alist->eq-hashtable 10 '((a . b) (c . d)))
(alist->eq-hashtable #f #f '((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label #f (hashtable-hash-function table))
(test-eq label eq? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))))
(test-group "eqv"
(let ((tables (list (make-eqv-hashtable)
(make-eqv-hashtable 10)
(make-eqv-hashtable #f #f)
(make-hashtable #f eqv?)
(alist->eqv-hashtable '((a . b) (c . d)))
(alist->eqv-hashtable 10 '((a . b) (c . d)))
(alist->eqv-hashtable #f #f '((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label #f (hashtable-hash-function table))
(test-eq label eqv? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))))
(test-group "equal"
(let ((tables (list (make-hashtable equal-hash equal?)
(make-hashtable equal-hash equal? 10)
(make-hashtable equal-hash equal? #f #f)
(alist->hashtable equal-hash equal?
'((a . b) (c . d)))
(alist->hashtable equal-hash equal? 10
'((a . b) (c . d)))
(alist->hashtable equal-hash equal? #f #f
'((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label equal-hash (hashtable-hash-function table))
(test-eq label equal? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))
(let ((table (make-hashtable (cons equal-hash equal-hash) equal?)))
(let ((hash (hashtable-hash-function table)))
(test-assert (or (eq? equal-hash hash)
(and (eq? equal-hash (car hash))
(eq? equal-hash (cdr hash)))))))))
(test-group "alist"
(let ((tables (list (alist->eq-hashtable '((a . b) (a . c)))
(alist->eqv-hashtable '((a . b) (a . c)))
(alist->hashtable equal-hash equal?
'((a . b) (a . c))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-eq label 'b (hashtable-ref table 'a)))))))
(test-group "procedures"
(test-group "basics"
(let ((table (make-eq-hashtable)))
(test-group "ref"
(test-error (hashtable-ref table 'a))
(test-eq 'b (hashtable-ref table 'a 'b))
(test-assert (not (hashtable-contains? table 'a)))
(test-eqv 0 (hashtable-size table)))
(test-group "set"
(hashtable-set! table 'a 'c)
(test-eq 'c (hashtable-ref table 'a))
(test-eq 'c (hashtable-ref table 'a 'b))
(test-assert (hashtable-contains? table 'a))
(test-eqv 1 (hashtable-size table)))
(test-group "delete"
(hashtable-delete! table 'a)
(test-error (hashtable-ref table 'a))
(test-eq 'b (hashtable-ref table 'a 'b))
(test-assert (not (hashtable-contains? table 'a)))
(test-eqv 0 (hashtable-size table)))))
(test-group "advanced"
(let ((table (make-eq-hashtable)))
(test-group "lookup"
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-assert (not found?))))
(test-group "update"
(test-error (hashtable-update! table 'a (lambda (x) (+ x 1))))
(hashtable-update! table 'a (lambda (x) (+ x 1)) 0)
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv 1 x)
(test-assert found?))
(hashtable-update! table 'a (lambda (x) (+ x 1)))
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv x 2)
(test-assert found?))
(hashtable-update! table 'a (lambda (x) (+ x 1)) 0)
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv x 3)
(test-assert found?)))
(test-group "intern"
(test-eqv 0 (hashtable-intern! table 'b (lambda () 0)))
(test-eqv 0 (hashtable-intern! table 'b (lambda () 1))))))
(test-group "copy/clear"
(let ((table (alist->hashtable equal-hash equal? '((a . b)))))
(test-group "copy"
(let ((table2 (hashtable-copy table)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(test-error (hashtable-set! table2 'a 'c)))
(let ((table2 (hashtable-copy table #f)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(test-error (hashtable-set! table2 'a 'c)))
(let ((table2 (hashtable-copy table #t)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(hashtable-set! table2 'a 'c)
(test-eq 'c (hashtable-ref table2 'a)))
(let ((table2 (hashtable-copy table #f #f)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq #f (hashtable-weakness table2))))
(test-group "clear"
(let ((table2 (hashtable-copy table #t)))
(hashtable-clear! table2)
(test-eqv 0 (hashtable-size table2)))
(let ((table2 (hashtable-copy table #t)))
(hashtable-clear! table2 10)
(test-eqv 0 (hashtable-size table2))))
(test-group "empty-copy"
(let ((table2 (hashtable-empty-copy table)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eqv 0 (hashtable-size table2)))
(let ((table2 (hashtable-empty-copy table 10)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eqv 0 (hashtable-size table2))))))
(test-group "keys/values"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= eq? '(a c) (vector->list (hashtable-keys table))))
(test-assert (lset= eq? '(b d) (vector->list (hashtable-values table))))
(let-values (((keys values) (hashtable-entries table)))
(test-assert (lset= eq? '(a c) (vector->list keys)))
(test-assert (lset= eq? '(b d) (vector->list values))))
(test-assert (lset= eq? '(a c) (hashtable-key-list table)))
(test-assert (lset= eq? '(b d) (hashtable-value-list table)))
(let-values (((keys values) (hashtable-entry-lists table)))
(test-assert (lset= eq? '(a c) keys))
(test-assert (lset= eq? '(b d) values)))))
(test-group "iteration"
(test-group "walk"
(let ((keys '())
(values '()))
(hashtable-walk (alist->eq-hashtable '((a . b) (c . d)))
(lambda (k v)
(set! keys (cons k keys))
(set! values (cons v values))))
(test-assert (lset= eq? '(a c) keys))
(test-assert (lset= eq? '(b d) values))))
(test-group "update-all"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(hashtable-update-all! table
(lambda (k v)
(string->symbol (string-append (symbol->string v) "x"))))
(test-assert (lset= eq? '(a c) (hashtable-key-list table)))
(test-assert (lset= eq? '(bx dx) (hashtable-value-list table)))))
(test-group "prune"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(hashtable-prune! table (lambda (k v) (eq? k 'a)))
(test-assert (not (hashtable-contains? table 'a)))
(test-assert (hashtable-contains? table 'c))))
(test-group "merge"
(let ((table (alist->eq-hashtable '((a . b) (c . d))))
(table2 (alist->eq-hashtable '((a . x) (e . f)))))
(hashtable-merge! table table2)
(test-assert (lset= eq? '(a c e) (hashtable-key-list table)))
(test-assert (lset= eq? '(x d f) (hashtable-value-list table)))))
(test-group "sum"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= eq? '(a b c d)
(hashtable-sum table '()
(lambda (k v acc)
(lset-adjoin eq? acc k v)))))))
(test-group "map->lset"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= equal? '((a . b) (c . d))
(hashtable-map->lset table cons)))))
(test-group "find"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(let-values (((k v f?) (hashtable-find table
(lambda (k v)
(eq? k 'a)))))
(test-assert (and f? (eq? k 'a) (eq? v 'b))))
(let-values (((k v f?) (hashtable-find table (lambda (k v) #f))))
(test-assert (not f?)))))
(test-group "misc"
(test-group "empty?"
(test-assert (hashtable-empty? (alist->eq-hashtable '())))
(test-assert (not (hashtable-empty? (alist->eq-hashtable '((a . b)))))))
(test-group "pop!"
(test-error (hashtable-pop! (make-eq-hashtable)))
(let ((table (alist->eq-hashtable '((a . b)))))
(let-values (((k v) (hashtable-pop! table)))
(test-eq 'a k)
(test-eq 'b v)
(test-assert (hashtable-empty? table)))))
(test-group "inc!"
(let ((table (alist->eq-hashtable '((a . 0)))))
(hashtable-inc! table 'a)
(test-eqv 1 (hashtable-ref table 'a))
(hashtable-inc! table 'a 2)
(test-eqv 3 (hashtable-ref table 'a))))
(test-group "dec!"
(let ((table (alist->eq-hashtable '((a . 0)))))
(hashtable-dec! table 'a)
(test-eqv -1 (hashtable-ref table 'a))
(hashtable-dec! table 'a 2)
(test-eqv -3 (hashtable-ref table 'a)))))))
(test-group "hashing"
(test-assert (and (exact-integer? (hash-salt))))
(test-assert (not (negative? (hash-salt))))
(test-assert (= (equal-hash (list "foo" 'bar 42))
(equal-hash (list "foo" 'bar 42))))
(test-assert (= (string-hash (string-copy "foo"))
(string-hash (string-copy "foo"))))
(test-assert (= (string-ci-hash (string-copy "foo"))
(string-ci-hash (string-copy "FOO"))))
(test-assert (= (symbol-hash (string->symbol "foo"))
(symbol-hash (string->symbol "foo")))))
(test-end "SRFI-126")
(display
(string-append
"\n"
"NOTE: On implementations using the (r6rs hashtables) library from Larceny,\n"
" 14 tests are expected to fail in relation to make-eq-hashtable and\n"
" make-eqv-hashtable returning hashtables whose hash functions are\n"
" exposed instead of being #f. We have no obvious way to detect this\n"
" within this portable test suite, hence no XFAIL results.\n"))
;; Local Variables:
;; eval: (put (quote test-group) (quote scheme-indent-function) 1)
;; End:
(import
(scheme base)
(scheme write)
(srfi 1)
(srfi 64)
(srfi 126))
;; INCLUDE test-suite.body.scm
;;; This doesn't test weakness, external representation, and quasiquote.
(test-begin "SRFI-126")
(test-group "constructors & inspection"
(test-group "eq"
(let ((tables (list (make-eq-hashtable)
(make-eq-hashtable 10)
(make-eq-hashtable #f #f)
(make-hashtable #f eq?)
(alist->eq-hashtable '((a . b) (c . d)))
(alist->eq-hashtable 10 '((a . b) (c . d)))
(alist->eq-hashtable #f #f '((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label #f (hashtable-hash-function table))
(test-eq label eq? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))))
(test-group "eqv"
(let ((tables (list (make-eqv-hashtable)
(make-eqv-hashtable 10)
(make-eqv-hashtable #f #f)
(make-hashtable #f eqv?)
(alist->eqv-hashtable '((a . b) (c . d)))
(alist->eqv-hashtable 10 '((a . b) (c . d)))
(alist->eqv-hashtable #f #f '((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label #f (hashtable-hash-function table))
(test-eq label eqv? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))))
(test-group "equal"
(let ((tables (list (make-hashtable equal-hash equal?)
(make-hashtable equal-hash equal? 10)
(make-hashtable equal-hash equal? #f #f)
(alist->hashtable equal-hash equal?
'((a . b) (c . d)))
(alist->hashtable equal-hash equal? 10
'((a . b) (c . d)))
(alist->hashtable equal-hash equal? #f #f
'((a . b) (c . d))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-assert label (hashtable? table))
(test-eq label equal-hash (hashtable-hash-function table))
(test-eq label equal? (hashtable-equivalence-function table))
(test-eq label #f (hashtable-weakness table))
(test-assert label (hashtable-mutable? table))))
(let ((table (make-hashtable (cons equal-hash equal-hash) equal?)))
(let ((hash (hashtable-hash-function table)))
(test-assert (or (eq? equal-hash hash)
(and (eq? equal-hash (car hash))
(eq? equal-hash (cdr hash)))))))))
(test-group "alist"
(let ((tables (list (alist->eq-hashtable '((a . b) (a . c)))
(alist->eqv-hashtable '((a . b) (a . c)))
(alist->hashtable equal-hash equal?
'((a . b) (a . c))))))
(do ((tables tables (cdr tables))
(i 0 (+ i 1)))
((null? tables))
(let ((table (car tables))
(label (number->string i)))
(test-eq label 'b (hashtable-ref table 'a)))))))
(test-group "procedures"
(test-group "basics"
(let ((table (make-eq-hashtable)))
(test-group "ref"
(test-error (hashtable-ref table 'a))
(test-eq 'b (hashtable-ref table 'a 'b))
(test-assert (not (hashtable-contains? table 'a)))
(test-eqv 0 (hashtable-size table)))
(test-group "set"
(hashtable-set! table 'a 'c)
(test-eq 'c (hashtable-ref table 'a))
(test-eq 'c (hashtable-ref table 'a 'b))
(test-assert (hashtable-contains? table 'a))
(test-eqv 1 (hashtable-size table)))
(test-group "delete"
(hashtable-delete! table 'a)
(test-error (hashtable-ref table 'a))
(test-eq 'b (hashtable-ref table 'a 'b))
(test-assert (not (hashtable-contains? table 'a)))
(test-eqv 0 (hashtable-size table)))))
(test-group "advanced"
(let ((table (make-eq-hashtable)))
(test-group "lookup"
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-assert (not found?))))
(test-group "update"
(test-error (hashtable-update! table 'a (lambda (x) (+ x 1))))
(hashtable-update! table 'a (lambda (x) (+ x 1)) 0)
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv 1 x)
(test-assert found?))
(hashtable-update! table 'a (lambda (x) (+ x 1)))
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv x 2)
(test-assert found?))
(hashtable-update! table 'a (lambda (x) (+ x 1)) 0)
(let-values (((x found?) (hashtable-lookup table 'a)))
(test-eqv x 3)
(test-assert found?)))
(test-group "intern"
(test-eqv 0 (hashtable-intern! table 'b (lambda () 0)))
(test-eqv 0 (hashtable-intern! table 'b (lambda () 1))))))
(test-group "copy/clear"
(let ((table (alist->hashtable equal-hash equal? '((a . b)))))
(test-group "copy"
(let ((table2 (hashtable-copy table)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(test-error (hashtable-set! table2 'a 'c)))
(let ((table2 (hashtable-copy table #f)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(test-error (hashtable-set! table2 'a 'c)))
(let ((table2 (hashtable-copy table #t)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq 'b (hashtable-ref table2 'a))
(hashtable-set! table2 'a 'c)
(test-eq 'c (hashtable-ref table2 'a)))
(let ((table2 (hashtable-copy table #f #f)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eq #f (hashtable-weakness table2))))
(test-group "clear"
(let ((table2 (hashtable-copy table #t)))
(hashtable-clear! table2)
(test-eqv 0 (hashtable-size table2)))
(let ((table2 (hashtable-copy table #t)))
(hashtable-clear! table2 10)
(test-eqv 0 (hashtable-size table2))))
(test-group "empty-copy"
(let ((table2 (hashtable-empty-copy table)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eqv 0 (hashtable-size table2)))
(let ((table2 (hashtable-empty-copy table 10)))
(test-eq equal-hash (hashtable-hash-function table2))
(test-eq equal? (hashtable-equivalence-function table2))
(test-eqv 0 (hashtable-size table2))))))
(test-group "keys/values"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= eq? '(a c) (vector->list (hashtable-keys table))))
(test-assert (lset= eq? '(b d) (vector->list (hashtable-values table))))
(let-values (((keys values) (hashtable-entries table)))
(test-assert (lset= eq? '(a c) (vector->list keys)))
(test-assert (lset= eq? '(b d) (vector->list values))))
(test-assert (lset= eq? '(a c) (hashtable-key-list table)))
(test-assert (lset= eq? '(b d) (hashtable-value-list table)))
(let-values (((keys values) (hashtable-entry-lists table)))
(test-assert (lset= eq? '(a c) keys))
(test-assert (lset= eq? '(b d) values)))))
(test-group "iteration"
(test-group "walk"
(let ((keys '())
(values '()))
(hashtable-walk (alist->eq-hashtable '((a . b) (c . d)))
(lambda (k v)
(set! keys (cons k keys))
(set! values (cons v values))))
(test-assert (lset= eq? '(a c) keys))
(test-assert (lset= eq? '(b d) values))))
(test-group "update-all"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(hashtable-update-all! table
(lambda (k v)
(string->symbol (string-append (symbol->string v) "x"))))
(test-assert (lset= eq? '(a c) (hashtable-key-list table)))
(test-assert (lset= eq? '(bx dx) (hashtable-value-list table)))))
(test-group "prune"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(hashtable-prune! table (lambda (k v) (eq? k 'a)))
(test-assert (not (hashtable-contains? table 'a)))
(test-assert (hashtable-contains? table 'c))))
(test-group "merge"
(let ((table (alist->eq-hashtable '((a . b) (c . d))))
(table2 (alist->eq-hashtable '((a . x) (e . f)))))
(hashtable-merge! table table2)
(test-assert (lset= eq? '(a c e) (hashtable-key-list table)))
(test-assert (lset= eq? '(x d f) (hashtable-value-list table)))))
(test-group "sum"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= eq? '(a b c d)
(hashtable-sum table '()
(lambda (k v acc)
(lset-adjoin eq? acc k v)))))))
(test-group "map->lset"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(test-assert (lset= equal? '((a . b) (c . d))
(hashtable-map->lset table cons)))))
(test-group "find"
(let ((table (alist->eq-hashtable '((a . b) (c . d)))))
(let-values (((k v f?) (hashtable-find table
(lambda (k v)
(eq? k 'a)))))
(test-assert (and f? (eq? k 'a) (eq? v 'b))))
(let-values (((k v f?) (hashtable-find table (lambda (k v) #f))))
(test-assert (not f?)))))
(test-group "misc"
(test-group "empty?"
(test-assert (hashtable-empty? (alist->eq-hashtable '())))
(test-assert (not (hashtable-empty? (alist->eq-hashtable '((a . b)))))))
(test-group "pop!"
(test-error (hashtable-pop! (make-eq-hashtable)))
(let ((table (alist->eq-hashtable '((a . b)))))
(let-values (((k v) (hashtable-pop! table)))
(test-eq 'a k)
(test-eq 'b v)
(test-assert (hashtable-empty? table)))))
(test-group "inc!"
(let ((table (alist->eq-hashtable '((a . 0)))))
(hashtable-inc! table 'a)
(test-eqv 1 (hashtable-ref table 'a))
(hashtable-inc! table 'a 2)
(test-eqv 3 (hashtable-ref table 'a))))
(test-group "dec!"
(let ((table (alist->eq-hashtable '((a . 0)))))
(hashtable-dec! table 'a)
(test-eqv -1 (hashtable-ref table 'a))
(hashtable-dec! table 'a 2)
(test-eqv -3 (hashtable-ref table 'a)))))))
(test-group "hashing"
(test-assert (and (exact-integer? (hash-salt))))
(test-assert (not (negative? (hash-salt))))
(test-assert (= (equal-hash (list "foo" 'bar 42))
(equal-hash (list "foo" 'bar 42))))
(test-assert (= (string-hash (string-copy "foo"))
(string-hash (string-copy "foo"))))
(test-assert (= (string-ci-hash (string-copy "foo"))
(string-ci-hash (string-copy "FOO"))))
(test-assert (= (symbol-hash (string->symbol "foo"))
(symbol-hash (string->symbol "foo")))))
(test-end "SRFI-126")
(display
(string-append
"\n"
"NOTE: On implementations using the (r6rs hashtables) library from Larceny,\n"
" 14 tests are expected to fail in relation to make-eq-hashtable and\n"
" make-eqv-hashtable returning hashtables whose hash functions are\n"
" exposed instead of being #f. We have no obvious way to detect this\n"
" within this portable test suite, hence no XFAIL results.\n"))
;; Local Variables:
;; eval: (put (quote test-group) (quote scheme-indent-function) 1)
;; End:
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Note: to prevent producing massive amounts of code from the macro-expand
;;; phase (which makes compile times suffer and may hit code size limits in some
;;; systems), keep macro bodies minimal by delegating work to procedures.
;;; Grouping
(define (maybe-install-default-runner suite-name)
(when (not (test-runner-current))
(let* ((log-file (string-append suite-name ".srfi64.log"))
(runner (test-runner-simple log-file)))
(%test-runner-auto-installed! runner #t)
(test-runner-current runner))))
(define (maybe-uninstall-default-runner)
(when (%test-runner-auto-installed? (test-runner-current))
(test-runner-current #f)))
(define test-begin
(case-lambda
((name)
(test-begin name #f))
((name count)
(maybe-install-default-runner name)
(let ((r (test-runner-current)))
(let ((skip-list (%test-runner-skip-list r))
(skip-save (%test-runner-skip-save r))
(fail-list (%test-runner-fail-list r))
(fail-save (%test-runner-fail-save r))
(total-count (%test-runner-total-count r))
(count-list (%test-runner-count-list r))
(group-stack (test-runner-group-stack r)))
((test-runner-on-group-begin r) r name count)
(%test-runner-skip-save! r (cons skip-list skip-save))
(%test-runner-fail-save! r (cons fail-list fail-save))
(%test-runner-count-list! r (cons (cons total-count count)
count-list))
(test-runner-group-stack! r (cons name group-stack)))))))
(define test-end
(case-lambda
(()
(test-end #f))
((name)
(let* ((r (test-runner-get))
(groups (test-runner-group-stack r)))
(test-result-clear r)
(when (null? groups)
(error "test-end not in a group"))
(when (and name (not (equal? name (car groups))))
((test-runner-on-bad-end-name r) r name (car groups)))
(let* ((count-list (%test-runner-count-list r))
(expected-count (cdar count-list))
(saved-count (caar count-list))
(group-count (- (%test-runner-total-count r) saved-count)))
(when (and expected-count
(not (= expected-count group-count)))
((test-runner-on-bad-count r) r group-count expected-count))
((test-runner-on-group-end r) r)
(test-runner-group-stack! r (cdr (test-runner-group-stack r)))
(%test-runner-skip-list! r (car (%test-runner-skip-save r)))
(%test-runner-skip-save! r (cdr (%test-runner-skip-save r)))
(%test-runner-fail-list! r (car (%test-runner-fail-save r)))
(%test-runner-fail-save! r (cdr (%test-runner-fail-save r)))
(%test-runner-count-list! r (cdr count-list))
(when (null? (test-runner-group-stack r))
((test-runner-on-final r) r)
(maybe-uninstall-default-runner)))))))
(define-syntax test-group
(syntax-rules ()
((_ <name> <body> . <body>*)
(%test-group <name> (lambda () <body> . <body>*)))))
(define (%test-group name thunk)
(begin
(maybe-install-default-runner name)
(let ((runner (test-runner-get)))
(test-result-clear runner)
(test-result-set! runner 'name name)
(unless (test-skip? runner)
(dynamic-wind
(lambda () (test-begin name))
thunk
(lambda () (test-end name)))))))
(define-syntax test-group-with-cleanup
(syntax-rules ()
((_ <name> <body> <body>* ... <cleanup>)
(test-group <name>
(dynamic-wind (lambda () #f)
(lambda () <body> <body>* ...)
(lambda () <cleanup>))))))
;;; Skipping, expected-failing, matching
(define (test-skip . specs)
(let ((runner (test-runner-get)))
(%test-runner-skip-list!
runner (cons (apply test-match-all specs)
(%test-runner-skip-list runner)))))
(define (test-skip? runner)
(let ((run-list (%test-runner-run-list runner))
(skip-list (%test-runner-skip-list runner)))
(or (and run-list (not (any-pred run-list runner)))
(any-pred skip-list runner))))
(define (test-expect-fail . specs)
(let ((runner (test-runner-get)))
(%test-runner-fail-list!
runner (cons (apply test-match-all specs)
(%test-runner-fail-list runner)))))
(define (test-match-any . specs)
(let ((preds (map make-pred specs)))
(lambda (runner)
(any-pred preds runner))))
(define (test-match-all . specs)
(let ((preds (map make-pred specs)))
(lambda (runner)
(every-pred preds runner))))
(define (make-pred spec)
(cond
((procedure? spec)
spec)
((integer? spec)
(test-match-nth 1 spec))
((string? spec)
(test-match-name spec))
(else
(error "not a valid test specifier" spec))))
(define test-match-nth
(case-lambda
((n) (test-match-nth n 1))
((n count)
(let ((i 0))
(lambda (runner)
(set! i (+ i 1))
(and (>= i n) (< i (+ n count))))))))
(define (test-match-name name)
(lambda (runner)
(equal? name (test-runner-test-name runner))))
;;; Beware: all predicates must be called because they might have side-effects;
;;; no early returning or and/or short-circuiting of procedure calls allowed.
(define (any-pred preds object)
(let loop ((matched? #f)
(preds preds))
(if (null? preds)
matched?
(let ((result ((car preds) object)))
(loop (or matched? result)
(cdr preds))))))
(define (every-pred preds object)
(let loop ((failed? #f)
(preds preds))
(if (null? preds)
(not failed?)
(let ((result ((car preds) object)))
(loop (or failed? (not result))
(cdr preds))))))
;;; Actual testing
(define-syntax false-if-error
(syntax-rules ()
((_ <expression> <runner>)
(guard (error
(else
(test-result-set! <runner> 'actual-error error)
#f))
<expression>))))
(define (test-prelude source-info runner name form)
(test-result-clear runner)
(set-source-info! runner source-info)
(when name
(test-result-set! runner 'name name))
(test-result-set! runner 'source-form form)
(let ((skip? (test-skip? runner)))
(if skip?
(test-result-set! runner 'result-kind 'skip)
(let ((fail-list (%test-runner-fail-list runner)))
(when (any-pred fail-list runner)
;; For later inspection only.
(test-result-set! runner 'result-kind 'xfail))))
((test-runner-on-test-begin runner) runner)
(not skip?)))
(define (test-postlude runner)
(let ((result-kind (test-result-kind runner)))
(case result-kind
((pass)
(test-runner-pass-count! runner (+ 1 (test-runner-pass-count runner))))
((fail)
(test-runner-fail-count! runner (+ 1 (test-runner-fail-count runner))))
((xpass)
(test-runner-xpass-count! runner (+ 1 (test-runner-xpass-count runner))))
((xfail)
(test-runner-xfail-count! runner (+ 1 (test-runner-xfail-count runner))))
((skip)
(test-runner-skip-count! runner (+ 1 (test-runner-skip-count runner)))))
(%test-runner-total-count! runner (+ 1 (%test-runner-total-count runner)))
((test-runner-on-test-end runner) runner)))
(define (set-result-kind! runner pass?)
(test-result-set! runner 'result-kind
(if (eq? (test-result-kind runner) 'xfail)
(if pass? 'xpass 'xfail)
(if pass? 'pass 'fail))))
;;; We need to use some trickery to get the source info right. The important
;;; thing is to pass a syntax object that is a pair to `source-info', and make
;;; sure this syntax object comes from user code and not from ourselves.
(define-syntax test-assert
(syntax-rules ()
((_ . <rest>)
(test-assert/source-info (source-info <rest>) . <rest>))))
(define-syntax test-assert/source-info
(syntax-rules ()
((_ <source-info> <expr>)
(test-assert/source-info <source-info> #f <expr>))
((_ <source-info> <name> <expr>)
(%test-assert <source-info> <name> '<expr> (lambda () <expr>)))))
(define (%test-assert source-info name form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(let ((val (false-if-error (thunk) runner)))
(test-result-set! runner 'actual-value val)
(set-result-kind! runner val)))
(test-postlude runner)))
(define-syntax test-compare
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) . <rest>))))
(define-syntax test-compare/source-info
(syntax-rules ()
((_ <source-info> <compare> <expected> <expr>)
(test-compare/source-info <source-info> <compare> #f <expected> <expr>))
((_ <source-info> <compare> <name> <expected> <expr>)
(%test-compare <source-info> <compare> <name> <expected> '<expr>
(lambda () <expr>)))))
(define (%test-compare source-info compare name expected form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(test-result-set! runner 'expected-value expected)
(let ((pass? (false-if-error
(let ((val (thunk)))
(test-result-set! runner 'actual-value val)
(compare expected val))
runner)))
(set-result-kind! runner pass?)))
(test-postlude runner)))
(define-syntax test-equal
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) equal? . <rest>))))
(define-syntax test-eqv
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) eqv? . <rest>))))
(define-syntax test-eq
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) eq? . <rest>))))
(define (approx= margin)
(lambda (value expected)
(let ((rval (real-part value))
(ival (imag-part value))
(rexp (real-part expected))
(iexp (imag-part expected)))
(and (>= rval (- rexp margin))
(>= ival (- iexp margin))
(<= rval (+ rexp margin))
(<= ival (+ iexp margin))))))
(define-syntax test-approximate
(syntax-rules ()
((_ . <rest>)
(test-approximate/source-info (source-info <rest>) . <rest>))))
(define-syntax test-approximate/source-info
(syntax-rules ()
((_ <source-info> <expected> <expr> <error-margin>)
(test-approximate/source-info
<source-info> #f <expected> <expr> <error-margin>))
((_ <source-info> <name> <expected> <expr> <error-margin>)
(test-compare/source-info
<source-info> (approx= <error-margin>) <name> <expected> <expr>))))
(define (error-matches? error type)
(cond
((eq? type #t)
#t)
((condition-type? type)
(and (condition? error) (condition-has-type? error type)))
((procedure? type)
(type error))
(else
(let ((runner (test-runner-get)))
((%test-runner-on-bad-error-type runner) runner type error))
#f)))
(define-syntax test-error
(syntax-rules ()
((_ . <rest>)
(test-error/source-info (source-info <rest>) . <rest>))))
(define-syntax test-error/source-info
(syntax-rules ()
((_ <source-info> <expr>)
(test-error/source-info <source-info> #f #t <expr>))
((_ <source-info> <error-type> <expr>)
(test-error/source-info <source-info> #f <error-type> <expr>))
((_ <source-info> <name> <error-type> <expr>)
(%test-error <source-info> <name> <error-type> '<expr>
(lambda () <expr>)))))
(define (%test-error source-info name error-type form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(test-result-set! runner 'expected-error error-type)
(let ((pass? (guard (error (else (test-result-set!
runner 'actual-error error)
(error-matches? error error-type)))
(let ((val (thunk)))
(test-result-set! runner 'actual-value val))
#f)))
(set-result-kind! runner pass?)))
(test-postlude runner)))
(define (default-module)
(cond-expand
(guile (current-module))
(else #f)))
(define test-read-eval-string
(case-lambda
((string)
(test-read-eval-string string (default-module)))
((string env)
(let* ((port (open-input-string string))
(form (read port)))
(if (eof-object? (read-char port))
(if env
(eval form env)
(eval form))
(error "(not at eof)"))))))
;;; Test runner control flow
(define-syntax test-with-runner
(syntax-rules ()
((_ <runner> <body> . <body>*)
(let ((saved-runner (test-runner-current)))
(dynamic-wind
(lambda () (test-runner-current <runner>))
(lambda () <body> . <body>*)
(lambda () (test-runner-current saved-runner)))))))
(define (test-apply first . rest)
(let ((runner (if (test-runner? first)
first
(or (test-runner-current) (test-runner-create))))
(run-list (if (test-runner? first)
(drop-right rest 1)
(cons first (drop-right rest 1))))
(proc (last rest)))
(test-with-runner runner
(let ((saved-run-list (%test-runner-run-list runner)))
(%test-runner-run-list! runner run-list)
(proc)
(%test-runner-run-list! runner saved-run-list)))))
;;; Indicate success/failure via exit status
(define (test-exit)
(let ((runner (test-runner-current)))
(when (not runner)
(error "No test runner installed. Might have been auto-removed
by test-end if you had not installed one explicitly."))
(if (and (zero? (test-runner-xpass-count runner))
(zero? (test-runner-fail-count runner)))
(exit 0)
(exit 1))))
;;; execution.scm ends here
;; Copyright (c) 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; In some systems, a macro use like (source-info ...), that resides in a
;;; syntax-rules macro body, first gets inserted into the place where the
;;; syntax-rules macro was used, and then the transformer of 'source-info' is
;;; called with a syntax object that has the source location information of that
;;; position. That works fine when the user calls e.g. (test-assert ...), whose
;;; body contains (source-info ...); the user gets the source location of the
;;; (test-assert ...) call as intended, and not the source location of the real
;;; (source-info ...) call.
;;; In other systems, *first* the (source-info ...) is processed to get its real
;;; position, which is within the body of a syntax-rules macro like test-assert,
;;; so no matter where the user calls (test-assert ...), they get source
;;; location information of where we defined test-assert with the call to
;;; (source-info ...) in its body. That's arguably more correct behavior,
;;; although in this case it makes our job a bit harder; we need to get the
;;; source location from an argument to 'source-info' instead.
(define (canonical-syntax form arg)
(cond-expand
(kawa arg)
(guile-2 form)
(else #f)))
(cond-expand
((or kawa guile-2)
(define-syntax source-info
(lambda (stx)
(syntax-case stx ()
((_ <x>)
(let* ((stx (canonical-syntax stx (syntax <x>)))
(file (syntax-source-file stx))
(line (syntax-source-line stx)))
(quasisyntax
(cons (unsyntax file) (unsyntax line)))))))))
(else
(define-syntax source-info
(syntax-rules ()
((_ <x>)
#f)))))
(define (syntax-source-file stx)
(cond-expand
(kawa
(syntax-source stx))
(guile-2
(let ((source (syntax-source stx)))
(and source (assq-ref source 'filename))))
(else
#f)))
(define (syntax-source-line stx)
(cond-expand
(kawa
(syntax-line stx))
(guile-2
(let ((source (syntax-source stx)))
(and source (assq-ref source 'line))))
(else
#f)))
(define (set-source-info! runner source-info)
(when source-info
(test-result-set! runner 'source-file (car source-info))
(test-result-set! runner 'source-line (cdr source-info))))
;;; source-info.body.scm ends here
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Helpers
(define (string-join strings delimiter)
(if (null? strings)
""
(let loop ((result (car strings))
(rest (cdr strings)))
(if (null? rest)
result
(loop (string-append result delimiter (car rest))
(cdr rest))))))
(define (truncate-string string length)
(define (newline->space c) (if (char=? #\newline c) #\space c))
(let* ((string (string-map newline->space string))
(fill "...")
(fill-len (string-length fill))
(string-len (string-length string)))
(if (<= string-len (+ length fill-len))
string
(let-values (((q r) (floor/ length 4)))
;; Left part gets 3/4 plus the remainder.
(let ((left-end (+ (* q 3) r))
(right-start (- string-len q)))
(string-append (substring string 0 left-end)
fill
(substring string right-start string-len)))))))
(define (print runner format-string . args)
(apply format #t format-string args)
(let ((port (%test-runner-log-port runner)))
(when port
(apply format port format-string args))))
;;; Main
(define test-runner-simple
(case-lambda
(()
(test-runner-simple #f))
((log-file)
(let ((runner (test-runner-null)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-on-group-begin-simple)
(test-runner-on-group-end! runner test-on-group-end-simple)
(test-runner-on-final! runner test-on-final-simple)
(test-runner-on-test-begin! runner test-on-test-begin-simple)
(test-runner-on-test-end! runner test-on-test-end-simple)
(test-runner-on-bad-count! runner test-on-bad-count-simple)
(test-runner-on-bad-end-name! runner test-on-bad-end-name-simple)
(%test-runner-on-bad-error-type! runner on-bad-error-type)
(%test-runner-log-file! runner log-file)
runner))))
(when (not (test-runner-factory))
(test-runner-factory test-runner-simple))
(define (test-on-group-begin-simple runner name count)
(when (null? (test-runner-group-stack runner))
(maybe-start-logging runner)
(print runner "Test suite begin: ~a~%" name)))
(define (test-on-group-end-simple runner)
(let ((name (car (test-runner-group-stack runner))))
(when (= 1 (length (test-runner-group-stack runner)))
(print runner "Test suite end: ~a~%" name))))
(define (test-on-final-simple runner)
(print runner "Passes: ~a\n" (test-runner-pass-count runner))
(print runner "Expected failures: ~a\n" (test-runner-xfail-count runner))
(print runner "Failures: ~a\n" (test-runner-fail-count runner))
(print runner "Unexpected passes: ~a\n" (test-runner-xpass-count runner))
(print runner "Skipped tests: ~a~%" (test-runner-skip-count runner))
(maybe-finish-logging runner))
(define (maybe-start-logging runner)
(let ((log-file (%test-runner-log-file runner)))
(when log-file
;; The possible race-condition here doesn't bother us.
(when (file-exists? log-file)
(delete-file log-file))
(%test-runner-log-port! runner (open-output-file log-file))
(print runner "Writing log file: ~a~%" log-file))))
(define (maybe-finish-logging runner)
(let ((log-file (%test-runner-log-file runner)))
(when log-file
(print runner "Wrote log file: ~a~%" log-file)
(close-output-port (%test-runner-log-port runner)))))
(define (test-on-test-begin-simple runner)
(values))
(define (test-on-test-end-simple runner)
(let* ((result-kind (test-result-kind runner))
(result-kind-name (case result-kind
((pass) "PASS") ((fail) "FAIL")
((xpass) "XPASS") ((xfail) "XFAIL")
((skip) "SKIP")))
(name (let ((name (test-runner-test-name runner)))
(if (string=? "" name)
(truncate-string
(format #f "~a" (test-result-ref runner 'source-form))
30)
name)))
(label (string-join (append (test-runner-group-path runner)
(list name))
": ")))
(print runner "[~a] ~a~%" result-kind-name label)
(when (memq result-kind '(fail xpass))
(let ((nil (cons #f #f)))
(define (found? value)
(not (eq? nil value)))
(define (maybe-print value message)
(when (found? value)
(print runner message value)))
(let ((file (test-result-ref runner 'source-file "(unknown file)"))
(line (test-result-ref runner 'source-line "(unknown line)"))
(expression (test-result-ref runner 'source-form))
(expected-value (test-result-ref runner 'expected-value nil))
(actual-value (test-result-ref runner 'actual-value nil))
(expected-error (test-result-ref runner 'expected-error nil))
(actual-error (test-result-ref runner 'actual-error nil)))
(print runner "~a:~a: ~s~%" file line expression)
(maybe-print expected-value "Expected value: ~s~%")
(maybe-print expected-error "Expected error: ~a~%")
(when (or (found? expected-value) (found? expected-error))
(maybe-print actual-value "Returned value: ~s~%"))
(maybe-print actual-error "Raised error: ~a~%")
(newline))))))
(define (test-on-bad-count-simple runner count expected-count)
(print runner "*** Total number of tests was ~a but should be ~a. ***~%"
count expected-count)
(print runner
"*** Discrepancy indicates testsuite error or exceptions. ***~%"))
(define (test-on-bad-end-name-simple runner begin-name end-name)
(error (format #f "Test-end \"~a\" does not match test-begin \"~a\"."
end-name begin-name)))
(define (on-bad-error-type runner type error)
(print runner "WARNING: unknown error type predicate: ~a~%" type)
(print runner " error was: ~a~%" error))
;;; test-runner-simple.scm ends here
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; The data type
(define-record-type <test-runner>
(make-test-runner) test-runner?
(result-alist test-result-alist test-result-alist!)
(pass-count test-runner-pass-count test-runner-pass-count!)
(fail-count test-runner-fail-count test-runner-fail-count!)
(xpass-count test-runner-xpass-count test-runner-xpass-count!)
(xfail-count test-runner-xfail-count test-runner-xfail-count!)
(skip-count test-runner-skip-count test-runner-skip-count!)
(total-count %test-runner-total-count %test-runner-total-count!)
;; Stack (list) of (count-at-start . expected-count):
(count-list %test-runner-count-list %test-runner-count-list!)
;; Normally #f, except when in a test-apply.
(run-list %test-runner-run-list %test-runner-run-list!)
(skip-list %test-runner-skip-list %test-runner-skip-list!)
(fail-list %test-runner-fail-list %test-runner-fail-list!)
(skip-save %test-runner-skip-save %test-runner-skip-save!)
(fail-save %test-runner-fail-save %test-runner-fail-save!)
(group-stack test-runner-group-stack test-runner-group-stack!)
;; Note: on-test-begin and on-test-end are unrelated to the test-begin and
;; test-end forms in the execution library. They're called at the
;; beginning/end of each individual test, whereas the test-begin and test-end
;; forms demarcate test groups.
(on-group-begin test-runner-on-group-begin test-runner-on-group-begin!)
(on-test-begin test-runner-on-test-begin test-runner-on-test-begin!)
(on-test-end test-runner-on-test-end test-runner-on-test-end!)
(on-group-end test-runner-on-group-end test-runner-on-group-end!)
(on-final test-runner-on-final test-runner-on-final!)
(on-bad-count test-runner-on-bad-count test-runner-on-bad-count!)
(on-bad-end-name test-runner-on-bad-end-name test-runner-on-bad-end-name!)
(on-bad-error-type %test-runner-on-bad-error-type
%test-runner-on-bad-error-type!)
(aux-value test-runner-aux-value test-runner-aux-value!)
(auto-installed %test-runner-auto-installed? %test-runner-auto-installed!)
(log-file %test-runner-log-file %test-runner-log-file!)
(log-port %test-runner-log-port %test-runner-log-port!))
(define (test-runner-group-path runner)
(reverse (test-runner-group-stack runner)))
(define (test-runner-reset runner)
(test-result-alist! runner '())
(test-runner-pass-count! runner 0)
(test-runner-fail-count! runner 0)
(test-runner-xpass-count! runner 0)
(test-runner-xfail-count! runner 0)
(test-runner-skip-count! runner 0)
(%test-runner-total-count! runner 0)
(%test-runner-count-list! runner '())
(%test-runner-run-list! runner #f)
(%test-runner-skip-list! runner '())
(%test-runner-fail-list! runner '())
(%test-runner-skip-save! runner '())
(%test-runner-fail-save! runner '())
(test-runner-group-stack! runner '()))
(define (test-runner-null)
(define (test-null-callback . args) #f)
(let ((runner (make-test-runner)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-null-callback)
(test-runner-on-group-end! runner test-null-callback)
(test-runner-on-final! runner test-null-callback)
(test-runner-on-test-begin! runner test-null-callback)
(test-runner-on-test-end! runner test-null-callback)
(test-runner-on-bad-count! runner test-null-callback)
(test-runner-on-bad-end-name! runner test-null-callback)
(%test-runner-on-bad-error-type! runner test-null-callback)
(%test-runner-auto-installed! runner #f)
(%test-runner-log-file! runner #f)
(%test-runner-log-port! runner #f)
runner))
;;; State
(define test-result-ref
(case-lambda
((runner key)
(test-result-ref runner key #f))
((runner key default)
(let ((entry (assq key (test-result-alist runner))))
(if entry (cdr entry) default)))))
(define (test-result-set! runner key value)
(let* ((alist (test-result-alist runner))
(entry (assq key alist)))
(if entry
(set-cdr! entry value)
(test-result-alist! runner (cons (cons key value) alist)))))
(define (test-result-remove runner key)
(test-result-alist! runner (remove (lambda (entry)
(eq? key (car entry)))
(test-result-alist runner))))
(define (test-result-clear runner)
(test-result-alist! runner '()))
(define (test-runner-test-name runner)
(or (test-result-ref runner 'name) ""))
(define test-result-kind
(case-lambda
(() (test-result-kind (test-runner-get)))
((runner) (test-result-ref runner 'result-kind))))
(define test-passed?
(case-lambda
(() (test-passed? (test-runner-get)))
((runner) (memq (test-result-kind runner) '(pass xpass)))))
;;; Factory and current instance
(define test-runner-factory (make-parameter #f))
(define (test-runner-create) ((test-runner-factory)))
(define test-runner-current (make-parameter #f))
(define (test-runner-get)
(or (test-runner-current)
(error "test-runner not initialized - test-begin missing?")))
;;; test-runner.scm ends here
(define-module (srfi srfi-64)
#\export
(test-begin
test-end test-assert test-eqv test-eq test-equal
test-approximate test-assert test-error test-apply test-with-runner
test-match-nth test-match-all test-match-any test-match-name
test-skip test-expect-fail test-read-eval-string
test-runner-group-path test-group test-group-with-cleanup
test-exit
test-result-ref test-result-set! test-result-clear test-result-remove
test-result-kind test-passed?
test-runner? test-runner-reset test-runner-null
test-runner-simple test-runner-current test-runner-factory test-runner-get
test-runner-create test-runner-test-name
test-runner-pass-count test-runner-pass-count!
test-runner-fail-count test-runner-fail-count!
test-runner-xpass-count test-runner-xpass-count!
test-runner-xfail-count test-runner-xfail-count!
test-runner-skip-count test-runner-skip-count!
test-runner-group-stack test-runner-group-stack!
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
test-result-alist test-result-alist!
test-runner-aux-value test-runner-aux-value!
test-on-group-begin-simple test-on-group-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
test-on-final-simple test-on-test-end-simple
test-on-final-simple))
(cond-expand-provide (current-module) '(srfi-64))
(import
(only (rnrs exceptions) guard)
(srfi srfi-1)
(srfi srfi-9)
(srfi srfi-11)
(srfi srfi-35))
(include-from-path "srfi/srfi-64/source-info.body.scm")
(include-from-path "srfi/srfi-64/test-runner.body.scm")
(include-from-path "srfi/srfi-64/test-runner-simple.body.scm")
(include-from-path "srfi/srfi-64/execution.body.scm")
(define-library (srfi-tests aux)
(export define-tests)
(import
(scheme base)
(scheme write)
(scheme case-lambda)
(srfi 64))
(begin
(define-syntax define-tests
(syntax-rules ()
((_ proc-name suite-name form ...)
(define proc-name
(case-lambda
(() (proc-name (test-runner-create)))
((runner)
(parameterize ((test-runner-current runner))
(test-begin suite-name)
form ...
(test-end suite-name)
(and (= 0 (test-runner-xpass-count runner))
(= 0 (test-runner-fail-count runner))))))))))
))
;; Copyright (C) Oleg Kiselyov (1998). All Rights Reserved.
;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-library (srfi-tests srfi-2)
(export run-tests)
(import
(scheme base)
(scheme eval)
(srfi 2)
(srfi 64)
(srfi-tests aux))
(begin
(define (test-eval form)
(eval form (environment '(scheme base) '(srfi 2))))
;; We want to check whether 'form' has indeed wrong syntax. We eval it and
;; check for any exception, which is our best approximation.
(define-syntax test-syntax-error
(syntax-rules ()
((_ form)
(test-error (test-eval 'form)))))
(define-tests run-tests "SRFI-2"
(test-equal 1 (and-let* () 1))
(test-equal 2 (and-let* () 1 2))
(test-equal #t (and-let* ()))
(test-equal #f (let ((x #f)) (and-let* (x))))
(test-equal 1 (let ((x 1)) (and-let* (x))))
(test-equal #f (and-let* ((x #f))))
(test-equal 1 (and-let* ((x 1))))
(test-equal #f (and-let* ((#f) (x 1))))
(test-equal 1 (and-let* ((2) (x 1))))
;; Gauche allows let-binding a constant, thus fails to signal an error on
;; the following two tests.
(cond-expand
(gauche (test-expect-fail 2))
(else))
(test-syntax-error (and-let* (#f (x 1))))
(test-syntax-error (and-let* (2 (x 1))))
(test-equal 2 (and-let* ((x 1) (2))))
(test-equal #f (let ((x #f)) (and-let* (x) x)))
(test-equal "" (let ((x "")) (and-let* (x) x)))
(test-equal "" (let ((x "")) (and-let* (x))))
(test-equal 2 (let ((x 1)) (and-let* (x) (+ x 1))))
(test-equal #f (let ((x #f)) (and-let* (x) (+ x 1))))
(test-equal 2 (let ((x 1)) (and-let* (((positive? x))) (+ x 1))))
(test-equal #t (let ((x 1)) (and-let* (((positive? x))))))
(test-equal #f (let ((x 0)) (and-let* (((positive? x))) (+ x 1))))
(test-equal 3
(let ((x 1)) (and-let* (((positive? x)) (x (+ x 1))) (+ x 1))))
;; This is marked as must-be-error in the original test suite; see
;; comments in the implementation for our rationale for intentionally
;; breaking off from the specification.
(test-equal 4
(let ((x 1))
(and-let* (((positive? x)) (x (+ x 1)) (x (+ x 1))) (+ x 1))))
(test-equal 2
(let ((x 1)) (and-let* (x ((positive? x))) (+ x 1))))
(test-equal 2
(let ((x 1)) (and-let* (((begin x)) ((positive? x))) (+ x 1))))
(test-equal #f
(let ((x 0)) (and-let* (x ((positive? x))) (+ x 1))))
(test-equal #f
(let ((x #f)) (and-let* (x ((positive? x))) (+ x 1))))
(test-equal #f
(let ((x #f)) (and-let* (((begin x)) ((positive? x))) (+ x 1))))
(test-equal #f
(let ((x 1)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))))
(test-equal #f
(let ((x 0)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))))
(test-equal #f
(let ((x #f)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y))))
(test-equal 3/2
(let ((x 3)) (and-let* (x (y (- x 1)) ((positive? y))) (/ x y)))))
))
(define-library (srfi-tests srfi-26)
(export run-tests)
(import
(scheme base)
(srfi 26)
(srfi 64)
(srfi-tests aux))
(begin
(define-tests run-tests "SRFI-26"
;; cut
(test-equal '() ((cut list)))
(test-equal '() ((cut list <___>)))
(test-equal '(1) ((cut list 1)))
(test-equal '(1) ((cut list <>) 1))
(test-equal '(1) ((cut list <___>) 1))
(test-equal '(1 2) ((cut list 1 2)))
(test-equal '(1 2) ((cut list 1 <>) 2))
(test-equal '(1 2) ((cut list 1 <___>) 2))
(test-equal '(1 2 3 4) ((cut list 1 <___>) 2 3 4))
(test-equal '(1 2 3 4) ((cut list 1 <> 3 <>) 2 4))
(test-equal '(1 2 3 4 5 6) ((cut list 1 <> 3 <___>) 2 4 5 6))
(test-equal '(ok) (let* ((x 'wrong) (y (cut list x))) (set! x 'ok) (y)))
(test-equal 2 (let ((a 0))
(map (cut + (begin (set! a (+ a 1)) a) <>)
'(1 2))
a))
;; cute
(test-equal '() ((cute list)))
(test-equal '() ((cute list <___>)))
(test-equal '(1) ((cute list 1)))
(test-equal '(1) ((cute list <>) 1))
(test-equal '(1) ((cute list <___>) 1))
(test-equal '(1 2) ((cute list 1 2)))
(test-equal '(1 2) ((cute list 1 <>) 2))
(test-equal '(1 2) ((cute list 1 <___>) 2))
(test-equal '(1 2 3 4) ((cute list 1 <___>) 2 3 4))
(test-equal '(1 2 3 4) ((cute list 1 <> 3 <>) 2 4))
(test-equal '(1 2 3 4 5 6) ((cute list 1 <> 3 <___>) 2 4 5 6))
(test-equal 1 (let ((a 0))
(map (cute + (begin (set! a (+ a 1)) a) <>)
'(1 2))
a)))))
(define-library (srfi-tests srfi-31)
(export run-tests)
(import
(scheme base)
(scheme lazy)
(srfi 31)
(srfi 64)
(srfi-tests aux))
(begin
(define-tests run-tests "SRFI-31"
(test-eqv "factorial" 3628800
((rec (! n)
(if (zero? n)
1
(* n (! (- n 1)))))
10))
(test-eqv "lazy stream" 'x
(car (force (cdr (force (cdr (rec xs (cons 'x (delay xs))))))))))))
(define-library (srfi-tests srfi-54)
(export run-tests)
(import
(scheme base)
(scheme char)
(scheme write)
(srfi 54)
(srfi 64)
(srfi-tests aux))
(begin
(define-syntax value-and-output
(syntax-rules ()
((_ expr)
(let ((port (open-output-string)))
(parameterize ((current-output-port port))
(let ((value expr))
(list value (get-output-string port))))))))
(define (string-reverse string)
(list->string (reverse (string->list string))))
(define-tests run-tests "SRFI-54"
(test-equal "130.00 " (cat 129.995 -10 2.))
(test-equal " 130.00" (cat 129.995 10 2.))
(test-equal " 129.98" (cat 129.985 10 2.))
(test-equal " 129.99" (cat 129.985001 10 2.))
(test-equal "#e130.00" (cat 129.995 2. 'exact))
(test-equal "129.00" (cat 129 -2.))
(test-equal "#e129.00" (cat 129 2.))
(test-equal "#e+0129.00" (cat 129 10 2. #\0 'sign))
(test-equal "*#e+129.00" (cat 129 10 2. #\* 'sign))
(test-equal "1/3" (cat 1/3))
(test-equal " #e0.33" (cat 1/3 10 2.))
(test-equal " 0.33" (cat 1/3 10 -2.))
(test-equal " 1,29.99,5" (cat 129.995 10 '(#\, 2)))
(test-equal " +129,995" (cat 129995 10 '(#\,) 'sign))
(test-equal "130" (cat (cat 129.995 0.) '(0 -1)))
;; These produce different results on Chibi, but I don't know if that's a
;; bug or whether the result is implementation-dependent.
;; (test-equal "#i#o+307/2" (cat 99.5 10 'sign 'octal))
;; (test-equal " #o+307/2" (cat 99.5 10 'sign 'octal 'exact))
(test-equal "#o+443" (cat #x123 'octal 'sign))
(test-equal "#e+291.00*" (cat #x123 -10 2. 'sign #\*))
;; These produce different results on Larceny, but I don't know if that's
;; a bug or whether the result is implementation-dependent.
;; (test-equal "-1.234e+15+1.236e-15i" (cat -1.2345e+15+1.2355e-15i 3.))
;; (test-equal "+1.234e+15" (cat 1.2345e+15 10 3. 'sign))
(test-equal "string " (cat "string" -10))
(test-equal " STRING" (cat "string" 10 (list string-upcase)))
(test-equal " RING" (cat "string" 10 (list string-upcase) '(-2)))
(test-equal " STING" (cat "string" 10 `(,string-upcase) '(2 3)))
(test-equal "GNIRTS" (cat "string" `(,string-reverse ,string-upcase)))
(test-equal " a" (cat #\a 10))
(test-equal " symbol" (cat 'symbol 10))
(test-equal "#(#\\a \"str\" s)" (cat '#(#\a "str" s)))
(test-equal "(#\\a \"str\" s)" (cat '(#\a "str" s)))
(test-equal '("(#\\a \"str\" s)" "(#\\a \"str\" s)")
(value-and-output (cat '(#\a "str" s) #t)))
(test-equal '("(#\\a \"str\" s)" "(#\\a \"str\" s)")
(value-and-output (cat '(#\a "str" s) (current-output-port))))
(test-equal "3s \"str\"" (cat 3 (cat 's) " " (cat "str" write)))
(test-equal '("3s \"str\"" "3s \"str\"")
(value-and-output (cat 3 #t (cat 's) " " (cat "str" write))))
(test-equal '("3s \"str\"" "s3s \"str\"")
(value-and-output (cat 3 #t (cat 's #t) " " (cat "str" write)))))
))
(import
(scheme base)
(scheme process-context)
(srfi 64))
;;;
;;; This is a test suite written in the notation of
;;; SRFI-64, A Scheme API for test suites
;;;
(test-begin "SRFI 64 - Meta-Test Suite")
;;;
;;; Ironically, in order to set up the meta-test environment,
;;; we have to invoke one of the most sophisticated features:
;;; custom test runners
;;;
;;; The `prop-runner' invokes `thunk' in the context of a new
;;; test runner, and returns the indicated properties of the
;;; last-executed test result.
(define (prop-runner props thunk)
(let ((r (test-runner-null))
(plist '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! plist (test-result-alist runner))))
;;
(test-with-runner r (thunk))
;; reorder the properties so they are in the order
;; given by `props'. Note that any property listed in `props'
;; that is not in the property alist will occur as #f
(map (lambda (k)
(assq k plist))
props)))
;;; `on-test-runner' creates a null test runner and then
;;; arranged for `visit' to be called with the runner
;;; whenever a test is run. The results of the calls to
;;; `visit' are returned in a list
(define (on-test-runner thunk visit)
(let ((r (test-runner-null))
(results '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! results (cons (visit r) results))))
;;
(test-with-runner r (thunk))
(reverse results)))
;;;
;;; The `triv-runner' invokes `thunk'
;;; and returns a list of 6 lists, the first 5 of which
;;; are a list of the names of the tests that, respectively,
;;; PASS, FAIL, XFAIL, XPASS, and SKIP.
;;; The last item is a list of counts.
;;;
(define (triv-runner thunk)
(let ((r (test-runner-null))
(accum-pass '())
(accum-fail '())
(accum-xfail '())
(accum-xpass '())
(accum-skip '()))
;;
(test-runner-on-bad-count!
r
(lambda (runner count expected-count)
(error (string-append "bad count " (number->string count)
" but expected "
(number->string expected-count)))))
(test-runner-on-bad-end-name!
r
(lambda (runner begin end)
(error (string-append "bad end group name " end
" but expected " begin))))
(test-runner-on-test-end!
r
(lambda (runner)
(let ((n (test-runner-test-name runner)))
(case (test-result-kind runner)
((pass) (set! accum-pass (cons n accum-pass)))
((fail) (set! accum-fail (cons n accum-fail)))
((xpass) (set! accum-xpass (cons n accum-xpass)))
((xfail) (set! accum-xfail (cons n accum-xfail)))
((skip) (set! accum-skip (cons n accum-skip)))))))
;;
(test-with-runner r (thunk))
(list (reverse accum-pass) ; passed as expected
(reverse accum-fail) ; failed, but was expected to pass
(reverse accum-xfail) ; failed as expected
(reverse accum-xpass) ; passed, but was expected to fail
(reverse accum-skip) ; was not executed
(list (test-runner-pass-count r)
(test-runner-fail-count r)
(test-runner-xfail-count r)
(test-runner-xpass-count r)
(test-runner-skip-count r)))))
(define (path-revealing-runner thunk)
(let ((r (test-runner-null))
(seq '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! seq (cons (list (test-runner-group-path runner)
(test-runner-test-name runner))
seq))))
(test-with-runner r (thunk))
(reverse seq)))
;;;
;;; Now we can start testing compliance with SRFI-64
;;;
(test-begin "1. Simple test-cases")
(test-begin "1.1. test-assert")
(define (t)
(triv-runner
(lambda ()
(test-assert "a" #t)
(test-assert "b" #f))))
(test-equal
"1.1.1. Very simple"
'(("a") ("b") () () () (1 1 0 0 0))
(t))
(test-equal
"1.1.2. A test with no name"
'(("a") ("") () () () (1 1 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert #f))))
(test-equal
"1.1.3. Tests can have the same name"
'(("a" "a") () () () () (2 0 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert "a" #t))))
(define (choke)
(vector-ref '#(1 2) 3))
(test-equal
"1.1.4. One way to FAIL is to throw an error"
'(() ("a") () () () (0 1 0 0 0))
(triv-runner (lambda () (test-assert "a" (choke)))))
(test-end);1.1
(test-begin "1.2. test-eqv")
(define (mean x y)
(/ (+ x y) 2.0))
(test-equal
"1.2.1. Simple numerical equivalence"
'(("c") ("a" "b") () () () (1 2 0 0 0))
(triv-runner
(lambda ()
(test-eqv "a" (mean 3 5) 4)
(test-eqv "b" (mean 3 5) 4.5)
(test-eqv "c" (mean 3 5) 4.0))))
(test-end);1.2
(test-begin "1.3. test-approximate")
(test-equal
"1.3.1. Simple numerical approximation"
'(("a" "c") ("b") () () () (2 1 0 0 0))
(triv-runner
(lambda ()
(test-approximate "a" (mean 3 5) 4 0.001)
(test-approximate "b" (mean 3 5) 4.5 0.001)
(test-approximate "c" (mean 3 5) 4.0 0.001))))
(test-end);1.3
(test-end "1. Simple test-cases")
;;;
;;;
;;;
(test-begin "2. Tests for catching errors")
(test-begin "2.1. test-error")
(test-equal
"2.1.1. Baseline test; PASS with no optional args"
'(("") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error (vector-ref '#(1 2) 9)))))
(test-equal
"2.1.2. Baseline test; FAIL with no optional args"
'(() ("") () () () (0 1 0 0 0))
(triv-runner
(lambda ()
;; FAIL: the expr does not raise an error and `test-error' is
;; claiming that it will, so this test should FAIL
(test-error (vector-ref '#(1 2) 0)))))
(test-equal
"2.1.3. PASS with a test name and error type"
'(("a") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error "a" #t (vector-ref '#(1 2) 9)))))
(test-equal
"2.1.4. FAIL with a test name and error type"
'(() ("a") () () () (0 1 0 0 0))
(triv-runner
(lambda ()
;; FAIL
(test-error "a" #t (vector-ref '#(1 2) 0)))))
(test-equal
"2.1.5. PASS with an error type but no name"
'(("") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error #t (vector-ref '#(1 2) 9)))))
(test-equal
"2.1.6. FAIL with an error type but no name"
'(() ("") () () () (0 1 0 0 0))
(triv-runner
(lambda ()
;; FAIL
(test-error #t (vector-ref '#(1 2) 0)))))
(test-end "2.1. test-error")
(test-end "2. Tests for catching errors")
;;;
;;;
;;;
(test-begin "3. Test groups and paths")
(test-equal
"3.1. test-begin with unspecific test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end))))
(test-equal
"3.2. test-begin with name-matching test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "a"))))
;;; since the error raised by `test-end' on a mismatch is not a test
;;; error, we actually expect the triv-runner itself to fail
(test-error
"3.3. test-begin with mismatched test-end"
#t
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "x"))))
(test-equal
"3.4. test-begin with name and count"
'(("b" "c") () () () () (2 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a" 2)
(test-assert "b" #t)
(test-assert "c" #t)
(test-end "a"))))
;; similarly here, a mismatched count is a lexical error
;; and not a test failure...
(test-error
"3.5. test-begin with mismatched count"
#t
(triv-runner
(lambda ()
(test-begin "a" 99)
(test-assert "b" #t)
(test-end "a"))))
(test-equal
"3.6. introspecting on the group path"
'((() "w")
(("a" "b") "x")
(("a" "b") "y")
(("a") "z"))
;;
;; `path-revealing-runner' is designed to return a list
;; of the tests executed, in order. Each entry is a list
;; (GROUP-PATH TEST-NAME), and each GROUP-PATH is a list
;; of test groups starting from the topmost
;;
(path-revealing-runner
(lambda ()
(test-assert "w" #t)
(test-begin "a")
(test-begin "b")
(test-assert "x" #t)
(test-assert "y" #t)
(test-end)
(test-assert "z" #t))))
(test-end "3. Test groups and paths")
;;;
;;;
;;;
(test-begin "4. Handling set-up and cleanup")
(test-equal "4.1. Normal exit path"
'(in 1 2 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in)
(do 1)
(do 2)
(do 'out))))
(reverse ex)))
(test-equal "4.2. Exception exit path"
'(in 1 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
;; the outer runner is to run the `test-error' in, to
;; catch the exception raised in the inner runner,
;; since we don't want to depend on any other
;; exception-catching support
;;
(triv-runner
(lambda ()
(test-error
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in) (test-assert #t)
(do 1) (test-assert #t)
(choke) (test-assert #t)
(do 2) (test-assert #t)
(do 'out)))))))
(reverse ex)))
(test-end "4. Handling set-up and cleanup")
;;;
;;;
;;;
(test-begin "5. Test specifiers")
(test-begin "5.1. test-match-named")
(test-equal "5.1.1. match test names"
'(("y") () () () ("x") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-assert "x" #t)
(test-assert "y" #t))))
(test-equal "5.1.2. but not group names"
'(("z") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-begin "x")
(test-assert "z" #t)
(test-end))))
(test-end)
(test-begin "5.2. test-match-nth")
;; See also: [6.4. Short-circuit evaluation]
(test-equal "5.2.1. skip the nth one after"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3
(test-assert "z" #t)))) ; 4
(test-equal "5.2.2. skip m, starting at n"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3 SKIP
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.3. test-match-any")
(test-equal "5.3.1. basic disjunction"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-nth 3)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.3.2. disjunction is commutative"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-name "x")
(test-match-nth 3)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.4. test-match-all")
(test-equal "5.4.1. basic conjunction"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-nth 2 2)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.4.2. conjunction is commutative"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-name "x")
(test-match-nth 2 2)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-end "5. Test specifiers")
;;;
;;;
;;;
(test-begin "6. Skipping selected tests")
(test-equal
"6.1. Skip by specifier - match-name"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-name "y"))
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-equal
"6.2. Shorthand specifiers"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-begin "6.3. Specifier Stack")
(test-equal
"6.3.1. Clearing the Specifier Stack"
'(("x" "x") ("y") () () ("y") (2 1 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; FAIL
(test-end))))
(test-equal
"6.3.2. Inheriting the Specifier Stack"
'(("x" "x") () () () ("y" "y") (2 0 0 0 2))
(triv-runner
(lambda ()
(test-skip "y")
(test-begin "a")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-end);6.3
(test-begin "6.4. Short-circuit evaluation")
(test-equal
"6.4.1. In test-match-all"
'(("x") ("y" "x" "z") () () ("y") (1 3 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-all "y" (test-match-nth 2)))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f FAIL
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-equal
"6.4.2. In separate skip-list entries"
'(("x") ("x" "z") () () ("y" "y") (1 2 0 0 2))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-skip (test-match-nth 2))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f SKIP
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-begin "6.4.3. Skipping test suites")
(test-equal
"6.4.3.1. Introduced using 'test-begin'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-begin "b") ; not skipped
(test-assert "x" #t)
(test-end "b")
(test-end "a"))))
(test-expect-fail 1) ;; ???
(test-equal
"6.4.3.2. Introduced using 'test-group'"
'(() () () () () (0 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-group
"b" ; skipped
(test-assert "x" #t))
(test-end "a"))))
(test-equal
"6.4.3.3. Non-skipped 'test-group'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "c")
(test-group "b" (test-assert "x" #t))
(test-end "a"))))
(test-end) ; 6.4.3
(test-end);6.4
(test-end "6. Skipping selected tests")
;;;
;;;
;;;
(test-begin "7. Expected failures")
(test-equal "7.1. Simple example"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" #f))))
(test-equal "7.2. Expected exception"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" (choke)))))
(test-equal "7.3. Unexpectedly PASS"
'(() () ("y") ("x") () (0 0 1 1 0))
(triv-runner
(lambda ()
(test-expect-fail "x")
(test-expect-fail "y")
(test-assert "x" #t)
(test-assert "y" #f))))
(test-end "7. Expected failures")
;;;
;;;
;;;
(test-begin "8. Test-runner")
;;;
;;; Because we want this test suite to be accurate even
;;; when the underlying implementation chooses to use, e.g.,
;;; a global variable to implement what could be thread variables
;;; or SRFI-39 parameter objects, we really need to save and restore
;;; their state ourselves
;;;
(define (with-factory-saved thunk)
(let* ((saved (test-runner-factory))
(result (thunk)))
(test-runner-factory saved)
result))
(test-begin "8.1. test-runner-current")
(test-assert "8.1.1. automatically restored"
(let ((a 0)
(b 1)
(c 2))
;
(triv-runner
(lambda ()
(set! a (test-runner-current))
;;
(triv-runner
(lambda ()
(set! b (test-runner-current))))
;;
(set! c (test-runner-current))))
;;
(and (eq? a c)
(not (eq? a b)))))
(test-end)
(test-begin "8.2. test-runner-simple")
(test-assert "8.2.1. default on-test hook"
(eq? (test-runner-on-test-end (test-runner-simple))
test-on-test-end-simple))
(test-assert "8.2.2. default on-final hook"
(eq? (test-runner-on-final (test-runner-simple))
test-on-final-simple))
(test-end)
(test-begin "8.3. test-runner-factory")
(test-assert "8.3.1. default factory"
(eq? (test-runner-factory) test-runner-simple))
(test-assert "8.3.2. settable factory"
(with-factory-saved
(lambda ()
(test-runner-factory test-runner-null)
;; we have no way, without bringing in other SRFIs,
;; to make sure the following doesn't print anything,
;; but it shouldn't:
(test-with-runner
(test-runner-create)
(lambda ()
(test-begin "a")
(test-assert #t) ; pass
(test-assert #f) ; fail
(test-assert (vector-ref '#(3) 10)) ; fail with error
(test-end "a")))
(eq? (test-runner-factory) test-runner-null))))
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.4. test-runner-create")
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.5. test-runner-factory")
(test-end)
(test-begin "8.6. test-apply")
(test-equal "8.6.1. Simple (form 1) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-equal "8.6.2. Simple (form 2) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-runner-current)
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-expect-fail 1) ;; depends on all test-match-nth being called.
(test-equal "8.6.3. test-apply with skips"
'(("w" "q" "v") () () () ("x" "p" "x") (3 0 0 0 3))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-skip (test-match-nth 2))
(test-skip (test-match-nth 4))
(test-apply
(test-runner-current)
(test-match-name "p")
(test-match-name "q")
(lambda ()
; only execute if SKIP=no and APPLY=yes
(test-assert "x" #t) ; # 1 SKIP=no APPLY=no
(test-assert "p" #t) ; # 2 SKIP=yes APPLY=yes
(test-assert "q" #t) ; # 3 SKIP=no APPLY=yes
(test-assert "x" #f) ; # 4 SKIP=yes APPLY=no
0))
(test-assert "v" #t))))
;;; Unfortunately, since there is no way to UNBIND the current test runner,
;;; there is no way to test the behavior of `test-apply' in the absence
;;; of a current runner within our little meta-test framework.
;;;
;;; To test the behavior manually, you should be able to invoke:
;;;
;;; (test-apply "a" (lambda () (test-assert "a" #t)))
;;;
;;; from the top level (with SRFI 64 available) and it should create a
;;; new, default (simple) test runner.
(test-end)
;;; This entire suite depends heavily on 'test-with-runner'. If it didn't
;;; work, this suite would probably go down in flames
(test-begin "8.7. test-with-runner")
(test-end)
;;; Again, this suite depends heavily on many of the test-runner
;;; components. We'll just test those that aren't being exercised
;;; by the meta-test framework
(test-begin "8.8. test-runner components")
(define (auxtrack-runner thunk)
(let ((r (test-runner-null)))
(test-runner-aux-value! r '())
(test-runner-on-test-end! r (lambda (r)
(test-runner-aux-value!
r
(cons (test-runner-test-name r)
(test-runner-aux-value r)))))
(test-with-runner r (thunk))
(reverse (test-runner-aux-value r))))
(test-equal "8.8.1. test-runner-aux-value"
'("x" "" "y")
(auxtrack-runner
(lambda ()
(test-assert "x" #t)
(test-begin "a")
(test-assert #t)
(test-end)
(test-assert "y" #f))))
(test-end) ; 8.8
(test-end "8. Test-runner")
(test-begin "9. Test Result Properties")
(test-begin "9.1. test-result-alist")
(define (symbol-alist? l)
(if (null? l)
#t
(and (pair? l)
(pair? (car l))
(symbol? (caar l))
(symbol-alist? (cdr l)))))
;;; check the various syntactic forms
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
;;; check to make sure the required properties are returned
(test-equal '((result-kind . pass))
(prop-runner
'(result-kind)
(lambda ()
(test-assert #t)))
)
(test-equal
'((result-kind . fail)
(expected-value . 2)
(actual-value . 3))
(prop-runner
'(result-kind expected-value actual-value)
(lambda ()
(test-equal 2 (+ 1 2)))))
(test-end "9.1. test-result-alist")
(test-begin "9.2. test-result-ref")
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(fail pass)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-end "9.2. test-result-ref")
(test-begin "9.3. test-result-set!")
(test-equal '(100 100)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-set! r 'foo 100)
(test-result-ref r 'foo))))
(test-end "9.3. test-result-set!")
(test-end "9. Test Result Properties")
;;;
;;;
;;;
;#| Time to stop having fun...
;
;(test-begin "9. For fun, some meta-test errors")
;
;(test-equal
; "9.1. Really PASSes, but test like it should FAIL"
; '(() ("b") () () ())
; (triv-runner
; (lambda ()
; (test-assert "b" #t))))
;
;(test-expect-fail "9.2. Expect to FAIL and do so")
;(test-expect-fail "9.3. Expect to FAIL but PASS")
;(test-skip "9.4. SKIP this one")
;
;(test-assert "9.2. Expect to FAIL and do so" #f)
;(test-assert "9.3. Expect to FAIL but PASS" #t)
;(test-assert "9.4. SKIP this one" #t)
;
;(test-end)
; |#
(test-end "SRFI 64 - Meta-Test Suite")
(let ((runner (test-runner-current)))
(unless (and (= 0 (test-runner-xpass-count runner))
(= 0 (test-runner-fail-count runner)))
(exit 1)))
;;;
;;;
;;; This is a test suite written in the notation of
;;; SRFI-64, A Scheme API for test suites
;;;
(test-begin "SRFI 64 - Meta-Test Suite")
;;;
;;; Ironically, in order to set up the meta-test environment,
;;; we have to invoke one of the most sophisticated features:
;;; custom test runners
;;;
;;; The `prop-runner' invokes `thunk' in the context of a new
;;; test runner, and returns the indicated properties of the
;;; last-executed test result.
(define (prop-runner props thunk)
(let ((r (test-runner-null))
(plist '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! plist (test-result-alist runner))))
;;
(test-with-runner r (thunk))
;; reorder the properties so they are in the order
;; given by `props'. Note that any property listed in `props'
;; that is not in the property alist will occur as #f
(map (lambda (k)
(assq k plist))
props)))
;;; `on-test-runner' creates a null test runner and then
;;; arranged for `visit' to be called with the runner
;;; whenever a test is run. The results of the calls to
;;; `visit' are returned in a list
(define (on-test-runner thunk visit)
(let ((r (test-runner-null))
(results '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! results (cons (visit r) results))))
;;
(test-with-runner r (thunk))
(reverse results)))
;;;
;;; The `triv-runner' invokes `thunk'
;;; and returns a list of 6 lists, the first 5 of which
;;; are a list of the names of the tests that, respectively,
;;; PASS, FAIL, XFAIL, XPASS, and SKIP.
;;; The last item is a list of counts.
;;;
(define (triv-runner thunk)
(let ((r (test-runner-null))
(accum-pass '())
(accum-fail '())
(accum-xfail '())
(accum-xpass '())
(accum-skip '()))
;;
(test-runner-on-bad-count!
r
(lambda (runner count expected-count)
(error (string-append "bad count " (number->string count)
" but expected "
(number->string expected-count)))))
(test-runner-on-bad-end-name!
r
(lambda (runner begin end)
(error (string-append "bad end group name " end
" but expected " begin))))
(test-runner-on-test-end!
r
(lambda (runner)
(let ((n (test-runner-test-name runner)))
(case (test-result-kind runner)
((pass) (set! accum-pass (cons n accum-pass)))
((fail) (set! accum-fail (cons n accum-fail)))
((xpass) (set! accum-xpass (cons n accum-xpass)))
((xfail) (set! accum-xfail (cons n accum-xfail)))
((skip) (set! accum-skip (cons n accum-skip)))))))
;;
(test-with-runner r (thunk))
(list (reverse accum-pass) ; passed as expected
(reverse accum-fail) ; failed, but was expected to pass
(reverse accum-xfail) ; failed as expected
(reverse accum-xpass) ; passed, but was expected to fail
(reverse accum-skip) ; was not executed
(list (test-runner-pass-count r)
(test-runner-fail-count r)
(test-runner-xfail-count r)
(test-runner-xpass-count r)
(test-runner-skip-count r)))))
(define (path-revealing-runner thunk)
(let ((r (test-runner-null))
(seq '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! seq (cons (list (test-runner-group-path runner)
(test-runner-test-name runner))
seq))))
(test-with-runner r (thunk))
(reverse seq)))
;;;
;;; Now we can start testing compliance with SRFI-64
;;;
(test-begin "1. Simple test-cases")
(test-begin "1.1. test-assert")
(define (t)
(triv-runner
(lambda ()
(test-assert "a" #t)
(test-assert "b" #f))))
(test-equal
"1.1.1. Very simple"
'(("a") ("b") () () () (1 1 0 0 0))
(t))
(test-equal
"1.1.2. A test with no name"
'(("a") ("") () () () (1 1 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert #f))))
(test-equal
"1.1.3. Tests can have the same name"
'(("a" "a") () () () () (2 0 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert "a" #t))))
(define (choke)
(vector-ref '#(1 2) 3))
(test-equal
"1.1.4. One way to FAIL is to throw an error"
'(() ("a") () () () (0 1 0 0 0))
(triv-runner (lambda () (test-assert "a" (choke)))))
(test-end);1.1
(test-begin "1.2. test-eqv")
(define (mean x y)
(/ (+ x y) 2.0))
(test-equal
"1.2.1. Simple numerical equivalence"
'(("c") ("a" "b") () () () (1 2 0 0 0))
(triv-runner
(lambda ()
(test-eqv "a" (mean 3 5) 4)
(test-eqv "b" (mean 3 5) 4.5)
(test-eqv "c" (mean 3 5) 4.0))))
(test-end);1.2
(test-end "1. Simple test-cases")
;;;
;;;
;;;
(test-begin "2. Tests for catching errors")
(test-begin "2.1. test-error")
(test-equal
"2.1.1. Baseline test; PASS with no optional args"
'(("") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error (vector-ref '#(1 2) 9)))))
(test-equal
"2.1.2. Baseline test; FAIL with no optional args"
'(() ("") () () () (0 1 0 0 0))
(triv-runner
(lambda ()
;; FAIL: the expr does not raise an error and `test-error' is
;; claiming that it will, so this test should FAIL
(test-error (vector-ref '#(1 2) 0)))))
(test-equal
"2.1.3. PASS with a test name and error type"
'(("a") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error "a" #t (vector-ref '#(1 2) 9)))))
(test-end "2.1. test-error")
(test-end "2. Tests for catching errors")
;;;
;;;
;;;
(test-begin "3. Test groups and paths")
(test-equal
"3.1. test-begin with unspecific test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end))))
(test-equal
"3.2. test-begin with name-matching test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "a"))))
;;; since the error raised by `test-end' on a mismatch is not a test
;;; error, we actually expect the triv-runner itself to fail
(test-error
"3.3. test-begin with mismatched test-end"
#t
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "x"))))
(test-equal
"3.4. test-begin with name and count"
'(("b" "c") () () () () (2 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a" 2)
(test-assert "b" #t)
(test-assert "c" #t)
(test-end "a"))))
;; similarly here, a mismatched count is a lexical error
;; and not a test failure...
(test-error
"3.5. test-begin with mismatched count"
#t
(triv-runner
(lambda ()
(test-begin "a" 99)
(test-assert "b" #t)
(test-end "a"))))
(test-equal
"3.6. introspecting on the group path"
'((() "w")
(("a" "b") "x")
(("a" "b") "y")
(("a") "z"))
;;
;; `path-revealing-runner' is designed to return a list
;; of the tests executed, in order. Each entry is a list
;; (GROUP-PATH TEST-NAME), and each GROUP-PATH is a list
;; of test groups starting from the topmost
;;
(path-revealing-runner
(lambda ()
(test-assert "w" #t)
(test-begin "a")
(test-begin "b")
(test-assert "x" #t)
(test-assert "y" #t)
(test-end)
(test-assert "z" #t))))
(test-end "3. Test groups and paths")
;;;
;;;
;;;
(test-begin "4. Handling set-up and cleanup")
(test-equal "4.1. Normal exit path"
'(in 1 2 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in)
(do 1)
(do 2)
(do 'out))))
(reverse ex)))
(test-equal "4.2. Exception exit path"
'(in 1 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
;; the outer runner is to run the `test-error' in, to
;; catch the exception raised in the inner runner,
;; since we don't want to depend on any other
;; exception-catching support
;;
(triv-runner
(lambda ()
(test-error
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in) (test-assert #t)
(do 1) (test-assert #t)
(choke) (test-assert #t)
(do 2) (test-assert #t)
(do 'out)))))))
(reverse ex)))
(test-end "4. Handling set-up and cleanup")
;;;
;;;
;;;
(test-begin "5. Test specifiers")
(test-begin "5.1. test-match-named")
(test-equal "5.1.1. match test names"
'(("y") () () () ("x") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-assert "x" #t)
(test-assert "y" #t))))
(test-equal "5.1.2. but not group names"
'(("z") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-begin "x")
(test-assert "z" #t)
(test-end))))
(test-end)
(test-begin "5.2. test-match-nth")
;; See also: [6.4. Short-circuit evaluation]
(test-equal "5.2.1. skip the nth one after"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3
(test-assert "z" #t)))) ; 4
(test-equal "5.2.2. skip m, starting at n"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3 SKIP
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.3. test-match-any")
(test-equal "5.3.1. basic disjunction"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-nth 3)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.3.2. disjunction is commutative"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-name "x")
(test-match-nth 3)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.4. test-match-all")
(test-equal "5.4.1. basic conjunction"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-nth 2 2)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.4.2. conjunction is commutative"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-name "x")
(test-match-nth 2 2)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-end "5. Test specifiers")
;;;
;;;
;;;
(test-begin "6. Skipping selected tests")
(test-equal
"6.1. Skip by specifier - match-name"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-name "y"))
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-equal
"6.2. Shorthand specifiers"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-begin "6.3. Specifier Stack")
(test-equal
"6.3.1. Clearing the Specifier Stack"
'(("x" "x") ("y") () () ("y") (2 1 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; FAIL
(test-end))))
(test-equal
"6.3.2. Inheriting the Specifier Stack"
'(("x" "x") () () () ("y" "y") (2 0 0 0 2))
(triv-runner
(lambda ()
(test-skip "y")
(test-begin "a")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-end);6.3
(test-begin "6.4. Short-circuit evaluation")
(test-equal
"6.4.1. In test-match-all"
'(("x") ("y" "x" "z") () () ("y") (1 3 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-all "y" (test-match-nth 2)))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f FAIL
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-equal
"6.4.2. In separate skip-list entries"
'(("x") ("x" "z") () () ("y" "y") (1 2 0 0 2))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-skip (test-match-nth 2))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f SKIP
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-begin "6.4.3. Skipping test suites")
(test-equal
"6.4.3.1. Introduced using 'test-begin'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-begin "b") ; not skipped
(test-assert "x" #t)
(test-end "b")
(test-end "a"))))
(test-expect-fail 1) ;; ???
(test-equal
"6.4.3.2. Introduced using 'test-group'"
'(() () () () () (0 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-group
"b" ; skipped
(test-assert "x" #t))
(test-end "a"))))
(test-equal
"6.4.3.3. Non-skipped 'test-group'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "c")
(test-group "b" (test-assert "x" #t))
(test-end "a"))))
(test-end) ; 6.4.3
(test-end);6.4
(test-end "6. Skipping selected tests")
;;;
;;;
;;;
(test-begin "7. Expected failures")
(test-equal "7.1. Simple example"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" #f))))
(test-equal "7.2. Expected exception"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" (choke)))))
(test-equal "7.3. Unexpectedly PASS"
'(() () ("y") ("x") () (0 0 1 1 0))
(triv-runner
(lambda ()
(test-expect-fail "x")
(test-expect-fail "y")
(test-assert "x" #t)
(test-assert "y" #f))))
(test-end "7. Expected failures")
;;;
;;;
;;;
(test-begin "8. Test-runner")
;;;
;;; Because we want this test suite to be accurate even
;;; when the underlying implementation chooses to use, e.g.,
;;; a global variable to implement what could be thread variables
;;; or SRFI-39 parameter objects, we really need to save and restore
;;; their state ourselves
;;;
(define (with-factory-saved thunk)
(let* ((saved (test-runner-factory))
(result (thunk)))
(test-runner-factory saved)
result))
(test-begin "8.1. test-runner-current")
(test-assert "8.1.1. automatically restored"
(let ((a 0)
(b 1)
(c 2))
;
(triv-runner
(lambda ()
(set! a (test-runner-current))
;;
(triv-runner
(lambda ()
(set! b (test-runner-current))))
;;
(set! c (test-runner-current))))
;;
(and (eq? a c)
(not (eq? a b)))))
(test-end)
(test-begin "8.2. test-runner-simple")
(test-assert "8.2.1. default on-test hook"
(eq? (test-runner-on-test-end (test-runner-simple))
test-on-test-end-simple))
(test-assert "8.2.2. default on-final hook"
(eq? (test-runner-on-final (test-runner-simple))
test-on-final-simple))
(test-end)
(test-begin "8.3. test-runner-factory")
(test-assert "8.3.1. default factory"
(eq? (test-runner-factory) test-runner-simple))
(test-assert "8.3.2. settable factory"
(with-factory-saved
(lambda ()
(test-runner-factory test-runner-null)
;; we have no way, without bringing in other SRFIs,
;; to make sure the following doesn't print anything,
;; but it shouldn't:
(test-with-runner
(test-runner-create)
(lambda ()
(test-begin "a")
(test-assert #t) ; pass
(test-assert #f) ; fail
(test-assert (vector-ref '#(3) 10)) ; fail with error
(test-end "a")))
(eq? (test-runner-factory) test-runner-null))))
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.4. test-runner-create")
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.5. test-runner-factory")
(test-end)
(test-begin "8.6. test-apply")
(test-equal "8.6.1. Simple (form 1) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-equal "8.6.2. Simple (form 2) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-runner-current)
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-expect-fail 1) ;; depends on all test-match-nth being called.
(test-equal "8.6.3. test-apply with skips"
'(("w" "q" "v") () () () ("x" "p" "x") (3 0 0 0 3))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-skip (test-match-nth 2))
(test-skip (test-match-nth 4))
(test-apply
(test-runner-current)
(test-match-name "p")
(test-match-name "q")
(lambda ()
; only execute if SKIP=no and APPLY=yes
(test-assert "x" #t) ; # 1 SKIP=no APPLY=no
(test-assert "p" #t) ; # 2 SKIP=yes APPLY=yes
(test-assert "q" #t) ; # 3 SKIP=no APPLY=yes
(test-assert "x" #f) ; # 4 SKIP=yes APPLY=no
0))
(test-assert "v" #t))))
;;; Unfortunately, since there is no way to UNBIND the current test runner,
;;; there is no way to test the behavior of `test-apply' in the absence
;;; of a current runner within our little meta-test framework.
;;;
;;; To test the behavior manually, you should be able to invoke:
;;;
;;; (test-apply "a" (lambda () (test-assert "a" #t)))
;;;
;;; from the top level (with SRFI 64 available) and it should create a
;;; new, default (simple) test runner.
(test-end)
;;; This entire suite depends heavily on 'test-with-runner'. If it didn't
;;; work, this suite would probably go down in flames
(test-begin "8.7. test-with-runner")
(test-end)
;;; Again, this suite depends heavily on many of the test-runner
;;; components. We'll just test those that aren't being exercised
;;; by the meta-test framework
(test-begin "8.8. test-runner components")
(define (auxtrack-runner thunk)
(let ((r (test-runner-null)))
(test-runner-aux-value! r '())
(test-runner-on-test-end! r (lambda (r)
(test-runner-aux-value!
r
(cons (test-runner-test-name r)
(test-runner-aux-value r)))))
(test-with-runner r (thunk))
(reverse (test-runner-aux-value r))))
(test-equal "8.8.1. test-runner-aux-value"
'("x" "" "y")
(auxtrack-runner
(lambda ()
(test-assert "x" #t)
(test-begin "a")
(test-assert #t)
(test-end)
(test-assert "y" #f))))
(test-end) ; 8.8
(test-end "8. Test-runner")
(test-begin "9. Test Result Properties")
(test-begin "9.1. test-result-alist")
(define (symbol-alist? l)
(if (null? l)
#t
(and (pair? l)
(pair? (car l))
(symbol? (caar l))
(symbol-alist? (cdr l)))))
;;; check the various syntactic forms
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
;;; check to make sure the required properties are returned
(test-equal '((result-kind . pass))
(prop-runner
'(result-kind)
(lambda ()
(test-assert #t)))
)
(test-equal
'((result-kind . fail)
(expected-value . 2)
(actual-value . 3))
(prop-runner
'(result-kind expected-value actual-value)
(lambda ()
(test-equal 2 (+ 1 2)))))
(test-end "9.1. test-result-alist")
(test-begin "9.2. test-result-ref")
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(fail pass)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-end "9.2. test-result-ref")
(test-begin "9.3. test-result-set!")
(test-equal '(100 100)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-set! r 'foo 100)
(test-result-ref r 'foo))))
(test-end "9.3. test-result-set!")
(test-end "9. Test Result Properties")
;;;
;;;
;;;
;#| Time to stop having fun...
;
;(test-begin "9. For fun, some meta-test errors")
;
;(test-equal
; "9.1. Really PASSes, but test like it should FAIL"
; '(() ("b") () () ())
; (triv-runner
; (lambda ()
; (test-assert "b" #t))))
;
;(test-expect-fail "9.2. Expect to FAIL and do so")
;(test-expect-fail "9.3. Expect to FAIL but PASS")
;(test-skip "9.4. SKIP this one")
;
;(test-assert "9.2. Expect to FAIL and do so" #f)
;(test-assert "9.3. Expect to FAIL but PASS" #t)
;(test-assert "9.4. SKIP this one" #t)
;
;(test-end)
; |#
(test-end "SRFI 64 - Meta-Test Suite")
;;;
;;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;; Eval these in Emacs:
;; (put 'stream-lambda 'scheme-indent-function 1)
;; (put 'stream-let 'scheme-indent-function 2)
(define-syntax define-stream
(syntax-rules ()
((define-stream (name . formal) body0 body1 ...)
(define name (stream-lambda formal body0 body1 ...)))))
(define (list->stream objs)
(define list->stream
(stream-lambda (objs)
(if (null? objs)
stream-null
(stream-cons (car objs) (list->stream (cdr objs))))))
(if (not (list? objs))
(error "non-list argument" objs)
(list->stream objs)))
(define (port->stream . port)
(define port->stream
(stream-lambda (p)
(let ((c (read-char p)))
(if (eof-object? c)
stream-null
(stream-cons c (port->stream p))))))
(let ((p (if (null? port) (current-input-port) (car port))))
(if (not (input-port? p))
(error "non-input-port argument" p)
(port->stream p))))
(define-syntax stream
(syntax-rules ()
((stream) stream-null)
((stream x y ...) (stream-cons x (stream y ...)))))
(define (stream->list . args)
(let ((n (if (= 1 (length args)) #f (car args)))
(strm (if (= 1 (length args)) (car args) (cadr args))))
(cond
((not (stream? strm)) (error "non-stream argument" strm))
((and n (not (integer? n))) (error "non-integer count" n))
((and n (negative? n)) (error "negative count" n))
(else (let loop ((n (if n n -1)) (strm strm))
(if (or (zero? n) (stream-null? strm))
'()
(cons (stream-car strm)
(loop (- n 1) (stream-cdr strm)))))))))
(define (stream-append . strms)
(define stream-append
(stream-lambda (strms)
(cond
((null? (cdr strms)) (car strms))
((stream-null? (car strms)) (stream-append (cdr strms)))
(else (stream-cons (stream-car (car strms))
(stream-append (cons (stream-cdr (car strms))
(cdr strms))))))))
(cond
((null? strms) stream-null)
((find (lambda (x) (not (stream? x))) strms)
=> (lambda (strm)
(error "non-stream argument" strm)))
(else (stream-append strms))))
(define (stream-concat strms)
(define stream-concat
(stream-lambda (strms)
(cond
((stream-null? strms) stream-null)
((not (stream? (stream-car strms)))
(error "non-stream object in input stream" strms))
((stream-null? (stream-car strms))
(stream-concat (stream-cdr strms)))
(else (stream-cons
(stream-car (stream-car strms))
(stream-concat
(stream-cons (stream-cdr (stream-car strms))
(stream-cdr strms))))))))
(if (not (stream? strms))
(error "non-stream argument" strms)
(stream-concat strms)))
(define stream-constant
(stream-lambda objs
(cond
((null? objs) stream-null)
((null? (cdr objs)) (stream-cons (car objs)
(stream-constant (car objs))))
(else (stream-cons (car objs)
(apply stream-constant
(append (cdr objs) (list (car objs)))))))))
(define (stream-drop n strm)
(define stream-drop
(stream-lambda (n strm)
(if (or (zero? n) (stream-null? strm))
strm
(stream-drop (- n 1) (stream-cdr strm)))))
(cond
((not (integer? n)) (error "non-integer argument" n))
((negative? n) (error "negative argument" n))
((not (stream? strm)) (error "non-stream argument" strm))
(else (stream-drop n strm))))
(define (stream-drop-while pred? strm)
(define stream-drop-while
(stream-lambda (strm)
(if (and (stream-pair? strm) (pred? (stream-car strm)))
(stream-drop-while (stream-cdr strm))
strm)))
(cond
((not (procedure? pred?)) (error "non-procedural argument" pred?))
((not (stream? strm)) (error "non-stream argument" strm))
(else (stream-drop-while strm))))
(define (stream-filter pred? strm)
(define stream-filter
(stream-lambda (strm)
(cond
((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (stream-filter (stream-cdr strm))))
(else (stream-filter (stream-cdr strm))))))
(cond
((not (procedure? pred?)) (error "non-procedural argument" pred?))
((not (stream? strm)) (error "non-stream argument" strm))
(else (stream-filter strm))))
(define (stream-fold proc base strm)
(cond
((not (procedure? proc)) (error "non-procedural argument" proc))
((not (stream? strm)) (error "non-stream argument" strm))
(else (let loop ((base base) (strm strm))
(if (stream-null? strm)
base
(loop (proc base (stream-car strm)) (stream-cdr strm)))))))
(define (stream-for-each proc . strms)
(define (stream-for-each strms)
(if (not (find stream-null? strms))
(begin (apply proc (map stream-car strms))
(stream-for-each (map stream-cdr strms)))))
(cond
((not (procedure? proc)) (error "non-procedural argument" proc))
((null? strms) (error "no stream arguments"))
((find (lambda (x) (not (stream? x))) strms)
=> (lambda (strm)
(error "non-stream argument" strm)))
(else (stream-for-each strms))))
(define (stream-from first . step)
(define stream-from
(stream-lambda (first delta)
(stream-cons first (stream-from (+ first delta) delta))))
(let ((delta (if (null? step) 1 (car step))))
(cond
((not (number? first)) (error "non-numeric starting number" first))
((not (number? delta)) (error "non-numeric step size" delta))
(else (stream-from first delta)))))
(define (stream-iterate proc base)
(define stream-iterate
(stream-lambda (base)
(stream-cons base (stream-iterate (proc base)))))
(if (not (procedure? proc))
(error "non-procedural argument" proc)
(stream-iterate base)))
(define (stream-length strm)
(if (not (stream? strm))
(error "non-stream argument" strm)
(let loop ((len 0) (strm strm))
(if (stream-null? strm)
len
(loop (+ len 1) (stream-cdr strm))))))
(define-syntax stream-let
(syntax-rules ()
((stream-let tag ((name val) ...) body1 body2 ...)
((letrec ((tag (stream-lambda (name ...) body1 body2 ...)))
tag)
val ...))))
(define (stream-map proc . strms)
(define stream-map
(stream-lambda (strms)
(if (find stream-null? strms)
stream-null
(stream-cons (apply proc (map stream-car strms))
(stream-map (map stream-cdr strms))))))
(cond
((not (procedure? proc)) (error "non-procedural argument" proc))
((null? strms) (error "no stream arguments"))
((find (lambda (x) (not (stream? x))) strms)
=> (lambda (strm)
(error "non-stream argument" strm)))
(else (stream-map strms))))
(define-syntax stream-match
(syntax-rules ()
((stream-match strm-expr clause ...)
(let ((strm strm-expr))
(cond
((not (stream? strm)) (error "non-stream argument" strm))
((stream-match-test strm clause) => car) ...
(else (error "pattern failure")))))))
(define-syntax stream-match-test
(syntax-rules ()
((stream-match-test strm (pattern fender expr))
(stream-match-pattern strm pattern () (and fender (list expr))))
((stream-match-test strm (pattern expr))
(stream-match-pattern strm pattern () (list expr)))))
(define-syntax stream-match-pattern
(syntax-rules (_)
((stream-match-pattern strm () (binding ...) body)
(and (stream-null? strm) (let (binding ...) body)))
((stream-match-pattern strm (_ . rest) (binding ...) body)
(and (stream-pair? strm)
(let ((strm (stream-cdr strm)))
(stream-match-pattern strm rest (binding ...) body))))
((stream-match-pattern strm (var . rest) (binding ...) body)
(and (stream-pair? strm)
(let ((temp (stream-car strm)) (strm (stream-cdr strm)))
(stream-match-pattern strm rest ((var temp) binding ...) body))))
((stream-match-pattern strm _ (binding ...) body)
(let (binding ...) body))
((stream-match-pattern strm var (binding ...) body)
(let ((var strm) binding ...) body))))
(define-syntax stream-of
(syntax-rules ()
((_ expr rest ...)
(stream-of-aux expr stream-null rest ...))))
(define-syntax stream-of-aux
(syntax-rules (in is)
((stream-of-aux expr base)
(stream-cons expr base))
((stream-of-aux expr base (var in stream) rest ...)
(stream-let loop ((strm stream))
(if (stream-null? strm)
base
(let ((var (stream-car strm)))
(stream-of-aux expr (loop (stream-cdr strm)) rest ...)))))
((stream-of-aux expr base (var is exp) rest ...)
(let ((var exp)) (stream-of-aux expr base rest ...)))
((stream-of-aux expr base pred? rest ...)
(if pred? (stream-of-aux expr base rest ...) base))))
(define (stream-range first past . step)
(define stream-range
(stream-lambda (first past delta lt?)
(if (lt? first past)
(stream-cons first (stream-range (+ first delta) past delta lt?))
stream-null)))
(cond
((not (number? first)) (error "non-numeric starting number" first))
((not (number? past)) (error "non-numeric ending number" past))
(else (let ((delta (cond ((pair? step) (car step))
((< first past) 1)
(else -1))))
(if (not (number? delta))
(error "non-numeric step size" delta)
(let ((lt? (if (< 0 delta) < >)))
(stream-range first past delta lt?)))))))
(define (stream-ref strm n)
(cond
((not (stream? strm)) (error "non-stream argument" strm))
((not (integer? n)) (error "non-integer argument" n))
((negative? n) (error "negative argument" n))
(else (let loop ((strm strm) (n n))
(cond
((stream-null? strm) (error "beyond end of stream" strm))
((zero? n) (stream-car strm))
(else (loop (stream-cdr strm) (- n 1))))))))
(define (stream-reverse strm)
(define stream-reverse
(stream-lambda (strm rev)
(if (stream-null? strm)
rev
(stream-reverse (stream-cdr strm)
(stream-cons (stream-car strm) rev)))))
(if (not (stream? strm))
(error "non-stream argument" strm)
(stream-reverse strm stream-null)))
(define (stream-scan proc base strm)
(define stream-scan
(stream-lambda (base strm)
(if (stream-null? strm)
(stream base)
(stream-cons base (stream-scan (proc base (stream-car strm))
(stream-cdr strm))))))
(cond
((not (procedure? proc)) (error "non-procedural argument" proc))
((not (stream? strm)) (error "non-stream argument" strm))
(else (stream-scan base strm))))
(define (stream-take n strm)
(define stream-take
(stream-lambda (n strm)
(if (or (stream-null? strm) (zero? n))
stream-null
(stream-cons (stream-car strm)
(stream-take (- n 1) (stream-cdr strm))))))
(cond
((not (stream? strm)) (error "non-stream argument" strm))
((not (integer? n)) (error "non-integer argument" n))
((negative? n) (error "negative argument" n))
(else (stream-take n strm))))
(define (stream-take-while pred? strm)
(define stream-take-while
(stream-lambda (strm)
(cond
((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm)
(stream-take-while (stream-cdr strm))))
(else stream-null))))
(cond
((not (stream? strm)) (error "non-stream argument" strm))
((not (procedure? pred?)) (error "non-procedural argument" pred?))
(else (stream-take-while strm))))
(define (stream-unfold mapper pred? generator base)
(define stream-unfold
(stream-lambda (base)
(if (pred? base)
(stream-cons (mapper base) (stream-unfold (generator base)))
stream-null)))
(cond
((not (procedure? mapper)) (error "non-procedural mapper" mapper))
((not (procedure? pred?)) (error "non-procedural pred?" pred?))
((not (procedure? generator)) (error "non-procedural generator" generator))
(else (stream-unfold base))))
(define (stream-unfolds gen seed)
(define (len-values gen seed)
(call-with-values
(lambda () (gen seed))
(lambda vs (- (length vs) 1))))
(define unfold-result-stream
(stream-lambda (gen seed)
(call-with-values
(lambda () (gen seed))
(lambda (next . results)
(stream-cons results (unfold-result-stream gen next))))))
(define result-stream->output-stream
(stream-lambda (result-stream i)
(let ((result (list-ref (stream-car result-stream) (- i 1))))
(cond
((pair? result)
(stream-cons
(car result)
(result-stream->output-stream (stream-cdr result-stream) i)))
((not result)
(result-stream->output-stream (stream-cdr result-stream) i))
((null? result) stream-null)
(else (error "can't happen"))))))
(define (result-stream->output-streams result-stream)
(let loop ((i (len-values gen seed)) (outputs '()))
(if (zero? i)
(apply values outputs)
(loop (- i 1) (cons (result-stream->output-stream result-stream i)
outputs)))))
(if (not (procedure? gen))
(error "non-procedural argument" gen)
(result-stream->output-streams (unfold-result-stream gen seed))))
(define (stream-zip . strms)
(define stream-zip
(stream-lambda (strms)
(if (find stream-null? strms)
stream-null
(stream-cons (map stream-car strms)
(stream-zip (map stream-cdr strms))))))
(cond
((null? strms) (error "no stream arguments"))
((find (lambda (x) (not (stream? x))) strms)
=> (lambda (strm)
(error "non-stream argument" strm)))
(else (stream-zip strms))))
(define-library (srfi 41 derived)
(export
stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match _
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip
)
(import
(scheme base)
(srfi 1)
(srfi 41 primitive))
(include "derived.body.scm"))
;;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(library (streams derived)
(export stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match _
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip)
(import (rnrs) (streams primitive))
(define-syntax define-stream
(syntax-rules ()
((define-stream (name . formal) body0 body1 ...)
(define name (stream-lambda formal body0 body1 ...)))))
(define (list->stream objs)
(define list->stream
(stream-lambda (objs)
(if (null? objs)
stream-null
(stream-cons (car objs) (list->stream (cdr objs))))))
(if (not (list? objs))
(error 'list->stream "non-list argument")
(list->stream objs)))
(define (port->stream . port)
(define port->stream
(stream-lambda (p)
(let ((c (read-char p)))
(if (eof-object? c)
stream-null
(stream-cons c (port->stream p))))))
(let ((p (if (null? port) (current-input-port) (car port))))
(if (not (input-port? p))
(error 'port->stream "non-input-port argument")
(port->stream p))))
(define-syntax stream
(syntax-rules ()
((stream) stream-null)
((stream x y ...) (stream-cons x (stream y ...)))))
(define (stream->list . args)
(let ((n (if (= 1 (length args)) #f (car args)))
(strm (if (= 1 (length args)) (car args) (cadr args))))
(cond ((not (stream? strm)) (error 'stream->list "non-stream argument"))
((and n (not (integer? n))) (error 'stream->list "non-integer count"))
((and n (negative? n)) (error 'stream->list "negative count"))
(else (let loop ((n (if n n -1)) (strm strm))
(if (or (zero? n) (stream-null? strm))
'()
(cons (stream-car strm) (loop (- n 1) (stream-cdr strm)))))))))
(define (stream-append . strms)
(define stream-append
(stream-lambda (strms)
(cond ((null? (cdr strms)) (car strms))
((stream-null? (car strms)) (stream-append (cdr strms)))
(else (stream-cons (stream-car (car strms))
(stream-append (cons (stream-cdr (car strms)) (cdr strms))))))))
(cond ((null? strms) stream-null)
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-append "non-stream argument"))
(else (stream-append strms))))
(define (stream-concat strms)
(define stream-concat
(stream-lambda (strms)
(cond ((stream-null? strms) stream-null)
((not (stream? (stream-car strms)))
(error 'stream-concat "non-stream object in input stream"))
((stream-null? (stream-car strms))
(stream-concat (stream-cdr strms)))
(else (stream-cons
(stream-car (stream-car strms))
(stream-concat
(stream-cons (stream-cdr (stream-car strms)) (stream-cdr strms))))))))
(if (not (stream? strms))
(error 'stream-concat "non-stream argument")
(stream-concat strms)))
(define stream-constant
(stream-lambda objs
(cond ((null? objs) stream-null)
((null? (cdr objs)) (stream-cons (car objs) (stream-constant (car objs))))
(else (stream-cons (car objs)
(apply stream-constant (append (cdr objs) (list (car objs)))))))))
(define (stream-drop n strm)
(define stream-drop
(stream-lambda (n strm)
(if (or (zero? n) (stream-null? strm))
strm
(stream-drop (- n 1) (stream-cdr strm)))))
(cond ((not (integer? n)) (error 'stream-drop "non-integer argument"))
((negative? n) (error 'stream-drop "negative argument"))
((not (stream? strm)) (error 'stream-drop "non-stream argument"))
(else (stream-drop n strm))))
(define (stream-drop-while pred? strm)
(define stream-drop-while
(stream-lambda (strm)
(if (and (stream-pair? strm) (pred? (stream-car strm)))
(stream-drop-while (stream-cdr strm))
strm)))
(cond ((not (procedure? pred?)) (error 'stream-drop-while "non-procedural argument"))
((not (stream? strm)) (error 'stream-drop-while "non-stream argument"))
(else (stream-drop-while strm))))
(define (stream-filter pred? strm)
(define stream-filter
(stream-lambda (strm)
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (stream-filter (stream-cdr strm))))
(else (stream-filter (stream-cdr strm))))))
(cond ((not (procedure? pred?)) (error 'stream-filter "non-procedural argument"))
((not (stream? strm)) (error 'stream-filter "non-stream argument"))
(else (stream-filter strm))))
(define (stream-fold proc base strm)
(cond ((not (procedure? proc)) (error 'stream-fold "non-procedural argument"))
((not (stream? strm)) (error 'stream-fold "non-stream argument"))
(else (let loop ((base base) (strm strm))
(if (stream-null? strm)
base
(loop (proc base (stream-car strm)) (stream-cdr strm)))))))
(define (stream-for-each proc . strms)
(define (stream-for-each strms)
(if (not (exists stream-null? strms))
(begin (apply proc (map stream-car strms))
(stream-for-each (map stream-cdr strms)))))
(cond ((not (procedure? proc)) (error 'stream-for-each "non-procedural argument"))
((null? strms) (error 'stream-for-each "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-for-each "non-stream argument"))
(else (stream-for-each strms))))
(define (stream-from first . step)
(define stream-from
(stream-lambda (first delta)
(stream-cons first (stream-from (+ first delta) delta))))
(let ((delta (if (null? step) 1 (car step))))
(cond ((not (number? first)) (error 'stream-from "non-numeric starting number"))
((not (number? delta)) (error 'stream-from "non-numeric step size"))
(else (stream-from first delta)))))
(define (stream-iterate proc base)
(define stream-iterate
(stream-lambda (base)
(stream-cons base (stream-iterate (proc base)))))
(if (not (procedure? proc))
(error 'stream-iterate "non-procedural argument")
(stream-iterate base)))
(define (stream-length strm)
(if (not (stream? strm))
(error 'stream-length "non-stream argument")
(let loop ((len 0) (strm strm))
(if (stream-null? strm)
len
(loop (+ len 1) (stream-cdr strm))))))
(define-syntax stream-let
(syntax-rules ()
((stream-let tag ((name val) ...) body1 body2 ...)
((letrec ((tag (stream-lambda (name ...) body1 body2 ...))) tag) val ...))))
(define (stream-map proc . strms)
(define stream-map
(stream-lambda (strms)
(if (exists stream-null? strms)
stream-null
(stream-cons (apply proc (map stream-car strms))
(stream-map (map stream-cdr strms))))))
(cond ((not (procedure? proc)) (error 'stream-map "non-procedural argument"))
((null? strms) (error 'stream-map "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-map "non-stream argument"))
(else (stream-map strms))))
(define-syntax stream-match
(syntax-rules ()
((stream-match strm-expr clause ...)
(let ((strm strm-expr))
(cond
((not (stream? strm)) (error 'stream-match "non-stream argument"))
((stream-match-test strm clause) => car) ...
(else (error 'stream-match "pattern failure")))))))
(define-syntax stream-match-test
(syntax-rules ()
((stream-match-test strm (pattern fender expr))
(stream-match-pattern strm pattern () (and fender (list expr))))
((stream-match-test strm (pattern expr))
(stream-match-pattern strm pattern () (list expr)))))
(define-syntax stream-match-pattern
(lambda (x)
(define (wildcard? x)
(and (identifier? x)
(free-identifier=? x (syntax _))))
(syntax-case x ()
((stream-match-pattern strm () (binding ...) body)
(syntax (and (stream-null? strm) (let (binding ...) body))))
((stream-match-pattern strm (w? . rest) (binding ...) body)
(wildcard? #'w?)
(syntax (and (stream-pair? strm)
(let ((strm (stream-cdr strm)))
(stream-match-pattern strm rest (binding ...) body)))))
((stream-match-pattern strm (var . rest) (binding ...) body)
(syntax (and (stream-pair? strm)
(let ((temp (stream-car strm)) (strm (stream-cdr strm)))
(stream-match-pattern strm rest ((var temp) binding ...) body)))))
((stream-match-pattern strm w? (binding ...) body)
(wildcard? #'w?)
(syntax (let (binding ...) body)))
((stream-match-pattern strm var (binding ...) body)
(syntax (let ((var strm) binding ...) body))))))
(define-syntax stream-of
(syntax-rules ()
((_ expr rest ...)
(stream-of-aux expr stream-null rest ...))))
(define-syntax stream-of-aux
(syntax-rules (in is)
((stream-of-aux expr base)
(stream-cons expr base))
((stream-of-aux expr base (var in stream) rest ...)
(stream-let loop ((strm stream))
(if (stream-null? strm)
base
(let ((var (stream-car strm)))
(stream-of-aux expr (loop (stream-cdr strm)) rest ...)))))
((stream-of-aux expr base (var is exp) rest ...)
(let ((var exp)) (stream-of-aux expr base rest ...)))
((stream-of-aux expr base pred? rest ...)
(if pred? (stream-of-aux expr base rest ...) base))))
(define (stream-range first past . step)
(define stream-range
(stream-lambda (first past delta lt?)
(if (lt? first past)
(stream-cons first (stream-range (+ first delta) past delta lt?))
stream-null)))
(cond ((not (number? first)) (error 'stream-range "non-numeric starting number"))
((not (number? past)) (error 'stream-range "non-numeric ending number"))
(else (let ((delta (cond ((pair? step) (car step)) ((< first past) 1) (else -1))))
(if (not (number? delta))
(error 'stream-range "non-numeric step size")
(let ((lt? (if (< 0 delta) < >)))
(stream-range first past delta lt?)))))))
(define (stream-ref strm n)
(cond ((not (stream? strm)) (error 'stream-ref "non-stream argument"))
((not (integer? n)) (error 'stream-ref "non-integer argument"))
((negative? n) (error 'stream-ref "negative argument"))
(else (let loop ((strm strm) (n n))
(cond ((stream-null? strm) (error 'stream-ref "beyond end of stream"))
((zero? n) (stream-car strm))
(else (loop (stream-cdr strm) (- n 1))))))))
(define (stream-reverse strm)
(define stream-reverse
(stream-lambda (strm rev)
(if (stream-null? strm)
rev
(stream-reverse (stream-cdr strm) (stream-cons (stream-car strm) rev)))))
(if (not (stream? strm))
(error 'stream-reverse "non-stream argument")
(stream-reverse strm stream-null)))
(define (stream-scan proc base strm)
(define stream-scan
(stream-lambda (base strm)
(if (stream-null? strm)
(stream base)
(stream-cons base (stream-scan (proc base (stream-car strm)) (stream-cdr strm))))))
(cond ((not (procedure? proc)) (error 'stream-scan "non-procedural argument"))
((not (stream? strm)) (error 'stream-scan "non-stream argument"))
(else (stream-scan base strm))))
(define (stream-take n strm)
(define stream-take
(stream-lambda (n strm)
(if (or (stream-null? strm) (zero? n))
stream-null
(stream-cons (stream-car strm) (stream-take (- n 1) (stream-cdr strm))))))
(cond ((not (stream? strm)) (error 'stream-take "non-stream argument"))
((not (integer? n)) (error 'stream-take "non-integer argument"))
((negative? n) (error 'stream-take "negative argument"))
(else (stream-take n strm))))
(define (stream-take-while pred? strm)
(define stream-take-while
(stream-lambda (strm)
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (stream-take-while (stream-cdr strm))))
(else stream-null))))
(cond ((not (stream? strm)) (error 'stream-take-while "non-stream argument"))
((not (procedure? pred?)) (error 'stream-take-while "non-procedural argument"))
(else (stream-take-while strm))))
(define (stream-unfold mapper pred? generator base)
(define stream-unfold
(stream-lambda (base)
(if (pred? base)
(stream-cons (mapper base) (stream-unfold (generator base)))
stream-null)))
(cond ((not (procedure? mapper)) (error 'stream-unfold "non-procedural mapper"))
((not (procedure? pred?)) (error 'stream-unfold "non-procedural pred?"))
((not (procedure? generator)) (error 'stream-unfold "non-procedural generator"))
(else (stream-unfold base))))
(define (stream-unfolds gen seed)
(define (len-values gen seed)
(call-with-values
(lambda () (gen seed))
(lambda vs (- (length vs) 1))))
(define unfold-result-stream
(stream-lambda (gen seed)
(call-with-values
(lambda () (gen seed))
(lambda (next . results)
(stream-cons results (unfold-result-stream gen next))))))
(define result-stream->output-stream
(stream-lambda (result-stream i)
(let ((result (list-ref (stream-car result-stream) (- i 1))))
(cond ((pair? result)
(stream-cons
(car result)
(result-stream->output-stream (stream-cdr result-stream) i)))
((not result)
(result-stream->output-stream (stream-cdr result-stream) i))
((null? result) stream-null)
(else (error 'stream-unfolds "can't happen"))))))
(define (result-stream->output-streams result-stream)
(let loop ((i (len-values gen seed)) (outputs '()))
(if (zero? i)
(apply values outputs)
(loop (- i 1) (cons (result-stream->output-stream result-stream i) outputs)))))
(if (not (procedure? gen))
(error 'stream-unfolds "non-procedural argument")
(result-stream->output-streams (unfold-result-stream gen seed))))
(define (stream-zip . strms)
(define stream-zip
(stream-lambda (strms)
(if (exists stream-null? strms)
stream-null
(stream-cons (map stream-car strms) (stream-zip (map stream-cdr strms))))))
(cond ((null? strms) (error 'stream-zip "no stream arguments"))
((exists (lambda (x) (not (stream? x))) strms)
(error 'stream-zip "non-stream argument"))
(else (stream-zip strms)))))
;;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-record-type <stream>
(make-stream promise)
stream?
(promise stream-promise stream-promise!))
(define-syntax stream-lazy
(syntax-rules ()
((stream-lazy expr)
(make-stream
(cons 'lazy (lambda () expr))))))
(define (stream-eager expr)
(make-stream
(cons 'eager expr)))
(define-syntax stream-delay
(syntax-rules ()
((stream-delay expr)
(stream-lazy (stream-eager expr)))))
(define (stream-force promise)
(let ((content (stream-promise promise)))
(case (car content)
((eager) (cdr content))
((lazy) (let* ((promise* ((cdr content)))
(content (stream-promise promise)))
(if (not (eqv? (car content) 'eager))
(begin (set-car! content (car (stream-promise promise*)))
(set-cdr! content (cdr (stream-promise promise*)))
(stream-promise! promise* content)))
(stream-force promise))))))
(define stream-null (stream-delay (cons 'stream 'null)))
(define-record-type <stream-pare>
(make-stream-pare kar kdr)
stream-pare?
(kar stream-kar)
(kdr stream-kdr))
(define (stream-pair? obj)
(and (stream? obj) (stream-pare? (stream-force obj))))
(define (stream-null? obj)
(and (stream? obj)
(eqv? (stream-force obj)
(stream-force stream-null))))
(define-syntax stream-cons
(syntax-rules ()
((stream-cons obj strm)
(stream-eager (make-stream-pare (stream-delay obj) (stream-lazy strm))))))
(define (stream-car strm)
(cond ((not (stream? strm)) (error "non-stream" strm))
((stream-null? strm) (error "null stream" strm))
(else (stream-force (stream-kar (stream-force strm))))))
(define (stream-cdr strm)
(cond ((not (stream? strm)) (error "non-stream" strm))
((stream-null? strm) (error "null stream" strm))
(else (stream-kdr (stream-force strm)))))
(define-syntax stream-lambda
(syntax-rules ()
((stream-lambda formals body0 body1 ...)
(lambda formals (stream-lazy (let () body0 body1 ...))))))
(define-library (srfi 41 primitive)
(export
stream-null stream-cons stream? stream-null? stream-pair?
stream-car stream-cdr stream-lambda
)
(import (scheme base))
(include "primitive.body.scm"))
;;; Copyright (C) Philip L. Bewig (2007). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(library (streams primitive)
(export stream-null stream-cons stream? stream-null? stream-pair?
stream-car stream-cdr stream-lambda)
(import (rnrs) (rnrs mutable-pairs))
(define-record-type (stream-type make-stream stream?)
(fields (mutable box stream-promise stream-promise!)))
(define-syntax stream-lazy
(syntax-rules ()
((stream-lazy expr)
(make-stream
(cons 'lazy (lambda () expr))))))
(define (stream-eager expr)
(make-stream
(cons 'eager expr)))
(define-syntax stream-delay
(syntax-rules ()
((stream-delay expr)
(stream-lazy (stream-eager expr)))))
(define (stream-force promise)
(let ((content (stream-promise promise)))
(case (car content)
((eager) (cdr content))
((lazy) (let* ((promise* ((cdr content)))
(content (stream-promise promise)))
(if (not (eqv? (car content) 'eager))
(begin (set-car! content (car (stream-promise promise*)))
(set-cdr! content (cdr (stream-promise promise*)))
(stream-promise! promise* content)))
(stream-force promise))))))
(define stream-null (stream-delay (cons 'stream 'null)))
(define-record-type (stream-pare-type make-stream-pare stream-pare?)
(fields (immutable kar stream-kar) (immutable kdr stream-kdr)))
(define (stream-pair? obj)
(and (stream? obj) (stream-pare? (stream-force obj))))
(define (stream-null? obj)
(and (stream? obj)
(eqv? (stream-force obj)
(stream-force stream-null))))
(define-syntax stream-cons
(syntax-rules ()
((stream-cons obj strm)
(stream-eager (make-stream-pare (stream-delay obj) (stream-lazy strm))))))
(define (stream-car strm)
(cond ((not (stream? strm)) (error 'stream-car "non-stream"))
((stream-null? strm) (error 'stream-car "null stream"))
(else (stream-force (stream-kar (stream-force strm))))))
(define (stream-cdr strm)
(cond ((not (stream? strm)) (error 'stream-cdr "non-stream"))
((stream-null? strm) (error 'stream-cdr "null stream"))
(else (stream-kdr (stream-force strm)))))
(define-syntax stream-lambda
(syntax-rules ()
((stream-lambda formals body0 body1 ...)
(lambda formals (stream-lazy (let () body0 body1 ...)))))))
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Note: to prevent producing massive amounts of code from the macro-expand
;;; phase (which makes compile times suffer and may hit code size limits in some
;;; systems), keep macro bodies minimal by delegating work to procedures.
;;; Grouping
(define (maybe-install-default-runner suite-name)
(when (not (test-runner-current))
(let* ((log-file (string-append suite-name ".srfi64.log"))
(runner (test-runner-simple log-file)))
(%test-runner-auto-installed! runner #t)
(test-runner-current runner))))
(define (maybe-uninstall-default-runner)
(when (%test-runner-auto-installed? (test-runner-current))
(test-runner-current #f)))
(define test-begin
(case-lambda
((name)
(test-begin name #f))
((name count)
(maybe-install-default-runner name)
(let ((r (test-runner-current)))
(let ((skip-list (%test-runner-skip-list r))
(skip-save (%test-runner-skip-save r))
(fail-list (%test-runner-fail-list r))
(fail-save (%test-runner-fail-save r))
(total-count (%test-runner-total-count r))
(count-list (%test-runner-count-list r))
(group-stack (test-runner-group-stack r)))
((test-runner-on-group-begin r) r name count)
(%test-runner-skip-save! r (cons skip-list skip-save))
(%test-runner-fail-save! r (cons fail-list fail-save))
(%test-runner-count-list! r (cons (cons total-count count)
count-list))
(test-runner-group-stack! r (cons name group-stack)))))))
(define test-end
(case-lambda
(()
(test-end #f))
((name)
(let* ((r (test-runner-get))
(groups (test-runner-group-stack r)))
(test-result-clear r)
(when (null? groups)
(error "test-end not in a group"))
(when (and name (not (equal? name (car groups))))
((test-runner-on-bad-end-name r) r name (car groups)))
(let* ((count-list (%test-runner-count-list r))
(expected-count (cdar count-list))
(saved-count (caar count-list))
(group-count (- (%test-runner-total-count r) saved-count)))
(when (and expected-count
(not (= expected-count group-count)))
((test-runner-on-bad-count r) r group-count expected-count))
((test-runner-on-group-end r) r)
(test-runner-group-stack! r (cdr (test-runner-group-stack r)))
(%test-runner-skip-list! r (car (%test-runner-skip-save r)))
(%test-runner-skip-save! r (cdr (%test-runner-skip-save r)))
(%test-runner-fail-list! r (car (%test-runner-fail-save r)))
(%test-runner-fail-save! r (cdr (%test-runner-fail-save r)))
(%test-runner-count-list! r (cdr count-list))
(when (null? (test-runner-group-stack r))
((test-runner-on-final r) r)
(maybe-uninstall-default-runner)))))))
(define-syntax test-group
(syntax-rules ()
((_ <name> <body> . <body>*)
(%test-group <name> (lambda () <body> . <body>*)))))
(define (%test-group name thunk)
(begin
(maybe-install-default-runner name)
(let ((runner (test-runner-get)))
(test-result-clear runner)
(test-result-set! runner 'name name)
(unless (test-skip? runner)
(dynamic-wind
(lambda () (test-begin name))
thunk
(lambda () (test-end name)))))))
(define-syntax test-group-with-cleanup
(syntax-rules ()
((_ <name> <body> <body>* ... <cleanup>)
(test-group <name>
(dynamic-wind (lambda () #f)
(lambda () <body> <body>* ...)
(lambda () <cleanup>))))))
;;; Skipping, expected-failing, matching
(define (test-skip . specs)
(let ((runner (test-runner-get)))
(%test-runner-skip-list!
runner (cons (apply test-match-all specs)
(%test-runner-skip-list runner)))))
(define (test-skip? runner)
(let ((run-list (%test-runner-run-list runner))
(skip-list (%test-runner-skip-list runner)))
(or (and run-list (not (any-pred run-list runner)))
(any-pred skip-list runner))))
(define (test-expect-fail . specs)
(let ((runner (test-runner-get)))
(%test-runner-fail-list!
runner (cons (apply test-match-all specs)
(%test-runner-fail-list runner)))))
(define (test-match-any . specs)
(let ((preds (map make-pred specs)))
(lambda (runner)
(any-pred preds runner))))
(define (test-match-all . specs)
(let ((preds (map make-pred specs)))
(lambda (runner)
(every-pred preds runner))))
(define (make-pred spec)
(cond
((procedure? spec)
spec)
((integer? spec)
(test-match-nth 1 spec))
((string? spec)
(test-match-name spec))
(else
(error "not a valid test specifier" spec))))
(define test-match-nth
(case-lambda
((n) (test-match-nth n 1))
((n count)
(let ((i 0))
(lambda (runner)
(set! i (+ i 1))
(and (>= i n) (< i (+ n count))))))))
(define (test-match-name name)
(lambda (runner)
(equal? name (test-runner-test-name runner))))
;;; Beware: all predicates must be called because they might have side-effects;
;;; no early returning or and/or short-circuiting of procedure calls allowed.
(define (any-pred preds object)
(let loop ((matched? #f)
(preds preds))
(if (null? preds)
matched?
(let ((result ((car preds) object)))
(loop (or matched? result)
(cdr preds))))))
(define (every-pred preds object)
(let loop ((failed? #f)
(preds preds))
(if (null? preds)
(not failed?)
(let ((result ((car preds) object)))
(loop (or failed? (not result))
(cdr preds))))))
;;; Actual testing
(define-syntax false-if-error
(syntax-rules ()
((_ <expression> <runner>)
(guard (error
(else
(test-result-set! <runner> 'actual-error error)
#f))
<expression>))))
(define (test-prelude source-info runner name form)
(test-result-clear runner)
(set-source-info! runner source-info)
(when name
(test-result-set! runner 'name name))
(test-result-set! runner 'source-form form)
(let ((skip? (test-skip? runner)))
(if skip?
(test-result-set! runner 'result-kind 'skip)
(let ((fail-list (%test-runner-fail-list runner)))
(when (any-pred fail-list runner)
;; For later inspection only.
(test-result-set! runner 'result-kind 'xfail))))
((test-runner-on-test-begin runner) runner)
(not skip?)))
(define (test-postlude runner)
(let ((result-kind (test-result-kind runner)))
(case result-kind
((pass)
(test-runner-pass-count! runner (+ 1 (test-runner-pass-count runner))))
((fail)
(test-runner-fail-count! runner (+ 1 (test-runner-fail-count runner))))
((xpass)
(test-runner-xpass-count! runner (+ 1 (test-runner-xpass-count runner))))
((xfail)
(test-runner-xfail-count! runner (+ 1 (test-runner-xfail-count runner))))
((skip)
(test-runner-skip-count! runner (+ 1 (test-runner-skip-count runner)))))
(%test-runner-total-count! runner (+ 1 (%test-runner-total-count runner)))
((test-runner-on-test-end runner) runner)))
(define (set-result-kind! runner pass?)
(test-result-set! runner 'result-kind
(if (eq? (test-result-kind runner) 'xfail)
(if pass? 'xpass 'xfail)
(if pass? 'pass 'fail))))
;;; We need to use some trickery to get the source info right. The important
;;; thing is to pass a syntax object that is a pair to `source-info', and make
;;; sure this syntax object comes from user code and not from ourselves.
(define-syntax test-assert
(syntax-rules ()
((_ . <rest>)
(test-assert/source-info (source-info <rest>) . <rest>))))
(define-syntax test-assert/source-info
(syntax-rules ()
((_ <source-info> <expr>)
(test-assert/source-info <source-info> #f <expr>))
((_ <source-info> <name> <expr>)
(%test-assert <source-info> <name> '<expr> (lambda () <expr>)))))
(define (%test-assert source-info name form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(let ((val (false-if-error (thunk) runner)))
(test-result-set! runner 'actual-value val)
(set-result-kind! runner val)))
(test-postlude runner)))
(define-syntax test-compare
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) . <rest>))))
(define-syntax test-compare/source-info
(syntax-rules ()
((_ <source-info> <compare> <expected> <expr>)
(test-compare/source-info <source-info> <compare> #f <expected> <expr>))
((_ <source-info> <compare> <name> <expected> <expr>)
(%test-compare <source-info> <compare> <name> <expected> '<expr>
(lambda () <expr>)))))
(define (%test-compare source-info compare name expected form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(test-result-set! runner 'expected-value expected)
(let ((pass? (false-if-error
(let ((val (thunk)))
(test-result-set! runner 'actual-value val)
(compare expected val))
runner)))
(set-result-kind! runner pass?)))
(test-postlude runner)))
(define-syntax test-equal
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) equal? . <rest>))))
(define-syntax test-eqv
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) eqv? . <rest>))))
(define-syntax test-eq
(syntax-rules ()
((_ . <rest>)
(test-compare/source-info (source-info <rest>) eq? . <rest>))))
(define (approx= margin)
(lambda (value expected)
(let ((rval (real-part value))
(ival (imag-part value))
(rexp (real-part expected))
(iexp (imag-part expected)))
(and (>= rval (- rexp margin))
(>= ival (- iexp margin))
(<= rval (+ rexp margin))
(<= ival (+ iexp margin))))))
(define-syntax test-approximate
(syntax-rules ()
((_ . <rest>)
(test-approximate/source-info (source-info <rest>) . <rest>))))
(define-syntax test-approximate/source-info
(syntax-rules ()
((_ <source-info> <expected> <expr> <error-margin>)
(test-approximate/source-info
<source-info> #f <expected> <expr> <error-margin>))
((_ <source-info> <name> <expected> <expr> <error-margin>)
(test-compare/source-info
<source-info> (approx= <error-margin>) <name> <expected> <expr>))))
(define (error-matches? error type)
(cond
((eq? type #t)
#t)
((condition-type? type)
(and (condition? error) (condition-has-type? error type)))
((procedure? type)
(type error))
(else
(let ((runner (test-runner-get)))
((%test-runner-on-bad-error-type runner) runner type error))
#f)))
(define-syntax test-error
(syntax-rules ()
((_ . <rest>)
(test-error/source-info (source-info <rest>) . <rest>))))
(define-syntax test-error/source-info
(syntax-rules ()
((_ <source-info> <expr>)
(test-error/source-info <source-info> #f #t <expr>))
((_ <source-info> <error-type> <expr>)
(test-error/source-info <source-info> #f <error-type> <expr>))
((_ <source-info> <name> <error-type> <expr>)
(%test-error <source-info> <name> <error-type> '<expr>
(lambda () <expr>)))))
(define (%test-error source-info name error-type form thunk)
(let ((runner (test-runner-get)))
(when (test-prelude source-info runner name form)
(test-result-set! runner 'expected-error error-type)
(let ((pass? (guard (error (else (test-result-set!
runner 'actual-error error)
(error-matches? error error-type)))
(let ((val (thunk)))
(test-result-set! runner 'actual-value val))
#f)))
(set-result-kind! runner pass?)))
(test-postlude runner)))
(define (default-module)
(cond-expand
(guile (current-module))
(else #f)))
(define test-read-eval-string
(case-lambda
((string)
(test-read-eval-string string (default-module)))
((string env)
(let* ((port (open-input-string string))
(form (read port)))
(if (eof-object? (read-char port))
(if env
(eval form env)
(eval form))
(error "(not at eof)"))))))
;;; Test runner control flow
(define-syntax test-with-runner
(syntax-rules ()
((_ <runner> <body> . <body>*)
(let ((saved-runner (test-runner-current)))
(dynamic-wind
(lambda () (test-runner-current <runner>))
(lambda () <body> . <body>*)
(lambda () (test-runner-current saved-runner)))))))
(define (test-apply first . rest)
(let ((runner (if (test-runner? first)
first
(or (test-runner-current) (test-runner-create))))
(run-list (if (test-runner? first)
(drop-right rest 1)
(cons first (drop-right rest 1))))
(proc (last rest)))
(test-with-runner runner
(let ((saved-run-list (%test-runner-run-list runner)))
(%test-runner-run-list! runner run-list)
(proc)
(%test-runner-run-list! runner saved-run-list)))))
;;; Indicate success/failure via exit status
(define (test-exit)
(let ((runner (test-runner-current)))
(when (not runner)
(error "No test runner installed. Might have been auto-removed
by test-end if you had not installed one explicitly."))
(if (and (zero? (test-runner-xpass-count runner))
(zero? (test-runner-fail-count runner)))
(exit 0)
(exit 1))))
;;; execution.scm ends here
(export
test-begin test-end test-group test-group-with-cleanup
test-skip test-expect-fail
test-match-name test-match-nth
test-match-all test-match-any
test-assert test-eqv test-eq test-equal test-approximate
test-error test-read-eval-string
test-apply test-with-runner
test-exit
)
(define-library (srfi 64 execution)
(import
(scheme base)
(scheme case-lambda)
(scheme complex)
(scheme eval)
(scheme process-context)
(scheme read)
(srfi 1)
(srfi 35)
(srfi 48)
(srfi 64 source-info)
(srfi 64 test-runner)
(srfi 64 test-runner-simple))
(include-library-declarations "execution.exports.sld")
(include "execution.body.scm"))
;; Copyright (c) 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; In some systems, a macro use like (source-info ...), that resides in a
;;; syntax-rules macro body, first gets inserted into the place where the
;;; syntax-rules macro was used, and then the transformer of 'source-info' is
;;; called with a syntax object that has the source location information of that
;;; position. That works fine when the user calls e.g. (test-assert ...), whose
;;; body contains (source-info ...); the user gets the source location of the
;;; (test-assert ...) call as intended, and not the source location of the real
;;; (source-info ...) call.
;;; In other systems, *first* the (source-info ...) is processed to get its real
;;; position, which is within the body of a syntax-rules macro like test-assert,
;;; so no matter where the user calls (test-assert ...), they get source
;;; location information of where we defined test-assert with the call to
;;; (source-info ...) in its body. That's arguably more correct behavior,
;;; although in this case it makes our job a bit harder; we need to get the
;;; source location from an argument to 'source-info' instead.
(define (canonical-syntax form arg)
(cond-expand
(kawa arg)
(guile-2 form)
(else #f)))
(cond-expand
((or kawa guile-2)
(define-syntax source-info
(lambda (stx)
(syntax-case stx ()
((_ <x>)
(let* ((stx (canonical-syntax stx (syntax <x>)))
(file (syntax-source-file stx))
(line (syntax-source-line stx)))
(quasisyntax
(cons (unsyntax file) (unsyntax line)))))))))
(else
(define-syntax source-info
(syntax-rules ()
((_ <x>)
#f)))))
(define (syntax-source-file stx)
(cond-expand
(kawa
(syntax-source stx))
(guile-2
(let ((source (syntax-source stx)))
(and source (assq-ref source 'filename))))
(else
#f)))
(define (syntax-source-line stx)
(cond-expand
(kawa
(syntax-line stx))
(guile-2
(let ((source (syntax-source stx)))
(and source (assq-ref source 'line))))
(else
#f)))
(define (set-source-info! runner source-info)
(when source-info
(test-result-set! runner 'source-file (car source-info))
(test-result-set! runner 'source-line (cdr source-info))))
;;; source-info.body.scm ends here
(define-library (srfi 64 source-info)
(import
(scheme base)
(srfi 64 test-runner))
(export source-info set-source-info!)
(include "source-info.body.scm"))
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Helpers
(define (string-join strings delimiter)
(if (null? strings)
""
(let loop ((result (car strings))
(rest (cdr strings)))
(if (null? rest)
result
(loop (string-append result delimiter (car rest))
(cdr rest))))))
(define (truncate-string string length)
(define (newline->space c) (if (char=? #\newline c) #\space c))
(let* ((string (string-map newline->space string))
(fill "...")
(fill-len (string-length fill))
(string-len (string-length string)))
(if (<= string-len (+ length fill-len))
string
(let-values (((q r) (floor/ length 4)))
;; Left part gets 3/4 plus the remainder.
(let ((left-end (+ (* q 3) r))
(right-start (- string-len q)))
(string-append (substring string 0 left-end)
fill
(substring string right-start string-len)))))))
(define (print runner format-string . args)
(apply format #t format-string args)
(let ((port (%test-runner-log-port runner)))
(when port
(apply format port format-string args))))
;;; Main
(define test-runner-simple
(case-lambda
(()
(test-runner-simple #f))
((log-file)
(let ((runner (test-runner-null)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-on-group-begin-simple)
(test-runner-on-group-end! runner test-on-group-end-simple)
(test-runner-on-final! runner test-on-final-simple)
(test-runner-on-test-begin! runner test-on-test-begin-simple)
(test-runner-on-test-end! runner test-on-test-end-simple)
(test-runner-on-bad-count! runner test-on-bad-count-simple)
(test-runner-on-bad-end-name! runner test-on-bad-end-name-simple)
(%test-runner-on-bad-error-type! runner on-bad-error-type)
(%test-runner-log-file! runner log-file)
runner))))
(when (not (test-runner-factory))
(test-runner-factory test-runner-simple))
(define (test-on-group-begin-simple runner name count)
(when (null? (test-runner-group-stack runner))
(maybe-start-logging runner)
(print runner "Test suite begin: ~a~%" name)))
(define (test-on-group-end-simple runner)
(let ((name (car (test-runner-group-stack runner))))
(when (= 1 (length (test-runner-group-stack runner)))
(print runner "Test suite end: ~a~%" name))))
(define (test-on-final-simple runner)
(print runner "Passes: ~a\n" (test-runner-pass-count runner))
(print runner "Expected failures: ~a\n" (test-runner-xfail-count runner))
(print runner "Failures: ~a\n" (test-runner-fail-count runner))
(print runner "Unexpected passes: ~a\n" (test-runner-xpass-count runner))
(print runner "Skipped tests: ~a~%" (test-runner-skip-count runner))
(maybe-finish-logging runner))
(define (maybe-start-logging runner)
(let ((log-file (%test-runner-log-file runner)))
(when log-file
;; The possible race-condition here doesn't bother us.
(when (file-exists? log-file)
(delete-file log-file))
(%test-runner-log-port! runner (open-output-file log-file))
(print runner "Writing log file: ~a~%" log-file))))
(define (maybe-finish-logging runner)
(let ((log-file (%test-runner-log-file runner)))
(when log-file
(print runner "Wrote log file: ~a~%" log-file)
(close-output-port (%test-runner-log-port runner)))))
(define (test-on-test-begin-simple runner)
(values))
(define (test-on-test-end-simple runner)
(let* ((result-kind (test-result-kind runner))
(result-kind-name (case result-kind
((pass) "PASS") ((fail) "FAIL")
((xpass) "XPASS") ((xfail) "XFAIL")
((skip) "SKIP")))
(name (let ((name (test-runner-test-name runner)))
(if (string=? "" name)
(truncate-string
(format #f "~a" (test-result-ref runner 'source-form))
30)
name)))
(label (string-join (append (test-runner-group-path runner)
(list name))
": ")))
(print runner "[~a] ~a~%" result-kind-name label)
(when (memq result-kind '(fail xpass))
(let ((nil (cons #f #f)))
(define (found? value)
(not (eq? nil value)))
(define (maybe-print value message)
(when (found? value)
(print runner message value)))
(let ((file (test-result-ref runner 'source-file "(unknown file)"))
(line (test-result-ref runner 'source-line "(unknown line)"))
(expression (test-result-ref runner 'source-form))
(expected-value (test-result-ref runner 'expected-value nil))
(actual-value (test-result-ref runner 'actual-value nil))
(expected-error (test-result-ref runner 'expected-error nil))
(actual-error (test-result-ref runner 'actual-error nil)))
(print runner "~a:~a: ~s~%" file line expression)
(maybe-print expected-value "Expected value: ~s~%")
(maybe-print expected-error "Expected error: ~a~%")
(when (or (found? expected-value) (found? expected-error))
(maybe-print actual-value "Returned value: ~s~%"))
(maybe-print actual-error "Raised error: ~a~%")
(newline))))))
(define (test-on-bad-count-simple runner count expected-count)
(print runner "*** Total number of tests was ~a but should be ~a. ***~%"
count expected-count)
(print runner
"*** Discrepancy indicates testsuite error or exceptions. ***~%"))
(define (test-on-bad-end-name-simple runner begin-name end-name)
(error (format #f "Test-end \"~a\" does not match test-begin \"~a\"."
end-name begin-name)))
(define (on-bad-error-type runner type error)
(print runner "WARNING: unknown error type predicate: ~a~%" type)
(print runner " error was: ~a~%" error))
;;; test-runner-simple.scm ends here
(export
test-runner-simple
;; The following are exported so you can leverage their existing functionality
;; when making more complex test runners.
test-on-group-begin-simple test-on-group-end-simple test-on-final-simple
test-on-test-begin-simple test-on-test-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
)
(define-library (srfi 64 test-runner-simple)
(import
(scheme base)
(scheme case-lambda)
(scheme file)
(scheme write)
(srfi 48)
(srfi 64 test-runner))
(include-library-declarations "test-runner-simple.exports.sld")
(include "test-runner-simple.body.scm"))
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;; Refactored by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014, 2015.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; The data type
(define-record-type <test-runner>
(make-test-runner) test-runner?
(result-alist test-result-alist test-result-alist!)
(pass-count test-runner-pass-count test-runner-pass-count!)
(fail-count test-runner-fail-count test-runner-fail-count!)
(xpass-count test-runner-xpass-count test-runner-xpass-count!)
(xfail-count test-runner-xfail-count test-runner-xfail-count!)
(skip-count test-runner-skip-count test-runner-skip-count!)
(total-count %test-runner-total-count %test-runner-total-count!)
;; Stack (list) of (count-at-start . expected-count):
(count-list %test-runner-count-list %test-runner-count-list!)
;; Normally #f, except when in a test-apply.
(run-list %test-runner-run-list %test-runner-run-list!)
(skip-list %test-runner-skip-list %test-runner-skip-list!)
(fail-list %test-runner-fail-list %test-runner-fail-list!)
(skip-save %test-runner-skip-save %test-runner-skip-save!)
(fail-save %test-runner-fail-save %test-runner-fail-save!)
(group-stack test-runner-group-stack test-runner-group-stack!)
;; Note: on-test-begin and on-test-end are unrelated to the test-begin and
;; test-end forms in the execution library. They're called at the
;; beginning/end of each individual test, whereas the test-begin and test-end
;; forms demarcate test groups.
(on-group-begin test-runner-on-group-begin test-runner-on-group-begin!)
(on-test-begin test-runner-on-test-begin test-runner-on-test-begin!)
(on-test-end test-runner-on-test-end test-runner-on-test-end!)
(on-group-end test-runner-on-group-end test-runner-on-group-end!)
(on-final test-runner-on-final test-runner-on-final!)
(on-bad-count test-runner-on-bad-count test-runner-on-bad-count!)
(on-bad-end-name test-runner-on-bad-end-name test-runner-on-bad-end-name!)
(on-bad-error-type %test-runner-on-bad-error-type
%test-runner-on-bad-error-type!)
(aux-value test-runner-aux-value test-runner-aux-value!)
(auto-installed %test-runner-auto-installed? %test-runner-auto-installed!)
(log-file %test-runner-log-file %test-runner-log-file!)
(log-port %test-runner-log-port %test-runner-log-port!))
(define (test-runner-group-path runner)
(reverse (test-runner-group-stack runner)))
(define (test-runner-reset runner)
(test-result-alist! runner '())
(test-runner-pass-count! runner 0)
(test-runner-fail-count! runner 0)
(test-runner-xpass-count! runner 0)
(test-runner-xfail-count! runner 0)
(test-runner-skip-count! runner 0)
(%test-runner-total-count! runner 0)
(%test-runner-count-list! runner '())
(%test-runner-run-list! runner #f)
(%test-runner-skip-list! runner '())
(%test-runner-fail-list! runner '())
(%test-runner-skip-save! runner '())
(%test-runner-fail-save! runner '())
(test-runner-group-stack! runner '()))
(define (test-runner-null)
(define (test-null-callback . args) #f)
(let ((runner (make-test-runner)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-null-callback)
(test-runner-on-group-end! runner test-null-callback)
(test-runner-on-final! runner test-null-callback)
(test-runner-on-test-begin! runner test-null-callback)
(test-runner-on-test-end! runner test-null-callback)
(test-runner-on-bad-count! runner test-null-callback)
(test-runner-on-bad-end-name! runner test-null-callback)
(%test-runner-on-bad-error-type! runner test-null-callback)
(%test-runner-auto-installed! runner #f)
(%test-runner-log-file! runner #f)
(%test-runner-log-port! runner #f)
runner))
;;; State
(define test-result-ref
(case-lambda
((runner key)
(test-result-ref runner key #f))
((runner key default)
(let ((entry (assq key (test-result-alist runner))))
(if entry (cdr entry) default)))))
(define (test-result-set! runner key value)
(let* ((alist (test-result-alist runner))
(entry (assq key alist)))
(if entry
(set-cdr! entry value)
(test-result-alist! runner (cons (cons key value) alist)))))
(define (test-result-remove runner key)
(test-result-alist! runner (remove (lambda (entry)
(eq? key (car entry)))
(test-result-alist runner))))
(define (test-result-clear runner)
(test-result-alist! runner '()))
(define (test-runner-test-name runner)
(or (test-result-ref runner 'name) ""))
(define test-result-kind
(case-lambda
(() (test-result-kind (test-runner-get)))
((runner) (test-result-ref runner 'result-kind))))
(define test-passed?
(case-lambda
(() (test-passed? (test-runner-get)))
((runner) (memq (test-result-kind runner) '(pass xpass)))))
;;; Factory and current instance
(define test-runner-factory (make-parameter #f))
(define (test-runner-create) ((test-runner-factory)))
(define test-runner-current (make-parameter #f))
(define (test-runner-get)
(or (test-runner-current)
(error "test-runner not initialized - test-begin missing?")))
;;; test-runner.scm ends here
(export
;; The data type
test-runner-null test-runner? test-runner-reset
test-result-alist test-result-alist!
test-runner-pass-count test-runner-pass-count!
test-runner-fail-count test-runner-fail-count!
test-runner-xpass-count test-runner-xpass-count!
test-runner-xfail-count test-runner-xfail-count!
test-runner-skip-count test-runner-skip-count!
%test-runner-total-count %test-runner-total-count!
%test-runner-count-list %test-runner-count-list!
%test-runner-run-list %test-runner-run-list!
%test-runner-skip-list %test-runner-skip-list!
%test-runner-fail-list %test-runner-fail-list!
%test-runner-skip-save %test-runner-skip-save!
%test-runner-fail-save %test-runner-fail-save!
test-runner-group-stack test-runner-group-stack!
test-runner-group-path
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
%test-runner-on-bad-error-type %test-runner-on-bad-error-type!
test-runner-aux-value test-runner-aux-value!
%test-runner-log-file %test-runner-log-file!
%test-runner-log-port %test-runner-log-port!
;; State
test-result-ref test-result-set!
test-result-remove test-result-clear
test-runner-test-name test-result-kind test-passed?
;; Factory and current instance
test-runner-factory test-runner-create
test-runner-current test-runner-get
)
(define-library (srfi 64 test-runner)
(import
(scheme base)
(scheme case-lambda)
(srfi 1))
(include-library-declarations "test-runner.exports.sld")
(include "test-runner.body.scm"))
;;; SRFI-1 list-processing library -*- Scheme -*-
;;; Reference implementation
;;;
;;; Copyright (c) 1998, 1999 by Olin Shivers. You may do as you please with
;;; this code as long as you do not remove this copyright notice or
;;; hold me liable for its use. Please send bug reports to shivers@ai.mit.edu.
;;; -Olin
;;;
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (c) 2014.
;;; See 1.upstream.scm in the same repository for a bunch of comments which I
;;; removed here because what they document does not necessarily correspond with
;;; the code anymore. Diff with the same file to see changes in the code.
;;; Constructors
;;;;;;;;;;;;;;;;
;;; Occasionally useful as a value to be passed to a fold or other
;;; higher-order procedure.
(define (xcons d a) (cons a d))
;;;; Recursively copy every cons.
;(define (tree-copy x)
; (let recur ((x x))
; (if (not (pair? x)) x
; (cons (recur (car x)) (recur (cdr x))))))
;(define (list . ans) ans) ; R4RS
;;; Make a list of length LEN. Elt i is (PROC i) for 0 <= i < LEN.
(define (list-tabulate len proc)
(check-arg (lambda (n) (and (integer? n) (>= n 0))) len list-tabulate)
(check-arg procedure? proc list-tabulate)
(do ((i (- len 1) (- i 1))
(ans '() (cons (proc i) ans)))
((< i 0) ans)))
;;; (cons* a1 a2 ... an) = (cons a1 (cons a2 (cons ... an)))
;;; (cons* a1) = a1 (cons* a1 a2 ...) = (cons a1 (cons* a2 ...))
;;;
;;; (cons first (unfold not-pair? car cdr rest values))
(define (cons* first . rest)
(let recur ((x first) (rest rest))
(if (pair? rest)
(cons x (recur (car rest) (cdr rest)))
x)))
;;; IOTA count [start step] (start start+step ... start+(count-1)*step)
(define (nonnegative? x)
(not (negative? x)))
(define/opt (iota count (start 0) (step 1))
(check-arg integer? count iota)
(check-arg nonnegative? count iota)
(check-arg number? start iota)
(check-arg number? step iota)
(let loop ((n 0) (r '()))
(if (= n count)
(reverse r)
(loop (+ 1 n)
(cons (+ start (* n step)) r)))))
;;; I thought these were lovely, but the public at large did not share my
;;; enthusiasm...
;;; :IOTA to (0 ... to-1)
;;; :IOTA from to (from ... to-1)
;;; :IOTA from to step (from from+step ...)
;;; IOTA: to (1 ... to)
;;; IOTA: from to (from+1 ... to)
;;; IOTA: from to step (from+step from+2step ...)
;(define (%parse-iota-args arg1 rest-args proc)
; (let ((check (lambda (n) (check-arg integer? n proc))))
; (check arg1)
; (if (pair? rest-args)
; (let ((arg2 (check (car rest-args)))
; (rest (cdr rest-args)))
; (if (pair? rest)
; (let ((arg3 (check (car rest)))
; (rest (cdr rest)))
; (if (pair? rest) (error "Too many parameters" proc arg1 rest-args)
; (values arg1 arg2 arg3)))
; (values arg1 arg2 1)))
; (values 0 arg1 1))))
;
;(define (iota: arg1 . rest-args)
; (receive (from to step) (%parse-iota-args arg1 rest-args iota:)
; (let* ((numsteps (floor (/ (- to from) step)))
; (last-val (+ from (* step numsteps))))
; (if (< numsteps 0) (error "Negative step count" iota: from to step))
; (do ((steps-left numsteps (- steps-left 1))
; (val last-val (- val step))
; (ans '() (cons val ans)))
; ((<= steps-left 0) ans)))))
;
;
;(define (\:iota arg1 . rest-args)
; (receive (from to step) (%parse-iota-args arg1 rest-args :iota)
; (let* ((numsteps (ceiling (/ (- to from) step)))
; (last-val (+ from (* step (- numsteps 1)))))
; (if (< numsteps 0) (error "Negative step count" :iota from to step))
; (do ((steps-left numsteps (- steps-left 1))
; (val last-val (- val step))
; (ans '() (cons val ans)))
; ((<= steps-left 0) ans)))))
(define (circular-list val1 . vals)
(let ((ans (cons val1 vals)))
(set-cdr! (last-pair ans) ans)
ans))
;;; <proper-list> ::= () ; Empty proper list
;;; | (cons <x> <proper-list>) ; Proper-list pair
;;; Note that this definition rules out circular lists -- and this
;;; function is required to detect this case and return false.
(define (proper-list? x)
(let lp ((x x) (lag x))
(if (pair? x)
(let ((x (cdr x)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(and (not (eq? x lag)) (lp x lag)))
(null? x)))
(null? x))))
;;; A dotted list is a finite list (possibly of length 0) terminated
;;; by a non-nil value. Any non-cons, non-nil value (e.g., "foo" or 5)
;;; is a dotted list of length 0.
;;;
;;; <dotted-list> ::= <non-nil,non-pair> ; Empty dotted list
;;; | (cons <x> <dotted-list>) ; Proper-list pair
(define (dotted-list? x)
(let lp ((x x) (lag x))
(if (pair? x)
(let ((x (cdr x)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(and (not (eq? x lag)) (lp x lag)))
(not (null? x))))
(not (null? x)))))
(define (circular-list? x)
(let lp ((x x) (lag x))
(and (pair? x)
(let ((x (cdr x)))
(and (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(or (eq? x lag) (lp x lag))))))))
(define (not-pair? x) (not (pair? x))) ; Inline me.
;;; This is a legal definition which is fast and sloppy:
;;; (define null-list? not-pair?)
;;; but we'll provide a more careful one:
(define (null-list? l)
(cond ((pair? l) #f)
((null? l) #t)
(else (error "null-list?: argument out of domain" l))))
(define (list= = . lists)
(or (null? lists) ; special case
(let lp1 ((list-a (car lists)) (others (cdr lists)))
(or (null? others)
(let ((list-b (car others))
(others (cdr others)))
(if (eq? list-a list-b) ; EQ? => LIST=
(lp1 list-b others)
(let lp2 ((list-a list-a) (list-b list-b))
(if (null-list? list-a)
(and (null-list? list-b)
(lp1 list-b others))
(and (not (null-list? list-b))
(= (car list-a) (car list-b))
(lp2 (cdr list-a) (cdr list-b)))))))))))
;;; R4RS, so commented out.
;(define (length x) ; LENGTH may diverge or
; (let lp ((x x) (len 0)) ; raise an error if X is
; (if (pair? x) ; a circular list. This version
; (lp (cdr x) (+ len 1)) ; diverges.
; len)))
(define (length+ x) ; Returns #f if X is circular.
(let lp ((x x) (lag x) (len 0))
(if (pair? x)
(let ((x (cdr x))
(len (+ len 1)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag))
(len (+ len 1)))
(and (not (eq? x lag)) (lp x lag len)))
len))
len)))
(define (zip list1 . more-lists) (apply map list list1 more-lists))
;;; Selectors
;;;;;;;;;;;;;
;;; R4RS non-primitives:
;(define (caar x) (car (car x)))
;(define (cadr x) (car (cdr x)))
;(define (cdar x) (cdr (car x)))
;(define (cddr x) (cdr (cdr x)))
;
;(define (caaar x) (caar (car x)))
;(define (caadr x) (caar (cdr x)))
;(define (cadar x) (cadr (car x)))
;(define (caddr x) (cadr (cdr x)))
;(define (cdaar x) (cdar (car x)))
;(define (cdadr x) (cdar (cdr x)))
;(define (cddar x) (cddr (car x)))
;(define (cdddr x) (cddr (cdr x)))
;
;(define (caaaar x) (caaar (car x)))
;(define (caaadr x) (caaar (cdr x)))
;(define (caadar x) (caadr (car x)))
;(define (caaddr x) (caadr (cdr x)))
;(define (cadaar x) (cadar (car x)))
;(define (cadadr x) (cadar (cdr x)))
;(define (caddar x) (caddr (car x)))
;(define (cadddr x) (caddr (cdr x)))
;(define (cdaaar x) (cdaar (car x)))
;(define (cdaadr x) (cdaar (cdr x)))
;(define (cdadar x) (cdadr (car x)))
;(define (cdaddr x) (cdadr (cdr x)))
;(define (cddaar x) (cddar (car x)))
;(define (cddadr x) (cddar (cdr x)))
;(define (cdddar x) (cdddr (car x)))
;(define (cddddr x) (cdddr (cdr x)))
(define first car)
(define second cadr)
(define third caddr)
(define fourth cadddr)
(define (fifth x) (car (cddddr x)))
(define (sixth x) (cadr (cddddr x)))
(define (seventh x) (caddr (cddddr x)))
(define (eighth x) (cadddr (cddddr x)))
(define (ninth x) (car (cddddr (cddddr x))))
(define (tenth x) (cadr (cddddr (cddddr x))))
(define (car+cdr pair) (values (car pair) (cdr pair)))
;;; take & drop
(define (take lis k)
(check-arg integer? k take)
(let recur ((lis lis) (k k))
(if (zero? k) '()
(cons (car lis)
(recur (cdr lis) (- k 1))))))
(define (drop lis k)
(check-arg integer? k drop)
(let iter ((lis lis) (k k))
(if (zero? k) lis (iter (cdr lis) (- k 1)))))
(define (take! lis k)
(check-arg integer? k take!)
(if (zero? k) '()
(begin (set-cdr! (drop lis (- k 1)) '())
lis)))
;;; TAKE-RIGHT and DROP-RIGHT work by getting two pointers into the list,
;;; off by K, then chasing down the list until the lead pointer falls off
;;; the end.
(define (take-right lis k)
(check-arg integer? k take-right)
(let lp ((lag lis) (lead (drop lis k)))
(if (pair? lead)
(lp (cdr lag) (cdr lead))
lag)))
(define (drop-right lis k)
(check-arg integer? k drop-right)
(let recur ((lag lis) (lead (drop lis k)))
(if (pair? lead)
(cons (car lag) (recur (cdr lag) (cdr lead)))
'())))
;;; In this function, LEAD is actually K+1 ahead of LAG. This lets
;;; us stop LAG one step early, in time to smash its cdr to ().
(define (drop-right! lis k)
(check-arg integer? k drop-right!)
(let ((lead (drop lis k)))
(if (pair? lead)
(let lp ((lag lis) (lead (cdr lead))) ; Standard case
(if (pair? lead)
(lp (cdr lag) (cdr lead))
(begin (set-cdr! lag '())
lis)))
'()))) ; Special case dropping everything -- no cons to side-effect.
;(define (list-ref lis i) (car (drop lis i))) ; R4RS
;;; These use the APL convention, whereby negative indices mean
;;; "from the right." I liked them, but they didn't win over the
;;; SRFI reviewers.
;;; K >= 0: Take and drop K elts from the front of the list.
;;; K <= 0: Take and drop -K elts from the end of the list.
;(define (take lis k)
; (check-arg integer? k take)
; (if (negative? k)
; (list-tail lis (+ k (length lis)))
; (let recur ((lis lis) (k k))
; (if (zero? k) '()
; (cons (car lis)
; (recur (cdr lis) (- k 1)))))))
;
;(define (drop lis k)
; (check-arg integer? k drop)
; (if (negative? k)
; (let recur ((lis lis) (nelts (+ k (length lis))))
; (if (zero? nelts) '()
; (cons (car lis)
; (recur (cdr lis) (- nelts 1)))))
; (list-tail lis k)))
;
;
;(define (take! lis k)
; (check-arg integer? k take!)
; (cond ((zero? k) '())
; ((positive? k)
; (set-cdr! (list-tail lis (- k 1)) '())
; lis)
; (else (list-tail lis (+ k (length lis))))))
;
;(define (drop! lis k)
; (check-arg integer? k drop!)
; (if (negative? k)
; (let ((nelts (+ k (length lis))))
; (if (zero? nelts) '()
; (begin (set-cdr! (list-tail lis (- nelts 1)) '())
; lis)))
; (list-tail lis k)))
(define (split-at x k)
(check-arg integer? k split-at)
(let recur ((lis x) (k k))
(if (zero? k) (values '() lis)
(receive (prefix suffix) (recur (cdr lis) (- k 1))
(values (cons (car lis) prefix) suffix)))))
(define (split-at! x k)
(check-arg integer? k split-at!)
(if (zero? k) (values '() x)
(let* ((prev (drop x (- k 1)))
(suffix (cdr prev)))
(set-cdr! prev '())
(values x suffix))))
(define (last lis) (car (last-pair lis)))
(define (last-pair lis)
(check-arg pair? lis last-pair)
(let lp ((lis lis))
(let ((tail (cdr lis)))
(if (pair? tail) (lp tail) lis))))
;;; Unzippers -- 1 through 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (unzip1 lis) (map car lis))
(define (unzip2 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle
(let ((elt (car lis))) ; dotted lists.
(receive (a b) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)))))))
(define (unzip3 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis)
(let ((elt (car lis)))
(receive (a b c) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)))))))
(define (unzip4 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis lis)
(let ((elt (car lis)))
(receive (a b c d) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)
(cons (cadddr elt) d)))))))
(define (unzip5 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis lis lis)
(let ((elt (car lis)))
(receive (a b c d e) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)
(cons (cadddr elt) d)
(cons (car (cddddr elt)) e)))))))
;;; append! append-reverse append-reverse! concatenate concatenate!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (append! . lists)
;; First, scan through lists looking for a non-empty one.
(let lp ((lists lists) (prev '()))
(if (not (pair? lists)) prev
(let ((first (car lists))
(rest (cdr lists)))
(if (not (pair? first)) (lp rest first)
;; Now, do the splicing.
(let lp2 ((tail-cons (last-pair first))
(rest rest))
(if (pair? rest)
(let ((next (car rest))
(rest (cdr rest)))
(set-cdr! tail-cons next)
(lp2 (if (pair? next) (last-pair next) tail-cons)
rest))
first)))))))
;;; APPEND is R4RS.
;(define (append . lists)
; (if (pair? lists)
; (let recur ((list1 (car lists)) (lists (cdr lists)))
; (if (pair? lists)
; (let ((tail (recur (car lists) (cdr lists))))
; (fold-right cons tail list1)) ; Append LIST1 & TAIL.
; list1))
; '()))
;(define (append-reverse rev-head tail) (fold cons tail rev-head))
;(define (append-reverse! rev-head tail)
; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair)
; tail
; rev-head))
;;; Hand-inline the FOLD and PAIR-FOLD ops for speed.
(define (append-reverse rev-head tail)
(let lp ((rev-head rev-head) (tail tail))
(if (null-list? rev-head) tail
(lp (cdr rev-head) (cons (car rev-head) tail)))))
(define (append-reverse! rev-head tail)
(let lp ((rev-head rev-head) (tail tail))
(if (null-list? rev-head) tail
(let ((next-rev (cdr rev-head)))
(set-cdr! rev-head tail)
(lp next-rev rev-head)))))
(define (concatenate lists) (reduce-right append '() lists))
(define (concatenate! lists) (reduce-right append! '() lists))
;;; Fold/map internal utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; These little internal utilities are used by the general
;;; fold & mapper funs for the n-ary cases . It'd be nice if they got inlined.
;;; One the other hand, the n-ary cases are painfully inefficient as it is.
;;; An aggressive implementation should simply re-write these functions
;;; for raw efficiency; I have written them for as much clarity, portability,
;;; and simplicity as can be achieved.
;;;
;;; I use the dreaded call/cc to do local aborts. A good compiler could
;;; handle this with extreme efficiency. An implementation that provides
;;; a one-shot, non-persistent continuation grabber could help the compiler
;;; out by using that in place of the call/cc's in these routines.
;;;
;;; These functions have funky definitions that are precisely tuned to
;;; the needs of the fold/map procs -- for example, to minimize the number
;;; of times the argument lists need to be examined.
;;; Return (map cdr lists).
;;; However, if any element of LISTS is empty, just abort and return '().
(define (%cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(let ((lis (car lists)))
(if (null-list? lis) (abort '())
(cons (cdr lis) (recur (cdr lists)))))
'())))))
(define (%cars+ lists last-elt) ; (append! (map car lists) (list last-elt))
(let recur ((lists lists))
(if (pair? lists) (cons (caar lists) (recur (cdr lists))) (list last-elt))))
;;; LISTS is a (not very long) non-empty list of lists.
;;; Return two lists: the cars & the cdrs of the lists.
;;; However, if any of the lists is empty, just abort and return [() ()].
(define (%cars+cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values '() '()))))))
;;; Like %CARS+CDRS, but we pass in a final elt tacked onto the end of the
;;; cars list. What a hack.
(define (%cars+cdrs+ lists cars-final)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values (list cars-final) '()))))))
;;; Like %CARS+CDRS, but blow up if any list is empty.
(define (%cars+cdrs/no-test lists)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs)))))
(values '() '()))))
;;; count
;;;;;;;;;
(define (count pred list1 . lists)
(check-arg procedure? pred count)
(if (pair? lists)
;; N-ary case
(let lp ((list1 list1) (lists lists) (i 0))
(if (null-list? list1) i
(receive (as ds) (%cars+cdrs lists)
(if (null? as) i
(lp (cdr list1) ds
(if (apply pred (car list1) as) (+ i 1) i))))))
;; Fast path
(let lp ((lis list1) (i 0))
(if (null-list? lis) i
(lp (cdr lis) (if (pred (car lis)) (+ i 1) i))))))
;;; fold/unfold
;;;;;;;;;;;;;;;
(define/opt (unfold-right p f g seed (tail '()))
(check-arg procedure? p unfold-right)
(check-arg procedure? f unfold-right)
(check-arg procedure? g unfold-right)
(let lp ((seed seed) (ans tail))
(if (p seed) ans
(lp (g seed)
(cons (f seed) ans)))))
(define/opt (unfold p f g seed (tail-gen #f))
(check-arg procedure? p unfold)
(check-arg procedure? f unfold)
(check-arg procedure? g unfold)
(check-arg procedure? tail-gen unfold)
(let recur ((seed seed))
(if (p seed)
(if tail-gen (tail-gen seed) '())
(cons (f seed) (recur (g seed))))))
(define (fold kons knil lis1 . lists)
(check-arg procedure? kons fold)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)) (ans knil)) ; N-ary case
(receive (cars+ans cdrs) (%cars+cdrs+ lists ans)
(if (null? cars+ans) ans ; Done.
(lp cdrs (apply kons cars+ans)))))
(let lp ((lis lis1) (ans knil)) ; Fast path
(if (null-list? lis) ans
(lp (cdr lis) (kons (car lis) ans))))))
(define (fold-right kons knil lis1 . lists)
(check-arg procedure? kons fold-right)
(if (pair? lists)
(let recur ((lists (cons lis1 lists))) ; N-ary case
(let ((cdrs (%cdrs lists)))
(if (null? cdrs) knil
(apply kons (%cars+ lists (recur cdrs))))))
(let recur ((lis lis1)) ; Fast path
(if (null-list? lis) knil
(let ((head (car lis)))
(kons head (recur (cdr lis))))))))
(define (pair-fold-right f zero lis1 . lists)
(check-arg procedure? f pair-fold-right)
(if (pair? lists)
(let recur ((lists (cons lis1 lists))) ; N-ary case
(let ((cdrs (%cdrs lists)))
(if (null? cdrs) zero
(apply f (append! lists (list (recur cdrs)))))))
(let recur ((lis lis1)) ; Fast path
(if (null-list? lis) zero (f lis (recur (cdr lis)))))))
(define (pair-fold f zero lis1 . lists)
(check-arg procedure? f pair-fold)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)) (ans zero)) ; N-ary case
(let ((tails (%cdrs lists)))
(if (null? tails) ans
(lp tails (apply f (append! lists (list ans)))))))
(let lp ((lis lis1) (ans zero))
(if (null-list? lis) ans
(let ((tail (cdr lis))) ; Grab the cdr now,
(lp tail (f lis ans))))))) ; in case F SET-CDR!s LIS.
;;; REDUCE and REDUCE-RIGHT only use RIDENTITY in the empty-list case.
;;; These cannot meaningfully be n-ary.
(define (reduce f ridentity lis)
(check-arg procedure? f reduce)
(if (null-list? lis) ridentity
(fold f (car lis) (cdr lis))))
(define (reduce-right f ridentity lis)
(check-arg procedure? f reduce-right)
(if (null-list? lis) ridentity
(let recur ((head (car lis)) (lis (cdr lis)))
(if (pair? lis)
(f head (recur (car lis) (cdr lis)))
head))))
;;; Mappers: append-map append-map! pair-for-each map! filter-map map-in-order
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (append-map f lis1 . lists)
(really-append-map append-map append f lis1 lists))
(define (append-map! f lis1 . lists)
(really-append-map append-map! append! f lis1 lists))
(define (really-append-map who appender f lis1 lists)
(check-arg procedure? f who)
(if (pair? lists)
(receive (cars cdrs) (%cars+cdrs (cons lis1 lists))
(if (null? cars) '()
(let recur ((cars cars) (cdrs cdrs))
(let ((vals (apply f cars)))
(receive (cars2 cdrs2) (%cars+cdrs cdrs)
(if (null? cars2) vals
(appender vals (recur cars2 cdrs2))))))))
;; Fast path
(if (null-list? lis1) '()
(let recur ((elt (car lis1)) (rest (cdr lis1)))
(let ((vals (f elt)))
(if (null-list? rest) vals
(appender vals (recur (car rest) (cdr rest)))))))))
(define (pair-for-each proc lis1 . lists)
(check-arg procedure? proc pair-for-each)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)))
(let ((tails (%cdrs lists)))
(if (pair? tails)
(begin (apply proc lists)
(lp tails)))))
;; Fast path.
(let lp ((lis lis1))
(if (not (null-list? lis))
(let ((tail (cdr lis))) ; Grab the cdr now,
(proc lis) ; in case PROC SET-CDR!s LIS.
(lp tail))))))
;;; We stop when LIS1 runs out, not when any list runs out.
(define (map! f lis1 . lists)
(check-arg procedure? f map!)
(if (pair? lists)
(let lp ((lis1 lis1) (lists lists))
(if (not (null-list? lis1))
(receive (heads tails) (%cars+cdrs/no-test lists)
(set-car! lis1 (apply f (car lis1) heads))
(lp (cdr lis1) tails))))
;; Fast path.
(pair-for-each (lambda (pair) (set-car! pair (f (car pair)))) lis1))
lis1)
;;; Map F across L, and save up all the non-false results.
(define (filter-map f lis1 . lists)
(check-arg procedure? f filter-map)
(if (pair? lists)
(let recur ((lists (cons lis1 lists)))
(receive (cars cdrs) (%cars+cdrs lists)
(if (pair? cars)
(cond ((apply f cars) => (lambda (x) (cons x (recur cdrs))))
(else (recur cdrs))) ; Tail call in this arm.
'())))
;; Fast path.
(let recur ((lis lis1))
(if (null-list? lis) lis
(let ((tail (recur (cdr lis))))
(cond ((f (car lis)) => (lambda (x) (cons x tail)))
(else tail)))))))
;;; Map F across lists, guaranteeing to go left-to-right.
;;; NOTE: Some implementations of R5RS MAP are compliant with this spec;
;;; in which case this procedure may simply be defined as a synonym for MAP.
(define (map-in-order f lis1 . lists)
(check-arg procedure? f map-in-order)
(if (pair? lists)
(let recur ((lists (cons lis1 lists)))
(receive (cars cdrs) (%cars+cdrs lists)
(if (pair? cars)
(let ((x (apply f cars))) ; Do head first,
(cons x (recur cdrs))) ; then tail.
'())))
;; Fast path.
(let recur ((lis lis1))
(if (null-list? lis) lis
(let ((tail (cdr lis))
(x (f (car lis)))) ; Do head first,
(cons x (recur tail))))))) ; then tail.
;;; We extend MAP to handle arguments of unequal length.
(define map map-in-order)
;;; filter, remove, partition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; FILTER, REMOVE, PARTITION and their destructive counterparts do not
;;; disorder the elements of their argument.
;; This FILTER shares the longest tail of L that has no deleted elements.
;; If Scheme had multi-continuation calls, they could be made more efficient.
(define (filter pred lis) ; Sleazing with EQ? makes this
(check-arg procedure? pred filter) ; one faster.
(let recur ((lis lis))
(if (null-list? lis) lis ; Use NOT-PAIR? to handle dotted lists.
(let ((head (car lis))
(tail (cdr lis)))
(if (pred head)
(let ((new-tail (recur tail))) ; Replicate the RECUR call so
(if (eq? tail new-tail) lis
(cons head new-tail)))
(recur tail)))))) ; this one can be a tail call.
;;; Another version that shares longest tail.
;(define (filter pred lis)
; (receive (ans no-del?)
; ;; (recur l) returns L with (pred x) values filtered.
; ;; It also returns a flag NO-DEL? if the returned value
; ;; is EQ? to L, i.e. if it didn't have to delete anything.
; (let recur ((l l))
; (if (null-list? l) (values l #t)
; (let ((x (car l))
; (tl (cdr l)))
; (if (pred x)
; (receive (ans no-del?) (recur tl)
; (if no-del?
; (values l #t)
; (values (cons x ans) #f)))
; (receive (ans no-del?) (recur tl) ; Delete X.
; (values ans #f))))))
; ans))
;(define (filter! pred lis) ; Things are much simpler
; (let recur ((lis lis)) ; if you are willing to
; (if (pair? lis) ; push N stack frames & do N
; (cond ((pred (car lis)) ; SET-CDR! writes, where N is
; (set-cdr! lis (recur (cdr lis))); the length of the answer.
; lis)
; (else (recur (cdr lis))))
; lis)))
;;; This implementation of FILTER!
;;; - doesn't cons, and uses no stack;
;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
;;; usually expensive on modern machines, and can be extremely expensive on
;;; modern Schemes (e.g., ones that have generational GC's).
;;; It just zips down contiguous runs of in and out elts in LIS doing the
;;; minimal number of SET-CDR!s to splice the tail of one run of ins to the
;;; beginning of the next.
(define (filter! pred lis)
(check-arg procedure? pred filter!)
(let lp ((ans lis))
(cond ((null-list? ans) ans) ; Scan looking for
((not (pred (car ans))) (lp (cdr ans))) ; first cons of result.
;; ANS is the eventual answer.
;; SCAN-IN: (CDR PREV) = LIS and (CAR PREV) satisfies PRED.
;; Scan over a contiguous segment of the list that
;; satisfies PRED.
;; SCAN-OUT: (CAR PREV) satisfies PRED. Scan over a contiguous
;; segment of the list that *doesn't* satisfy PRED.
;; When the segment ends, patch in a link from PREV
;; to the start of the next good segment, and jump to
;; SCAN-IN.
(else (letrec ((scan-in (lambda (prev lis)
(if (pair? lis)
(if (pred (car lis))
(scan-in lis (cdr lis))
(scan-out prev (cdr lis))))))
(scan-out (lambda (prev lis)
(let lp ((lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin (set-cdr! prev lis)
(scan-in lis (cdr lis)))
(lp (cdr lis)))
(set-cdr! prev lis))))))
(scan-in ans (cdr ans))
ans)))))
;;; Answers share common tail with LIS where possible;
;;; the technique is slightly subtle.
(define (partition pred lis)
(check-arg procedure? pred partition)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle dotted lists.
(let ((elt (car lis))
(tail (cdr lis)))
(receive (in out) (recur tail)
(if (pred elt)
(values (if (pair? out) (cons elt in) lis) out)
(values in (if (pair? in) (cons elt out) lis))))))))
;(define (partition! pred lis) ; Things are much simpler
; (let recur ((lis lis)) ; if you are willing to
; (if (null-list? lis) (values lis lis) ; push N stack frames & do N
; (let ((elt (car lis))) ; SET-CDR! writes, where N is
; (receive (in out) (recur (cdr lis)) ; the length of LIS.
; (cond ((pred elt)
; (set-cdr! lis in)
; (values lis out))
; (else (set-cdr! lis out)
; (values in lis))))))))
;;; This implementation of PARTITION!
;;; - doesn't cons, and uses no stack;
;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
;;; usually expensive on modern machines, and can be extremely expensive on
;;; modern Schemes (e.g., ones that have generational GC's).
;;; It just zips down contiguous runs of in and out elts in LIS doing the
;;; minimal number of SET-CDR!s to splice these runs together into the result
;;; lists.
(define (partition! pred lis)
(check-arg procedure? pred partition!)
(if (null-list? lis) (values lis lis)
;; This pair of loops zips down contiguous in & out runs of the
;; list, splicing the runs together. The invariants are
;; SCAN-IN: (cdr in-prev) = LIS.
;; SCAN-OUT: (cdr out-prev) = LIS.
(letrec ((scan-in (lambda (in-prev out-prev lis)
(let lp ((in-prev in-prev) (lis lis))
(if (pair? lis)
(if (pred (car lis))
(lp lis (cdr lis))
(begin (set-cdr! out-prev lis)
(scan-out in-prev lis (cdr lis))))
(set-cdr! out-prev lis))))) ; Done.
(scan-out (lambda (in-prev out-prev lis)
(let lp ((out-prev out-prev) (lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin (set-cdr! in-prev lis)
(scan-in lis out-prev (cdr lis)))
(lp lis (cdr lis)))
(set-cdr! in-prev lis)))))) ; Done.
;; Crank up the scan&splice loops.
(if (pred (car lis))
;; LIS begins in-list. Search for out-list's first pair.
(let lp ((prev-l lis) (l (cdr lis)))
(cond ((not (pair? l)) (values lis l))
((pred (car l)) (lp l (cdr l)))
(else (scan-out prev-l l (cdr l))
(values lis l)))) ; Done.
;; LIS begins out-list. Search for in-list's first pair.
(let lp ((prev-l lis) (l (cdr lis)))
(cond ((not (pair? l)) (values l lis))
((pred (car l))
(scan-in l prev-l (cdr l))
(values l lis)) ; Done.
(else (lp l (cdr l)))))))))
;;; Inline us, please.
(define (remove pred l) (filter (lambda (x) (not (pred x))) l))
(define (remove! pred l) (filter! (lambda (x) (not (pred x))) l))
;;; Here's the taxonomy for the DELETE/ASSOC/MEMBER functions.
;;; (I don't actually think these are the world's most important
;;; functions -- the procedural FILTER/REMOVE/FIND/FIND-TAIL variants
;;; are far more general.)
;;;
;;; Function Action
;;; ---------------------------------------------------------------------------
;;; remove pred lis Delete by general predicate
;;; delete x lis [=] Delete by element comparison
;;;
;;; find pred lis Search by general predicate
;;; find-tail pred lis Search by general predicate
;;; member x lis [=] Search by element comparison
;;;
;;; assoc key lis [=] Search alist by key comparison
;;; alist-delete key alist [=] Alist-delete by key comparison
(define/opt (delete x lis (= equal?))
(filter (lambda (y) (not (= x y))) lis))
(define/opt (delete! x lis (= equal?))
(filter! (lambda (y) (not (= x y))) lis))
;;; Extended from R4RS to take an optional comparison argument.
(define/opt (member x lis (= equal?))
(find-tail (lambda (y) (= x y)) lis))
;;; R4RS, hence we don't bother to define.
;;; The MEMBER and then FIND-TAIL call should definitely
;;; be inlined for MEMQ & MEMV.
;(define (memq x lis) (member x lis eq?))
;(define (memv x lis) (member x lis eqv?))
;;; right-duplicate deletion
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; delete-duplicates delete-duplicates!
;;;
;;; Beware -- these are N^2 algorithms. To efficiently remove duplicates
;;; in long lists, sort the list to bring duplicates together, then use a
;;; linear-time algorithm to kill the dups. Or use an algorithm based on
;;; element-marking. The former gives you O(n lg n), the latter is linear.
(define/opt (delete-duplicates lis (elt= equal?))
(check-arg procedure? elt= delete-duplicates)
(let recur ((lis lis))
(if (null-list? lis) lis
(let* ((x (car lis))
(tail (cdr lis))
(new-tail (recur (delete x tail elt=))))
(if (eq? tail new-tail) lis (cons x new-tail))))))
(define/opt (delete-duplicates! lis (elt= equal?))
(check-arg procedure? elt= delete-duplicates!)
(let recur ((lis lis))
(if (null-list? lis) lis
(let* ((x (car lis))
(tail (cdr lis))
(new-tail (recur (delete! x tail elt=))))
(if (eq? tail new-tail) lis (cons x new-tail))))))
;;; alist stuff
;;;;;;;;;;;;;;;
;;; Extended from R4RS to take an optional comparison argument.
(define/opt (assoc x lis (= equal?))
(find (lambda (entry) (= x (car entry))) lis))
(define (alist-cons key datum alist) (cons (cons key datum) alist))
(define (alist-copy alist)
(map (lambda (elt) (cons (car elt) (cdr elt)))
alist))
(define/opt (alist-delete key alist (= equal?))
(filter (lambda (elt) (not (= key (car elt)))) alist))
(define/opt (alist-delete! key alist (= equal?))
(filter! (lambda (elt) (not (= key (car elt)))) alist))
;;; find find-tail take-while drop-while span break any every list-index
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (find pred list)
(cond ((find-tail pred list) => car)
(else #f)))
(define (find-tail pred list)
(check-arg procedure? pred find-tail)
(let lp ((list list))
(and (not (null-list? list))
(if (pred (car list)) list
(lp (cdr list))))))
(define (take-while pred lis)
(check-arg procedure? pred take-while)
(let recur ((lis lis))
(if (null-list? lis) '()
(let ((x (car lis)))
(if (pred x)
(cons x (recur (cdr lis)))
'())))))
(define (drop-while pred lis)
(check-arg procedure? pred drop-while)
(let lp ((lis lis))
(if (null-list? lis) '()
(if (pred (car lis))
(lp (cdr lis))
lis))))
(define (take-while! pred lis)
(check-arg procedure? pred take-while!)
(if (or (null-list? lis) (not (pred (car lis)))) '()
(begin (let lp ((prev lis) (rest (cdr lis)))
(if (pair? rest)
(let ((x (car rest)))
(if (pred x) (lp rest (cdr rest))
(set-cdr! prev '())))))
lis)))
(define (span pred lis)
(check-arg procedure? pred span)
(let recur ((lis lis))
(if (null-list? lis) (values '() '())
(let ((x (car lis)))
(if (pred x)
(receive (prefix suffix) (recur (cdr lis))
(values (cons x prefix) suffix))
(values '() lis))))))
(define (span! pred lis)
(check-arg procedure? pred span!)
(if (or (null-list? lis) (not (pred (car lis)))) (values '() lis)
(let ((suffix (let lp ((prev lis) (rest (cdr lis)))
(if (null-list? rest) rest
(let ((x (car rest)))
(if (pred x) (lp rest (cdr rest))
(begin (set-cdr! prev '())
rest)))))))
(values lis suffix))))
(define (break pred lis) (span (lambda (x) (not (pred x))) lis))
(define (break! pred lis) (span! (lambda (x) (not (pred x))) lis))
(define (any pred lis1 . lists)
(check-arg procedure? pred any)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(and (pair? heads)
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(or (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(and (not (null-list? lis1))
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(or (pred head) (lp (car tail) (cdr tail))))))))
;(define (every pred list) ; Simple definition.
; (let lp ((list list)) ; Doesn't return the last PRED value.
; (or (not (pair? list))
; (and (pred (car list))
; (lp (cdr list))))))
(define (every pred lis1 . lists)
(check-arg procedure? pred every)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(or (not (pair? heads))
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(and (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(or (null-list? lis1)
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(and (pred head) (lp (car tail) (cdr tail))))))))
(define (list-index pred lis1 . lists)
(check-arg procedure? pred list-index)
(if (pair? lists)
;; N-ary case
(let lp ((lists (cons lis1 lists)) (n 0))
(receive (heads tails) (%cars+cdrs lists)
(and (pair? heads)
(if (apply pred heads) n
(lp tails (+ n 1))))))
;; Fast path
(let lp ((lis lis1) (n 0))
(and (not (null-list? lis))
(if (pred (car lis)) n (lp (cdr lis) (+ n 1)))))))
;;; Reverse
;;;;;;;;;;;
;R4RS, so not defined here.
;(define (reverse lis) (fold cons '() lis))
;(define (reverse! lis)
; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair) '() lis))
(define (reverse! lis)
(let lp ((lis lis) (ans '()))
(if (null-list? lis) ans
(let ((tail (cdr lis)))
(set-cdr! lis ans)
(lp tail lis)))))
;;; Lists-as-sets
;;;;;;;;;;;;;;;;;
;;; This is carefully tuned code; do not modify casually.
;;; - It is careful to share storage when possible;
;;; - Side-effecting code tries not to perform redundant writes.
;;; - It tries to avoid linear-time scans in special cases where constant-time
;;; computations can be performed.
;;; - It relies on similar properties from the other list-lib procs it calls.
;;; For example, it uses the fact that the implementations of MEMBER and
;;; FILTER in this source code share longest common tails between args
;;; and results to get structure sharing in the lset procedures.
(define (%lset2<= = lis1 lis2) (every (lambda (x) (member x lis2 =)) lis1))
(define (lset<= = . lists)
(check-arg procedure? = lset<=)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest)) (rest (cdr rest)))
(and (or (eq? s2 s1) ; Fast path
(%lset2<= = s1 s2)) ; Real test
(lp s2 rest)))))))
(define (lset= = . lists)
(check-arg procedure? = lset=)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest))
(rest (cdr rest)))
(and (or (eq? s1 s2) ; Fast path
(and (%lset2<= = s1 s2) (%lset2<= = s2 s1))) ; Real test
(lp s2 rest)))))))
(define (lset-adjoin = lis . elts)
(check-arg procedure? = lset-adjoin)
(fold (lambda (elt ans) (if (member elt ans =) ans (cons elt ans)))
lis elts))
(define (lset-union = . lists)
(check-arg procedure? = lset-union)
(reduce (lambda (lis ans) ; Compute ANS + LIS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(fold (lambda (elt ans) (if (any (lambda (x) (= x elt)) ans)
ans
(cons elt ans)))
ans lis))))
'() lists))
(define (lset-union! = . lists)
(check-arg procedure? = lset-union!)
(reduce (lambda (lis ans) ; Splice new elts of LIS onto the front of ANS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(pair-fold (lambda (pair ans)
(let ((elt (car pair)))
(if (any (lambda (x) (= x elt)) ans)
ans
(begin (set-cdr! pair ans) pair))))
ans lis))))
'() lists))
(define (lset-intersection = lis1 . lists)
(check-arg procedure? = lset-intersection)
(let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
(cond ((any null-list? lists) '()) ; Short cut
((null? lists) lis1) ; Short cut
(else (filter (lambda (x)
(every (lambda (lis) (member x lis =)) lists))
lis1)))))
(define (lset-intersection! = lis1 . lists)
(check-arg procedure? = lset-intersection!)
(let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
(cond ((any null-list? lists) '()) ; Short cut
((null? lists) lis1) ; Short cut
(else (filter! (lambda (x)
(every (lambda (lis) (member x lis =)) lists))
lis1)))))
(define (lset-difference = lis1 . lists)
(check-arg procedure? = lset-difference)
(let ((lists (filter pair? lists))) ; Throw out empty lists.
(cond ((null? lists) lis1) ; Short cut
((memq lis1 lists) '()) ; Short cut
(else (filter (lambda (x)
(every (lambda (lis) (not (member x lis =)))
lists))
lis1)))))
(define (lset-difference! = lis1 . lists)
(check-arg procedure? = lset-difference!)
(let ((lists (filter pair? lists))) ; Throw out empty lists.
(cond ((null? lists) lis1) ; Short cut
((memq lis1 lists) '()) ; Short cut
(else (filter! (lambda (x)
(every (lambda (lis) (not (member x lis =)))
lists))
lis1)))))
(define (lset-xor = . lists)
(check-arg procedure? = lset-xor)
(reduce (lambda (b a) ; Compute A xor B:
;; Note that this code relies on the constant-time
;; short-cuts provided by LSET-DIFF+INTERSECTION,
;; LSET-DIFFERENCE & APPEND to provide constant-time short
;; cuts for the cases A = (), B = (), and A eq? B. It takes
;; a careful case analysis to see it, but it's carefully
;; built in.
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection = a b)
(cond ((null? a-b) (lset-difference = b a))
((null? a-int-b) (append b a))
(else (fold (lambda (xb ans)
(if (member xb a-int-b =) ans (cons xb ans)))
a-b
b)))))
'() lists))
(define (lset-xor! = . lists)
(check-arg procedure? = lset-xor!)
(reduce (lambda (b a) ; Compute A xor B:
;; Note that this code relies on the constant-time
;; short-cuts provided by LSET-DIFF+INTERSECTION,
;; LSET-DIFFERENCE & APPEND to provide constant-time short
;; cuts for the cases A = (), B = (), and A eq? B. It takes
;; a careful case analysis to see it, but it's carefully
;; built in.
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection! = a b)
(cond ((null? a-b) (lset-difference! = b a))
((null? a-int-b) (append! b a))
(else (pair-fold (lambda (b-pair ans)
(if (member (car b-pair) a-int-b =) ans
(begin (set-cdr! b-pair ans) b-pair)))
a-b
b)))))
'() lists))
(define (lset-diff+intersection = lis1 . lists)
(check-arg procedure? = lset-diff+intersection)
(cond ((every null-list? lists) (values lis1 '())) ; Short cut
((memq lis1 lists) (values '() lis1)) ; Short cut
(else (partition (lambda (elt)
(not (any (lambda (lis) (member elt lis =))
lists)))
lis1))))
(define (lset-diff+intersection! = lis1 . lists)
(check-arg procedure? = lset-diff+intersection!)
(cond ((every null-list? lists) (values lis1 '())) ; Short cut
((memq lis1 lists) (values '() lis1)) ; Short cut
(else (partition! (lambda (elt)
(not (any (lambda (lis) (member elt lis =))
lists)))
lis1))))
(define-library (srfi 1)
(export
xcons list-tabulate cons*
proper-list? circular-list? dotted-list? not-pair? null-list? list=
circular-list length+
iota
first second third fourth fifth sixth seventh eighth ninth tenth
car+cdr
take drop
take-right drop-right
take! drop-right!
split-at split-at!
last last-pair
zip unzip1 unzip2 unzip3 unzip4 unzip5
count
append! append-reverse append-reverse! concatenate concatenate!
unfold fold pair-fold reduce
unfold-right fold-right pair-fold-right reduce-right
append-map append-map! map! pair-for-each filter-map map-in-order
filter partition remove
filter! partition! remove!
find find-tail any every list-index
take-while drop-while take-while!
span break span! break!
delete delete!
alist-cons alist-copy
delete-duplicates delete-duplicates!
alist-delete alist-delete!
reverse!
lset<= lset= lset-adjoin
lset-union lset-intersection lset-difference lset-xor lset-diff+intersection
lset-union! lset-intersection! lset-difference! lset-xor! lset-diff+intersection!
)
(import
(except (scheme base) map member assoc)
(scheme case-lambda)
(scheme cxr)
(srfi 8)
(srfi aux))
(begin
(define-check-arg check-arg))
(include "1.body.scm"))
;;;;"array.scm" Arrays for Scheme
; Copyright (C) 2001, 2003 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;@code{(require 'array)} or @code{(require 'srfi-63)}
;;@ftindex array
(define-record-type <array>
(array:construct dimensions scales offset store)
array:array?
(dimensions dimensions)
(scales scales)
(offset offset)
(store store))
(define (array:dimensions array)
(cond ((vector? array) (list (vector-length array)))
((string? array) (list (string-length array)))
(else (dimensions array))))
(define (array:scales array)
(cond ((vector? array) '(1))
((string? array) '(1))
(else (scales array))))
(define (array:store array)
(cond ((vector? array) array)
((string? array) array)
(else (store array))))
(define (array:offset array)
(cond ((vector? array) 0)
((string? array) 0)
(else (offset array))))
;;@args obj
;;Returns @code{#t} if the @1 is an array, and @code{#f} if not.
(define (array? obj)
(or (vector? obj) (string? obj) (array:array? obj)))
;;@noindent
;;@emph{Note:} Arrays are not disjoint from other Scheme types.
;;Vectors and possibly strings also satisfy @code{array?}.
;;A disjoint array predicate can be written:
;;
;;@example
;;(define (strict-array? obj)
;; (and (array? obj) (not (string? obj)) (not (vector? obj))))
;;@end example
;;@body
;;Returns @code{#t} if @1 and @2 have the same rank and dimensions and the
;;corresponding elements of @1 and @2 are @code{equal?}.
;;@body
;;@0 recursively compares the contents of pairs, vectors, strings, and
;;@emph{arrays}, applying @code{eqv?} on other objects such as numbers
;;and symbols. A rule of thumb is that objects are generally @0 if
;;they print the same. @0 may fail to terminate if its arguments are
;;circular data structures.
;;
;;@example
;;(equal? 'a 'a) @result{} #t
;;(equal? '(a) '(a)) @result{} #t
;;(equal? '(a (b) c)
;; '(a (b) c)) @result{} #t
;;(equal? "abc" "abc") @result{} #t
;;(equal? 2 2) @result{} #t
;;(equal? (make-vector 5 'a)
;; (make-vector 5 'a)) @result{} #t
;;(equal? (make-array (a:fixN32b 4) 5 3)
;; (make-array (a:fixN32b 4) 5 3)) @result{} #t
;;(equal? (make-array '#(foo) 3 3)
;; (make-array '#(foo) 3 3)) @result{} #t
;;(equal? (lambda (x) x)
;; (lambda (y) y)) @result{} @emph{unspecified}
;;@end example
(define (equal? obj1 obj2)
(cond ((eqv? obj1 obj2) #t)
((or (pair? obj1) (pair? obj2))
(and (pair? obj1) (pair? obj2)
(equal? (car obj1) (car obj2))
(equal? (cdr obj1) (cdr obj2))))
((or (string? obj1) (string? obj2))
(and (string? obj1) (string? obj2)
(string=? obj1 obj2)))
((or (vector? obj1) (vector? obj2))
(and (vector? obj1) (vector? obj2)
(equal? (vector-length obj1) (vector-length obj2))
(do ((idx (+ -1 (vector-length obj1)) (+ -1 idx)))
((or (negative? idx)
(not (equal? (vector-ref obj1 idx)
(vector-ref obj2 idx))))
(negative? idx)))))
((or (array? obj1) (array? obj2))
(and (array? obj1) (array? obj2)
(equal? (array:dimensions obj1) (array:dimensions obj2))
(equal? (array:store obj1) (array:store obj2))))
(else #f)))
;;@body
;;Returns the number of dimensions of @1. If @1 is not an array, 0 is
;;returned.
(define (array-rank obj)
(if (array? obj) (length (array:dimensions obj)) 0))
;;@args array
;;Returns a list of dimensions.
;;
;;@example
;;(array-dimensions (make-array '#() 3 5))
;; @result{} (3 5)
;;@end example
(define array-dimensions array:dimensions)
;;@args prototype k1 @dots{}
;;
;;Creates and returns an array of type @1 with dimensions @2, @dots{}
;;and filled with elements from @1. @1 must be an array, vector, or
;;string. The implementation-dependent type of the returned array
;;will be the same as the type of @1; except if that would be a vector
;;or string with rank not equal to one, in which case some variety of
;;array will be returned.
;;
;;If the @1 has no elements, then the initial contents of the returned
;;array are unspecified. Otherwise, the returned array will be filled
;;with the element at the origin of @1.
(define (make-array prototype . dimensions)
(define tcnt (apply * dimensions))
(let ((store
(if (string? prototype)
(case (string-length prototype)
((0) (make-string tcnt))
(else (make-string tcnt
(string-ref prototype 0))))
(let ((pdims (array:dimensions prototype)))
(case (apply * pdims)
((0) (make-vector tcnt))
(else (make-vector tcnt
(apply array-ref prototype
(map (lambda (x) 0) pdims)))))))))
(define (loop dims scales)
(if (null? dims)
(array:construct dimensions (cdr scales) 0 store)
(loop (cdr dims) (cons (* (car dims) (car scales)) scales))))
(loop (reverse dimensions) '(1))))
;;@args prototype k1 @dots{}
;;@0 is an alias for @code{make-array}.
(define create-array make-array)
;;@args array mapper k1 @dots{}
;;@0 can be used to create shared subarrays of other
;;arrays. The @var{mapper} is a function that translates coordinates in
;;the new array into coordinates in the old array. A @var{mapper} must be
;;linear, and its range must stay within the bounds of the old array, but
;;it can be otherwise arbitrary. A simple example:
;;
;;@example
;;(define fred (make-array '#(#f) 8 8))
;;(define freds-diagonal
;; (make-shared-array fred (lambda (i) (list i i)) 8))
;;(array-set! freds-diagonal 'foo 3)
;;(array-ref fred 3 3)
;; @result{} FOO
;;(define freds-center
;; (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
;; 2 2))
;;(array-ref freds-center 0 0)
;; @result{} FOO
;;@end example
(define (make-shared-array array mapper . dimensions)
(define odl (array:scales array))
(define rank (length dimensions))
(define shape
(map (lambda (dim) (if (list? dim) dim (list 0 (+ -1 dim)))) dimensions))
(do ((idx (+ -1 rank) (+ -1 idx))
(uvt (append (cdr (vector->list (make-vector rank 0))) '(1))
(append (cdr uvt) '(0)))
(uvts '() (cons uvt uvts)))
((negative? idx)
(let ((ker0 (apply + (map * odl (apply mapper uvt)))))
(array:construct
(map (lambda (dim) (+ 1 (- (cadr dim) (car dim)))) shape)
(map (lambda (uvt) (- (apply + (map * odl (apply mapper uvt))) ker0))
uvts)
(apply +
(array:offset array)
(map * odl (apply mapper (map car shape))))
(array:store array))))))
;;@args rank proto list
;;@3 must be a rank-nested list consisting of all the elements, in
;;row-major order, of the array to be created.
;;
;;@0 returns an array of rank @1 and type @2 consisting of all the
;;elements, in row-major order, of @3. When @1 is 0, @3 is the lone
;;array element; not necessarily a list.
;;
;;@example
;;(list->array 2 '#() '((1 2) (3 4)))
;; @result{} #2A((1 2) (3 4))
;;(list->array 0 '#() 3)
;; @result{} #0A 3
;;@end example
(define (list->array rank proto lst)
(define dimensions
(do ((shp '() (cons (length row) shp))
(row lst (car lst))
(rnk (+ -1 rank) (+ -1 rnk)))
((negative? rnk) (reverse shp))))
(let ((nra (apply make-array proto dimensions)))
(define (l2ra dims idxs row)
(cond ((null? dims)
(apply array-set! nra row (reverse idxs)))
(else
(if (not (eqv? (car dims) (length row)))
(error "Array not rectangular:" dims dimensions))
(do ((idx 0 (+ 1 idx))
(row row (cdr row)))
((>= idx (car dims)))
(l2ra (cdr dims) (cons idx idxs) (car row))))))
(l2ra dimensions '() lst)
nra))
;;@args array
;;Returns a rank-nested list consisting of all the elements, in
;;row-major order, of @1. In the case of a rank-0 array, @0 returns
;;the single element.
;;
;;@example
;;(array->list #2A((ho ho ho) (ho oh oh)))
;; @result{} ((ho ho ho) (ho oh oh))
;;(array->list #0A ho)
;; @result{} ho
;;@end example
(define (array->list ra)
(define (ra2l dims idxs)
(if (null? dims)
(apply array-ref ra (reverse idxs))
(do ((lst '() (cons (ra2l (cdr dims) (cons idx idxs)) lst))
(idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) lst))))
(ra2l (array-dimensions ra) '()))
;;@args vect proto dim1 @dots{}
;;@1 must be a vector of length equal to the product of exact
;;nonnegative integers @3, @dots{}.
;;
;;@0 returns an array of type @2 consisting of all the elements, in
;;row-major order, of @1. In the case of a rank-0 array, @1 has a
;;single element.
;;
;;@example
;;(vector->array #(1 2 3 4) #() 2 2)
;; @result{} #2A((1 2) (3 4))
;;(vector->array '#(3) '#())
;; @result{} #0A 3
;;@end example
(define (vector->array vect prototype . dimensions)
(define vdx (vector-length vect))
(if (not (eqv? vdx (apply * dimensions)))
(error "Vector length does not equal product of dimensions:"
vdx dimensions))
(let ((ra (apply make-array prototype dimensions)))
(define (v2ra dims idxs)
(cond ((null? dims)
(set! vdx (+ -1 vdx))
(apply array-set! ra (vector-ref vect vdx) (reverse idxs)))
(else
(do ((idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) vect)
(v2ra (cdr dims) (cons idx idxs))))))
(v2ra dimensions '())
ra))
;;@args array
;;Returns a new vector consisting of all the elements of @1 in
;;row-major order.
;;
;;@example
;;(array->vector #2A ((1 2)( 3 4)))
;; @result{} #(1 2 3 4)
;;(array->vector #0A ho)
;; @result{} #(ho)
;;@end example
(define (array->vector ra)
(define dims (array-dimensions ra))
(let* ((vdx (apply * dims))
(vect (make-vector vdx)))
(define (ra2v dims idxs)
(if (null? dims)
(let ((val (apply array-ref ra (reverse idxs))))
(set! vdx (+ -1 vdx))
(vector-set! vect vdx val)
vect)
(do ((idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) vect)
(ra2v (cdr dims) (cons idx idxs)))))
(ra2v dims '())))
(define (array:in-bounds? array indices)
(do ((bnds (array:dimensions array) (cdr bnds))
(idxs indices (cdr idxs)))
((or (null? bnds)
(null? idxs)
(not (integer? (car idxs)))
(not (< -1 (car idxs) (car bnds))))
(and (null? bnds) (null? idxs)))))
;;@args array index1 @dots{}
;;Returns @code{#t} if its arguments would be acceptable to
;;@code{array-ref}.
(define (array-in-bounds? array . indices)
(array:in-bounds? array indices))
;;@args array k1 @dots{}
;;Returns the (@2, @dots{}) element of @1.
(define (array-ref array . indices)
(define store (array:store array))
(or (array:in-bounds? array indices)
(error "Bad indices:" indices))
((if (string? store) string-ref vector-ref)
store (apply + (array:offset array) (map * (array:scales array) indices))))
;;@args array obj k1 @dots{}
;;Stores @2 in the (@3, @dots{}) element of @1. The value returned
;;by @0 is unspecified.
(define (array-set! array obj . indices)
(define store (array:store array))
(or (array:in-bounds? array indices)
(error "Bad indices:" indices))
((if (string? store) string-set! vector-set!)
store (apply + (array:offset array) (map * (array:scales array) indices))
obj))
;;@noindent
;;These functions return a prototypical uniform-array enclosing the
;;optional argument (which must be of the correct type). If the
;;uniform-array type is supported by the implementation, then it is
;;returned; defaulting to the next larger precision type; resorting
;;finally to vector.
(define (make-prototype-checker name pred? creator)
(lambda args
(case (length args)
((1) (if (pred? (car args))
(creator (car args))
(error "Incompatible type:" name (car args))))
((0) (creator))
(else (error "Wrong number of arguments:" name args)))))
(define (integer-bytes?? n)
(lambda (obj)
(and (integer? obj)
(exact? obj)
(or (negative? n) (not (negative? obj)))
(do ((num obj (quotient num 256))
(n (+ -1 (abs n)) (+ -1 n)))
((or (zero? num) (negative? n))
(zero? num))))))
;;@args z
;;@args
;;Returns an inexact 128.bit flonum complex uniform-array prototype.
(define a:floc128b (make-prototype-checker 'a:floc128b complex? vector))
;;@args z
;;@args
;;Returns an inexact 64.bit flonum complex uniform-array prototype.
(define a:floc64b (make-prototype-checker 'a:floc64b complex? vector))
;;@args z
;;@args
;;Returns an inexact 32.bit flonum complex uniform-array prototype.
(define a:floc32b (make-prototype-checker 'a:floc32b complex? vector))
;;@args z
;;@args
;;Returns an inexact 16.bit flonum complex uniform-array prototype.
(define a:floc16b (make-prototype-checker 'a:floc16b complex? vector))
;;@args z
;;@args
;;Returns an inexact 128.bit flonum real uniform-array prototype.
(define a:flor128b (make-prototype-checker 'a:flor128b real? vector))
;;@args z
;;@args
;;Returns an inexact 64.bit flonum real uniform-array prototype.
(define a:flor64b (make-prototype-checker 'a:flor64b real? vector))
;;@args z
;;@args
;;Returns an inexact 32.bit flonum real uniform-array prototype.
(define a:flor32b (make-prototype-checker 'a:flor32b real? vector))
;;@args z
;;@args
;;Returns an inexact 16.bit flonum real uniform-array prototype.
(define a:flor16b (make-prototype-checker 'a:flor16b real? vector))
;;@args z
;;@args
;;Returns an exact 128.bit decimal flonum rational uniform-array prototype.
(define a:flor128b (make-prototype-checker 'a:flor128b real? vector))
;;@args z
;;@args
;;Returns an exact 64.bit decimal flonum rational uniform-array prototype.
(define a:flor64b (make-prototype-checker 'a:flor64b real? vector))
;;@args z
;;@args
;;Returns an exact 32.bit decimal flonum rational uniform-array prototype.
(define a:flor32b (make-prototype-checker 'a:flor32b real? vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;64 bits of precision.
(define a:fixz64b (make-prototype-checker 'a:fixz64b (integer-bytes?? -8) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;32 bits of precision.
(define a:fixz32b (make-prototype-checker 'a:fixz32b (integer-bytes?? -4) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;16 bits of precision.
(define a:fixz16b (make-prototype-checker 'a:fixz16b (integer-bytes?? -2) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;8 bits of precision.
(define a:fixz8b (make-prototype-checker 'a:fixz8b (integer-bytes?? -1) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 64 bits of precision.
(define a:fixn64b (make-prototype-checker 'a:fixn64b (integer-bytes?? 8) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 32 bits of precision.
(define a:fixn32b (make-prototype-checker 'a:fixn32b (integer-bytes?? 4) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 16 bits of precision.
(define a:fixn16b (make-prototype-checker 'a:fixn16b (integer-bytes?? 2) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 8 bits of precision.
(define a:fixn8b (make-prototype-checker 'a:fixn8b (integer-bytes?? 1) vector))
;;@args bool
;;@args
;;Returns a boolean uniform-array prototype.
(define a:bool (make-prototype-checker 'a:bool boolean? vector))
;;; SRFI-1 list-processing library -*- Scheme -*-
;;; Reference implementation
;;;
;;; Copyright (c) 1998, 1999 by Olin Shivers. You may do as you please with
;;; this code as long as you do not remove this copyright notice or
;;; hold me liable for its use. Please send bug reports to shivers@ai.mit.edu.
;;; -Olin
;;; This is a library of list- and pair-processing functions. I wrote it after
;;; carefully considering the functions provided by the libraries found in
;;; R4RS/R5RS Scheme, MIT Scheme, Gambit, RScheme, MzScheme, slib, Common
;;; Lisp, Bigloo, guile, T, APL and the SML standard basis. It is a pretty
;;; rich toolkit, providing a superset of the functionality found in any of
;;; the various Schemes I considered.
;;; This implementation is intended as a portable reference implementation
;;; for SRFI-1. See the porting notes below for more information.
;;; Exported:
;;; xcons tree-copy make-list list-tabulate cons* list-copy
;;; proper-list? circular-list? dotted-list? not-pair? null-list? list=
;;; circular-list length+
;;; iota
;;; first second third fourth fifth sixth seventh eighth ninth tenth
;;; car+cdr
;;; take drop
;;; take-right drop-right
;;; take! drop-right!
;;; split-at split-at!
;;; last last-pair
;;; zip unzip1 unzip2 unzip3 unzip4 unzip5
;;; count
;;; append! append-reverse append-reverse! concatenate concatenate!
;;; unfold fold pair-fold reduce
;;; unfold-right fold-right pair-fold-right reduce-right
;;; append-map append-map! map! pair-for-each filter-map map-in-order
;;; filter partition remove
;;; filter! partition! remove!
;;; find find-tail any every list-index
;;; take-while drop-while take-while!
;;; span break span! break!
;;; delete delete!
;;; alist-cons alist-copy
;;; delete-duplicates delete-duplicates!
;;; alist-delete alist-delete!
;;; reverse!
;;; lset<= lset= lset-adjoin
;;; lset-union lset-intersection lset-difference lset-xor lset-diff+intersection
;;; lset-union! lset-intersection! lset-difference! lset-xor! lset-diff+intersection!
;;;
;;; In principle, the following R4RS list- and pair-processing procedures
;;; are also part of this package's exports, although they are not defined
;;; in this file:
;;; Primitives: cons pair? null? car cdr set-car! set-cdr!
;;; Non-primitives: list length append reverse cadr ... cddddr list-ref
;;; memq memv assq assv
;;; (The non-primitives are defined in this file, but commented out.)
;;;
;;; These R4RS procedures have extended definitions in SRFI-1 and are defined
;;; in this file:
;;; map for-each member assoc
;;;
;;; The remaining two R4RS list-processing procedures are not included:
;;; list-tail (use drop)
;;; list? (use proper-list?)
;;; A note on recursion and iteration/reversal:
;;; Many iterative list-processing algorithms naturally compute the elements
;;; of the answer list in the wrong order (left-to-right or head-to-tail) from
;;; the order needed to cons them into the proper answer (right-to-left, or
;;; tail-then-head). One style or idiom of programming these algorithms, then,
;;; loops, consing up the elements in reverse order, then destructively
;;; reverses the list at the end of the loop. I do not do this. The natural
;;; and efficient way to code these algorithms is recursively. This trades off
;;; intermediate temporary list structure for intermediate temporary stack
;;; structure. In a stack-based system, this improves cache locality and
;;; lightens the load on the GC system. Don't stand on your head to iterate!
;;; Recurse, where natural. Multiple-value returns make this even more
;;; convenient, when the recursion/iteration has multiple state values.
;;; Porting:
;;; This is carefully tuned code; do not modify casually.
;;; - It is careful to share storage when possible;
;;; - Side-effecting code tries not to perform redundant writes.
;;;
;;; That said, a port of this library to a specific Scheme system might wish
;;; to tune this code to exploit particulars of the implementation.
;;; The single most important compiler-specific optimisation you could make
;;; to this library would be to add rewrite rules or transforms to:
;;; - transform applications of n-ary procedures (e.g. LIST=, CONS*, APPEND,
;;; LSET-UNION) into multiple applications of a primitive two-argument
;;; variant.
;;; - transform applications of the mapping functions (MAP, FOR-EACH, FOLD,
;;; ANY, EVERY) into open-coded loops. The killer here is that these
;;; functions are n-ary. Handling the general case is quite inefficient,
;;; requiring many intermediate data structures to be allocated and
;;; discarded.
;;; - transform applications of procedures that take optional arguments
;;; into calls to variants that do not take optional arguments. This
;;; eliminates unnecessary consing and parsing of the rest parameter.
;;;
;;; These transforms would provide BIG speedups. In particular, the n-ary
;;; mapping functions are particularly slow and cons-intensive, and are good
;;; candidates for tuning. I have coded fast paths for the single-list cases,
;;; but what you really want to do is exploit the fact that the compiler
;;; usually knows how many arguments are being passed to a particular
;;; application of these functions -- they are usually explicitly called, not
;;; passed around as higher-order values. If you can arrange to have your
;;; compiler produce custom code or custom linkages based on the number of
;;; arguments in the call, you can speed these functions up a *lot*. But this
;;; kind of compiler technology no longer exists in the Scheme world as far as
;;; I can see.
;;;
;;; Note that this code is, of course, dependent upon standard bindings for
;;; the R5RS procedures -- i.e., it assumes that the variable CAR is bound
;;; to the procedure that takes the car of a list. If your Scheme
;;; implementation allows user code to alter the bindings of these procedures
;;; in a manner that would be visible to these definitions, then there might
;;; be trouble. You could consider horrible kludgery along the lines of
;;; (define fact
;;; (let ((= =) (- -) (* *))
;;; (letrec ((real-fact (lambda (n)
;;; (if (= n 0) 1 (* n (real-fact (- n 1)))))))
;;; real-fact)))
;;; Or you could consider shifting to a reasonable Scheme system that, say,
;;; has a module system protecting code from this kind of lossage.
;;;
;;; This code does a fair amount of run-time argument checking. If your
;;; Scheme system has a sophisticated compiler that can eliminate redundant
;;; error checks, this is no problem. However, if not, these checks incur
;;; some performance overhead -- and, in a safe Scheme implementation, they
;;; are in some sense redundant: if we don't check to see that the PROC
;;; parameter is a procedure, we'll find out anyway three lines later when
;;; we try to call the value. It's pretty easy to rip all this argument
;;; checking code out if it's inappropriate for your implementation -- just
;;; nuke every call to CHECK-ARG.
;;;
;;; On the other hand, if you *do* have a sophisticated compiler that will
;;; actually perform soft-typing and eliminate redundant checks (Rice's systems
;;; being the only possible candidate of which I'm aware), leaving these checks
;;; in can *help*, since their presence can be elided in redundant cases,
;;; and in cases where they are needed, performing the checks early, at
;;; procedure entry, can "lift" a check out of a loop.
;;;
;;; Finally, I have only checked the properties that can portably be checked
;;; with R5RS Scheme -- and this is not complete. You may wish to alter
;;; the CHECK-ARG parameter checks to perform extra, implementation-specific
;;; checks, such as procedure arity for higher-order values.
;;;
;;; The code has only these non-R4RS dependencies:
;;; A few calls to an ERROR procedure;
;;; Uses of the R5RS multiple-value procedure VALUES and the m-v binding
;;; RECEIVE macro (which isn't R5RS, but is a trivial macro).
;;; Many calls to a parameter-checking procedure check-arg:
;;; (define (check-arg pred val caller)
;;; (let lp ((val val))
;;; (if (pred val) val (lp (error "Bad argument" val pred caller)))))
;;; A few uses of the LET-OPTIONAL and :OPTIONAL macros for parsing
;;; optional arguments.
;;;
;;; Most of these procedures use the NULL-LIST? test to trigger the
;;; base case in the inner loop or recursion. The NULL-LIST? function
;;; is defined to be a careful one -- it raises an error if passed a
;;; non-nil, non-pair value. The spec allows an implementation to use
;;; a less-careful implementation that simply defines NULL-LIST? to
;;; be NOT-PAIR?. This would speed up the inner loops of these procedures
;;; at the expense of having them silently accept dotted lists.
;;; A note on dotted lists:
;;; I, personally, take the view that the only consistent view of lists
;;; in Scheme is the view that *everything* is a list -- values such as
;;; 3 or "foo" or 'bar are simply empty dotted lists. This is due to the
;;; fact that Scheme actually has no true list type. It has a pair type,
;;; and there is an *interpretation* of the trees built using this type
;;; as lists.
;;;
;;; I lobbied to have these list-processing procedures hew to this
;;; view, and accept any value as a list argument. I was overwhelmingly
;;; overruled during the SRFI discussion phase. So I am inserting this
;;; text in the reference lib and the SRFI spec as a sort of "minority
;;; opinion" dissent.
;;;
;;; Many of the procedures in this library can be trivially redefined
;;; to handle dotted lists, just by changing the NULL-LIST? base-case
;;; check to NOT-PAIR?, meaning that any non-pair value is taken to be
;;; an empty list. For most of these procedures, that's all that is
;;; required.
;;;
;;; However, we have to do a little more work for some procedures that
;;; *produce* lists from other lists. Were we to extend these procedures to
;;; accept dotted lists, we would have to define how they terminate the lists
;;; produced as results when passed a dotted list. I designed a coherent set
;;; of termination rules for these cases; this was posted to the SRFI-1
;;; discussion list. I additionally wrote an earlier version of this library
;;; that implemented that spec. It has been discarded during later phases of
;;; the definition and implementation of this library.
;;;
;;; The argument *against* defining these procedures to work on dotted
;;; lists is that dotted lists are the rare, odd case, and that by
;;; arranging for the procedures to handle them, we lose error checking
;;; in the cases where a dotted list is passed by accident -- e.g., when
;;; the programmer swaps a two arguments to a list-processing function,
;;; one being a scalar and one being a list. For example,
;;; (member '(1 3 5 7 9) 7)
;;; This would quietly return #f if we extended MEMBER to accept dotted
;;; lists.
;;;
;;; The SRFI discussion record contains more discussion on this topic.
;;; Constructors
;;;;;;;;;;;;;;;;
;;; Occasionally useful as a value to be passed to a fold or other
;;; higher-order procedure.
(define (xcons d a) (cons a d))
;;;; Recursively copy every cons.
;(define (tree-copy x)
; (let recur ((x x))
; (if (not (pair? x)) x
; (cons (recur (car x)) (recur (cdr x))))))
;;; Make a list of length LEN.
(define (make-list len . maybe-elt)
(check-arg (lambda (n) (and (integer? n) (>= n 0))) len make-list)
(let ((elt (cond ((null? maybe-elt) #f) ; Default value
((null? (cdr maybe-elt)) (car maybe-elt))
(else (error "Too many arguments to MAKE-LIST"
(cons len maybe-elt))))))
(do ((i len (- i 1))
(ans '() (cons elt ans)))
((<= i 0) ans))))
;(define (list . ans) ans) ; R4RS
;;; Make a list of length LEN. Elt i is (PROC i) for 0 <= i < LEN.
(define (list-tabulate len proc)
(check-arg (lambda (n) (and (integer? n) (>= n 0))) len list-tabulate)
(check-arg procedure? proc list-tabulate)
(do ((i (- len 1) (- i 1))
(ans '() (cons (proc i) ans)))
((< i 0) ans)))
;;; (cons* a1 a2 ... an) = (cons a1 (cons a2 (cons ... an)))
;;; (cons* a1) = a1 (cons* a1 a2 ...) = (cons a1 (cons* a2 ...))
;;;
;;; (cons first (unfold not-pair? car cdr rest values))
(define (cons* first . rest)
(let recur ((x first) (rest rest))
(if (pair? rest)
(cons x (recur (car rest) (cdr rest)))
x)))
;;; (unfold not-pair? car cdr lis values)
(define (list-copy lis)
(let recur ((lis lis))
(if (pair? lis)
(cons (car lis) (recur (cdr lis)))
lis)))
;;; IOTA count [start step] (start start+step ... start+(count-1)*step)
(define (iota count . maybe-start+step)
(check-arg integer? count iota)
(if (< count 0) (error "Negative step count" iota count))
(let-optionals maybe-start+step ((start 0) (step 1))
(check-arg number? start iota)
(check-arg number? step iota)
(let loop ((n 0) (r '()))
(if (= n count)
(reverse r)
(loop (+ 1 n)
(cons (+ start (* n step)) r))))))
;;; I thought these were lovely, but the public at large did not share my
;;; enthusiasm...
;;; :IOTA to (0 ... to-1)
;;; :IOTA from to (from ... to-1)
;;; :IOTA from to step (from from+step ...)
;;; IOTA: to (1 ... to)
;;; IOTA: from to (from+1 ... to)
;;; IOTA: from to step (from+step from+2step ...)
;(define (%parse-iota-args arg1 rest-args proc)
; (let ((check (lambda (n) (check-arg integer? n proc))))
; (check arg1)
; (if (pair? rest-args)
; (let ((arg2 (check (car rest-args)))
; (rest (cdr rest-args)))
; (if (pair? rest)
; (let ((arg3 (check (car rest)))
; (rest (cdr rest)))
; (if (pair? rest) (error "Too many parameters" proc arg1 rest-args)
; (values arg1 arg2 arg3)))
; (values arg1 arg2 1)))
; (values 0 arg1 1))))
;
;(define (iota: arg1 . rest-args)
; (receive (from to step) (%parse-iota-args arg1 rest-args iota:)
; (let* ((numsteps (floor (/ (- to from) step)))
; (last-val (+ from (* step numsteps))))
; (if (< numsteps 0) (error "Negative step count" iota: from to step))
; (do ((steps-left numsteps (- steps-left 1))
; (val last-val (- val step))
; (ans '() (cons val ans)))
; ((<= steps-left 0) ans)))))
;
;
;(define (\:iota arg1 . rest-args)
; (receive (from to step) (%parse-iota-args arg1 rest-args :iota)
; (let* ((numsteps (ceiling (/ (- to from) step)))
; (last-val (+ from (* step (- numsteps 1)))))
; (if (< numsteps 0) (error "Negative step count" :iota from to step))
; (do ((steps-left numsteps (- steps-left 1))
; (val last-val (- val step))
; (ans '() (cons val ans)))
; ((<= steps-left 0) ans)))))
(define (circular-list val1 . vals)
(let ((ans (cons val1 vals)))
(set-cdr! (last-pair ans) ans)
ans))
;;; <proper-list> ::= () ; Empty proper list
;;; | (cons <x> <proper-list>) ; Proper-list pair
;;; Note that this definition rules out circular lists -- and this
;;; function is required to detect this case and return false.
(define (proper-list? x)
(let lp ((x x) (lag x))
(if (pair? x)
(let ((x (cdr x)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(and (not (eq? x lag)) (lp x lag)))
(null? x)))
(null? x))))
;;; A dotted list is a finite list (possibly of length 0) terminated
;;; by a non-nil value. Any non-cons, non-nil value (e.g., "foo" or 5)
;;; is a dotted list of length 0.
;;;
;;; <dotted-list> ::= <non-nil,non-pair> ; Empty dotted list
;;; | (cons <x> <dotted-list>) ; Proper-list pair
(define (dotted-list? x)
(let lp ((x x) (lag x))
(if (pair? x)
(let ((x (cdr x)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(and (not (eq? x lag)) (lp x lag)))
(not (null? x))))
(not (null? x)))))
(define (circular-list? x)
(let lp ((x x) (lag x))
(and (pair? x)
(let ((x (cdr x)))
(and (pair? x)
(let ((x (cdr x))
(lag (cdr lag)))
(or (eq? x lag) (lp x lag))))))))
(define (not-pair? x) (not (pair? x))) ; Inline me.
;;; This is a legal definition which is fast and sloppy:
;;; (define null-list? not-pair?)
;;; but we'll provide a more careful one:
(define (null-list? l)
(cond ((pair? l) #f)
((null? l) #t)
(else (error "null-list?: argument out of domain" l))))
(define (list= = . lists)
(or (null? lists) ; special case
(let lp1 ((list-a (car lists)) (others (cdr lists)))
(or (null? others)
(let ((list-b (car others))
(others (cdr others)))
(if (eq? list-a list-b) ; EQ? => LIST=
(lp1 list-b others)
(let lp2 ((list-a list-a) (list-b list-b))
(if (null-list? list-a)
(and (null-list? list-b)
(lp1 list-b others))
(and (not (null-list? list-b))
(= (car list-a) (car list-b))
(lp2 (cdr list-a) (cdr list-b)))))))))))
;;; R4RS, so commented out.
;(define (length x) ; LENGTH may diverge or
; (let lp ((x x) (len 0)) ; raise an error if X is
; (if (pair? x) ; a circular list. This version
; (lp (cdr x) (+ len 1)) ; diverges.
; len)))
(define (length+ x) ; Returns #f if X is circular.
(let lp ((x x) (lag x) (len 0))
(if (pair? x)
(let ((x (cdr x))
(len (+ len 1)))
(if (pair? x)
(let ((x (cdr x))
(lag (cdr lag))
(len (+ len 1)))
(and (not (eq? x lag)) (lp x lag len)))
len))
len)))
(define (zip list1 . more-lists) (apply map list list1 more-lists))
;;; Selectors
;;;;;;;;;;;;;
;;; R4RS non-primitives:
;(define (caar x) (car (car x)))
;(define (cadr x) (car (cdr x)))
;(define (cdar x) (cdr (car x)))
;(define (cddr x) (cdr (cdr x)))
;
;(define (caaar x) (caar (car x)))
;(define (caadr x) (caar (cdr x)))
;(define (cadar x) (cadr (car x)))
;(define (caddr x) (cadr (cdr x)))
;(define (cdaar x) (cdar (car x)))
;(define (cdadr x) (cdar (cdr x)))
;(define (cddar x) (cddr (car x)))
;(define (cdddr x) (cddr (cdr x)))
;
;(define (caaaar x) (caaar (car x)))
;(define (caaadr x) (caaar (cdr x)))
;(define (caadar x) (caadr (car x)))
;(define (caaddr x) (caadr (cdr x)))
;(define (cadaar x) (cadar (car x)))
;(define (cadadr x) (cadar (cdr x)))
;(define (caddar x) (caddr (car x)))
;(define (cadddr x) (caddr (cdr x)))
;(define (cdaaar x) (cdaar (car x)))
;(define (cdaadr x) (cdaar (cdr x)))
;(define (cdadar x) (cdadr (car x)))
;(define (cdaddr x) (cdadr (cdr x)))
;(define (cddaar x) (cddar (car x)))
;(define (cddadr x) (cddar (cdr x)))
;(define (cdddar x) (cdddr (car x)))
;(define (cddddr x) (cdddr (cdr x)))
(define first car)
(define second cadr)
(define third caddr)
(define fourth cadddr)
(define (fifth x) (car (cddddr x)))
(define (sixth x) (cadr (cddddr x)))
(define (seventh x) (caddr (cddddr x)))
(define (eighth x) (cadddr (cddddr x)))
(define (ninth x) (car (cddddr (cddddr x))))
(define (tenth x) (cadr (cddddr (cddddr x))))
(define (car+cdr pair) (values (car pair) (cdr pair)))
;;; take & drop
(define (take lis k)
(check-arg integer? k take)
(let recur ((lis lis) (k k))
(if (zero? k) '()
(cons (car lis)
(recur (cdr lis) (- k 1))))))
(define (drop lis k)
(check-arg integer? k drop)
(let iter ((lis lis) (k k))
(if (zero? k) lis (iter (cdr lis) (- k 1)))))
(define (take! lis k)
(check-arg integer? k take!)
(if (zero? k) '()
(begin (set-cdr! (drop lis (- k 1)) '())
lis)))
;;; TAKE-RIGHT and DROP-RIGHT work by getting two pointers into the list,
;;; off by K, then chasing down the list until the lead pointer falls off
;;; the end.
(define (take-right lis k)
(check-arg integer? k take-right)
(let lp ((lag lis) (lead (drop lis k)))
(if (pair? lead)
(lp (cdr lag) (cdr lead))
lag)))
(define (drop-right lis k)
(check-arg integer? k drop-right)
(let recur ((lag lis) (lead (drop lis k)))
(if (pair? lead)
(cons (car lag) (recur (cdr lag) (cdr lead)))
'())))
;;; In this function, LEAD is actually K+1 ahead of LAG. This lets
;;; us stop LAG one step early, in time to smash its cdr to ().
(define (drop-right! lis k)
(check-arg integer? k drop-right!)
(let ((lead (drop lis k)))
(if (pair? lead)
(let lp ((lag lis) (lead (cdr lead))) ; Standard case
(if (pair? lead)
(lp (cdr lag) (cdr lead))
(begin (set-cdr! lag '())
lis)))
'()))) ; Special case dropping everything -- no cons to side-effect.
;(define (list-ref lis i) (car (drop lis i))) ; R4RS
;;; These use the APL convention, whereby negative indices mean
;;; "from the right." I liked them, but they didn't win over the
;;; SRFI reviewers.
;;; K >= 0: Take and drop K elts from the front of the list.
;;; K <= 0: Take and drop -K elts from the end of the list.
;(define (take lis k)
; (check-arg integer? k take)
; (if (negative? k)
; (list-tail lis (+ k (length lis)))
; (let recur ((lis lis) (k k))
; (if (zero? k) '()
; (cons (car lis)
; (recur (cdr lis) (- k 1)))))))
;
;(define (drop lis k)
; (check-arg integer? k drop)
; (if (negative? k)
; (let recur ((lis lis) (nelts (+ k (length lis))))
; (if (zero? nelts) '()
; (cons (car lis)
; (recur (cdr lis) (- nelts 1)))))
; (list-tail lis k)))
;
;
;(define (take! lis k)
; (check-arg integer? k take!)
; (cond ((zero? k) '())
; ((positive? k)
; (set-cdr! (list-tail lis (- k 1)) '())
; lis)
; (else (list-tail lis (+ k (length lis))))))
;
;(define (drop! lis k)
; (check-arg integer? k drop!)
; (if (negative? k)
; (let ((nelts (+ k (length lis))))
; (if (zero? nelts) '()
; (begin (set-cdr! (list-tail lis (- nelts 1)) '())
; lis)))
; (list-tail lis k)))
(define (split-at x k)
(check-arg integer? k split-at)
(let recur ((lis x) (k k))
(if (zero? k) (values '() lis)
(receive (prefix suffix) (recur (cdr lis) (- k 1))
(values (cons (car lis) prefix) suffix)))))
(define (split-at! x k)
(check-arg integer? k split-at!)
(if (zero? k) (values '() x)
(let* ((prev (drop x (- k 1)))
(suffix (cdr prev)))
(set-cdr! prev '())
(values x suffix))))
(define (last lis) (car (last-pair lis)))
(define (last-pair lis)
(check-arg pair? lis last-pair)
(let lp ((lis lis))
(let ((tail (cdr lis)))
(if (pair? tail) (lp tail) lis))))
;;; Unzippers -- 1 through 5
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (unzip1 lis) (map car lis))
(define (unzip2 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle
(let ((elt (car lis))) ; dotted lists.
(receive (a b) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)))))))
(define (unzip3 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis)
(let ((elt (car lis)))
(receive (a b c) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)))))))
(define (unzip4 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis lis)
(let ((elt (car lis)))
(receive (a b c d) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)
(cons (cadddr elt) d)))))))
(define (unzip5 lis)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis lis lis lis)
(let ((elt (car lis)))
(receive (a b c d e) (recur (cdr lis))
(values (cons (car elt) a)
(cons (cadr elt) b)
(cons (caddr elt) c)
(cons (cadddr elt) d)
(cons (car (cddddr elt)) e)))))))
;;; append! append-reverse append-reverse! concatenate concatenate!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (append! . lists)
;; First, scan through lists looking for a non-empty one.
(let lp ((lists lists) (prev '()))
(if (not (pair? lists)) prev
(let ((first (car lists))
(rest (cdr lists)))
(if (not (pair? first)) (lp rest first)
;; Now, do the splicing.
(let lp2 ((tail-cons (last-pair first))
(rest rest))
(if (pair? rest)
(let ((next (car rest))
(rest (cdr rest)))
(set-cdr! tail-cons next)
(lp2 (if (pair? next) (last-pair next) tail-cons)
rest))
first)))))))
;;; APPEND is R4RS.
;(define (append . lists)
; (if (pair? lists)
; (let recur ((list1 (car lists)) (lists (cdr lists)))
; (if (pair? lists)
; (let ((tail (recur (car lists) (cdr lists))))
; (fold-right cons tail list1)) ; Append LIST1 & TAIL.
; list1))
; '()))
;(define (append-reverse rev-head tail) (fold cons tail rev-head))
;(define (append-reverse! rev-head tail)
; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair)
; tail
; rev-head))
;;; Hand-inline the FOLD and PAIR-FOLD ops for speed.
(define (append-reverse rev-head tail)
(let lp ((rev-head rev-head) (tail tail))
(if (null-list? rev-head) tail
(lp (cdr rev-head) (cons (car rev-head) tail)))))
(define (append-reverse! rev-head tail)
(let lp ((rev-head rev-head) (tail tail))
(if (null-list? rev-head) tail
(let ((next-rev (cdr rev-head)))
(set-cdr! rev-head tail)
(lp next-rev rev-head)))))
(define (concatenate lists) (reduce-right append '() lists))
(define (concatenate! lists) (reduce-right append! '() lists))
;;; Fold/map internal utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; These little internal utilities are used by the general
;;; fold & mapper funs for the n-ary cases . It'd be nice if they got inlined.
;;; One the other hand, the n-ary cases are painfully inefficient as it is.
;;; An aggressive implementation should simply re-write these functions
;;; for raw efficiency; I have written them for as much clarity, portability,
;;; and simplicity as can be achieved.
;;;
;;; I use the dreaded call/cc to do local aborts. A good compiler could
;;; handle this with extreme efficiency. An implementation that provides
;;; a one-shot, non-persistent continuation grabber could help the compiler
;;; out by using that in place of the call/cc's in these routines.
;;;
;;; These functions have funky definitions that are precisely tuned to
;;; the needs of the fold/map procs -- for example, to minimize the number
;;; of times the argument lists need to be examined.
;;; Return (map cdr lists).
;;; However, if any element of LISTS is empty, just abort and return '().
(define (%cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(let ((lis (car lists)))
(if (null-list? lis) (abort '())
(cons (cdr lis) (recur (cdr lists)))))
'())))))
(define (%cars+ lists last-elt) ; (append! (map car lists) (list last-elt))
(let recur ((lists lists))
(if (pair? lists) (cons (caar lists) (recur (cdr lists))) (list last-elt))))
;;; LISTS is a (not very long) non-empty list of lists.
;;; Return two lists: the cars & the cdrs of the lists.
;;; However, if any of the lists is empty, just abort and return [() ()].
(define (%cars+cdrs lists)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values '() '()))))))
;;; Like %CARS+CDRS, but we pass in a final elt tacked onto the end of the
;;; cars list. What a hack.
(define (%cars+cdrs+ lists cars-final)
(call-with-current-continuation
(lambda (abort)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(if (null-list? list) (abort '() '()) ; LIST is empty -- bail out
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs))))))
(values (list cars-final) '()))))))
;;; Like %CARS+CDRS, but blow up if any list is empty.
(define (%cars+cdrs/no-test lists)
(let recur ((lists lists))
(if (pair? lists)
(receive (list other-lists) (car+cdr lists)
(receive (a d) (car+cdr list)
(receive (cars cdrs) (recur other-lists)
(values (cons a cars) (cons d cdrs)))))
(values '() '()))))
;;; count
;;;;;;;;;
(define (count pred list1 . lists)
(check-arg procedure? pred count)
(if (pair? lists)
;; N-ary case
(let lp ((list1 list1) (lists lists) (i 0))
(if (null-list? list1) i
(receive (as ds) (%cars+cdrs lists)
(if (null? as) i
(lp (cdr list1) ds
(if (apply pred (car list1) as) (+ i 1) i))))))
;; Fast path
(let lp ((lis list1) (i 0))
(if (null-list? lis) i
(lp (cdr lis) (if (pred (car lis)) (+ i 1) i))))))
;;; fold/unfold
;;;;;;;;;;;;;;;
(define (unfold-right p f g seed . maybe-tail)
(check-arg procedure? p unfold-right)
(check-arg procedure? f unfold-right)
(check-arg procedure? g unfold-right)
(let lp ((seed seed) (ans (#\:optional maybe-tail '())))
(if (p seed) ans
(lp (g seed)
(cons (f seed) ans)))))
(define (unfold p f g seed . maybe-tail-gen)
(check-arg procedure? p unfold)
(check-arg procedure? f unfold)
(check-arg procedure? g unfold)
(if (pair? maybe-tail-gen)
(let ((tail-gen (car maybe-tail-gen)))
(if (pair? (cdr maybe-tail-gen))
(apply error "Too many arguments" unfold p f g seed maybe-tail-gen)
(let recur ((seed seed))
(if (p seed) (tail-gen seed)
(cons (f seed) (recur (g seed)))))))
(let recur ((seed seed))
(if (p seed) '()
(cons (f seed) (recur (g seed)))))))
(define (fold kons knil lis1 . lists)
(check-arg procedure? kons fold)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)) (ans knil)) ; N-ary case
(receive (cars+ans cdrs) (%cars+cdrs+ lists ans)
(if (null? cars+ans) ans ; Done.
(lp cdrs (apply kons cars+ans)))))
(let lp ((lis lis1) (ans knil)) ; Fast path
(if (null-list? lis) ans
(lp (cdr lis) (kons (car lis) ans))))))
(define (fold-right kons knil lis1 . lists)
(check-arg procedure? kons fold-right)
(if (pair? lists)
(let recur ((lists (cons lis1 lists))) ; N-ary case
(let ((cdrs (%cdrs lists)))
(if (null? cdrs) knil
(apply kons (%cars+ lists (recur cdrs))))))
(let recur ((lis lis1)) ; Fast path
(if (null-list? lis) knil
(let ((head (car lis)))
(kons head (recur (cdr lis))))))))
(define (pair-fold-right f zero lis1 . lists)
(check-arg procedure? f pair-fold-right)
(if (pair? lists)
(let recur ((lists (cons lis1 lists))) ; N-ary case
(let ((cdrs (%cdrs lists)))
(if (null? cdrs) zero
(apply f (append! lists (list (recur cdrs)))))))
(let recur ((lis lis1)) ; Fast path
(if (null-list? lis) zero (f lis (recur (cdr lis)))))))
(define (pair-fold f zero lis1 . lists)
(check-arg procedure? f pair-fold)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)) (ans zero)) ; N-ary case
(let ((tails (%cdrs lists)))
(if (null? tails) ans
(lp tails (apply f (append! lists (list ans)))))))
(let lp ((lis lis1) (ans zero))
(if (null-list? lis) ans
(let ((tail (cdr lis))) ; Grab the cdr now,
(lp tail (f lis ans))))))) ; in case F SET-CDR!s LIS.
;;; REDUCE and REDUCE-RIGHT only use RIDENTITY in the empty-list case.
;;; These cannot meaningfully be n-ary.
(define (reduce f ridentity lis)
(check-arg procedure? f reduce)
(if (null-list? lis) ridentity
(fold f (car lis) (cdr lis))))
(define (reduce-right f ridentity lis)
(check-arg procedure? f reduce-right)
(if (null-list? lis) ridentity
(let recur ((head (car lis)) (lis (cdr lis)))
(if (pair? lis)
(f head (recur (car lis) (cdr lis)))
head))))
;;; Mappers: append-map append-map! pair-for-each map! filter-map map-in-order
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (append-map f lis1 . lists)
(really-append-map append-map append f lis1 lists))
(define (append-map! f lis1 . lists)
(really-append-map append-map! append! f lis1 lists))
(define (really-append-map who appender f lis1 lists)
(check-arg procedure? f who)
(if (pair? lists)
(receive (cars cdrs) (%cars+cdrs (cons lis1 lists))
(if (null? cars) '()
(let recur ((cars cars) (cdrs cdrs))
(let ((vals (apply f cars)))
(receive (cars2 cdrs2) (%cars+cdrs cdrs)
(if (null? cars2) vals
(appender vals (recur cars2 cdrs2))))))))
;; Fast path
(if (null-list? lis1) '()
(let recur ((elt (car lis1)) (rest (cdr lis1)))
(let ((vals (f elt)))
(if (null-list? rest) vals
(appender vals (recur (car rest) (cdr rest)))))))))
(define (pair-for-each proc lis1 . lists)
(check-arg procedure? proc pair-for-each)
(if (pair? lists)
(let lp ((lists (cons lis1 lists)))
(let ((tails (%cdrs lists)))
(if (pair? tails)
(begin (apply proc lists)
(lp tails)))))
;; Fast path.
(let lp ((lis lis1))
(if (not (null-list? lis))
(let ((tail (cdr lis))) ; Grab the cdr now,
(proc lis) ; in case PROC SET-CDR!s LIS.
(lp tail))))))
;;; We stop when LIS1 runs out, not when any list runs out.
(define (map! f lis1 . lists)
(check-arg procedure? f map!)
(if (pair? lists)
(let lp ((lis1 lis1) (lists lists))
(if (not (null-list? lis1))
(receive (heads tails) (%cars+cdrs/no-test lists)
(set-car! lis1 (apply f (car lis1) heads))
(lp (cdr lis1) tails))))
;; Fast path.
(pair-for-each (lambda (pair) (set-car! pair (f (car pair)))) lis1))
lis1)
;;; Map F across L, and save up all the non-false results.
(define (filter-map f lis1 . lists)
(check-arg procedure? f filter-map)
(if (pair? lists)
(let recur ((lists (cons lis1 lists)))
(receive (cars cdrs) (%cars+cdrs lists)
(if (pair? cars)
(cond ((apply f cars) => (lambda (x) (cons x (recur cdrs))))
(else (recur cdrs))) ; Tail call in this arm.
'())))
;; Fast path.
(let recur ((lis lis1))
(if (null-list? lis) lis
(let ((tail (recur (cdr lis))))
(cond ((f (car lis)) => (lambda (x) (cons x tail)))
(else tail)))))))
;;; Map F across lists, guaranteeing to go left-to-right.
;;; NOTE: Some implementations of R5RS MAP are compliant with this spec;
;;; in which case this procedure may simply be defined as a synonym for MAP.
(define (map-in-order f lis1 . lists)
(check-arg procedure? f map-in-order)
(if (pair? lists)
(let recur ((lists (cons lis1 lists)))
(receive (cars cdrs) (%cars+cdrs lists)
(if (pair? cars)
(let ((x (apply f cars))) ; Do head first,
(cons x (recur cdrs))) ; then tail.
'())))
;; Fast path.
(let recur ((lis lis1))
(if (null-list? lis) lis
(let ((tail (cdr lis))
(x (f (car lis)))) ; Do head first,
(cons x (recur tail))))))) ; then tail.
;;; We extend MAP to handle arguments of unequal length.
(define map map-in-order)
;;; filter, remove, partition
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; FILTER, REMOVE, PARTITION and their destructive counterparts do not
;;; disorder the elements of their argument.
;; This FILTER shares the longest tail of L that has no deleted elements.
;; If Scheme had multi-continuation calls, they could be made more efficient.
(define (filter pred lis) ; Sleazing with EQ? makes this
(check-arg procedure? pred filter) ; one faster.
(let recur ((lis lis))
(if (null-list? lis) lis ; Use NOT-PAIR? to handle dotted lists.
(let ((head (car lis))
(tail (cdr lis)))
(if (pred head)
(let ((new-tail (recur tail))) ; Replicate the RECUR call so
(if (eq? tail new-tail) lis
(cons head new-tail)))
(recur tail)))))) ; this one can be a tail call.
;;; Another version that shares longest tail.
;(define (filter pred lis)
; (receive (ans no-del?)
; ;; (recur l) returns L with (pred x) values filtered.
; ;; It also returns a flag NO-DEL? if the returned value
; ;; is EQ? to L, i.e. if it didn't have to delete anything.
; (let recur ((l l))
; (if (null-list? l) (values l #t)
; (let ((x (car l))
; (tl (cdr l)))
; (if (pred x)
; (receive (ans no-del?) (recur tl)
; (if no-del?
; (values l #t)
; (values (cons x ans) #f)))
; (receive (ans no-del?) (recur tl) ; Delete X.
; (values ans #f))))))
; ans))
;(define (filter! pred lis) ; Things are much simpler
; (let recur ((lis lis)) ; if you are willing to
; (if (pair? lis) ; push N stack frames & do N
; (cond ((pred (car lis)) ; SET-CDR! writes, where N is
; (set-cdr! lis (recur (cdr lis))); the length of the answer.
; lis)
; (else (recur (cdr lis))))
; lis)))
;;; This implementation of FILTER!
;;; - doesn't cons, and uses no stack;
;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
;;; usually expensive on modern machines, and can be extremely expensive on
;;; modern Schemes (e.g., ones that have generational GC's).
;;; It just zips down contiguous runs of in and out elts in LIS doing the
;;; minimal number of SET-CDR!s to splice the tail of one run of ins to the
;;; beginning of the next.
(define (filter! pred lis)
(check-arg procedure? pred filter!)
(let lp ((ans lis))
(cond ((null-list? ans) ans) ; Scan looking for
((not (pred (car ans))) (lp (cdr ans))) ; first cons of result.
;; ANS is the eventual answer.
;; SCAN-IN: (CDR PREV) = LIS and (CAR PREV) satisfies PRED.
;; Scan over a contiguous segment of the list that
;; satisfies PRED.
;; SCAN-OUT: (CAR PREV) satisfies PRED. Scan over a contiguous
;; segment of the list that *doesn't* satisfy PRED.
;; When the segment ends, patch in a link from PREV
;; to the start of the next good segment, and jump to
;; SCAN-IN.
(else (letrec ((scan-in (lambda (prev lis)
(if (pair? lis)
(if (pred (car lis))
(scan-in lis (cdr lis))
(scan-out prev (cdr lis))))))
(scan-out (lambda (prev lis)
(let lp ((lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin (set-cdr! prev lis)
(scan-in lis (cdr lis)))
(lp (cdr lis)))
(set-cdr! prev lis))))))
(scan-in ans (cdr ans))
ans)))))
;;; Answers share common tail with LIS where possible;
;;; the technique is slightly subtle.
(define (partition pred lis)
(check-arg procedure? pred partition)
(let recur ((lis lis))
(if (null-list? lis) (values lis lis) ; Use NOT-PAIR? to handle dotted lists.
(let ((elt (car lis))
(tail (cdr lis)))
(receive (in out) (recur tail)
(if (pred elt)
(values (if (pair? out) (cons elt in) lis) out)
(values in (if (pair? in) (cons elt out) lis))))))))
;(define (partition! pred lis) ; Things are much simpler
; (let recur ((lis lis)) ; if you are willing to
; (if (null-list? lis) (values lis lis) ; push N stack frames & do N
; (let ((elt (car lis))) ; SET-CDR! writes, where N is
; (receive (in out) (recur (cdr lis)) ; the length of LIS.
; (cond ((pred elt)
; (set-cdr! lis in)
; (values lis out))
; (else (set-cdr! lis out)
; (values in lis))))))))
;;; This implementation of PARTITION!
;;; - doesn't cons, and uses no stack;
;;; - is careful not to do redundant SET-CDR! writes, as writes to memory are
;;; usually expensive on modern machines, and can be extremely expensive on
;;; modern Schemes (e.g., ones that have generational GC's).
;;; It just zips down contiguous runs of in and out elts in LIS doing the
;;; minimal number of SET-CDR!s to splice these runs together into the result
;;; lists.
(define (partition! pred lis)
(check-arg procedure? pred partition!)
(if (null-list? lis) (values lis lis)
;; This pair of loops zips down contiguous in & out runs of the
;; list, splicing the runs together. The invariants are
;; SCAN-IN: (cdr in-prev) = LIS.
;; SCAN-OUT: (cdr out-prev) = LIS.
(letrec ((scan-in (lambda (in-prev out-prev lis)
(let lp ((in-prev in-prev) (lis lis))
(if (pair? lis)
(if (pred (car lis))
(lp lis (cdr lis))
(begin (set-cdr! out-prev lis)
(scan-out in-prev lis (cdr lis))))
(set-cdr! out-prev lis))))) ; Done.
(scan-out (lambda (in-prev out-prev lis)
(let lp ((out-prev out-prev) (lis lis))
(if (pair? lis)
(if (pred (car lis))
(begin (set-cdr! in-prev lis)
(scan-in lis out-prev (cdr lis)))
(lp lis (cdr lis)))
(set-cdr! in-prev lis)))))) ; Done.
;; Crank up the scan&splice loops.
(if (pred (car lis))
;; LIS begins in-list. Search for out-list's first pair.
(let lp ((prev-l lis) (l (cdr lis)))
(cond ((not (pair? l)) (values lis l))
((pred (car l)) (lp l (cdr l)))
(else (scan-out prev-l l (cdr l))
(values lis l)))) ; Done.
;; LIS begins out-list. Search for in-list's first pair.
(let lp ((prev-l lis) (l (cdr lis)))
(cond ((not (pair? l)) (values l lis))
((pred (car l))
(scan-in l prev-l (cdr l))
(values l lis)) ; Done.
(else (lp l (cdr l)))))))))
;;; Inline us, please.
(define (remove pred l) (filter (lambda (x) (not (pred x))) l))
(define (remove! pred l) (filter! (lambda (x) (not (pred x))) l))
;;; Here's the taxonomy for the DELETE/ASSOC/MEMBER functions.
;;; (I don't actually think these are the world's most important
;;; functions -- the procedural FILTER/REMOVE/FIND/FIND-TAIL variants
;;; are far more general.)
;;;
;;; Function Action
;;; ---------------------------------------------------------------------------
;;; remove pred lis Delete by general predicate
;;; delete x lis [=] Delete by element comparison
;;;
;;; find pred lis Search by general predicate
;;; find-tail pred lis Search by general predicate
;;; member x lis [=] Search by element comparison
;;;
;;; assoc key lis [=] Search alist by key comparison
;;; alist-delete key alist [=] Alist-delete by key comparison
(define (delete x lis . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(filter (lambda (y) (not (= x y))) lis)))
(define (delete! x lis . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(filter! (lambda (y) (not (= x y))) lis)))
;;; Extended from R4RS to take an optional comparison argument.
(define (member x lis . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(find-tail (lambda (y) (= x y)) lis)))
;;; R4RS, hence we don't bother to define.
;;; The MEMBER and then FIND-TAIL call should definitely
;;; be inlined for MEMQ & MEMV.
;(define (memq x lis) (member x lis eq?))
;(define (memv x lis) (member x lis eqv?))
;;; right-duplicate deletion
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; delete-duplicates delete-duplicates!
;;;
;;; Beware -- these are N^2 algorithms. To efficiently remove duplicates
;;; in long lists, sort the list to bring duplicates together, then use a
;;; linear-time algorithm to kill the dups. Or use an algorithm based on
;;; element-marking. The former gives you O(n lg n), the latter is linear.
(define (delete-duplicates lis . maybe-=)
(let ((elt= (#\:optional maybe-= equal?)))
(check-arg procedure? elt= delete-duplicates)
(let recur ((lis lis))
(if (null-list? lis) lis
(let* ((x (car lis))
(tail (cdr lis))
(new-tail (recur (delete x tail elt=))))
(if (eq? tail new-tail) lis (cons x new-tail)))))))
(define (delete-duplicates! lis maybe-=)
(let ((elt= (#\:optional maybe-= equal?)))
(check-arg procedure? elt= delete-duplicates!)
(let recur ((lis lis))
(if (null-list? lis) lis
(let* ((x (car lis))
(tail (cdr lis))
(new-tail (recur (delete! x tail elt=))))
(if (eq? tail new-tail) lis (cons x new-tail)))))))
;;; alist stuff
;;;;;;;;;;;;;;;
;;; Extended from R4RS to take an optional comparison argument.
(define (assoc x lis . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(find (lambda (entry) (= x (car entry))) lis)))
(define (alist-cons key datum alist) (cons (cons key datum) alist))
(define (alist-copy alist)
(map (lambda (elt) (cons (car elt) (cdr elt)))
alist))
(define (alist-delete key alist . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(filter (lambda (elt) (not (= key (car elt)))) alist)))
(define (alist-delete! key alist . maybe-=)
(let ((= (#\:optional maybe-= equal?)))
(filter! (lambda (elt) (not (= key (car elt)))) alist)))
;;; find find-tail take-while drop-while span break any every list-index
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (find pred list)
(cond ((find-tail pred list) => car)
(else #f)))
(define (find-tail pred list)
(check-arg procedure? pred find-tail)
(let lp ((list list))
(and (not (null-list? list))
(if (pred (car list)) list
(lp (cdr list))))))
(define (take-while pred lis)
(check-arg procedure? pred take-while)
(let recur ((lis lis))
(if (null-list? lis) '()
(let ((x (car lis)))
(if (pred x)
(cons x (recur (cdr lis)))
'())))))
(define (drop-while pred lis)
(check-arg procedure? pred drop-while)
(let lp ((lis lis))
(if (null-list? lis) '()
(if (pred (car lis))
(lp (cdr lis))
lis))))
(define (take-while! pred lis)
(check-arg procedure? pred take-while!)
(if (or (null-list? lis) (not (pred (car lis)))) '()
(begin (let lp ((prev lis) (rest (cdr lis)))
(if (pair? rest)
(let ((x (car rest)))
(if (pred x) (lp rest (cdr rest))
(set-cdr! prev '())))))
lis)))
(define (span pred lis)
(check-arg procedure? pred span)
(let recur ((lis lis))
(if (null-list? lis) (values '() '())
(let ((x (car lis)))
(if (pred x)
(receive (prefix suffix) (recur (cdr lis))
(values (cons x prefix) suffix))
(values '() lis))))))
(define (span! pred lis)
(check-arg procedure? pred span!)
(if (or (null-list? lis) (not (pred (car lis)))) (values '() lis)
(let ((suffix (let lp ((prev lis) (rest (cdr lis)))
(if (null-list? rest) rest
(let ((x (car rest)))
(if (pred x) (lp rest (cdr rest))
(begin (set-cdr! prev '())
rest)))))))
(values lis suffix))))
(define (break pred lis) (span (lambda (x) (not (pred x))) lis))
(define (break! pred lis) (span! (lambda (x) (not (pred x))) lis))
(define (any pred lis1 . lists)
(check-arg procedure? pred any)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(and (pair? heads)
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(or (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(and (not (null-list? lis1))
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(or (pred head) (lp (car tail) (cdr tail))))))))
;(define (every pred list) ; Simple definition.
; (let lp ((list list)) ; Doesn't return the last PRED value.
; (or (not (pair? list))
; (and (pred (car list))
; (lp (cdr list))))))
(define (every pred lis1 . lists)
(check-arg procedure? pred every)
(if (pair? lists)
;; N-ary case
(receive (heads tails) (%cars+cdrs (cons lis1 lists))
(or (not (pair? heads))
(let lp ((heads heads) (tails tails))
(receive (next-heads next-tails) (%cars+cdrs tails)
(if (pair? next-heads)
(and (apply pred heads) (lp next-heads next-tails))
(apply pred heads)))))) ; Last PRED app is tail call.
;; Fast path
(or (null-list? lis1)
(let lp ((head (car lis1)) (tail (cdr lis1)))
(if (null-list? tail)
(pred head) ; Last PRED app is tail call.
(and (pred head) (lp (car tail) (cdr tail))))))))
(define (list-index pred lis1 . lists)
(check-arg procedure? pred list-index)
(if (pair? lists)
;; N-ary case
(let lp ((lists (cons lis1 lists)) (n 0))
(receive (heads tails) (%cars+cdrs lists)
(and (pair? heads)
(if (apply pred heads) n
(lp tails (+ n 1))))))
;; Fast path
(let lp ((lis lis1) (n 0))
(and (not (null-list? lis))
(if (pred (car lis)) n (lp (cdr lis) (+ n 1)))))))
;;; Reverse
;;;;;;;;;;;
;R4RS, so not defined here.
;(define (reverse lis) (fold cons '() lis))
;(define (reverse! lis)
; (pair-fold (lambda (pair tail) (set-cdr! pair tail) pair) '() lis))
(define (reverse! lis)
(let lp ((lis lis) (ans '()))
(if (null-list? lis) ans
(let ((tail (cdr lis)))
(set-cdr! lis ans)
(lp tail lis)))))
;;; Lists-as-sets
;;;;;;;;;;;;;;;;;
;;; This is carefully tuned code; do not modify casually.
;;; - It is careful to share storage when possible;
;;; - Side-effecting code tries not to perform redundant writes.
;;; - It tries to avoid linear-time scans in special cases where constant-time
;;; computations can be performed.
;;; - It relies on similar properties from the other list-lib procs it calls.
;;; For example, it uses the fact that the implementations of MEMBER and
;;; FILTER in this source code share longest common tails between args
;;; and results to get structure sharing in the lset procedures.
(define (%lset2<= = lis1 lis2) (every (lambda (x) (member x lis2 =)) lis1))
(define (lset<= = . lists)
(check-arg procedure? = lset<=)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest)) (rest (cdr rest)))
(and (or (eq? s2 s1) ; Fast path
(%lset2<= = s1 s2)) ; Real test
(lp s2 rest)))))))
(define (lset= = . lists)
(check-arg procedure? = lset=)
(or (not (pair? lists)) ; 0-ary case
(let lp ((s1 (car lists)) (rest (cdr lists)))
(or (not (pair? rest))
(let ((s2 (car rest))
(rest (cdr rest)))
(and (or (eq? s1 s2) ; Fast path
(and (%lset2<= = s1 s2) (%lset2<= = s2 s1))) ; Real test
(lp s2 rest)))))))
(define (lset-adjoin = lis . elts)
(check-arg procedure? = lset-adjoin)
(fold (lambda (elt ans) (if (member elt ans =) ans (cons elt ans)))
lis elts))
(define (lset-union = . lists)
(check-arg procedure? = lset-union)
(reduce (lambda (lis ans) ; Compute ANS + LIS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(fold (lambda (elt ans) (if (any (lambda (x) (= x elt)) ans)
ans
(cons elt ans)))
ans lis))))
'() lists))
(define (lset-union! = . lists)
(check-arg procedure? = lset-union!)
(reduce (lambda (lis ans) ; Splice new elts of LIS onto the front of ANS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(pair-fold (lambda (pair ans)
(let ((elt (car pair)))
(if (any (lambda (x) (= x elt)) ans)
ans
(begin (set-cdr! pair ans) pair))))
ans lis))))
'() lists))
(define (lset-intersection = lis1 . lists)
(check-arg procedure? = lset-intersection)
(let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
(cond ((any null-list? lists) '()) ; Short cut
((null? lists) lis1) ; Short cut
(else (filter (lambda (x)
(every (lambda (lis) (member x lis =)) lists))
lis1)))))
(define (lset-intersection! = lis1 . lists)
(check-arg procedure? = lset-intersection!)
(let ((lists (delete lis1 lists eq?))) ; Throw out any LIS1 vals.
(cond ((any null-list? lists) '()) ; Short cut
((null? lists) lis1) ; Short cut
(else (filter! (lambda (x)
(every (lambda (lis) (member x lis =)) lists))
lis1)))))
(define (lset-difference = lis1 . lists)
(check-arg procedure? = lset-difference)
(let ((lists (filter pair? lists))) ; Throw out empty lists.
(cond ((null? lists) lis1) ; Short cut
((memq lis1 lists) '()) ; Short cut
(else (filter (lambda (x)
(every (lambda (lis) (not (member x lis =)))
lists))
lis1)))))
(define (lset-difference! = lis1 . lists)
(check-arg procedure? = lset-difference!)
(let ((lists (filter pair? lists))) ; Throw out empty lists.
(cond ((null? lists) lis1) ; Short cut
((memq lis1 lists) '()) ; Short cut
(else (filter! (lambda (x)
(every (lambda (lis) (not (member x lis =)))
lists))
lis1)))))
(define (lset-xor = . lists)
(check-arg procedure? = lset-xor)
(reduce (lambda (b a) ; Compute A xor B:
;; Note that this code relies on the constant-time
;; short-cuts provided by LSET-DIFF+INTERSECTION,
;; LSET-DIFFERENCE & APPEND to provide constant-time short
;; cuts for the cases A = (), B = (), and A eq? B. It takes
;; a careful case analysis to see it, but it's carefully
;; built in.
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection = a b)
(cond ((null? a-b) (lset-difference = b a))
((null? a-int-b) (append b a))
(else (fold (lambda (xb ans)
(if (member xb a-int-b =) ans (cons xb ans)))
a-b
b)))))
'() lists))
(define (lset-xor! = . lists)
(check-arg procedure? = lset-xor!)
(reduce (lambda (b a) ; Compute A xor B:
;; Note that this code relies on the constant-time
;; short-cuts provided by LSET-DIFF+INTERSECTION,
;; LSET-DIFFERENCE & APPEND to provide constant-time short
;; cuts for the cases A = (), B = (), and A eq? B. It takes
;; a careful case analysis to see it, but it's carefully
;; built in.
;; Compute a-b and a^b, then compute b-(a^b) and
;; cons it onto the front of a-b.
(receive (a-b a-int-b) (lset-diff+intersection! = a b)
(cond ((null? a-b) (lset-difference! = b a))
((null? a-int-b) (append! b a))
(else (pair-fold (lambda (b-pair ans)
(if (member (car b-pair) a-int-b =) ans
(begin (set-cdr! b-pair ans) b-pair)))
a-b
b)))))
'() lists))
(define (lset-diff+intersection = lis1 . lists)
(check-arg procedure? = lset-diff+intersection)
(cond ((every null-list? lists) (values lis1 '())) ; Short cut
((memq lis1 lists) (values '() lis1)) ; Short cut
(else (partition (lambda (elt)
(not (any (lambda (lis) (member elt lis =))
lists)))
lis1))))
(define (lset-diff+intersection! = lis1 . lists)
(check-arg procedure? = lset-diff+intersection!)
(cond ((every null-list? lists) (values lis1 '())) ; Short cut
((memq lis1 lists) (values '() lis1)) ; Short cut
(else (partition! (lambda (elt)
(not (any (lambda (lis) (member elt lis =))
lists)))
lis1))))
;;; Copyright (C) John Cowan 2013. All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-library (srfi 111)
(export box box? unbox set-box!)
(import (scheme base))
(begin
(define-record-type <box>
(box value)
box?
(value unbox set-box!))))
;; Copyright (C) Taylan Ulrich Bayırlı/Kammer (2015). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(define-library (srfi 17)
(export set! setter getter-with-setter)
(import
(rename (scheme base) (set! %set!))
(srfi 1))
(begin
(define-syntax set!
(syntax-rules ()
((_ (getter arg ...) val)
((setter getter) arg ... val))
((_ var val)
(%set! var val))))
(define setter
(let ((setters `((,car . ,set-car!)
(,cdr . ,set-cdr!)
(,caar . ,(lambda (p v) (set-car! (car p) v)))
(,cadr . ,(lambda (p v) (set-car! (cdr p) v)))
(,cdar . ,(lambda (p v) (set-cdr! (car p) v)))
(,cddr . ,(lambda (p v) (set-cdr! (cdr p) v)))
(,list-ref . ,list-set!)
(,vector-ref . ,vector-set!)
(,string-ref . ,string-set!)
(,bytevector-u8-ref . ,bytevector-u8-set!))))
(letrec ((setter
(lambda (proc)
(let ((probe (assv proc setters)))
(if probe
(cdr probe)
(error "No setter for " proc)))))
(set-setter!
(lambda (proc setter)
(set! setters (cons (cons proc setter) setters)))))
(set-setter! setter set-setter!)
setter)))
(define (getter-with-setter get set)
(let ((proc (lambda args (apply get args))))
(set! (setter proc) set)
proc))
))
;; Copyright (C) Taylan Ulrich Bayırlı/Kammer (2015). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;;; The SRFI claims that having the same variable appear multiple times is an
;;; error in let* and so also in and-let*. In fact let* allows rebinding the
;;; same variable, so we also allow it here.
(define-library (srfi 2)
(export and-let*)
(import (scheme base))
(begin
(define-syntax and-let*
(syntax-rules ()
;; Handle zero-clauses special-case.
((_ () . body)
(begin #t . body))
;; Reduce clauses down to one regardless of body.
((_ ((var expr) rest . rest*) . body)
(let ((var expr))
(and var (and-let* (rest . rest*) . body))))
((_ ((expr) rest . rest*) . body)
(and expr (and-let* (rest . rest*) . body)))
((_ (var rest . rest*) . body)
(begin
(let ((var #f)) #f) ;(identifier? var)
(and var (and-let* (rest . rest*) . body))))
;; Handle 1-clause cases without a body.
((_ ((var expr)))
expr)
((_ ((expr)))
expr)
((_ (var))
(begin
(let ((var #f)) #f) ;(identifier? var)
var))
;; Handle 1-clause cases with a body.
((_ ((var expr)) . body)
(let ((var expr))
(and var (begin . body))))
((_ ((expr)) . body)
(and expr (begin . body)))
((_ (var) . body)
(begin
(let ((var #f)) #f) ;(identifier? var)
(and var (begin . body))))))))
;;; Copyright (C) André van Tonder (2004). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;============================================================================================
; IMPLEMENTATION:
;
; Andre van Tonder, 2004.
;
;============================================================================================
(define-syntax define-record-type
(syntax-rules ()
((define-record-type . body)
(parse-declaration #f . body))))
(define-syntax define-record-scheme
(syntax-rules ()
((define-record-scheme . body)
(parse-declaration #t . body))))
(define-syntax parse-declaration
(syntax-rules ()
((parse-declaration is-scheme? (name super ...) constructor-clause predicate field-clause ...)
(build-record 0 constructor-clause (super ...) (field-clause ...) name predicate is-scheme?))
((parse-declaration is-scheme? (name super ...) constructor-clause)
(parse-declaration is-scheme? (name super ...) constructor-clause #f))
((parse-declaration is-scheme? (name super ...))
(parse-declaration is-scheme? (name super ...) #f #f))
((parse-declaration is-scheme? name . rest)
(parse-declaration is-scheme? (name) . rest))))
(define-syntax record-update!
(syntax-rules ()
((record-update! record name (label exp) ...)
(meta
`(let ((r record))
((meta ,(name ("setter") label)) r exp)
...
r)))))
(define-syntax record-update
(syntax-rules ()
((record-update record name (label exp) ...)
(name ("is-scheme?")
(meta
`(let ((new ((meta ,(name ("copier"))) record)))
(record-update! new name (label exp) ...)))
(record-compose (name record) (name (label exp) ...))))))
(define-syntax record-compose
(syntax-rules ()
((record-compose (export-name (label exp) ...))
(export-name (label exp) ...))
((record-compose (import-name record) ... (export-name (label exp) ...))
(help-compose 1 (import-name record) ... (export-name (label exp) ...)))))
(define-syntax help-compose
(syntax-rules ()
((help-compose 1 (import-name record) import ... (export-name (label exp) ...))
(meta
`(help-compose 2
(meta ,(intersection
(meta ,(export-name ("labels")))
(meta ,(remove-from (meta ,(import-name ("labels")))
(label ...)
if-free=))
if-free=))
(import-name record)
import ...
(export-name (label exp) ...))))
((help-compose 2 (copy-label ...) (import-name record) import ... (export-name . bindings))
(meta
`(let ((r record))
(record-compose import ...
(export-name (copy-label ((meta ,(import-name ("getter") copy-label)) r))
...
. bindings)))))))
(define-syntax build-record
(syntax-rules ()
((build-record 0 (constructor . pos-labels) . rest) ; extract positional labels from constructor clause
(build-record 1 (constructor . pos-labels) pos-labels . rest)) ;
((build-record 0 constructor . rest) ;
(build-record 1 (constructor . #f) () . rest)) ;
((build-record 1 constructor-clause (pos-label ...) (super ...)
((label . accessors) ...) . rest)
(meta
`(build-record 2
constructor-clause
(meta ,(union (meta ,(super ("labels"))) ; compute union of labels from supers,
... ; constructor clause and field clauses
(pos-label ...)
(label ...)
top:if-free=))
((label . accessors) ...)
(meta ,(union (meta ,(super ("supers"))) ; compute transitive union of supers
...
top:if-free=))
. rest)))
((build-record 2 (constructor . pos-labels) labels . rest) ; insert default constructor labels if not given
(syntax-if pos-labels
(build-record 3 (constructor . pos-labels) labels . rest)
(build-record 3 (constructor . labels) labels . rest)))
((build-record 3 constructor-clause labels ((label . accessors) ...) . rest)
(meta
`(build-record 4
(meta ,(remove-from labels ; separate the labels that do not appear in a
(label ...) ; field clause for next step
top:if-free=))
((label . accessors) ...)
constructor-clause
labels
. rest)))
((build-record 4
(undeclared-label ...)
(field-clause ...)
(constructor . pos-labels)
labels
supers
name
predicate
is-scheme?)
(meta
`(build-record 5 ; generate identifiers for constructor, predicate
is-scheme? ; getters and setters as needed
name
supers
supers
labels
(meta ,(to-identifier constructor))
(meta ,(add-temporaries pos-labels)) ; needed for constructor below
(meta ,(to-identifier predicate))
(meta ,(augment-field field-clause))
...
(undeclared-label (meta ,(generate-identifier))
(meta ,(generate-identifier)))
...)))
((build-record 5
is-scheme?
name
(super ...)
supers
(label ...)
constructor
((pos-label pos-temp) ...)
predicate
(field-label getter setter)
...)
(begin
(syntax-if is-scheme?
(begin
(define-generic (predicate x) (lambda (x) #f))
(define-generic (getter x))
...
(define-generic (setter x v))
...
(define-generic (copy x)))
(begin
(srfi-9:define-record-type internal-name
(maker field-label ...)
predicate
(field-label getter setter) ...)
(define constructor
(lambda (pos-temp ...)
(populate 1 maker (field-label ...) (pos-label pos-temp) ...)))
(extend-predicates supers predicate)
(extend-accessors supers field-label predicate getter setter)
...
(define (copy x)
(maker (getter x) ...))
(extend-copiers supers copy predicate)
(define-method (show (r predicate))
(list 'name
(list 'field-label (getter r))
...))))
(define-syntax name
(syntax-rules (field-label ...)
((name ("is-scheme?") sk fk) (syntax-if is-scheme? sk fk))
((name ("predicate") k) (syntax-apply k predicate))
((name ("supers") k) (syntax-apply k (super ... name)))
((name ("labels") k) (syntax-apply k (label ...)))
((name ("pos-labels") k) (syntax-apply k (pos-label ...)))
((name ("getter") field-label k) (syntax-apply k getter))
...
((name ("getter") other k) (syntax-apply k #f))
((name ("setter") field-label k) (syntax-apply k setter))
...
((name ("setter") other k) (syntax-apply k #f))
((name ("copier") k) (syntax-apply k copy))
((name . bindings) (populate 1 maker (field-label ...) . bindings))))))))
(define-syntax to-identifier
(syntax-rules ()
((to-identifier #f k) (syntax-apply k generated-identifier))
((to-identifier id k) (syntax-apply k id))))
(define-syntax augment-field
(syntax-rules ()
((augment-field (label) k) (syntax-apply k (label generated-getter generated-setter)))
((augment-field (label getter) k) (meta `(label (meta ,(to-identifier getter)) generated-setter) k))
((augment-field (label getter setter) k) (meta `(label (meta ,(to-identifier getter))
(meta ,(to-identifier setter))) k))))
(define-syntax extend-predicates
(syntax-rules ()
((extend-predicates (super ...) predicate)
(begin
(meta
`(define-method (meta ,(super ("predicate")))
(predicate)
(x)
any?))
...))))
(define-syntax extend-copiers
(syntax-rules ()
((extend-copiers (super ...) copy predicate)
(begin
(meta
`(define-method (meta ,(super ("copier")))
(predicate)
(x)
copy))
...))))
(define-syntax extend-accessors
(syntax-rules ()
((extend-accessors (super ...) label predicate selector modifier)
(meta
`(begin
(syntax-if (meta ,(super ("getter") label))
(define-method (meta ,(super ("getter") label))
(predicate)
(x)
selector)
(begin))
...
(syntax-if (meta ,(super ("setter") label))
(define-method (meta ,(super ("setter") label))
(predicate any?)
(x v)
modifier)
(begin))
...)))))
(define-syntax populate
(syntax-rules ()
((populate 1 maker labels . bindings)
(meta
`(populate 2 maker
(meta ,(order labels bindings ('<undefined>))))))
((populate 2 maker ((label exp) ...))
(maker exp ...))))
(define-syntax order
(syntax-rules ()
((order (label ...) ((label* . binding) ...) default k)
(meta
`(if-empty? (meta ,(remove-from (label* ...)
(label ...)
if-free=))
(order "emit" (label ...) ((label* . binding) ...) default k)
(syntax-error "Illegal labels in" ((label* . binding) ...)
"Legal labels are" (label ...)))))
((order "emit" (label ...) bindings default k)
(meta
`((label . (meta ,(syntax-lookup label
bindings
if-free=
default)))
...)
k))))
;============================================================================================
; Simple generic functions:
(define-syntax define-generic
(syntax-rules ()
((define-generic (name arg ...))
(define-generic (name arg ...)
(lambda (arg ...) (error "Inapplicable method:" 'name
"Arguments:" (show arg) ... ))))
((define-generic (name arg ...) proc)
(define name (make-generic (arg ...) proc)))))
(define-syntax define-method
(syntax-rules ()
((define-method (generic (arg pred?) ...) . body)
(define-method generic (pred? ...) (arg ...) (lambda (arg ...) . body)))
((define-method generic (pred? ...) (arg ...) procedure)
(let ((next ((generic) 'get-proc))
(proc procedure))
(((generic) 'set-proc)
(lambda (arg ...)
(if (and (pred? arg) ...)
(proc arg ...)
(next arg ...))))))))
(define-syntax make-generic
(syntax-rules ()
((make-generic (arg arg+ ...) default-proc)
(let ((proc default-proc))
(case-lambda
((arg arg+ ...)
(proc arg arg+ ...))
(()
(lambda (msg)
(case msg
((get-proc) proc)
((set-proc) (lambda (new)
(set! proc new)))))))))))
(define-generic (show x)
(lambda (x) x))
(define (any? x) #t)
;============================================================================================
; Syntax utilities:
(define-syntax syntax-error
(syntax-rules ()))
(define-syntax syntax-apply
(syntax-rules ()
((syntax-apply (f . args) exp ...)
(f exp ... . args))))
(define-syntax syntax-cons
(syntax-rules ()
((syntax-cons x rest k)
(syntax-apply k (x . rest)))))
(define-syntax syntax-cons-after
(syntax-rules ()
((syntax-cons-after rest x k)
(syntax-apply k (x . rest)))))
(define-syntax if-empty?
(syntax-rules ()
((if-empty? () sk fk) sk)
((if-empty? (h . t) sk fk) fk)))
(define-syntax add-temporaries
(syntax-rules ()
((add-temporaries lst k) (add-temporaries lst () k))
((add-temporaries () lst-temps k) (syntax-apply k lst-temps))
((add-temporaries (h . t) (done ...) k) (add-temporaries t (done ... (h temp)) k))))
(define-syntax if-free=
(syntax-rules ()
((if-free= x y kt kf)
(let-syntax
((test (syntax-rules (x)
((test x kt* kf*) kt*)
((test z kt* kf*) kf*))))
(test y kt kf)))))
(define-syntax top:if-free=
(syntax-rules ()
((top:if-free= x y kt kf)
(begin
(define-syntax if-free=:test
(syntax-rules (x)
((if-free=:test x kt* kf*) kt*)
((if-free=:test z kt* kf*) kf*)))
(if-free=:test y kt kf)))))
(define-syntax meta
(syntax-rules (meta quasiquote unquote)
((meta `(meta ,(function argument ...)) k)
(meta `(argument ...) (syntax-apply-to function k)))
((meta `(a . b) k)
(meta `a (descend-right b k)))
((meta `whatever k) (syntax-apply k whatever))
((meta `arg)
(meta `arg (syntax-id)))))
(define-syntax syntax-apply-to
(syntax-rules ()
((syntax-apply-to (argument ...) function k)
(function argument ... k))))
(define-syntax descend-right
(syntax-rules ()
((descend-right evaled b k)
(meta `b (syntax-cons-after evaled k)))))
(define-syntax syntax-id
(syntax-rules ()
((syntax-id arg) arg)))
(define-syntax remove-duplicates
(syntax-rules ()
((remove-duplicates lst compare? k)
(remove-duplicates lst () compare? k))
((remove-duplicates () done compare? k)
(syntax-apply k done))
((remove-duplicates (h . t) (d ...) compare? k)
(if-member? h (d ...) compare?
(remove-duplicates t (d ...) compare? k)
(remove-duplicates t (d ... h) compare? k)))))
(define-syntax syntax-filter
(syntax-rules ()
((syntax-filter () (if-p? arg ...) k)
(syntax-apply k ()))
((syntax-filter (h . t) (if-p? arg ...) k)
(if-p? h arg ...
(syntax-filter t (if-p? arg ...) (syntax-cons-after h k))
(syntax-filter t (if-p? arg ...) k)))))
(define-syntax if-member?
(syntax-rules ()
((if-member? x () compare? sk fk)
fk)
((if-member? x (h . t) compare? sk fk)
(compare? x h
sk
(if-member? x t compare? sk fk)))))
(define-syntax union
(syntax-rules ()
((union (x ...) ... compare? k)
(remove-duplicates (x ... ...) compare? k))))
(define-syntax intersection
(syntax-rules ()
((intersection list1 list2 compare? k)
(syntax-filter list1 (if-member? list2 compare?) k))))
(define-syntax remove-from
(syntax-rules ()
((remove-from list1 list2 compare? k)
(syntax-filter list1 (if-not-member? list2 compare?) k))))
(define-syntax if-not-member?
(syntax-rules ()
((if-not-member? x list compare? sk fk)
(if-member? x list compare? fk sk))))
(define-syntax generate-identifier
(syntax-rules ()
((generate-identifier k) (syntax-apply k generated-identifier))))
(define-syntax syntax-if
(syntax-rules ()
((syntax-if #f sk fk) fk)
((syntax-if other sk fk) sk)))
(define-syntax syntax-lookup
(syntax-rules ()
((syntax-lookup label () compare fail k)
(syntax-apply k fail))
((syntax-lookup label ((label* . value) . bindings) compare fail k)
(compare label label*
(syntax-apply k value)
(syntax-lookup label bindings compare fail k)))))
;;; array as-srfi-9-record
;;; 2001 Jussi Piitulainen
;;; Untested.
(define-record-type
array:srfi-9-record-type-descriptor
(array:make vec ind shp)
array:array?
(vec array:vector)
(ind array:index)
(shp array:shape))
(define-library (srfi 60)
(export
;; Bitwise Operations
logand
bitwise-and
logior
bitwise-ior
logxor
bitwise-xor
lognot
bitwise-not
bitwise-if
bitwise-merge
logtest
any-bits-set?
;; Integer Properties
logcount
bit-count
integer-length
log2-binary-factors
first-set-bit
;; Bit Within Word
logbit?
bit-set?
copy-bit
;; Field of Bits
bit-field
copy-bit-field
ash
arithmetic-shift
rotate-bit-field
reverse-bit-field
;; Bits as Booleans
integer->list
list->integer
booleans->integer
)
(import (scheme base))
(include "60.upstream.scm"))
;;; Copyright (C) Jussi Piitulainen (2001). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define (array-ref a . xs)
(or (array:array? a)
(error "not an array"))
(let ((shape (array:shape a)))
(if (null? xs)
(array:check-indices "array-ref" xs shape)
(let ((x (car xs)))
(if (vector? x)
(array:check-index-vector "array-ref" x shape)
(if (integer? x)
(array:check-indices "array-ref" xs shape)
(if (array:array? x)
(array:check-index-actor "array-ref" x shape)
(error "not an index object"))))))
(vector-ref
(array:vector a)
(if (null? xs)
(vector-ref (array:index a) 0)
(let ((x (car xs)))
(if (vector? x)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(if (integer? x)
(array:vector-index (array:index a) xs)
(if (array:array? x)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(error "array-ref: bad index object")))))))))
(define (array-set! a x . xs)
(or (array:array? a)
(error "array-set!: not an array"))
(let ((shape (array:shape a)))
(if (null? xs)
(array:check-indices "array-set!" '() shape)
(if (vector? x)
(array:check-index-vector "array-set!" x shape)
(if (integer? x)
(array:check-indices.o "array-set!" (cons x xs) shape)
(if (array:array? x)
(array:check-index-actor "array-set!" x shape)
(error "not an index object")))))
(if (null? xs)
(vector-set! (array:vector a) (vector-ref (array:index a) 0) x)
(if (vector? x)
(vector-set! (array:vector a)
(array:index/vector
(quotient (vector-length shape) 2)
(array:index a)
x)
(car xs))
(if (integer? x)
(let ((v (array:vector a))
(i (array:index a))
(r (quotient (vector-length shape) 2)))
(do ((sum (* (vector-ref i 0) x)
(+ sum (* (vector-ref i k) (car ks))))
(ks xs (cdr ks))
(k 1 (+ k 1)))
((= k r)
(vector-set! v (+ sum (vector-ref i k)) (car ks)))))
(if (array:array? x)
(vector-set! (array:vector a)
(array:index/array
(quotient (vector-length shape) 2)
(array:index a)
(array:vector x)
(array:index x))
(car xs))
(error (string-append
"array-set!: bad index object: "
(array:thing->string x)))))))))
(define-library (srfi 63)
(export
array?
equal?
array-rank
array-dimensions
make-array
make-shared-array
list->array
array->list
vector->array
array->vector
array-in-bounds?
array-ref
array-set!
a:floc128b
a:floc64b
a:floc32b
a:floc16b
a:flor128b
a:flor64b
a:flor32b
a:flor16b
a:fixz64b
a:fixz32b
a:fixz16b
a:fixz8b
a:fixn64b
a:fixn32b
a:fixn16b
a:fixn8b
a:bool
)
(import (except (scheme base) equal?))
(include "63.body.scm"))
;;; array
;;; 1997 - 2001 Jussi Piitulainen
;;; --- Intro ---
;;; This interface to arrays is based on Alan Bawden's array.scm of
;;; 1993 (earlier version in the Internet Repository and another
;;; version in SLIB). This is a complete rewrite, to be consistent
;;; with the rest of Scheme and to make arrays independent of lists.
;;; Some modifications are due to discussion in srfi-25 mailing list.
;;; (array? obj)
;;; (make-array shape [obj]) changed arguments
;;; (shape bound ...) new
;;; (array shape obj ...) new
;;; (array-rank array) changed name back
;;; (array-start array dimension) new
;;; (array-end array dimension) new
;;; (array-ref array k ...)
;;; (array-ref array index) new variant
;;; (array-set! array k ... obj) changed argument order
;;; (array-set! array index obj) new variant
;;; (share-array array shape proc) changed arguments
;;; All other variables in this file have names in "array:".
;;; Should there be a way to make arrays with initial values mapped
;;; from indices? Sure. The current "initial object" is lame.
;;;
;;; Removed (array-shape array) from here. There is a new version
;;; in arlib though.
;;; --- Representation type dependencies ---
;;; The mapping from array indices to the index to the underlying vector
;;; is whatever array:optimize returns. The file "opt" provides three
;;; representations:
;;;
;;; mbda) mapping is a procedure that allows an optional argument
;;; tter) mapping is two procedures that takes exactly the indices
;;; ctor) mapping is a vector of a constant term and coefficients
;;;
;;; Choose one in "opt" to make the optimizer. Then choose the matching
;;; implementation of array-ref and array-set!.
;;;
;;; These should be made macros to inline them. Or have a good compiler
;;; and plant the package as a module.
;;; 1. Pick an optimizer.
;;; 2. Pick matching index representation.
;;; 3. Pick a record implementation; as-procedure is generic; syntax inlines.
;;; 3. This file is otherwise portable.
;;; --- Portable R5RS (R4RS and multiple values) ---
;;; (array? obj)
;;; returns #t if `obj' is an array and #t or #f otherwise.
(define (array? obj)
(array:array? obj))
;;; (make-array shape)
;;; (make-array shape obj)
;;; makes array of `shape' with each cell containing `obj' initially.
(define (make-array shape . rest)
(or (array:good-shape? shape)
(error "make-array: shape is not a shape"))
(apply array:make-array shape rest))
(define (array:make-array shape . rest)
(let ((size (array:size shape)))
(array:make
(if (pair? rest)
(apply (lambda (o) (make-vector size o)) rest)
(make-vector size))
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape))))
;;; (shape bound ...)
;;; makes a shape. Bounds must be an even number of exact, pairwise
;;; non-decreasing integers. Note that any such array can be a shape.
(define (shape . bounds)
(let ((v (list->vector bounds)))
(or (even? (vector-length v))
(error (string-append "shape: uneven number of bounds: "
(array:list->string bounds))))
(let ((shp (array:make
v
(if (pair? bounds)
(array:shape-index)
(array:empty-shape-index))
(vector 0 (quotient (vector-length v) 2)
0 2))))
(or (array:good-shape? shp)
(error (string-append "shape: bounds are not pairwise "
"non-decreasing exact integers: "
(array:list->string bounds))))
shp)))
;;; (array shape obj ...)
;;; is analogous to `vector'.
(define (array shape . elts)
(or (array:good-shape? shape)
(error (string-append "array: shape " (array:thing->string shape)
" is not a shape")))
(let ((size (array:size shape)))
(let ((vector (list->vector elts)))
(or (= (vector-length vector) size)
(error (string-append "array: an array of shape "
(array:shape-vector->string
(array:vector shape))
" has "
(number->string size)
" elements but got "
(number->string (vector-length vector))
" values: "
(array:list->string elts))))
(array:make
vector
(if (= size 0)
(array:optimize-empty
(vector-ref (array:shape shape) 1))
(array:optimize
(array:make-index shape)
(vector-ref (array:shape shape) 1)))
(array:shape->vector shape)))))
;;; (array-rank array)
;;; returns the number of dimensions of `array'.
(define (array-rank array)
(quotient (vector-length (array:shape array)) 2))
;;; (array-start array k)
;;; returns the lower bound index of array along dimension k. This is
;;; the least valid index along that dimension if the dimension is not
;;; empty.
(define (array-start array d)
(vector-ref (array:shape array) (+ d d)))
;;; (array-end array k)
;;; returns the upper bound index of array along dimension k. This is
;;; not a valid index. If the dimension is empty, this is the same as
;;; the lower bound along it.
(define (array-end array d)
(vector-ref (array:shape array) (+ d d 1)))
;;; (share-array array shape proc)
;;; makes an array that shares elements of `array' at shape `shape'.
;;; The arguments to `proc' are indices of the result. The values of
;;; `proc' are indices of `array'.
;;; Todo: in the error message, should recognise the mapping and show it.
(define (share-array array subshape f)
(or (array:good-shape? subshape)
(error (string-append "share-array: shape "
(array:thing->string subshape)
" is not a shape")))
(let ((subsize (array:size subshape)))
(or (array:good-share? subshape subsize f (array:shape array))
(error (string-append "share-array: subshape "
(array:shape-vector->string
(array:vector subshape))
" does not map into supershape "
(array:shape-vector->string
(array:shape array))
" under mapping "
(array:map->string
f
(vector-ref (array:shape subshape) 1)))))
(let ((g (array:index array)))
(array:make
(array:vector array)
(if (= subsize 0)
(array:optimize-empty
(vector-ref (array:shape subshape) 1))
(array:optimize
(lambda ks
(call-with-values
(lambda () (apply f ks))
(lambda ks (array:vector-index g ks))))
(vector-ref (array:shape subshape) 1)))
(array:shape->vector subshape)))))
;;; --- Hrmph ---
;;; (array:share/index! ...)
;;; reuses a user supplied index object when recognising the
;;; mapping. The mind balks at the very nasty side effect that
;;; exposes the implementation. So this is not in the spec.
;;; But letting index objects in at all creates a pressure
;;; to go the whole hog. Arf.
;;; Use array:optimize-empty for an empty array to get a
;;; clearly invalid vector index.
;;; Surely it's perverse to use an actor for index here? But
;;; the possibility is provided for completeness.
(define (array:share/index! array subshape proc index)
(array:make
(array:vector array)
(if (= (array:size subshape) 0)
(array:optimize-empty
(quotient (vector-length (array:shape array)) 2))
((if (vector? index)
array:optimize/vector
array:optimize/actor)
(lambda (subindex)
(let ((superindex (proc subindex)))
(if (vector? superindex)
(array:index/vector
(quotient (vector-length (array:shape array)) 2)
(array:index array)
superindex)
(array:index/array
(quotient (vector-length (array:shape array)) 2)
(array:index array)
(array:vector superindex)
(array:index superindex)))))
index))
(array:shape->vector subshape)))
(define (array:optimize/vector f v)
(let ((r (vector-length v)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v k 0))
(let ((n0 (f v))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1)))
(vector-set! v k 1)
(let ((nk (- (f v) n0)))
(vector-set! v k 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
(define (array:optimize/actor f a)
(let ((r (array-end a 0))
(v (array:vector a))
(i (array:index a)))
(do ((k 0 (+ k 1)))
((= k r))
(vector-set! v (array:actor-index i k) 0))
(let ((n0 (f a))
(cs (make-vector (+ r 1)))
(apply (array:applier-to-vector (+ r 1))))
(vector-set! cs 0 n0)
(let wok ((k 0))
(if (< k r)
(let ((k1 (+ k 1))
(t (array:actor-index i k)))
(vector-set! v t 1)
(let ((nk (- (f a) n0)))
(vector-set! v t 0)
(vector-set! cs k1 nk)
(wok k1)))))
(apply (array:maker r) cs))))
;;; --- Internals ---
(define (array:shape->vector shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(let ((vec (make-vector (* rnk 2))))
(do ((k 0 (+ k 1)))
((= k rnk)
vec)
(vector-set! vec (+ k k)
(vector-ref shv (array:shape-vector-index idx k 0)))
(vector-set! vec (+ k k 1)
(vector-ref shv (array:shape-vector-index idx k 1)))))))
;;; (array:size shape)
;;; returns the number of elements in arrays of shape `shape'.
(define (array:size shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((k 0 (+ k 1))
(s 1 (* s
(- (vector-ref shv (array:shape-vector-index idx k 1))
(vector-ref shv (array:shape-vector-index idx k 0))))))
((= k rnk) s))))
;;; (array:make-index shape)
;;; returns an index function for arrays of shape `shape'. This is a
;;; runtime composition of several variable arity procedures, to be
;;; passed to array:optimize for recognition as an affine function of
;;; as many variables as there are dimensions in arrays of this shape.
(define (array:make-index shape)
(let ((idx (array:index shape))
(shv (array:vector shape))
(rnk (vector-ref (array:shape shape) 1)))
(do ((f (lambda () 0)
(lambda (k . ks)
(+ (* s (- k (vector-ref
shv
(array:shape-vector-index idx (- j 1) 0))))
(apply f ks))))
(s 1 (* s (- (vector-ref
shv
(array:shape-vector-index idx (- j 1) 1))
(vector-ref
shv
(array:shape-vector-index idx (- j 1) 0)))))
(j rnk (- j 1)))
((= j 0)
f))))
;;; --- Error checking ---
;;; (array:good-shape? shape)
;;; returns true if `shape' is an array of the right shape and its
;;; elements are exact integers that pairwise bound intervals `[lo..hi)´.
(define (array:good-shape? shape)
(and (array:array? shape)
(let ((u (array:shape shape))
(v (array:vector shape))
(x (array:index shape)))
(and (= (vector-length u) 4)
(= (vector-ref u 0) 0)
(= (vector-ref u 2) 0)
(= (vector-ref u 3) 2))
(let ((p (vector-ref u 1)))
(do ((k 0 (+ k 1))
(true #t (let ((lo (vector-ref
v
(array:shape-vector-index x k 0)))
(hi (vector-ref
v
(array:shape-vector-index x k 1))))
(and true
(integer? lo)
(exact? lo)
(integer? hi)
(exact? hi)
(<= lo hi)))))
((= k p) true))))))
;;; (array:good-share? subv subsize mapping superv)
;;; returns true if the extreme indices in the subshape vector map
;;; into the bounds in the supershape vector.
;;; If some interval in `subv' is empty, then `subv' is empty and its
;;; image under `f' is empty and it is trivially alright. One must
;;; not call `f', though.
(define (array:good-share? subshape subsize f super)
(or (zero? subsize)
(letrec
((sub (array:vector subshape))
(dex (array:index subshape))
(ck (lambda (k ks)
(if (zero? k)
(call-with-values
(lambda () (apply f ks))
(lambda qs (array:good-indices? qs super)))
(and (ck (- k 1)
(cons (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
0))
ks))
(ck (- k 1)
(cons (- (vector-ref
sub
(array:shape-vector-index
dex
(- k 1)
1))
1)
ks)))))))
(let ((rnk (vector-ref (array:shape subshape) 1)))
(or (array:unchecked-share-depth? rnk)
(ck rnk '()))))))
;;; Check good-share on 10 dimensions at most. The trouble is,
;;; the cost of this check is exponential in the number of dimensions.
(define (array:unchecked-share-depth? rank)
(if (> rank 10)
(begin
(display `(warning unchecked depth in share
,rank subdimensions))
(newline)
#t)
#f))
;;; (array:check-indices caller indices shape-vector)
;;; (array:check-indices.o caller indices shape-vector)
;;; (array:check-index-vector caller index-vector shape-vector)
;;; return if the index is in bounds, else signal error.
;;;
;;; Shape-vector is the internal representation, with
;;; b and e for dimension k at 2k and 2k + 1.
(define (array:check-indices who ks shv)
(or (array:good-indices? ks shv)
(error (array:not-in who ks shv))))
(define (array:check-indices.o who ks shv)
(or (array:good-indices.o? ks shv)
(error (array:not-in who (reverse (cdr (reverse ks))) shv))))
(define (array:check-index-vector who ks shv)
(or (array:good-index-vector? ks shv)
(error (array:not-in who (vector->list ks) shv))))
(define (array:check-index-actor who ks shv)
(let ((shape (array:shape ks)))
(or (and (= (vector-length shape) 2)
(= (vector-ref shape 0) 0))
(error "not an actor"))
(or (array:good-index-actor?
(vector-ref shape 1)
(array:vector ks)
(array:index ks)
shv)
(array:not-in who (do ((k (vector-ref shape 1) (- k 1))
(m '() (cons (vector-ref
(array:vector ks)
(array:actor-index
(array:index ks)
(- k 1)))
m)))
((= k 0) m))
shv))))
(define (array:good-indices? ks shv)
(let ((d2 (vector-length shv)))
(do ((kp ks (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (null? kp))))))
(define (array:good-indices.o? ks.o shv)
(let ((d2 (vector-length shv)))
(do ((kp ks.o (if (pair? kp)
(cdr kp)))
(k 0 (+ k 2))
(true #t (and true (pair? kp)
(array:good-index? (car kp) shv k))))
((= k d2)
(and true (pair? kp) (null? (cdr kp)))))))
(define (array:good-index-vector? ks shv)
(let ((r2 (vector-length shv)))
(and (= (* 2 (vector-length ks)) r2)
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref ks j) shv k))))
((= k r2) true)))))
(define (array:good-index-actor? r v i shv)
(and (= (* 2 r) (vector-length shv))
(do ((j 0 (+ j 1))
(k 0 (+ k 2))
(true #t (and true
(array:good-index? (vector-ref
v
(array:actor-index i j))
shv
k))))
((= j r) true))))
;;; (array:good-index? index shape-vector 2d)
;;; returns true if index is within bounds for dimension 2d/2.
(define (array:good-index? w shv k)
(and (integer? w)
(exact? w)
(<= (vector-ref shv k) w)
(< w (vector-ref shv (+ k 1)))))
(define (array:not-in who ks shv)
(let ((index (array:list->string ks))
(bounds (array:shape-vector->string shv)))
(error (string-append who
": index " index
" not in bounds " bounds))))
(define (array:list->string ks)
(do ((index "" (string-append index (array:thing->string (car ks)) " "))
(ks ks (cdr ks)))
((null? ks) index)))
(define (array:shape-vector->string shv)
(do ((bounds "" (string-append bounds
"["
(number->string (vector-ref shv t))
".."
(number->string (vector-ref shv (+ t 1)))
")"
" "))
(t 0 (+ t 2)))
((= t (vector-length shv)) bounds)))
(define (array:thing->string thing)
(cond
((number? thing) (number->string thing))
((symbol? thing) (string-append "#<symbol>" (symbol->string thing)))
((char? thing) "#<char>")
((string? thing) "#<string>")
((list? thing) (string-append "#" (number->string (length thing))
"<list>"))
((pair? thing) "#<pair>")
((array? thing) "#<array>")
((vector? thing) (string-append "#" (number->string
(vector-length thing))
"<vector>"))
((procedure? thing) "#<procedure>")
(else
(case thing
((()) "()")
((#t) "#t")
((#f) "#f")
(else
"#<whatsit>")))))
;;; And to grok an affine map, vector->vector type. Column k of arr
;;; will contain coefficients n0 ... nm of 1 k1 ... km for kth value.
;;;
;;; These are for the error message when share fails.
(define (array:index-ref ind k)
(if (vector? ind)
(vector-ref ind k)
(vector-ref
(array:vector ind)
(array:actor-index (array:index ind) k))))
(define (array:index-set! ind k o)
(if (vector? ind)
(vector-set! ind k o)
(vector-set!
(array:vector ind)
(array:actor-index (array:index ind) k)
o)))
(define (array:index-length ind)
(if (vector? ind)
(vector-length ind)
(vector-ref (array:shape ind) 1)))
(define (array:map->string proc r)
(let* ((m (array:grok/arguments proc r))
(s (vector-ref (array:shape m) 3)))
(do ((i "" (string-append i c "k" (number->string k)))
(c "" ", ")
(k 1 (+ k 1)))
((< r k)
(do ((o "" (string-append o c (array:map-column->string m r k)))
(c "" ", ")
(k 0 (+ k 1)))
((= k s)
(string-append i " => " o)))))))
(define (array:map-column->string m r k)
(let ((v (array:vector m))
(i (array:index m)))
(let ((n0 (vector-ref v (array:vector-index i (list 0 k)))))
(let wok ((j 1)
(e (if (= n0 0) "" (number->string n0))))
(if (<= j r)
(let ((nj (vector-ref v (array:vector-index i (list j k)))))
(if (= nj 0)
(wok (+ j 1) e)
(let* ((nj (if (= nj 1) ""
(if (= nj -1) "-"
(string-append (number->string nj)
" "))))
(njkj (string-append nj "k" (number->string j))))
(if (string=? e "")
(wok (+ j 1) njkj)
(wok (+ j 1) (string-append e " + " njkj))))))
(if (string=? e "") "0" e))))))
(define (array:grok/arguments proc r)
(array:grok/index!
(lambda (vec)
(call-with-values
(lambda ()
(array:apply-to-vector r proc vec))
vector))
(make-vector r)))
(define (array:grok/index! proc in)
(let ((m (array:index-length in)))
(do ((k 0 (+ k 1)))
((= k m))
(array:index-set! in k 0))
(let* ((n0 (proc in))
(n (array:index-length n0)))
(let ((arr (make-array (shape 0 (+ m 1) 0 n)))) ; (*)
(do ((k 0 (+ k 1)))
((= k n))
(array-set! arr 0 k (array:index-ref n0 k))) ; (**)
(do ((j 0 (+ j 1)))
((= j m))
(array:index-set! in j 1)
(let ((nj (proc in)))
(array:index-set! in j 0)
(do ((k 0 (+ k 1)))
((= k n))
(array-set! arr (+ j 1) k (- (array:index-ref nj k) ; (**)
(array:index-ref n0 k))))))
arr))))
;; (*) Should not use `make-array' and `shape' here
;; (**) Should not use `array-set!' here
;; Should use something internal to the library instead: either lower
;; level code (preferable but complex) or alternative names to these same.
;; Copyright (C) John David Stone (1999). All Rights Reserved.
;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-library (srfi 8)
(export receive)
(import (scheme base))
(begin
(define-syntax receive
(syntax-rules ()
((receive formals expression body ...)
(call-with-values (lambda () expression)
(lambda formals body ...)))))))
;;; Copyright (C) Jussi Piitulainen (2001). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(begin
(define array:opt-args '(ctor (4)))
(define (array:optimize f r)
(case r
((0) (let ((n0 (f))) (array:0 n0)))
((1) (let ((n0 (f 0))) (array:1 n0 (- (f 1) n0))))
((2)
(let ((n0 (f 0 0)))
(array:2 n0 (- (f 1 0) n0) (- (f 0 1) n0))))
((3)
(let ((n0 (f 0 0 0)))
(array:3
n0
(- (f 1 0 0) n0)
(- (f 0 1 0) n0)
(- (f 0 0 1) n0))))
(else
(let ((v
(do ((k 0 (+ k 1)) (v '() (cons 0 v)))
((= k r) v))))
(let ((n0 (apply f v)))
(apply
array:n
n0
(array:coefficients f n0 v v)))))))
(define (array:optimize-empty r)
(let ((x (make-vector (+ r 1) 0)))
(vector-set! x r -1)
x))
(define (array:coefficients f n0 vs vp)
(case vp
((()) '())
(else
(set-car! vp 1)
(let ((n (- (apply f vs) n0)))
(set-car! vp 0)
(cons n (array:coefficients f n0 vs (cdr vp)))))))
(define (array:vector-index x ks)
(do ((sum 0 (+ sum (* (vector-ref x k) (car ks))))
(ks ks (cdr ks))
(k 0 (+ k 1)))
((null? ks) (+ sum (vector-ref x k)))))
(define (array:shape-index) '#(2 1 0))
(define (array:empty-shape-index) '#(0 0 -1))
(define (array:shape-vector-index x r k)
(+
(* (vector-ref x 0) r)
(* (vector-ref x 1) k)
(vector-ref x 2)))
(define (array:actor-index x k)
(+ (* (vector-ref x 0) k) (vector-ref x 1)))
(define (array:0 n0) (vector n0))
(define (array:1 n0 n1) (vector n1 n0))
(define (array:2 n0 n1 n2) (vector n1 n2 n0))
(define (array:3 n0 n1 n2 n3) (vector n1 n2 n3 n0))
(define (array:n n0 n1 n2 n3 n4 . ns)
(apply vector n1 n2 n3 n4 (append ns (list n0))))
(define (array:maker r)
(case r
((0) array:0)
((1) array:1)
((2) array:2)
((3) array:3)
(else array:n)))
(define array:indexer/vector
(let ((em
(vector
(lambda (x i) (+ (vector-ref x 0)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(vector-ref x 1)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(vector-ref x 2)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(vector-ref x 3)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(vector-ref x 4)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(vector-ref x 5)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(vector-ref x 6)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(vector-ref x 7)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(vector-ref x 8)))
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x i)
(+
(* (vector-ref x 0) (vector-ref i 0))
(* (vector-ref x 1) (vector-ref i 1))
(* (vector-ref x 2) (vector-ref i 2))
(* (vector-ref x 3) (vector-ref i 3))
(* (vector-ref x 4) (vector-ref i 4))
(* (vector-ref x 5) (vector-ref i 5))
(* (vector-ref x 6) (vector-ref i 6))
(* (vector-ref x 7) (vector-ref i 7))
(* (vector-ref x 8) (vector-ref i 8))
(* (vector-ref x 9) (vector-ref i 9))
(do ((xi
0
(+
(* (vector-ref x u) (vector-ref i u))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:indexer/array
(let ((em
(vector
(lambda (x v i) (+ (vector-ref x 0)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(vector-ref x 1)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(vector-ref x 2)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(vector-ref x 3)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(vector-ref x 4)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(vector-ref x 5)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(vector-ref x 6)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(vector-ref x 7)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(vector-ref x 8)))
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(vector-ref x 9)))))
(it
(lambda (w)
(lambda (x v i)
(+
(*
(vector-ref x 0)
(vector-ref v (array:actor-index i 0)))
(*
(vector-ref x 1)
(vector-ref v (array:actor-index i 1)))
(*
(vector-ref x 2)
(vector-ref v (array:actor-index i 2)))
(*
(vector-ref x 3)
(vector-ref v (array:actor-index i 3)))
(*
(vector-ref x 4)
(vector-ref v (array:actor-index i 4)))
(*
(vector-ref x 5)
(vector-ref v (array:actor-index i 5)))
(*
(vector-ref x 6)
(vector-ref v (array:actor-index i 6)))
(*
(vector-ref x 7)
(vector-ref v (array:actor-index i 7)))
(*
(vector-ref x 8)
(vector-ref v (array:actor-index i 8)))
(*
(vector-ref x 9)
(vector-ref v (array:actor-index i 9)))
(do ((xi
0
(+
(*
(vector-ref x u)
(vector-ref
v
(array:actor-index i u)))
xi))
(u (- w 1) (- u 1)))
((< u 10) xi))
(vector-ref x w))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-vector
(let ((em
(vector
(lambda (p v) (p))
(lambda (p v) (p (vector-ref v 0)))
(lambda (p v)
(p (vector-ref v 0) (vector-ref v 1)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)))
(lambda (p v)
(p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)))))
(it
(lambda (r)
(lambda (p v)
(apply
p
(vector-ref v 0)
(vector-ref v 1)
(vector-ref v 2)
(vector-ref v 3)
(vector-ref v 4)
(vector-ref v 5)
(vector-ref v 6)
(vector-ref v 7)
(vector-ref v 8)
(vector-ref v 9)
(do ((k r (- k 1))
(r
'()
(cons (vector-ref v (- k 1)) r)))
((= k 10) r)))))))
(lambda (r) (if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-actor
(let ((em
(vector
(lambda (p a) (p))
(lambda (p a) (p (array-ref a 0)))
(lambda (p a)
(p (array-ref a 0) (array-ref a 1)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)))
(lambda (p a)
(p
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)))))
(it
(lambda (r)
(lambda (p a)
(apply
a
(array-ref a 0)
(array-ref a 1)
(array-ref a 2)
(array-ref a 3)
(array-ref a 4)
(array-ref a 5)
(array-ref a 6)
(array-ref a 7)
(array-ref a 8)
(array-ref a 9)
(do ((k r (- k 1))
(r '() (cons (array-ref a (- k 1)) r)))
((= k 10) r)))))))
(lambda (r)
"These are high level, hiding implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define array:applier-to-backing-vector
(let ((em
(vector
(lambda (p ai av) (p))
(lambda (p ai av)
(p (vector-ref av (array:actor-index ai 0))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))))
(lambda (p ai av)
(p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))))))
(it
(lambda (r)
(lambda (p ai av)
(apply
p
(vector-ref av (array:actor-index ai 0))
(vector-ref av (array:actor-index ai 1))
(vector-ref av (array:actor-index ai 2))
(vector-ref av (array:actor-index ai 3))
(vector-ref av (array:actor-index ai 4))
(vector-ref av (array:actor-index ai 5))
(vector-ref av (array:actor-index ai 6))
(vector-ref av (array:actor-index ai 7))
(vector-ref av (array:actor-index ai 8))
(vector-ref av (array:actor-index ai 9))
(do ((k r (- k 1))
(r
'()
(cons
(vector-ref
av
(array:actor-index ai (- k 1)))
r)))
((= k 10) r)))))))
(lambda (r)
"These are low level, exposing implementation at call site."
(if (< r 10) (vector-ref em r) (it r)))))
(define (array:index/vector r x v)
((array:indexer/vector r) x v))
(define (array:index/array r x av ai)
((array:indexer/array r) x av ai))
(define (array:apply-to-vector r p v)
((array:applier-to-vector r) p v))
(define (array:apply-to-actor r p a)
((array:applier-to-actor r) p a)))
(define-library (srfi 25)
(export
array?
make-array
shape
array
array-rank
array-start
array-end
array-ref
array-set!
share-array
)
(import
(scheme base)
(scheme write))
(include "25.as-srfi-9-record.upstream.scm")
(include "25.ix-ctor.upstream.scm")
(include "25.op-ctor.upstream.scm")
(include "25.main.upstream.scm"))
(define-library (srfi 26)
(export cut cute)
(import (scheme base))
(include "26.upstream.scm"))
;;;;"array.scm" Arrays for Scheme
; Copyright (C) 2001, 2003 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
;;@code{(require 'array)} or @code{(require 'srfi-63)}
;;@ftindex array
(require 'record)
(define array:rtd
(make-record-type "array"
'(dimensions
scales ;list of dimension scales
offset ;exact integer
store ;data
)))
(define array:dimensions
(let ((dimensions (record-accessor array:rtd 'dimensions)))
(lambda (array)
(cond ((vector? array) (list (vector-length array)))
((string? array) (list (string-length array)))
(else (dimensions array))))))
(define array:scales
(let ((scales (record-accessor array:rtd 'scales)))
(lambda (obj)
(cond ((string? obj) '(1))
((vector? obj) '(1))
(else (scales obj))))))
(define array:store
(let ((store (record-accessor array:rtd 'store)))
(lambda (obj)
(cond ((string? obj) obj)
((vector? obj) obj)
(else (store obj))))))
(define array:offset
(let ((offset (record-accessor array:rtd 'offset)))
(lambda (obj)
(cond ((string? obj) 0)
((vector? obj) 0)
(else (offset obj))))))
(define array:construct
(record-constructor array:rtd '(dimensions scales offset store)))
;;@args obj
;;Returns @code{#t} if the @1 is an array, and @code{#f} if not.
(define array?
(let ((array:array? (record-predicate array:rtd)))
(lambda (obj) (or (string? obj) (vector? obj) (array:array? obj)))))
;;@noindent
;;@emph{Note:} Arrays are not disjoint from other Scheme types.
;;Vectors and possibly strings also satisfy @code{array?}.
;;A disjoint array predicate can be written:
;;
;;@example
;;(define (strict-array? obj)
;; (and (array? obj) (not (string? obj)) (not (vector? obj))))
;;@end example
;;@body
;;Returns @code{#t} if @1 and @2 have the same rank and dimensions and the
;;corresponding elements of @1 and @2 are @code{equal?}.
;;@body
;;@0 recursively compares the contents of pairs, vectors, strings, and
;;@emph{arrays}, applying @code{eqv?} on other objects such as numbers
;;and symbols. A rule of thumb is that objects are generally @0 if
;;they print the same. @0 may fail to terminate if its arguments are
;;circular data structures.
;;
;;@example
;;(equal? 'a 'a) @result{} #t
;;(equal? '(a) '(a)) @result{} #t
;;(equal? '(a (b) c)
;; '(a (b) c)) @result{} #t
;;(equal? "abc" "abc") @result{} #t
;;(equal? 2 2) @result{} #t
;;(equal? (make-vector 5 'a)
;; (make-vector 5 'a)) @result{} #t
;;(equal? (make-array (A:fixN32b 4) 5 3)
;; (make-array (A:fixN32b 4) 5 3)) @result{} #t
;;(equal? (make-array '#(foo) 3 3)
;; (make-array '#(foo) 3 3)) @result{} #t
;;(equal? (lambda (x) x)
;; (lambda (y) y)) @result{} @emph{unspecified}
;;@end example
(define (equal? obj1 obj2)
(cond ((eqv? obj1 obj2) #t)
((or (pair? obj1) (pair? obj2))
(and (pair? obj1) (pair? obj2)
(equal? (car obj1) (car obj2))
(equal? (cdr obj1) (cdr obj2))))
((or (string? obj1) (string? obj2))
(and (string? obj1) (string? obj2)
(string=? obj1 obj2)))
((or (vector? obj1) (vector? obj2))
(and (vector? obj1) (vector? obj2)
(equal? (vector-length obj1) (vector-length obj2))
(do ((idx (+ -1 (vector-length obj1)) (+ -1 idx)))
((or (negative? idx)
(not (equal? (vector-ref obj1 idx)
(vector-ref obj2 idx))))
(negative? idx)))))
((or (array? obj1) (array? obj2))
(and (array? obj1) (array? obj2)
(equal? (array:dimensions obj1) (array:dimensions obj2))
(equal? (array:store obj1) (array:store obj2))))
(else #f)))
;;@body
;;Returns the number of dimensions of @1. If @1 is not an array, 0 is
;;returned.
(define (array-rank obj)
(if (array? obj) (length (array:dimensions obj)) 0))
;;@args array
;;Returns a list of dimensions.
;;
;;@example
;;(array-dimensions (make-array '#() 3 5))
;; @result{} (3 5)
;;@end example
(define array-dimensions array:dimensions)
;;@args prototype k1 @dots{}
;;
;;Creates and returns an array of type @1 with dimensions @2, @dots{}
;;and filled with elements from @1. @1 must be an array, vector, or
;;string. The implementation-dependent type of the returned array
;;will be the same as the type of @1; except if that would be a vector
;;or string with rank not equal to one, in which case some variety of
;;array will be returned.
;;
;;If the @1 has no elements, then the initial contents of the returned
;;array are unspecified. Otherwise, the returned array will be filled
;;with the element at the origin of @1.
(define (make-array prototype . dimensions)
(define tcnt (apply * dimensions))
(let ((store
(if (string? prototype)
(case (string-length prototype)
((0) (make-string tcnt))
(else (make-string tcnt
(string-ref prototype 0))))
(let ((pdims (array:dimensions prototype)))
(case (apply * pdims)
((0) (make-vector tcnt))
(else (make-vector tcnt
(apply array-ref prototype
(map (lambda (x) 0) pdims)))))))))
(define (loop dims scales)
(if (null? dims)
(array:construct dimensions (cdr scales) 0 store)
(loop (cdr dims) (cons (* (car dims) (car scales)) scales))))
(loop (reverse dimensions) '(1))))
;;@args prototype k1 @dots{}
;;@0 is an alias for @code{make-array}.
(define create-array make-array)
;;@args array mapper k1 @dots{}
;;@0 can be used to create shared subarrays of other
;;arrays. The @var{mapper} is a function that translates coordinates in
;;the new array into coordinates in the old array. A @var{mapper} must be
;;linear, and its range must stay within the bounds of the old array, but
;;it can be otherwise arbitrary. A simple example:
;;
;;@example
;;(define fred (make-array '#(#f) 8 8))
;;(define freds-diagonal
;; (make-shared-array fred (lambda (i) (list i i)) 8))
;;(array-set! freds-diagonal 'foo 3)
;;(array-ref fred 3 3)
;; @result{} FOO
;;(define freds-center
;; (make-shared-array fred (lambda (i j) (list (+ 3 i) (+ 3 j)))
;; 2 2))
;;(array-ref freds-center 0 0)
;; @result{} FOO
;;@end example
(define (make-shared-array array mapper . dimensions)
(define odl (array:scales array))
(define rank (length dimensions))
(define shape
(map (lambda (dim) (if (list? dim) dim (list 0 (+ -1 dim)))) dimensions))
(do ((idx (+ -1 rank) (+ -1 idx))
(uvt (append (cdr (vector->list (make-vector rank 0))) '(1))
(append (cdr uvt) '(0)))
(uvts '() (cons uvt uvts)))
((negative? idx)
(let ((ker0 (apply + (map * odl (apply mapper uvt)))))
(array:construct
(map (lambda (dim) (+ 1 (- (cadr dim) (car dim)))) shape)
(map (lambda (uvt) (- (apply + (map * odl (apply mapper uvt))) ker0))
uvts)
(apply +
(array:offset array)
(map * odl (apply mapper (map car shape))))
(array:store array))))))
;;@args rank proto list
;;@3 must be a rank-nested list consisting of all the elements, in
;;row-major order, of the array to be created.
;;
;;@0 returns an array of rank @1 and type @2 consisting of all the
;;elements, in row-major order, of @3. When @1 is 0, @3 is the lone
;;array element; not necessarily a list.
;;
;;@example
;;(list->array 2 '#() '((1 2) (3 4)))
;; @result{} #2A((1 2) (3 4))
;;(list->array 0 '#() 3)
;; @result{} #0A 3
;;@end example
(define (list->array rank proto lst)
(define dimensions
(do ((shp '() (cons (length row) shp))
(row lst (car lst))
(rnk (+ -1 rank) (+ -1 rnk)))
((negative? rnk) (reverse shp))))
(let ((nra (apply make-array proto dimensions)))
(define (l2ra dims idxs row)
(cond ((null? dims)
(apply array-set! nra row (reverse idxs)))
((if (not (eqv? (car dims) (length row)))
(slib:error 'list->array
'non-rectangular 'array dims dimensions))
(do ((idx 0 (+ 1 idx))
(row row (cdr row)))
((>= idx (car dims)))
(l2ra (cdr dims) (cons idx idxs) (car row))))))
(l2ra dimensions '() lst)
nra))
;;@args array
;;Returns a rank-nested list consisting of all the elements, in
;;row-major order, of @1. In the case of a rank-0 array, @0 returns
;;the single element.
;;
;;@example
;;(array->list #2A((ho ho ho) (ho oh oh)))
;; @result{} ((ho ho ho) (ho oh oh))
;;(array->list #0A ho)
;; @result{} ho
;;@end example
(define (array->list ra)
(define (ra2l dims idxs)
(if (null? dims)
(apply array-ref ra (reverse idxs))
(do ((lst '() (cons (ra2l (cdr dims) (cons idx idxs)) lst))
(idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) lst))))
(ra2l (array-dimensions ra) '()))
;;@args vect proto dim1 @dots{}
;;@1 must be a vector of length equal to the product of exact
;;nonnegative integers @3, @dots{}.
;;
;;@0 returns an array of type @2 consisting of all the elements, in
;;row-major order, of @1. In the case of a rank-0 array, @1 has a
;;single element.
;;
;;@example
;;(vector->array #(1 2 3 4) #() 2 2)
;; @result{} #2A((1 2) (3 4))
;;(vector->array '#(3) '#())
;; @result{} #0A 3
;;@end example
(define (vector->array vect prototype . dimensions)
(define vdx (vector-length vect))
(if (not (eqv? vdx (apply * dimensions)))
(slib:error 'vector->array vdx '<> (cons '* dimensions)))
(let ((ra (apply make-array prototype dimensions)))
(define (v2ra dims idxs)
(cond ((null? dims)
(set! vdx (+ -1 vdx))
(apply array-set! ra (vector-ref vect vdx) (reverse idxs)))
(else
(do ((idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) vect)
(v2ra (cdr dims) (cons idx idxs))))))
(v2ra dimensions '())
ra))
;;@args array
;;Returns a new vector consisting of all the elements of @1 in
;;row-major order.
;;
;;@example
;;(array->vector #2A ((1 2)( 3 4)))
;; @result{} #(1 2 3 4)
;;(array->vector #0A ho)
;; @result{} #(ho)
;;@end example
(define (array->vector ra)
(define dims (array-dimensions ra))
(let* ((vdx (apply * dims))
(vect (make-vector vdx)))
(define (ra2v dims idxs)
(if (null? dims)
(let ((val (apply array-ref ra (reverse idxs))))
(set! vdx (+ -1 vdx))
(vector-set! vect vdx val)
vect)
(do ((idx (+ -1 (car dims)) (+ -1 idx)))
((negative? idx) vect)
(ra2v (cdr dims) (cons idx idxs)))))
(ra2v dims '())))
(define (array:in-bounds? array indices)
(do ((bnds (array:dimensions array) (cdr bnds))
(idxs indices (cdr idxs)))
((or (null? bnds)
(null? idxs)
(not (integer? (car idxs)))
(not (< -1 (car idxs) (car bnds))))
(and (null? bnds) (null? idxs)))))
;;@args array index1 @dots{}
;;Returns @code{#t} if its arguments would be acceptable to
;;@code{array-ref}.
(define (array-in-bounds? array . indices)
(array:in-bounds? array indices))
;;@args array k1 @dots{}
;;Returns the (@2, @dots{}) element of @1.
(define (array-ref array . indices)
(define store (array:store array))
(or (array:in-bounds? array indices)
(slib:error 'array-ref 'bad-indices indices))
((if (string? store) string-ref vector-ref)
store (apply + (array:offset array) (map * (array:scales array) indices))))
;;@args array obj k1 @dots{}
;;Stores @2 in the (@3, @dots{}) element of @1. The value returned
;;by @0 is unspecified.
(define (array-set! array obj . indices)
(define store (array:store array))
(or (array:in-bounds? array indices)
(slib:error 'array-set! 'bad-indices indices))
((if (string? store) string-set! vector-set!)
store (apply + (array:offset array) (map * (array:scales array) indices))
obj))
;;@noindent
;;These functions return a prototypical uniform-array enclosing the
;;optional argument (which must be of the correct type). If the
;;uniform-array type is supported by the implementation, then it is
;;returned; defaulting to the next larger precision type; resorting
;;finally to vector.
(define (make-prototype-checker name pred? creator)
(lambda args
(case (length args)
((1) (if (pred? (car args))
(creator (car args))
(slib:error name 'incompatible 'type (car args))))
((0) (creator))
(else (slib:error name 'wrong 'number 'of 'args args)))))
(define (integer-bytes?? n)
(lambda (obj)
(and (integer? obj)
(exact? obj)
(or (negative? n) (not (negative? obj)))
(do ((num obj (quotient num 256))
(n (+ -1 (abs n)) (+ -1 n)))
((or (zero? num) (negative? n))
(zero? num))))))
;;@args z
;;@args
;;Returns an inexact 128.bit flonum complex uniform-array prototype.
(define A:floC128b (make-prototype-checker 'A:floC128b complex? vector))
;;@args z
;;@args
;;Returns an inexact 64.bit flonum complex uniform-array prototype.
(define A:floC64b (make-prototype-checker 'A:floC64b complex? vector))
;;@args z
;;@args
;;Returns an inexact 32.bit flonum complex uniform-array prototype.
(define A:floC32b (make-prototype-checker 'A:floC32b complex? vector))
;;@args z
;;@args
;;Returns an inexact 16.bit flonum complex uniform-array prototype.
(define A:floC16b (make-prototype-checker 'A:floC16b complex? vector))
;;@args z
;;@args
;;Returns an inexact 128.bit flonum real uniform-array prototype.
(define A:floR128b (make-prototype-checker 'A:floR128b real? vector))
;;@args z
;;@args
;;Returns an inexact 64.bit flonum real uniform-array prototype.
(define A:floR64b (make-prototype-checker 'A:floR64b real? vector))
;;@args z
;;@args
;;Returns an inexact 32.bit flonum real uniform-array prototype.
(define A:floR32b (make-prototype-checker 'A:floR32b real? vector))
;;@args z
;;@args
;;Returns an inexact 16.bit flonum real uniform-array prototype.
(define A:floR16b (make-prototype-checker 'A:floR16b real? vector))
;;@args z
;;@args
;;Returns an exact 128.bit decimal flonum rational uniform-array prototype.
(define A:floR128b (make-prototype-checker 'A:floR128b real? vector))
;;@args z
;;@args
;;Returns an exact 64.bit decimal flonum rational uniform-array prototype.
(define A:floR64b (make-prototype-checker 'A:floR64b real? vector))
;;@args z
;;@args
;;Returns an exact 32.bit decimal flonum rational uniform-array prototype.
(define A:floR32b (make-prototype-checker 'A:floR32b real? vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;64 bits of precision.
(define A:fixZ64b (make-prototype-checker 'A:fixZ64b (integer-bytes?? -8) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;32 bits of precision.
(define A:fixZ32b (make-prototype-checker 'A:fixZ32b (integer-bytes?? -4) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;16 bits of precision.
(define A:fixZ16b (make-prototype-checker 'A:fixZ16b (integer-bytes?? -2) vector))
;;@args n
;;@args
;;Returns an exact binary fixnum uniform-array prototype with at least
;;8 bits of precision.
(define A:fixZ8b (make-prototype-checker 'A:fixZ8b (integer-bytes?? -1) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 64 bits of precision.
(define A:fixN64b (make-prototype-checker 'A:fixN64b (integer-bytes?? 8) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 32 bits of precision.
(define A:fixN32b (make-prototype-checker 'A:fixN32b (integer-bytes?? 4) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 16 bits of precision.
(define A:fixN16b (make-prototype-checker 'A:fixN16b (integer-bytes?? 2) vector))
;;@args k
;;@args
;;Returns an exact non-negative binary fixnum uniform-array prototype with at
;;least 8 bits of precision.
(define A:fixN8b (make-prototype-checker 'A:fixN8b (integer-bytes?? 1) vector))
;;@args bool
;;@args
;;Returns a boolean uniform-array prototype.
(define A:bool (make-prototype-checker 'A:bool boolean? vector))
; REFERENCE IMPLEMENTATION FOR SRFI-26 "CUT"
; ==========================================
;
; Sebastian.Egner@philips.com, 5-Jun-2002.
; adapted from the posting by Al Petrofsky <al@petrofsky.org>
; placed in the public domain
;
; The code to handle the variable argument case was originally
; proposed by Michael Sperber and has been adapted to the new
; syntax of the macro using an explicit rest-slot symbol. The
; code to evaluate the non-slots for cute has been proposed by
; Dale Jordan. The code to allow a slot for the procedure position
; and to process the macro using an internal macro is based on
; a suggestion by Al Petrofsky. The code found below is, with
; exception of this header and some changes in variable names,
; entirely written by Al Petrofsky.
;
; compliance:
; Scheme R5RS (including macros).
;
; loading this file into Scheme 48 0.57:
; ,load cut.scm
;
; history of this file:
; SE, 6-Feb-2002: initial version as 'curry' with ". <>" notation
; SE, 14-Feb-2002: revised for <___>
; SE, 27-Feb-2002: revised for 'cut'
; SE, 03-Jun-2002: revised for proc-slot, cute
; SE, 04-Jun-2002: rewritten with internal transformer (no "loop" pattern)
; SE, 05-Jun-2002: replace my code by Al's; substituted "constant" etc.
; to match the convention in the SRFI-document
; (srfi-26-internal-cut slot-names combination . se)
; transformer used internally
; slot-names : the internal names of the slots
; combination : procedure being specialized, followed by its arguments
; se : slots-or-exprs, the qualifiers of the macro
(define-syntax srfi-26-internal-cut
(syntax-rules (<> <___>)
;; construct fixed- or variable-arity procedure:
;; (begin proc) throws an error if proc is not an <expression>
((srfi-26-internal-cut (slot-name ...) (proc arg ...))
(lambda (slot-name ...) ((begin proc) arg ...)))
((srfi-26-internal-cut (slot-name ...) (proc arg ...) <___>)
(lambda (slot-name ... . rest-slot) (apply proc arg ... rest-slot)))
;; process one slot-or-expr
((srfi-26-internal-cut (slot-name ...) (position ...) <> . se)
(srfi-26-internal-cut (slot-name ... x) (position ... x) . se))
((srfi-26-internal-cut (slot-name ...) (position ...) nse . se)
(srfi-26-internal-cut (slot-name ...) (position ... nse) . se))))
; (srfi-26-internal-cute slot-names nse-bindings combination . se)
; transformer used internally
; slot-names : the internal names of the slots
; nse-bindings : let-style bindings for the non-slot expressions.
; combination : procedure being specialized, followed by its arguments
; se : slots-or-exprs, the qualifiers of the macro
(define-syntax srfi-26-internal-cute
(syntax-rules (<> <___>)
;; If there are no slot-or-exprs to process, then:
;; construct a fixed-arity procedure,
((srfi-26-internal-cute
(slot-name ...) nse-bindings (proc arg ...))
(let nse-bindings (lambda (slot-name ...) (proc arg ...))))
;; or a variable-arity procedure
((srfi-26-internal-cute
(slot-name ...) nse-bindings (proc arg ...) <___>)
(let nse-bindings (lambda (slot-name ... . x) (apply proc arg ... x))))
;; otherwise, process one slot:
((srfi-26-internal-cute
(slot-name ...) nse-bindings (position ...) <> . se)
(srfi-26-internal-cute
(slot-name ... x) nse-bindings (position ... x) . se))
;; or one non-slot expression
((srfi-26-internal-cute
slot-names nse-bindings (position ...) nse . se)
(srfi-26-internal-cute
slot-names ((x nse) . nse-bindings) (position ... x) . se))))
; exported syntax
(define-syntax cut
(syntax-rules ()
((cut . slots-or-exprs)
(srfi-26-internal-cut () () . slots-or-exprs))))
(define-syntax cute
(syntax-rules ()
((cute . slots-or-exprs)
(srfi-26-internal-cute () () () . slots-or-exprs))))
;;;; "logical.scm", bit access and operations for integers for Scheme
;;; Copyright (C) 1991, 1993, 2001, 2003, 2005 Aubrey Jaffer
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(define logical:boole-xor
'#(#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
#(1 0 3 2 5 4 7 6 9 8 11 10 13 12 15 14)
#(2 3 0 1 6 7 4 5 10 11 8 9 14 15 12 13)
#(3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12)
#(4 5 6 7 0 1 2 3 12 13 14 15 8 9 10 11)
#(5 4 7 6 1 0 3 2 13 12 15 14 9 8 11 10)
#(6 7 4 5 2 3 0 1 14 15 12 13 10 11 8 9)
#(7 6 5 4 3 2 1 0 15 14 13 12 11 10 9 8)
#(8 9 10 11 12 13 14 15 0 1 2 3 4 5 6 7)
#(9 8 11 10 13 12 15 14 1 0 3 2 5 4 7 6)
#(10 11 8 9 14 15 12 13 2 3 0 1 6 7 4 5)
#(11 10 9 8 15 14 13 12 3 2 1 0 7 6 5 4)
#(12 13 14 15 8 9 10 11 4 5 6 7 0 1 2 3)
#(13 12 15 14 9 8 11 10 5 4 7 6 1 0 3 2)
#(14 15 12 13 10 11 8 9 6 7 4 5 2 3 0 1)
#(15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0)))
(define logical:boole-and
'#(#(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0)
#(0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1)
#(0 0 2 2 0 0 2 2 0 0 2 2 0 0 2 2)
#(0 1 2 3 0 1 2 3 0 1 2 3 0 1 2 3)
#(0 0 0 0 4 4 4 4 0 0 0 0 4 4 4 4)
#(0 1 0 1 4 5 4 5 0 1 0 1 4 5 4 5)
#(0 0 2 2 4 4 6 6 0 0 2 2 4 4 6 6)
#(0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7)
#(0 0 0 0 0 0 0 0 8 8 8 8 8 8 8 8)
#(0 1 0 1 0 1 0 1 8 9 8 9 8 9 8 9)
#(0 0 2 2 0 0 2 2 8 8 10 10 8 8 10 10)
#(0 1 2 3 0 1 2 3 8 9 10 11 8 9 10 11)
#(0 0 0 0 4 4 4 4 8 8 8 8 12 12 12 12)
#(0 1 0 1 4 5 4 5 8 9 8 9 12 13 12 13)
#(0 0 2 2 4 4 6 6 8 8 10 10 12 12 14 14)
#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)))
(define (logical:ash-4 x)
(if (negative? x)
(+ -1 (quotient (+ 1 x) 16))
(quotient x 16)))
(define (logical:reduce op4 ident)
(lambda args
(do ((res ident (op4 res (car rgs) 1 0))
(rgs args (cdr rgs)))
((null? rgs) res))))
;@
(define logand
(letrec
((lgand
(lambda (n2 n1 scl acc)
(cond ((= n1 n2) (+ acc (* scl n1)))
((zero? n2) acc)
((zero? n1) acc)
(else (lgand (logical:ash-4 n2)
(logical:ash-4 n1)
(* 16 scl)
(+ (* (vector-ref (vector-ref logical:boole-and
(modulo n1 16))
(modulo n2 16))
scl)
acc)))))))
(logical:reduce lgand -1)))
;@
(define logior
(letrec
((lgior
(lambda (n2 n1 scl acc)
(cond ((= n1 n2) (+ acc (* scl n1)))
((zero? n2) (+ acc (* scl n1)))
((zero? n1) (+ acc (* scl n2)))
(else (lgior (logical:ash-4 n2)
(logical:ash-4 n1)
(* 16 scl)
(+ (* (- 15 (vector-ref
(vector-ref logical:boole-and
(- 15 (modulo n1 16)))
(- 15 (modulo n2 16))))
scl)
acc)))))))
(logical:reduce lgior 0)))
;@
(define logxor
(letrec
((lgxor
(lambda (n2 n1 scl acc)
(cond ((= n1 n2) acc)
((zero? n2) (+ acc (* scl n1)))
((zero? n1) (+ acc (* scl n2)))
(else (lgxor (logical:ash-4 n2)
(logical:ash-4 n1)
(* 16 scl)
(+ (* (vector-ref (vector-ref logical:boole-xor
(modulo n1 16))
(modulo n2 16))
scl)
acc)))))))
(logical:reduce lgxor 0)))
;@
(define (lognot n) (- -1 n))
;@
(define (logtest n1 n2)
(not (zero? (logand n1 n2))))
;@
(define (logbit? index n)
(logtest (expt 2 index) n))
;@
(define (copy-bit index to bool)
(if bool
(logior to (arithmetic-shift 1 index))
(logand to (lognot (arithmetic-shift 1 index)))))
;@
(define (bitwise-if mask n0 n1)
(logior (logand mask n0)
(logand (lognot mask) n1)))
;@
(define (bit-field n start end)
(logand (lognot (ash -1 (- end start)))
(arithmetic-shift n (- start))))
;@
(define (copy-bit-field to from start end)
(bitwise-if (arithmetic-shift (lognot (ash -1 (- end start))) start)
(arithmetic-shift from start)
to))
;@
(define (rotate-bit-field n count start end)
(define width (- end start))
(set! count (modulo count width))
(let ((mask (lognot (ash -1 width))))
(define zn (logand mask (arithmetic-shift n (- start))))
(logior (arithmetic-shift
(logior (logand mask (arithmetic-shift zn count))
(arithmetic-shift zn (- count width)))
start)
(logand (lognot (ash mask start)) n))))
;@
(define (arithmetic-shift n count)
(if (negative? count)
(let ((k (expt 2 (- count))))
(if (negative? n)
(+ -1 (quotient (+ 1 n) k))
(quotient n k)))
(* (expt 2 count) n)))
;@
(define integer-length
(letrec ((intlen (lambda (n tot)
(case n
((0 -1) (+ 0 tot))
((1 -2) (+ 1 tot))
((2 3 -3 -4) (+ 2 tot))
((4 5 6 7 -5 -6 -7 -8) (+ 3 tot))
(else (intlen (logical:ash-4 n) (+ 4 tot)))))))
(lambda (n) (intlen n 0))))
;@
(define logcount
(letrec ((logcnt (lambda (n tot)
(if (zero? n)
tot
(logcnt (quotient n 16)
(+ (vector-ref
'#(0 1 1 2 1 2 2 3 1 2 2 3 2 3 3 4)
(modulo n 16))
tot))))))
(lambda (n)
(cond ((negative? n) (logcnt (lognot n) 0))
((positive? n) (logcnt n 0))
(else 0)))))
;@
(define (log2-binary-factors n)
(+ -1 (integer-length (logand n (- n)))))
(define (bit-reverse k n)
(do ((m (if (negative? n) (lognot n) n) (arithmetic-shift m -1))
(k (+ -1 k) (+ -1 k))
(rvs 0 (logior (arithmetic-shift rvs 1) (logand 1 m))))
((negative? k) (if (negative? n) (lognot rvs) rvs))))
;@
(define (reverse-bit-field n start end)
(define width (- end start))
(let ((mask (lognot (ash -1 width))))
(define zn (logand mask (arithmetic-shift n (- start))))
(logior (arithmetic-shift (bit-reverse width zn) start)
(logand (lognot (ash mask start)) n))))
;@
(define (integer->list k . len)
(if (null? len)
(do ((k k (arithmetic-shift k -1))
(lst '() (cons (odd? k) lst)))
((<= k 0) lst))
(do ((idx (+ -1 (car len)) (+ -1 idx))
(k k (arithmetic-shift k -1))
(lst '() (cons (odd? k) lst)))
((negative? idx) lst))))
;@
(define (list->integer bools)
(do ((bs bools (cdr bs))
(acc 0 (+ acc acc (if (car bs) 1 0))))
((null? bs) acc)))
(define (booleans->integer . bools)
(list->integer bools))
;;;;@ SRFI-60 aliases
(define ash arithmetic-shift)
(define bitwise-ior logior)
(define bitwise-xor logxor)
(define bitwise-and logand)
(define bitwise-not lognot)
(define bit-count logcount)
(define bit-set? logbit?)
(define any-bits-set? logtest)
(define first-set-bit log2-binary-factors)
(define bitwise-merge bitwise-if)
;;; Legacy
;;(define (logical:rotate k count len) (rotate-bit-field k count 0 len))
;;(define (logical:ones deg) (lognot (ash -1 deg)))
;;(define integer-expt expt) ; legacy name
; 54-BIT INTEGER IMPLEMENTATION OF THE "MRG32K3A"-GENERATOR
; =========================================================
;
; Sebastian.Egner@philips.com, Mar-2002.
;
; This file is an implementation of Pierre L'Ecuyer's MRG32k3a
; pseudo random number generator. Please refer to 'mrg32k3a.scm'
; for more information.
;
; compliance:
; Scheme R5RS with integers covering at least {-2^53..2^53-1}.
;
; history of this file:
; SE, 18-Mar-2002: initial version
; SE, 22-Mar-2002: comments adjusted, range added
; SE, 25-Mar-2002: pack/unpack just return their argument
; the actual generator
(define (mrg32k3a-random-m1 state)
(let ((x11 (vector-ref state 0))
(x12 (vector-ref state 1))
(x13 (vector-ref state 2))
(x21 (vector-ref state 3))
(x22 (vector-ref state 4))
(x23 (vector-ref state 5)))
(let ((x10 (modulo (- (* 1403580 x12) (* 810728 x13)) 4294967087))
(x20 (modulo (- (* 527612 x21) (* 1370589 x23)) 4294944443)))
(vector-set! state 0 x10)
(vector-set! state 1 x11)
(vector-set! state 2 x12)
(vector-set! state 3 x20)
(vector-set! state 4 x21)
(vector-set! state 5 x22)
(modulo (- x10 x20) 4294967087))))
; interface to the generic parts of the generator
(define (mrg32k3a-pack-state unpacked-state)
unpacked-state)
(define (mrg32k3a-unpack-state state)
state)
(define (mrg32k3a-random-range) ; m1
4294967087)
(define (mrg32k3a-random-integer state range) ; rejection method
(let* ((q (quotient 4294967087 range))
(qn (* q range)))
(do ((x (mrg32k3a-random-m1 state) (mrg32k3a-random-m1 state)))
((< x qn) (quotient x q)))))
(define (mrg32k3a-random-real state) ; normalization is 1/(m1+1)
(* 0.0000000002328306549295728 (+ 1.0 (mrg32k3a-random-m1 state))))
;;; Copyright (C) 2004 Taylor Campbell. All rights reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-library (srfi 61)
(export cond)
(import (except (scheme base) cond))
(begin
(define-syntax cond
(syntax-rules (=> else)
((cond (else else1 else2 ...))
;; The (if #t (begin ...)) wrapper ensures that there may be no
;; internal definitions in the body of the clause. R5RS mandates
;; this in text (by referring to each subform of the clauses as
;; <expression>) but not in its reference implementation of `cond',
;; which just expands to (begin ...) with no (if #t ...) wrapper.
(if #t (begin else1 else2 ...)))
((cond (test => receiver) more-clause ...)
(let ((t test))
(cond/maybe-more t
(receiver t)
more-clause ...)))
((cond (generator guard => receiver) more-clause ...)
(call-with-values (lambda () generator)
(lambda t
(cond/maybe-more (apply guard t)
(apply receiver t)
more-clause ...))))
((cond (test) more-clause ...)
(let ((t test))
(cond/maybe-more t t more-clause ...)))
((cond (test body1 body2 ...) more-clause ...)
(cond/maybe-more test
(begin body1 body2 ...)
more-clause ...))))
(define-syntax cond/maybe-more
(syntax-rules ()
((cond/maybe-more test consequent)
(if test
consequent))
((cond/maybe-more test consequent clause ...)
(if test
consequent
(cond clause ...)))))
))
; GENERIC PART OF MRG32k3a-GENERATOR FOR SRFI-27
; ==============================================
;
; Sebastian.Egner@philips.com, 2002.
;
; This is the generic R5RS-part of the implementation of the MRG32k3a
; generator to be used in SRFI-27. It is based on a separate implementation
; of the core generator (presumably in native code) and on code to
; provide essential functionality not available in R5RS (see below).
;
; compliance:
; Scheme R5RS with integer covering at least {-2^53..2^53-1}.
; In addition,
; SRFI-23: error
;
; history of this file:
; SE, 22-Mar-2002: refactored from earlier versions
; SE, 25-Mar-2002: pack/unpack need not allocate
; SE, 27-Mar-2002: changed interface to core generator
; SE, 10-Apr-2002: updated spec of mrg32k3a-random-integer
; Generator
; =========
;
; Pierre L'Ecuyer's MRG32k3a generator is a Combined Multiple Recursive
; Generator. It produces the sequence {(x[1,n] - x[2,n]) mod m1 : n}
; defined by the two recursive generators
;
; x[1,n] = ( a12 x[1,n-2] + a13 x[1,n-3]) mod m1,
; x[2,n] = (a21 x[2,n-1] + a23 x[2,n-3]) mod m2,
;
; where the constants are
; m1 = 4294967087 = 2^32 - 209 modulus of 1st component
; m2 = 4294944443 = 2^32 - 22853 modulus of 2nd component
; a12 = 1403580 recursion coefficients
; a13 = -810728
; a21 = 527612
; a23 = -1370589
;
; The generator passes all tests of G. Marsaglia's Diehard testsuite.
; Its period is (m1^3 - 1)(m2^3 - 1)/2 which is nearly 2^191.
; L'Ecuyer reports: "This generator is well-behaved in all dimensions
; up to at least 45: ..." [with respect to the spectral test, SE].
;
; The period is maximal for all values of the seed as long as the
; state of both recursive generators is not entirely zero.
;
; As the successor state is a linear combination of previous
; states, it is possible to advance the generator by more than one
; iteration by applying a linear transformation. The following
; publication provides detailed information on how to do that:
;
; [1] P. L'Ecuyer, R. Simard, E. J. Chen, W. D. Kelton:
; An Object-Oriented Random-Number Package With Many Long
; Streams and Substreams. 2001.
; To appear in Operations Research.
;
; Arithmetics
; ===========
;
; The MRG32k3a generator produces values in {0..2^32-209-1}. All
; subexpressions of the actual generator fit into {-2^53..2^53-1}.
; The code below assumes that Scheme's "integer" covers this range.
; In addition, it is assumed that floating point literals can be
; read and there is some arithmetics with inexact numbers.
;
; However, for advancing the state of the generator by more than
; one step at a time, the full range {0..2^32-209-1} is needed.
; Required: Backbone Generator
; ============================
;
; At this point in the code, the following procedures are assumed
; to be defined to execute the core generator:
;
; (mrg32k3a-pack-state unpacked-state) -> packed-state
; (mrg32k3a-unpack-state packed-state) -> unpacked-state
; pack/unpack a state of the generator. The core generator works
; on packed states, passed as an explicit argument, only. This
; allows native code implementations to store their state in a
; suitable form. Unpacked states are #(x10 x11 x12 x20 x21 x22)
; with integer x_ij. Pack/unpack need not allocate new objects
; in case packed and unpacked states are identical.
;
; (mrg32k3a-random-range) -> m-max
; (mrg32k3a-random-integer packed-state range) -> x in {0..range-1}
; advance the state of the generator and return the next random
; range-limited integer.
; Note that the state is not necessarily advanced by just one
; step because we use the rejection method to avoid any problems
; with distribution anomalies.
; The range argument must be an exact integer in {1..m-max}.
; It can be assumed that range is a fixnum if the Scheme system
; has such a number representation.
;
; (mrg32k3a-random-real packed-state) -> x in (0,1)
; advance the state of the generator and return the next random
; real number between zero and one (both excluded). The type of
; the result should be a flonum if possible.
; Required: Record Data Type
; ==========================
;
; At this point in the code, the following procedures are assumed
; to be defined to create and access a new record data type:
;
; (\:random-source-make a0 a1 a2 a3 a4 a5) -> s
; constructs a new random source object s consisting of the
; objects a0 .. a5 in this order.
;
; (\:random-source? obj) -> bool
; tests if a Scheme object is a :random-source.
;
; (\:random-source-state-ref s) -> a0
; (\:random-source-state-set! s) -> a1
; (\:random-source-randomize! s) -> a2
; (\:random-source-pseudo-randomize! s) -> a3
; (\:random-source-make-integers s) -> a4
; (\:random-source-make-reals s) -> a5
; retrieve the values in the fields of the object s.
; Required: Current Time as an Integer
; ====================================
;
; At this point in the code, the following procedure is assumed
; to be defined to obtain a value that is likely to be different
; for each invokation of the Scheme system:
;
; (\:random-source-current-time) -> x
; an integer that depends on the system clock. It is desired
; that the integer changes as fast as possible.
; Accessing the State
; ===================
(define (mrg32k3a-state-ref packed-state)
(cons 'lecuyer-mrg32k3a
(vector->list (mrg32k3a-unpack-state packed-state))))
(define (mrg32k3a-state-set external-state)
(define (check-value x m)
(if (and (integer? x)
(exact? x)
(<= 0 x (- m 1)))
#t
(error "illegal value" x)))
(if (and (list? external-state)
(= (length external-state) 7)
(eq? (car external-state) 'lecuyer-mrg32k3a))
(let ((s (cdr external-state)))
(check-value (list-ref s 0) mrg32k3a-m1)
(check-value (list-ref s 1) mrg32k3a-m1)
(check-value (list-ref s 2) mrg32k3a-m1)
(check-value (list-ref s 3) mrg32k3a-m2)
(check-value (list-ref s 4) mrg32k3a-m2)
(check-value (list-ref s 5) mrg32k3a-m2)
(if (or (zero? (+ (list-ref s 0) (list-ref s 1) (list-ref s 2)))
(zero? (+ (list-ref s 3) (list-ref s 4) (list-ref s 5))))
(error "illegal degenerate state" external-state))
(mrg32k3a-pack-state (list->vector s)))
(error "malformed state" external-state)))
; Pseudo-Randomization
; ====================
;
; Reference [1] above shows how to obtain many long streams and
; substream from the backbone generator.
;
; The idea is that the generator is a linear operation on the state.
; Hence, we can express this operation as a 3x3-matrix acting on the
; three most recent states. Raising the matrix to the k-th power, we
; obtain the operation to advance the state by k steps at once. The
; virtual streams and substreams are now simply parts of the entire
; periodic sequence (which has period around 2^191).
;
; For the implementation it is necessary to compute with matrices in
; the ring (Z/(m1*m1)*Z)^(3x3). By the Chinese-Remainder Theorem, this
; is isomorphic to ((Z/m1*Z) x (Z/m2*Z))^(3x3). We represent such a pair
; of matrices
; [ [[x00 x01 x02],
; [x10 x11 x12],
; [x20 x21 x22]], mod m1
; [[y00 y01 y02],
; [y10 y11 y12],
; [y20 y21 y22]] mod m2]
; as a vector of length 18 of the integers as writen above:
; #(x00 x01 x02 x10 x11 x12 x20 x21 x22
; y00 y01 y02 y10 y11 y12 y20 y21 y22)
;
; As the implementation should only use the range {-2^53..2^53-1}, the
; fundamental operation (x*y) mod m, where x, y, m are nearly 2^32,
; is computed by breaking up x and y as x = x1*w + x0 and y = y1*w + y0
; where w = 2^16. In this case, all operations fit the range because
; w^2 mod m is a small number. If proper multiprecision integers are
; available this is not necessary, but pseudo-randomize! is an expected
; to be called only occasionally so we do not provide this implementation.
(define mrg32k3a-m1 4294967087) ; modulus of component 1
(define mrg32k3a-m2 4294944443) ; modulus of component 2
(define mrg32k3a-initial-state ; 0 3 6 9 12 15 of A^16, see below
'#( 1062452522
2961816100
342112271
2854655037
3321940838
3542344109))
(define mrg32k3a-generators #f) ; computed when needed
(define (mrg32k3a-pseudo-randomize-state i j)
(define (product A B) ; A*B in ((Z/m1*Z) x (Z/m2*Z))^(3x3)
(define w 65536) ; wordsize to split {0..2^32-1}
(define w-sqr1 209) ; w^2 mod m1
(define w-sqr2 22853) ; w^2 mod m2
(define (lc i0 i1 i2 j0 j1 j2 m w-sqr) ; linear combination
(let ((a0h (quotient (vector-ref A i0) w))
(a0l (modulo (vector-ref A i0) w))
(a1h (quotient (vector-ref A i1) w))
(a1l (modulo (vector-ref A i1) w))
(a2h (quotient (vector-ref A i2) w))
(a2l (modulo (vector-ref A i2) w))
(b0h (quotient (vector-ref B j0) w))
(b0l (modulo (vector-ref B j0) w))
(b1h (quotient (vector-ref B j1) w))
(b1l (modulo (vector-ref B j1) w))
(b2h (quotient (vector-ref B j2) w))
(b2l (modulo (vector-ref B j2) w)))
(modulo
(+ (* (+ (* a0h b0h)
(* a1h b1h)
(* a2h b2h))
w-sqr)
(* (+ (* a0h b0l)
(* a0l b0h)
(* a1h b1l)
(* a1l b1h)
(* a2h b2l)
(* a2l b2h))
w)
(* a0l b0l)
(* a1l b1l)
(* a2l b2l))
m)))
(vector
(lc 0 1 2 0 3 6 mrg32k3a-m1 w-sqr1) ; (A*B)_00 mod m1
(lc 0 1 2 1 4 7 mrg32k3a-m1 w-sqr1) ; (A*B)_01
(lc 0 1 2 2 5 8 mrg32k3a-m1 w-sqr1)
(lc 3 4 5 0 3 6 mrg32k3a-m1 w-sqr1) ; (A*B)_10
(lc 3 4 5 1 4 7 mrg32k3a-m1 w-sqr1)
(lc 3 4 5 2 5 8 mrg32k3a-m1 w-sqr1)
(lc 6 7 8 0 3 6 mrg32k3a-m1 w-sqr1)
(lc 6 7 8 1 4 7 mrg32k3a-m1 w-sqr1)
(lc 6 7 8 2 5 8 mrg32k3a-m1 w-sqr1)
(lc 9 10 11 9 12 15 mrg32k3a-m2 w-sqr2) ; (A*B)_00 mod m2
(lc 9 10 11 10 13 16 mrg32k3a-m2 w-sqr2)
(lc 9 10 11 11 14 17 mrg32k3a-m2 w-sqr2)
(lc 12 13 14 9 12 15 mrg32k3a-m2 w-sqr2)
(lc 12 13 14 10 13 16 mrg32k3a-m2 w-sqr2)
(lc 12 13 14 11 14 17 mrg32k3a-m2 w-sqr2)
(lc 15 16 17 9 12 15 mrg32k3a-m2 w-sqr2)
(lc 15 16 17 10 13 16 mrg32k3a-m2 w-sqr2)
(lc 15 16 17 11 14 17 mrg32k3a-m2 w-sqr2)))
(define (power A e) ; A^e
(cond
((zero? e)
'#(1 0 0 0 1 0 0 0 1 1 0 0 0 1 0 0 0 1))
((= e 1)
A)
((even? e)
(power (product A A) (quotient e 2)))
(else
(product (power A (- e 1)) A))))
(define (power-power A b) ; A^(2^b)
(if (zero? b)
A
(power-power (product A A) (- b 1))))
(define A ; the MRG32k3a recursion
'#( 0 1403580 4294156359
1 0 0
0 1 0
527612 0 4293573854
1 0 0
0 1 0))
; check arguments
(if (not (and (integer? i)
(exact? i)
(integer? j)
(exact? j)))
(error "i j must be exact integer" i j))
; precompute A^(2^127) and A^(2^76) only once
(if (not mrg32k3a-generators)
(set! mrg32k3a-generators
(list (power-power A 127)
(power-power A 76)
(power A 16))))
; compute M = A^(16 + i*2^127 + j*2^76)
(let ((M (product
(list-ref mrg32k3a-generators 2)
(product
(power (list-ref mrg32k3a-generators 0)
(modulo i (expt 2 28)))
(power (list-ref mrg32k3a-generators 1)
(modulo j (expt 2 28)))))))
(mrg32k3a-pack-state
(vector
(vector-ref M 0)
(vector-ref M 3)
(vector-ref M 6)
(vector-ref M 9)
(vector-ref M 12)
(vector-ref M 15)))))
; True Randomization
; ==================
;
; The value obtained from the system time is feed into a very
; simple pseudo random number generator. This in turn is used
; to obtain numbers to randomize the state of the MRG32k3a
; generator, avoiding period degeneration.
(define (mrg32k3a-randomize-state state)
;; G. Marsaglia's simple 16-bit generator with carry
(let* ((m 65536)
(x (modulo (random-source-current-time) m)))
(define (random-m)
(let ((y (modulo x m)))
(set! x (+ (* 30903 y) (quotient x m)))
y))
(define (random n) ; m < n < m^2
(modulo (+ (* (random-m) m) (random-m)) n))
; modify the state
(let ((m1 mrg32k3a-m1)
(m2 mrg32k3a-m2)
(s (mrg32k3a-unpack-state state)))
(mrg32k3a-pack-state
(vector
(+ 1 (modulo (+ (vector-ref s 0) (random (- m1 1))) (- m1 1)))
(modulo (+ (vector-ref s 1) (random m1)) m1)
(modulo (+ (vector-ref s 2) (random m1)) m1)
(+ 1 (modulo (+ (vector-ref s 3) (random (- m2 1))) (- m2 1)))
(modulo (+ (vector-ref s 4) (random m2)) m2)
(modulo (+ (vector-ref s 5) (random m2)) m2))))))
; Large Integers
; ==============
;
; To produce large integer random deviates, for n > m-max, we first
; construct large random numbers in the range {0..m-max^k-1} for some
; k such that m-max^k >= n and then use the rejection method to choose
; uniformly from the range {0..n-1}.
(define mrg32k3a-m-max
(mrg32k3a-random-range))
(define (mrg32k3a-random-power state k) ; n = m-max^k, k >= 1
(if (= k 1)
(mrg32k3a-random-integer state mrg32k3a-m-max)
(+ (* (mrg32k3a-random-power state (- k 1)) mrg32k3a-m-max)
(mrg32k3a-random-integer state mrg32k3a-m-max))))
(define (mrg32k3a-random-large state n) ; n > m-max
(do ((k 2 (+ k 1))
(mk (* mrg32k3a-m-max mrg32k3a-m-max) (* mk mrg32k3a-m-max)))
((>= mk n)
(let* ((mk-by-n (quotient mk n))
(a (* mk-by-n n)))
(do ((x (mrg32k3a-random-power state k)
(mrg32k3a-random-power state k)))
((< x a) (quotient x mk-by-n)))))))
; Multiple Precision Reals
; ========================
;
; To produce multiple precision reals we produce a large integer value
; and convert it into a real value. This value is then normalized.
; The precision goal is unit <= 1/(m^k + 1), or 1/unit - 1 <= m^k.
; If you know more about the floating point number types of the
; Scheme system, this can be improved.
(define (mrg32k3a-random-real-mp state unit)
(do ((k 1 (+ k 1))
(u (- (/ 1 unit) 1) (/ u mrg32k3a-m1)))
((<= u 1)
(/ (exact->inexact (+ (mrg32k3a-random-power state k) 1))
(exact->inexact (+ (expt mrg32k3a-m-max k) 1))))))
; Provide the Interface as Specified in the SRFI
; ==============================================
;
; An object of type random-source is a record containing the procedures
; as components. The actual state of the generator is stored in the
; binding-time environment of make-random-source.
(define (make-random-source)
(let ((state (mrg32k3a-pack-state ; make a new copy
(list->vector (vector->list mrg32k3a-initial-state)))))
(\:random-source-make
(lambda ()
(mrg32k3a-state-ref state))
(lambda (new-state)
(set! state (mrg32k3a-state-set new-state)))
(lambda ()
(set! state (mrg32k3a-randomize-state state)))
(lambda (i j)
(set! state (mrg32k3a-pseudo-randomize-state i j)))
(lambda ()
(lambda (n)
(cond
((not (and (integer? n) (exact? n) (positive? n)))
(error "range must be exact positive integer" n))
((<= n mrg32k3a-m-max)
(mrg32k3a-random-integer state n))
(else
(mrg32k3a-random-large state n)))))
(lambda args
(cond
((null? args)
(lambda ()
(mrg32k3a-random-real state)))
((null? (cdr args))
(let ((unit (car args)))
(cond
((not (and (real? unit) (< 0 unit 1)))
(error "unit must be real in (0,1)" unit))
((<= (- (/ 1 unit) 1) mrg32k3a-m1)
(lambda ()
(mrg32k3a-random-real state)))
(else
(lambda ()
(mrg32k3a-random-real-mp state unit))))))
(else
(error "illegal arguments" args)))))))
(define random-source?
\:random-source?)
(define (random-source-state-ref s)
((\:random-source-state-ref s)))
(define (random-source-state-set! s state)
((\:random-source-state-set! s) state))
(define (random-source-randomize! s)
((\:random-source-randomize! s)))
(define (random-source-pseudo-randomize! s i j)
((\:random-source-pseudo-randomize! s) i j))
; ---
(define (random-source-make-integers s)
((\:random-source-make-integers s)))
(define (random-source-make-reals s . unit)
(apply (\:random-source-make-reals s) unit))
; ---
(define default-random-source
(make-random-source))
(define random-integer
(random-source-make-integers default-random-source))
(define random-real
(random-source-make-reals default-random-source))
(define-library (srfi 27)
(export
random-integer
random-real
default-random-source
make-random-source
random-source?
random-source-state-ref
random-source-state-set!
random-source-randomize!
random-source-pseudo-randomize!
random-source-make-integers
random-source-make-reals
)
(import
(scheme base)
(scheme time))
(begin
(define-record-type \:random-source
(\\:random-source-make
state-ref
state-set!
randomize!
pseudo-randomize!
make-integers
make-reals)
\:random-source?
(state-ref \:random-source-state-ref)
(state-set! \:random-source-state-set!)
(randomize! \:random-source-randomize!)
(pseudo-randomize! \:random-source-pseudo-randomize!)
(make-integers \:random-source-make-integers)
(make-reals \:random-source-make-reals))
(define (\\:random-source-current-time)
(current-jiffy))
(define exact->inexact inexact)
)
(include "27.mrg32k3a-a.upstream.scm")
(include "27.mrg32k3a.upstream.scm"))
;; Copyright (C) Scott G. Miller (2002). All Rights Reserved.
;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-library (srfi 28)
(export format)
(import
(scheme base)
(scheme write))
(begin
(define format
(lambda (format-string . objects)
(let ((buffer (open-output-string)))
(let loop ((format-list (string->list format-string))
(objects objects))
(cond ((null? format-list) (get-output-string buffer))
((char=? (car format-list) #\~)
(if (null? (cdr format-list))
(error 'format "Incomplete escape sequence")
(case (cadr format-list)
((#\a)
(if (null? objects)
(error 'format "No value for escape sequence")
(begin
(display (car objects) buffer)
(loop (cddr format-list) (cdr objects)))))
((#\s)
(if (null? objects)
(error 'format "No value for escape sequence")
(begin
(write (car objects) buffer)
(loop (cddr format-list) (cdr objects)))))
((#\%)
(newline buffer)
(loop (cddr format-list) objects))
((#\~)
(write-char #\~ buffer)
(loop (cddr format-list) objects))
(else
(error 'format "Unrecognized escape sequence")))))
(else (write-char (car format-list) buffer)
(loop (cdr format-list) objects)))))))))
;; Copyright (C) Taylan Ulrich Bayırlı/Kammer (2015). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(define-library (srfi 31)
(export rec)
(import (scheme base))
(begin
(define-syntax rec
(syntax-rules ()
((rec (name . args) body ...)
(letrec ((name (lambda args body ...)))
name))
((rec name expr)
(letrec ((name expr))
name))))))
;; Copyright (C) Richard Kelsey, Michael Sperber (2002). All Rights Reserved.
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-record-type <condition-type>
(really-make-condition-type name supertype fields all-fields)
condition-type?
(name condition-type-name)
(supertype condition-type-supertype)
(fields condition-type-fields)
(all-fields condition-type-all-fields))
(define (make-condition-type name supertype fields)
(if (not (symbol? name))
(error "make-condition-type: name is not a symbol"
name))
(if (not (condition-type? supertype))
(error "make-condition-type: supertype is not a condition type"
supertype))
(if (not
(null? (lset-intersection eq?
(condition-type-all-fields supertype)
fields)))
(error "duplicate field name" ))
(really-make-condition-type name
supertype
fields
(append (condition-type-all-fields supertype)
fields)))
(define-syntax define-condition-type
(syntax-rules ()
((define-condition-type ?name ?supertype ?predicate
(?field1 ?accessor1) ...)
(begin
(define ?name
(make-condition-type '?name
?supertype
'(?field1 ...)))
(define (?predicate thing)
(and (condition? thing)
(condition-has-type? thing ?name)))
(define (?accessor1 condition)
(condition-ref (extract-condition condition ?name)
'?field1))
...))))
(define (condition-subtype? subtype supertype)
(let recur ((subtype subtype))
(cond ((not subtype) #f)
((eq? subtype supertype) #t)
(else
(recur (condition-type-supertype subtype))))))
(define (condition-type-field-supertype condition-type field)
(let loop ((condition-type condition-type))
(cond ((not condition-type) #f)
((memq field (condition-type-fields condition-type))
condition-type)
(else
(loop (condition-type-supertype condition-type))))))
; The type-field-alist is of the form
; ((<type> (<field-name> . <value>) ...) ...)
(define-record-type <condition>
(really-make-condition type-field-alist)
condition?
(type-field-alist condition-type-field-alist))
(define (make-condition type . field-plist)
(let ((alist (let label ((plist field-plist))
(if (null? plist)
'()
(cons (cons (car plist)
(cadr plist))
(label (cddr plist)))))))
(if (not (lset= eq?
(condition-type-all-fields type)
(map car alist)))
(error "condition fields don't match condition type"))
(really-make-condition (list (cons type alist)))))
(define (condition-has-type? condition type)
(any (lambda (has-type)
(condition-subtype? has-type type))
(condition-types condition)))
(define (condition-ref condition field)
(type-field-alist-ref (condition-type-field-alist condition)
field))
(define (type-field-alist-ref type-field-alist field)
(let loop ((type-field-alist type-field-alist))
(cond ((null? type-field-alist)
(error "type-field-alist-ref: field not found"
type-field-alist field))
((assq field (cdr (car type-field-alist)))
=> cdr)
(else
(loop (cdr type-field-alist))))))
(define (make-compound-condition condition-1 . conditions)
(really-make-condition
(apply append (map condition-type-field-alist
(cons condition-1 conditions)))))
(define (extract-condition condition type)
(let ((entry (find (lambda (entry)
(condition-subtype? (car entry) type))
(condition-type-field-alist condition))))
(if (not entry)
(error "extract-condition: invalid condition type"
condition type))
(really-make-condition
(list (cons type
(map (lambda (field)
(assq field (cdr entry)))
(condition-type-all-fields type)))))))
(define-syntax condition
(syntax-rules ()
((condition (?type1 (?field1 ?value1) ...) ...)
(type-field-alist->condition
(list
(cons ?type1
(list (cons '?field1 ?value1) ...))
...)))))
(define (type-field-alist->condition type-field-alist)
(really-make-condition
(map (lambda (entry)
(cons (car entry)
(map (lambda (field)
(or (assq field (cdr entry))
(cons field
(type-field-alist-ref type-field-alist field))))
(condition-type-all-fields (car entry)))))
type-field-alist)))
(define (condition-types condition)
(map car (condition-type-field-alist condition)))
(define (check-condition-type-field-alist the-type-field-alist)
(let loop ((type-field-alist the-type-field-alist))
(if (not (null? type-field-alist))
(let* ((entry (car type-field-alist))
(type (car entry))
(field-alist (cdr entry))
(fields (map car field-alist))
(all-fields (condition-type-all-fields type)))
(for-each (lambda (missing-field)
(let ((supertype
(condition-type-field-supertype type missing-field)))
(if (not
(any (lambda (entry)
(let ((type (car entry)))
(condition-subtype? type supertype)))
the-type-field-alist))
(error "missing field in condition construction"
type
missing-field))))
(lset-difference eq? all-fields fields))
(loop (cdr type-field-alist))))))
(define &condition (really-make-condition-type '&condition
#f
'()
'()))
(define-condition-type &message &condition
message-condition?
(message condition-message))
(define-condition-type &serious &condition
serious-condition?)
(define-condition-type &error &serious
error?)
(define-library (srfi 35)
(export
make-condition-type
condition-type?
make-condition
condition?
condition-has-type?
condition-ref
make-compound-condition
extract-condition
define-condition-type
condition
&condition
&message
&serious
&error
)
(import
(scheme base)
(srfi 1))
(include "35.body.scm"))
(define-library (srfi 64)
(import
(srfi 64 test-runner)
(srfi 64 test-runner-simple)
(srfi 64 execution))
(export
;; Execution
test-begin test-end test-group test-group-with-cleanup
test-skip test-expect-fail
test-match-name test-match-nth
test-match-all test-match-any
test-assert test-eqv test-eq test-equal test-approximate
test-error test-read-eval-string
test-apply test-with-runner
test-exit
;; Test runner
test-runner-null test-runner? test-runner-reset
test-result-alist test-result-alist!
test-result-ref test-result-set!
test-result-remove test-result-clear
test-runner-pass-count
test-runner-fail-count
test-runner-xpass-count
test-runner-xfail-count
test-runner-skip-count
test-runner-test-name
test-runner-group-path
test-runner-group-stack
test-runner-aux-value test-runner-aux-value!
test-result-kind test-passed?
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
test-runner-factory test-runner-create
test-runner-current test-runner-get
;; Simple test runner
test-runner-simple
test-on-group-begin-simple test-on-group-end-simple test-on-final-simple
test-on-test-begin-simple test-on-test-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
))
;; Copyright (C) Richard Kelsey, Michael Sperber (2002). All Rights Reserved.
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-record-type condition-type
(really-make-condition-type name supertype fields all-fields)
condition-type?
(name condition-type-name)
(supertype condition-type-supertype)
(fields condition-type-fields)
(all-fields condition-type-all-fields))
(define (make-condition-type name supertype fields)
(if (not (symbol? name))
(error "make-condition-type: name is not a symbol"
name))
(if (not (condition-type? supertype))
(error "make-condition-type: supertype is not a condition type"
supertype))
(if (not
(null? (lset-intersection eq?
(condition-type-all-fields supertype)
fields)))
(error "duplicate field name" ))
(really-make-condition-type name
supertype
fields
(append (condition-type-all-fields supertype)
fields)))
(define-syntax define-condition-type
(syntax-rules ()
((define-condition-type ?name ?supertype ?predicate
(?field1 ?accessor1) ...)
(begin
(define ?name
(make-condition-type '?name
?supertype
'(?field1 ...)))
(define (?predicate thing)
(and (condition? thing)
(condition-has-type? thing ?name)))
(define (?accessor1 condition)
(condition-ref (extract-condition condition ?name)
'?field1))
...))))
(define (condition-subtype? subtype supertype)
(let recur ((subtype subtype))
(cond ((not subtype) #f)
((eq? subtype supertype) #t)
(else
(recur (condition-type-supertype subtype))))))
(define (condition-type-field-supertype condition-type field)
(let loop ((condition-type condition-type))
(cond ((not condition-type) #f)
((memq field (condition-type-fields condition-type))
condition-type)
(else
(loop (condition-type-supertype condition-type))))))
; The type-field-alist is of the form
; ((<type> (<field-name> . <value>) ...) ...)
(define-record-type condition
(really-make-condition type-field-alist)
condition?
(type-field-alist condition-type-field-alist))
(define (make-condition type . field-plist)
(let ((alist (let label ((plist field-plist))
(if (null? plist)
'()
(cons (cons (car plist)
(cadr plist))
(label (cddr plist)))))))
(if (not (lset= eq?
(condition-type-all-fields type)
(map car alist)))
(error "condition fields don't match condition type"))
(really-make-condition (list (cons type alist)))))
(define (condition-has-type? condition type)
(any (lambda (has-type)
(condition-subtype? has-type type))
(condition-types condition)))
(define (condition-ref condition field)
(type-field-alist-ref (condition-type-field-alist condition)
field))
(define (type-field-alist-ref type-field-alist field)
(let loop ((type-field-alist type-field-alist))
(cond ((null? type-field-alist)
(error "type-field-alist-ref: field not found"
type-field-alist field))
((assq field (cdr (car type-field-alist)))
=> cdr)
(else
(loop (cdr type-field-alist))))))
(define (make-compound-condition condition-1 . conditions)
(really-make-condition
(apply append (map condition-type-field-alist
(cons condition-1 conditions)))))
(define (extract-condition condition type)
(let ((entry (find (lambda (entry)
(condition-subtype? (car entry) type))
(condition-type-field-alist condition))))
(if (not entry)
(error "extract-condition: invalid condition type"
condition type))
(really-make-condition
(list (cons type
(map (lambda (field)
(assq field (cdr entry)))
(condition-type-all-fields type)))))))
(define-syntax condition
(syntax-rules ()
((condition (?type1 (?field1 ?value1) ...) ...)
(type-field-alist->condition
(list
(cons ?type1
(list (cons '?field1 ?value1) ...))
...)))))
(define (type-field-alist->condition type-field-alist)
(really-make-condition
(map (lambda (entry)
(cons (car entry)
(map (lambda (field)
(or (assq field (cdr entry))
(cons field
(type-field-alist-ref type-field-alist field))))
(condition-type-all-fields (car entry)))))
type-field-alist)))
(define (condition-types condition)
(map car (condition-type-field-alist condition)))
(define (check-condition-type-field-alist the-type-field-alist)
(let loop ((type-field-alist the-type-field-alist))
(if (not (null? type-field-alist))
(let* ((entry (car type-field-alist))
(type (car entry))
(field-alist (cdr entry))
(fields (map car field-alist))
(all-fields (condition-type-all-fields type)))
(for-each (lambda (missing-field)
(let ((supertype
(condition-type-field-supertype type missing-field)))
(if (not
(any (lambda (entry)
(let ((type (car entry)))
(condition-subtype? type supertype)))
the-type-field-alist))
(error "missing field in condition construction"
type
missing-field))))
(lset-difference eq? all-fields fields))
(loop (cdr type-field-alist))))))
(define &condition (really-make-condition-type '&condition
#f
'()
'()))
(define-condition-type &message &condition
message-condition?
(message condition-message))
(define-condition-type &serious &condition
serious-condition?)
(define-condition-type &error &serious
error?)
;;; args-fold.scm - a program argument processor
;;;
;;; Copyright (c) 2002 Anthony Carrico
;;; Copyright (c) 2014 Taylan Ulrich Bayırlı/Kammer
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; 3. The name of the authors may not be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(define-record-type <option>
(option names required-arg? optional-arg? processor)
option?
(names option-names)
(required-arg? option-required-arg?)
(optional-arg? option-optional-arg?)
(processor option-processor))
(define (args-fold args options unrecognized-option-proc operand-proc . seeds)
(define (find-option name)
;; ISSUE: This is a brute force search. Could use a table.
(find (lambda (option)
(find (lambda (test-name)
(equal? name test-name))
(option-names option)))
options))
(define (scan-short-options index shorts args seeds)
(if (= index (string-length shorts))
(scan-args args seeds)
(let* ((name (string-ref shorts index))
(option (or (find-option name)
(option (list name)
#f
#f
unrecognized-option-proc))))
(cond
((and (< (+ index 1) (string-length shorts))
(or (option-required-arg? option)
(option-optional-arg? option)))
(let-values
((seeds (apply (option-processor option)
option
name
(substring
shorts
(+ index 1)
(string-length shorts))
seeds)))
(scan-args args seeds)))
((and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds)))
(else
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-short-options
(+ index 1)
shorts
args
seeds)))))))
(define (scan-operands operands seeds)
(if (null? operands)
(apply values seeds)
(let-values ((seeds (apply operand-proc
(car operands)
seeds)))
(scan-operands (cdr operands) seeds))))
(define (scan-args args seeds)
(if (null? args)
(apply values seeds)
(let ((arg (car args))
(args (cdr args)))
;; NOTE: This string matching code would be simpler
;; using a regular expression matcher.
(cond
((string=? "--" arg)
;; End option scanning:
(scan-operands args seeds))
((and (> (string-length arg) 4)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1))
(not (char=? #\= (string-ref arg 2)))
(let loop ((index 3))
(cond ((= index (string-length arg))
#f)
((char=? #\= (string-ref arg index))
index)
(else
(loop (+ 1 index))))))
;; Found long option with arg:
=> (lambda (=-index)
(let*-values
(((name)
(substring arg 2 =-index))
((option-arg)
(substring arg
(+ =-index 1)
(string-length arg)))
((option)
(or (find-option name)
(option (list name)
#t
#f
unrecognized-option-proc)))
(seeds
(apply (option-processor option)
option
name
option-arg
seeds)))
(scan-args args seeds))))
((and (> (string-length arg) 3)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1)))
;; Found long option:
(let* ((name (substring arg 2 (string-length arg)))
(option (or (find-option name)
(option
(list name)
#f
#f
unrecognized-option-proc))))
(if (and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds))
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-args args seeds)))))
((and (> (string-length arg) 1)
(char=? #\- (string-ref arg 0)))
;; Found short options
(let ((shorts (substring arg 1 (string-length arg))))
(scan-short-options 0 shorts args seeds)))
(else
(let-values ((seeds (apply operand-proc arg seeds)))
(scan-args args seeds)))))))
(scan-args args seeds))
(define-library (srfi 37)
(export
args-fold
option
option-names
option-required-arg?
option-optional-arg?
option-processor
)
(import
(scheme base)
(srfi 1))
(include "37.body.scm"))
;;; Copyright (C) 2006 Chongkai Zhu. All Rights Reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-library (srfi 87)
(export case)
(import (except (scheme base) case))
(begin
(define-syntax case
(syntax-rules (else =>)
((case (key ...)
clauses ...)
(let ((atom-key (key ...)))
(case atom-key clauses ...)))
((case key
(else => result))
(result key))
((case key
((atoms ...) => result))
(if (memv key '(atoms ...))
(result key)))
((case key
((atoms ...) => result)
clause clauses ...)
(if (memv key '(atoms ...))
(result key)
(case key clause clauses ...)))
((case key
(else result1 result2 ...))
(begin result1 result2 ...))
((case key
((atoms ...) result1 result2 ...))
(if (memv key '(atoms ...))
(begin result1 result2 ...)))
((case key
((atoms ...) result1 result2 ...)
clause clauses ...)
(if (memv key '(atoms ...))
(begin result1 result2 ...)
(case key clause clauses ...)))))))
;;; args-fold.scm - a program argument processor
;;;
;;; Copyright (c) 2002 Anthony Carrico
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; 3. The name of the authors may not be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;; NOTE: This implementation uses the following SRFIs:
;;; "SRFI 9: Defining Record Types"
;;; "SRFI 11: Syntax for receiving multiple values"
;;;
;;; NOTE: The scsh-utils and Chicken implementations use regular
;;; expressions. These might be easier to read and understand.
(define option #f)
(define option-names #f)
(define option-required-arg? #f)
(define option-optional-arg? #f)
(define option-processor #f)
(define option? #f)
(let ()
(define-record-type option-type
($option names required-arg? optional-arg? processor)
$option?
(names $option-names)
(required-arg? $option-required-arg?)
(optional-arg? $option-optional-arg?)
(processor $option-processor))
(set! option $option)
(set! option-names $option-names)
(set! option-required-arg? $option-required-arg?)
(set! option-optional-arg? $option-optional-arg?)
(set! option-processor $option-processor)
(set! option? $option?))
(define args-fold
(lambda (args
options
unrecognized-option-proc
operand-proc
. seeds)
(letrec
((find
(lambda (l ?)
(cond ((null? l) #f)
((? (car l)) (car l))
(else (find (cdr l) ?)))))
(find-option
;; ISSUE: This is a brute force search. Could use a table.
(lambda (name)
(find
options
(lambda (option)
(find
(option-names option)
(lambda (test-name)
(equal? name test-name)))))))
(scan-short-options
(lambda (index shorts args seeds)
(if (= index (string-length shorts))
(scan-args args seeds)
(let* ((name (string-ref shorts index))
(option (or (find-option name)
(option (list name)
#f
#f
unrecognized-option-proc))))
(cond ((and (< (+ index 1) (string-length shorts))
(or (option-required-arg? option)
(option-optional-arg? option)))
(let-values
((seeds (apply (option-processor option)
option
name
(substring
shorts
(+ index 1)
(string-length shorts))
seeds)))
(scan-args args seeds)))
((and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds)))
(else
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-short-options
(+ index 1)
shorts
args
seeds))))))))
(scan-operands
(lambda (operands seeds)
(if (null? operands)
(apply values seeds)
(let-values ((seeds (apply operand-proc
(car operands)
seeds)))
(scan-operands (cdr operands) seeds)))))
(scan-args
(lambda (args seeds)
(if (null? args)
(apply values seeds)
(let ((arg (car args))
(args (cdr args)))
;; NOTE: This string matching code would be simpler
;; using a regular expression matcher.
(cond
(;; (rx bos "--" eos)
(string=? "--" arg)
;; End option scanning:
(scan-operands args seeds))
(;;(rx bos
;; "--"
;; (submatch (+ (~ "=")))
;; "="
;; (submatch (* any)))
(and (> (string-length arg) 4)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1))
(not (char=? #\= (string-ref arg 2)))
(let loop ((index 3))
(cond ((= index (string-length arg))
#f)
((char=? #\= (string-ref arg index))
index)
(else
(loop (+ 1 index))))))
;; Found long option with arg:
=> (lambda (=-index)
(let*-values
(((name)
(substring arg 2 =-index))
((option-arg)
(substring arg
(+ =-index 1)
(string-length arg)))
((option)
(or (find-option name)
(option (list name)
#t
#f
unrecognized-option-proc)))
(seeds
(apply (option-processor option)
option
name
option-arg
seeds)))
(scan-args args seeds))))
(;;(rx bos "--" (submatch (+ any)))
(and (> (string-length arg) 3)
(char=? #\- (string-ref arg 0))
(char=? #\- (string-ref arg 1)))
;; Found long option:
(let* ((name (substring arg 2 (string-length arg)))
(option (or (find-option name)
(option
(list name)
#f
#f
unrecognized-option-proc))))
(if (and (option-required-arg? option)
(pair? args))
(let-values
((seeds (apply (option-processor option)
option
name
(car args)
seeds)))
(scan-args (cdr args) seeds))
(let-values
((seeds (apply (option-processor option)
option
name
#f
seeds)))
(scan-args args seeds)))))
(;; (rx bos "-" (submatch (+ any)))
(and (> (string-length arg) 1)
(char=? #\- (string-ref arg 0)))
;; Found short options
(let ((shorts (substring arg 1 (string-length arg))))
(scan-short-options 0 shorts args seeds)))
(else
(let-values ((seeds (apply operand-proc arg seeds)))
(scan-args args seeds)))))))))
(scan-args args seeds))))
(define-library (srfi 41)
(export
stream-null stream-cons stream? stream-null? stream-pair? stream-car
stream-cdr stream-lambda define-stream list->stream port->stream stream
stream->list stream-append stream-concat stream-constant stream-drop
stream-drop-while stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map stream-match _
stream-of stream-range stream-ref stream-reverse stream-scan stream-take
stream-take-while stream-unfold stream-unfolds stream-zip
)
(import
(srfi 41 primitive)
(srfi 41 derived)))
; <PLAINTEXT>
; Eager Comprehensions in [outer..inner|expr]-Convention
; ======================================================
;
; sebastian.egner@philips.com, Eindhoven, The Netherlands, 26-Dec-2007
; Scheme R5RS (incl. macros), SRFI-23 (error).
;
; Loading the implementation into Scheme48 0.57:
; ,open srfi-23
; ,load ec.scm
;
; Loading the implementation into PLT/DrScheme 317:
; ; File > Open ... "ec.scm", click Execute
;
; Loading the implementation into SCM 5d7:
; (require 'macro) (require 'record)
; (load "ec.scm")
;
; Implementation comments:
; * All local (not exported) identifiers are named ec-<something>.
; * This implementation focuses on portability, performance,
; readability, and simplicity roughly in this order. Design
; decisions related to performance are taken for Scheme48.
; * Alternative implementations, Comments and Warnings are
; mentioned after the definition with a heading.
; ==========================================================================
; The fundamental comprehension do-ec
; ==========================================================================
;
; All eager comprehensions are reduced into do-ec and
; all generators are reduced to :do.
;
; We use the following short names for syntactic variables
; q - qualifier
; cc - current continuation, thing to call at the end;
; the CPS is (m (cc ...) arg ...) -> (cc ... expr ...)
; cmd - an expression being evaluated for its side-effects
; expr - an expression
; gen - a generator of an eager comprehension
; ob - outer binding
; oc - outer command
; lb - loop binding
; ne1? - not-end1? (before the payload)
; ib - inner binding
; ic - inner command
; ne2? - not-end2? (after the payload)
; ls - loop step
; etc - more arguments of mixed type
; (do-ec q ... cmd)
; handles nested, if/not/and/or, begin, :let, and calls generator
; macros in CPS to transform them into fully decorated :do.
; The code generation for a :do is delegated to do-ec:do.
(define-syntax do-ec
(syntax-rules (nested if not and or begin do let)
; explicit nesting -> implicit nesting
((do-ec (nested q ...) etc ...)
(do-ec q ... etc ...) )
; implicit nesting -> fold do-ec
((do-ec q1 q2 etc1 etc ...)
(do-ec q1 (do-ec q2 etc1 etc ...)) )
; no qualifiers at all -> evaluate cmd once
((do-ec cmd)
(begin cmd (if #f #f)) )
; now (do-ec q cmd) remains
; filter -> make conditional
((do-ec (if test) cmd)
(if test (do-ec cmd)) )
((do-ec (not test) cmd)
(if (not test) (do-ec cmd)) )
((do-ec (and test ...) cmd)
(if (and test ...) (do-ec cmd)) )
((do-ec (or test ...) cmd)
(if (or test ...) (do-ec cmd)) )
; begin -> make a sequence
((do-ec (begin etc ...) cmd)
(begin etc ... (do-ec cmd)) )
; fully decorated :do-generator -> delegate to do-ec:do
((do-ec (#\:do olet lbs ne1? ilet ne2? lss) cmd)
(do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss)) )
; anything else -> call generator-macro in CPS; reentry at (*)
((do-ec (g arg1 arg ...) cmd)
(g (do-ec:do cmd) arg1 arg ...) )))
; (do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss))
; generates code for a single fully decorated :do-generator
; with cmd as payload, taking care of special cases.
(define-syntax do-ec:do
(syntax-rules (#\:do let)
; reentry point (*) -> generate code
((do-ec:do cmd
(#\:do (let obs oc ...)
lbs
ne1?
(let ibs ic ...)
ne2?
(ls ...) ))
(ec-simplify
(let obs
oc ...
(let loop lbs
(ec-simplify
(if ne1?
(ec-simplify
(let ibs
ic ...
cmd
(ec-simplify
(if ne2?
(loop ls ...) )))))))))) ))
; (ec-simplify <expression>)
; generates potentially more efficient code for <expression>.
; The macro handles if, (begin <command>*), and (let () <command>*)
; and takes care of special cases.
(define-syntax ec-simplify
(syntax-rules (if not let begin)
; one- and two-sided if
; literal <test>
((ec-simplify (if #t consequent))
consequent )
((ec-simplify (if #f consequent))
(if #f #f) )
((ec-simplify (if #t consequent alternate))
consequent )
((ec-simplify (if #f consequent alternate))
alternate )
; (not (not <test>))
((ec-simplify (if (not (not test)) consequent))
(ec-simplify (if test consequent)) )
((ec-simplify (if (not (not test)) consequent alternate))
(ec-simplify (if test consequent alternate)) )
; (let () <command>*)
; empty <binding spec>*
((ec-simplify (let () command ...))
(ec-simplify (begin command ...)) )
; begin
; flatten use helper (ec-simplify 1 done to-do)
((ec-simplify (begin command ...))
(ec-simplify 1 () (command ...)) )
((ec-simplify 1 done ((begin to-do1 ...) to-do2 ...))
(ec-simplify 1 done (to-do1 ... to-do2 ...)) )
((ec-simplify 1 (done ...) (to-do1 to-do ...))
(ec-simplify 1 (done ... to-do1) (to-do ...)) )
; exit helper
((ec-simplify 1 () ())
(if #f #f) )
((ec-simplify 1 (command) ())
command )
((ec-simplify 1 (command1 command ...) ())
(begin command1 command ...) )
; anything else
((ec-simplify expression)
expression )))
; ==========================================================================
; The special generators :do, :let, :parallel, :while, and :until
; ==========================================================================
(define-syntax \:do
(syntax-rules ()
; full decorated -> continue with cc, reentry at (*)
((#\:do (cc ...) olet lbs ne1? ilet ne2? lss)
(cc ... (#\:do olet lbs ne1? ilet ne2? lss)) )
; short form -> fill in default values
((#\:do cc lbs ne1? lss)
(#\:do cc (let ()) lbs ne1? (let ()) #t lss) )))
(define-syntax \:let
(syntax-rules (index)
((\:let cc var (index i) expression)
(#\:do cc (let ((var expression) (i 0))) () #t (let ()) #f ()) )
((\:let cc var expression)
(#\:do cc (let ((var expression))) () #t (let ()) #f ()) )))
(define-syntax \:parallel
(syntax-rules (#\:do)
((\:parallel cc)
cc )
((\:parallel cc (g arg1 arg ...) gen ...)
(g (\:parallel-1 cc (gen ...)) arg1 arg ...) )))
; (\:parallel-1 cc (to-do ...) result [ next ] )
; iterates over to-do by converting the first generator into
; the :do-generator next and merging next into result.
(define-syntax \:parallel-1 ; used as
(syntax-rules (#\:do let)
; process next element of to-do, reentry at (**)
((\:parallel-1 cc ((g arg1 arg ...) gen ...) result)
(g (\:parallel-1 cc (gen ...) result) arg1 arg ...) )
; reentry point (**) -> merge next into result
((\:parallel-1
cc
gens
(#\:do (let (ob1 ...) oc1 ...)
(lb1 ...)
ne1?1
(let (ib1 ...) ic1 ...)
ne2?1
(ls1 ...) )
(#\:do (let (ob2 ...) oc2 ...)
(lb2 ...)
ne1?2
(let (ib2 ...) ic2 ...)
ne2?2
(ls2 ...) ))
(\:parallel-1
cc
gens
(#\:do (let (ob1 ... ob2 ...) oc1 ... oc2 ...)
(lb1 ... lb2 ...)
(and ne1?1 ne1?2)
(let (ib1 ... ib2 ...) ic1 ... ic2 ...)
(and ne2?1 ne2?2)
(ls1 ... ls2 ...) )))
; no more gens -> continue with cc, reentry at (*)
((\:parallel-1 (cc ...) () result)
(cc ... result) )))
(define-syntax \:while
(syntax-rules ()
((\:while cc (g arg1 arg ...) test)
(g (\:while-1 cc test) arg1 arg ...) )))
; (\:while-1 cc test (#\:do ...))
; modifies the fully decorated :do-generator such that it
; runs while test is a true value.
; The original implementation just replaced ne1? by
; (and ne1? test) as follows:
;
; (define-syntax \:while-1
; (syntax-rules (#\:do)
; ((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
; (#\:do cc olet lbs (and ne1? test) ilet ne2? lss) )))
;
; Bug #1:
; Unfortunately, this code is wrong because ne1? may depend
; in the inner bindings introduced in ilet, but ne1? is evaluated
; outside of the inner bindings. (Refer to the specification of
; :do to see the structure.)
; The problem manifests itself (as sunnan@handgranat.org
; observed, 25-Apr-2005) when the :list-generator is modified:
;
; (do-ec (\:while (\:list x '(1 2)) (= x 1)) (display x)).
;
; In order to generate proper code, we introduce temporary
; variables saving the values of the inner bindings. The inner
; bindings are executed in a new ne1?, which also evaluates ne1?
; outside the scope of the inner bindings, then the inner commands
; are executed (possibly changing the variables), and then the
; values of the inner bindings are saved and (and ne1? test) is
; returned. In the new ilet, the inner variables are bound and
; initialized and their values are restored. So we construct:
;
; (let (ob .. (ib-tmp #f) ...)
; oc ...
; (let loop (lb ...)
; (if (let (ne1?-value ne1?)
; (let ((ib-var ib-rhs) ...)
; ic ...
; (set! ib-tmp ib-var) ...)
; (and ne1?-value test))
; (let ((ib-var ib-tmp) ...)
; /payload/
; (if ne2?
; (loop ls ...) )))))
;
; Bug #2:
; Unfortunately, the above expansion is still incorrect (as Jens-Axel
; Soegaard pointed out, 4-Jun-2007) because ib-rhs are evaluated even
; if ne1?-value is #f, indicating that the loop has ended.
; The problem manifests itself in the following example:
;
; (do-ec (\:while (\:list x '(1)) #t) (display x))
;
; Which iterates :list beyond exhausting the list '(1).
;
; For the fix, we follow Jens-Axel's approach of guarding the evaluation
; of ib-rhs with a check on ne1?-value.
(define-syntax \:while-1
(syntax-rules (#\:do let)
((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(\:while-2 cc test () () () (#\:do olet lbs ne1? ilet ne2? lss)))))
(define-syntax \:while-2
(syntax-rules (#\:do let)
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do olet
lbs
ne1?
(let ((ib-var ib-rhs) ib ...) ic ...)
ne2?
lss))
(\:while-2 cc
test
(ib-let ... (ib-tmp #f))
(ib-save ... (ib-var ib-rhs))
(ib-restore ... (ib-var ib-tmp))
(#\:do olet
lbs
ne1?
(let (ib ...) ic ... (set! ib-tmp ib-var))
ne2?
lss)))
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do (let (ob ...) oc ...) lbs ne1? (let () ic ...) ne2? lss))
(#\:do cc
(let (ob ... ib-let ...) oc ...)
lbs
(let ((ne1?-value ne1?))
(and ne1?-value
(let (ib-save ...)
ic ...
test)))
(let (ib-restore ...))
ne2?
lss))))
(define-syntax \:until
(syntax-rules ()
((\:until cc (g arg1 arg ...) test)
(g (\:until-1 cc test) arg1 arg ...) )))
(define-syntax \:until-1
(syntax-rules (#\:do)
((\:until-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(#\:do cc olet lbs ne1? ilet (and ne2? (not test)) lss) )))
; ==========================================================================
; The typed generators :list :string :vector etc.
; ==========================================================================
(define-syntax \:list
(syntax-rules (index)
((\:list cc var (index i) arg ...)
(\:parallel cc (\:list var arg ...) (\:integers i)) )
((\:list cc var arg1 arg2 arg ...)
(\:list cc var (append arg1 arg2 arg ...)) )
((\:list cc var arg)
(#\:do cc
(let ())
((t arg))
(not (null? t))
(let ((var (car t))))
#t
((cdr t)) ))))
(define-syntax \:string
(syntax-rules (index)
((\:string cc var (index i) arg)
(#\:do cc
(let ((str arg) (len 0))
(set! len (string-length str)))
((i 0))
(< i len)
(let ((var (string-ref str i))))
#t
((+ i 1)) ))
((\:string cc var (index i) arg1 arg2 arg ...)
(\:string cc var (index i) (string-append arg1 arg2 arg ...)) )
((\:string cc var arg1 arg ...)
(\:string cc var (index i) arg1 arg ...) )))
; Alternative: An implementation in the style of :vector can also
; be used for :string. However, it is less interesting as the
; overhead of string-append is much less than for 'vector-append'.
(define-syntax \:vector
(syntax-rules (index)
((\:vector cc var arg)
(\:vector cc var (index i) arg) )
((\:vector cc var (index i) arg)
(#\:do cc
(let ((vec arg) (len 0))
(set! len (vector-length vec)))
((i 0))
(< i len)
(let ((var (vector-ref vec i))))
#t
((+ i 1)) ))
((\:vector cc var (index i) arg1 arg2 arg ...)
(\:parallel cc (\:vector cc var arg1 arg2 arg ...) (\:integers i)) )
((\:vector cc var arg1 arg2 arg ...)
(#\:do cc
(let ((vec #f)
(len 0)
(vecs (ec-:vector-filter (list arg1 arg2 arg ...))) ))
((k 0))
(if (< k len)
#t
(if (null? vecs)
#f
(begin (set! vec (car vecs))
(set! vecs (cdr vecs))
(set! len (vector-length vec))
(set! k 0)
#t )))
(let ((var (vector-ref vec k))))
#t
((+ k 1)) ))))
(define (ec-:vector-filter vecs)
(if (null? vecs)
'()
(if (zero? (vector-length (car vecs)))
(ec-:vector-filter (cdr vecs))
(cons (car vecs) (ec-:vector-filter (cdr vecs))) )))
; Alternative: A simpler implementation for :vector uses vector->list
; append and :list in the multi-argument case. Please refer to the
; 'design.scm' for more details.
(define-syntax \:integers
(syntax-rules (index)
((\:integers cc var (index i))
(#\:do cc ((var 0) (i 0)) #t ((+ var 1) (+ i 1))) )
((\:integers cc var)
(#\:do cc ((var 0)) #t ((+ var 1))) )))
(define-syntax \:range
(syntax-rules (index)
; handle index variable and add optional args
((\:range cc var (index i) arg1 arg ...)
(\:parallel cc (\:range var arg1 arg ...) (\:integers i)) )
((\:range cc var arg1)
(\:range cc var 0 arg1 1) )
((\:range cc var arg1 arg2)
(\:range cc var arg1 arg2 1) )
; special cases (partially evaluated by hand from general case)
((\:range cc var 0 arg2 1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var 0 arg2 -1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(> var b)
(let ())
#t
((- var 1)) ))
((\:range cc var arg1 arg2 1)
(#\:do cc
(let ((a arg1) (b arg2))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b 1 )) )
((var a))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var arg1 arg2 -1)
(#\:do cc
(let ((a arg1) (b arg2) (s -1) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b -1 )) )
((var a))
(> var b)
(let ())
#t
((- var 1)) ))
; the general case
((\:range cc var arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b)
(integer? s) (exact? s) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b s ))
(if (zero? s)
(error "step size must not be zero in :range") )
(set! stop (+ a (* (max 0 (ceiling (/ (- b a) s))) s))) )
((var a))
(not (= var stop))
(let ())
#t
((+ var s)) ))))
; Comment: The macro :range inserts some code to make sure the values
; are exact integers. This overhead has proven very helpful for
; saving users from themselves.
(define-syntax \:real-range
(syntax-rules (index)
; add optional args and index variable
((\:real-range cc var arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var (index i) arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var (index i) arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var arg1 arg2 arg3)
(\:real-range cc var (index i) arg1 arg2 arg3) )
; the fully qualified case
((\:real-range cc var (index i) arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (istop 0))
(if (not (and (real? a) (real? b) (real? s)))
(error "arguments of :real-range are not real" a b s) )
(if (and (exact? a) (or (not (exact? b)) (not (exact? s))))
(set! a (inexact a)) )
(set! istop (/ (- b a) s)) )
((i 0))
(< i istop)
(let ((var (+ a (* s i)))))
#t
((+ i 1)) ))))
; Comment: The macro :real-range adapts the exactness of the start
; value in case any of the other values is inexact. This is a
; precaution to avoid (list-ec (\: x 0 3.0) x) => '(0 1.0 2.0).
(define-syntax \:char-range
(syntax-rules (index)
((\:char-range cc var (index i) arg1 arg2)
(\:parallel cc (\:char-range var arg1 arg2) (\:integers i)) )
((\:char-range cc var arg1 arg2)
(#\:do cc
(let ((imax (char->integer arg2))))
((i (char->integer arg1)))
(<= i imax)
(let ((var (integer->char i))))
#t
((+ i 1)) ))))
; Warning: There is no R5RS-way to implement the :char-range generator
; because the integers obtained by char->integer are not necessarily
; consecutive. We simply assume this anyhow for illustration.
(define-syntax \:port
(syntax-rules (index)
((\:port cc var (index i) arg1 arg ...)
(\:parallel cc (\:port var arg1 arg ...) (\:integers i)) )
((\:port cc var arg)
(\:port cc var arg read) )
((\:port cc var arg1 arg2)
(#\:do cc
(let ((port arg1) (read-proc arg2)))
((var (read-proc port)))
(not (eof-object? var))
(let ())
#t
((read-proc port)) ))))
; ==========================================================================
; The typed generator :dispatched and utilities for constructing dispatchers
; ==========================================================================
(define-syntax \:dispatched
(syntax-rules (index)
((\:dispatched cc var (index i) dispatch arg1 arg ...)
(\:parallel cc
(\:integers i)
(\:dispatched var dispatch arg1 arg ...) ))
((\:dispatched cc var dispatch arg1 arg ...)
(#\:do cc
(let ((d dispatch)
(args (list arg1 arg ...))
(g #f)
(empty (list #f)) )
(set! g (d args))
(if (not (procedure? g))
(error "unrecognized arguments in dispatching"
args
(d '()) )))
((var (g empty)))
(not (eq? var empty))
(let ())
#t
((g empty)) ))))
; Comment: The unique object empty is created as a newly allocated
; non-empty list. It is compared using eq? which distinguishes
; the object from any other object, according to R5RS 6.1.
(define-syntax \:generator-proc
(syntax-rules (#\:do let)
; call g with a variable, reentry at (**)
((\:generator-proc (g arg ...))
(g (\:generator-proc var) var arg ...) )
; reentry point (**) -> make the code from a single :do
((\:generator-proc
var
(#\:do (let obs oc ...)
((lv li) ...)
ne1?
(let ((i v) ...) ic ...)
ne2?
(ls ...)) )
(ec-simplify
(let obs
oc ...
(let ((lv li) ... (ne2 #t))
(ec-simplify
(let ((i #f) ...) ; v not yet valid
(lambda (empty)
(if (and ne1? ne2)
(ec-simplify
(begin
(set! i v) ...
ic ...
(let ((value var))
(ec-simplify
(if ne2?
(ec-simplify
(begin (set! lv ls) ...) )
(set! ne2 #f) ))
value )))
empty ))))))))
; silence warnings of some macro expanders
((\:generator-proc var)
(error "illegal macro call") )))
(define (dispatch-union d1 d2)
(lambda (args)
(let ((g1 (d1 args)) (g2 (d2 args)))
(if g1
(if g2
(if (null? args)
(append (if (list? g1) g1 (list g1))
(if (list? g2) g2 (list g2)) )
(error "dispatching conflict" args (d1 '()) (d2 '())) )
g1 )
(if g2 g2 #f) ))))
; ==========================================================================
; The dispatching generator :
; ==========================================================================
(define (make-initial-:-dispatch)
(lambda (args)
(case (length args)
((0) 'SRFI42)
((1) (let ((a1 (car args)))
(cond
((list? a1)
(\:generator-proc (\:list a1)) )
((string? a1)
(\:generator-proc (\:string a1)) )
((vector? a1)
(\:generator-proc (\:vector a1)) )
((and (integer? a1) (exact? a1))
(\:generator-proc (\:range a1)) )
((real? a1)
(\:generator-proc (\:real-range a1)) )
((input-port? a1)
(\:generator-proc (\:port a1)) )
(else
#f ))))
((2) (let ((a1 (car args)) (a2 (cadr args)))
(cond
((and (list? a1) (list? a2))
(\:generator-proc (\:list a1 a2)) )
((and (string? a1) (string? a1))
(\:generator-proc (\:string a1 a2)) )
((and (vector? a1) (vector? a2))
(\:generator-proc (\:vector a1 a2)) )
((and (integer? a1) (exact? a1) (integer? a2) (exact? a2))
(\:generator-proc (\:range a1 a2)) )
((and (real? a1) (real? a2))
(\:generator-proc (\:real-range a1 a2)) )
((and (char? a1) (char? a2))
(\:generator-proc (\:char-range a1 a2)) )
((and (input-port? a1) (procedure? a2))
(\:generator-proc (\:port a1 a2)) )
(else
#f ))))
((3) (let ((a1 (car args)) (a2 (cadr args)) (a3 (caddr args)))
(cond
((and (list? a1) (list? a2) (list? a3))
(\:generator-proc (\:list a1 a2 a3)) )
((and (string? a1) (string? a1) (string? a3))
(\:generator-proc (\:string a1 a2 a3)) )
((and (vector? a1) (vector? a2) (vector? a3))
(\:generator-proc (\:vector a1 a2 a3)) )
((and (integer? a1) (exact? a1)
(integer? a2) (exact? a2)
(integer? a3) (exact? a3))
(\:generator-proc (\:range a1 a2 a3)) )
((and (real? a1) (real? a2) (real? a3))
(\:generator-proc (\:real-range a1 a2 a3)) )
(else
#f ))))
(else
(letrec ((every?
(lambda (pred args)
(if (null? args)
#t
(and (pred (car args))
(every? pred (cdr args)) )))))
(cond
((every? list? args)
(\:generator-proc (\:list (apply append args))) )
((every? string? args)
(\:generator-proc (\:string (apply string-append args))) )
((every? vector? args)
(\:generator-proc (\:list (apply append (map vector->list args)))) )
(else
#f )))))))
(define \:-dispatch
(make-initial-:-dispatch) )
(define (\:-dispatch-ref)
\:-dispatch )
(define (\:-dispatch-set! dispatch)
(if (not (procedure? dispatch))
(error "not a procedure" dispatch) )
(set! \:-dispatch dispatch) )
(define-syntax \:
(syntax-rules (index)
((\: cc var (index i) arg1 arg ...)
(\:dispatched cc var (index i) \:-dispatch arg1 arg ...) )
((\: cc var arg1 arg ...)
(\:dispatched cc var \:-dispatch arg1 arg ...) )))
; ==========================================================================
; The utility comprehensions fold-ec, fold3-ec
; ==========================================================================
(define-syntax fold3-ec
(syntax-rules (nested)
((fold3-ec x0 (nested q1 ...) q etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 ... q) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 q1 q2 etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 q2) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 expression f1 f2)
(fold3-ec x0 (nested) expression f1 f2) )
((fold3-ec x0 qualifier expression f1 f2)
(let ((result #f) (empty #t))
(do-ec qualifier
(let ((value expression)) ; don't duplicate
(if empty
(begin (set! result (f1 value))
(set! empty #f) )
(set! result (f2 value result)) )))
(if empty x0 result) ))))
(define-syntax fold-ec
(syntax-rules (nested)
((fold-ec x0 (nested q1 ...) q etc1 etc2 etc ...)
(fold-ec x0 (nested q1 ... q) etc1 etc2 etc ...) )
((fold-ec x0 q1 q2 etc1 etc2 etc ...)
(fold-ec x0 (nested q1 q2) etc1 etc2 etc ...) )
((fold-ec x0 expression f2)
(fold-ec x0 (nested) expression f2) )
((fold-ec x0 qualifier expression f2)
(let ((result x0))
(do-ec qualifier (set! result (f2 expression result)))
result ))))
; ==========================================================================
; The comprehensions list-ec string-ec vector-ec etc.
; ==========================================================================
(define-syntax list-ec
(syntax-rules ()
((list-ec etc1 etc ...)
(reverse (fold-ec '() etc1 etc ... cons)) )))
; Alternative: Reverse can safely be replaced by reverse! if you have it.
;
; Alternative: It is possible to construct the result in the correct order
; using set-cdr! to add at the tail. This removes the overhead of copying
; at the end, at the cost of more book-keeping.
(define-syntax append-ec
(syntax-rules ()
((append-ec etc1 etc ...)
(apply append (list-ec etc1 etc ...)) )))
(define-syntax string-ec
(syntax-rules ()
((string-ec etc1 etc ...)
(list->string (list-ec etc1 etc ...)) )))
; Alternative: For very long strings, the intermediate list may be a
; problem. A more space-aware implementation collect the characters
; in an intermediate list and when this list becomes too large it is
; converted into an intermediate string. At the end, the intermediate
; strings are concatenated with string-append.
(define-syntax string-append-ec
(syntax-rules ()
((string-append-ec etc1 etc ...)
(apply string-append (list-ec etc1 etc ...)) )))
(define-syntax vector-ec
(syntax-rules ()
((vector-ec etc1 etc ...)
(list->vector (list-ec etc1 etc ...)) )))
; Comment: A similar approach as for string-ec can be used for vector-ec.
; However, the space overhead for the intermediate list is much lower
; than for string-ec and as there is no vector-append, the intermediate
; vectors must be copied explicitly.
(define-syntax vector-of-length-ec
(syntax-rules (nested)
((vector-of-length-ec k (nested q1 ...) q etc1 etc ...)
(vector-of-length-ec k (nested q1 ... q) etc1 etc ...) )
((vector-of-length-ec k q1 q2 etc1 etc ...)
(vector-of-length-ec k (nested q1 q2) etc1 etc ...) )
((vector-of-length-ec k expression)
(vector-of-length-ec k (nested) expression) )
((vector-of-length-ec k qualifier expression)
(let ((len k))
(let ((vec (make-vector len))
(i 0) )
(do-ec qualifier
(if (< i len)
(begin (vector-set! vec i expression)
(set! i (+ i 1)) )
(error "vector is too short for the comprehension") ))
(if (= i len)
vec
(error "vector is too long for the comprehension") ))))))
(define-syntax sum-ec
(syntax-rules ()
((sum-ec etc1 etc ...)
(fold-ec (+) etc1 etc ... +) )))
(define-syntax product-ec
(syntax-rules ()
((product-ec etc1 etc ...)
(fold-ec (*) etc1 etc ... *) )))
(define-syntax min-ec
(syntax-rules ()
((min-ec etc1 etc ...)
(fold3-ec (min) etc1 etc ... min min) )))
(define-syntax max-ec
(syntax-rules ()
((max-ec etc1 etc ...)
(fold3-ec (max) etc1 etc ... max max) )))
(define-syntax last-ec
(syntax-rules (nested)
((last-ec default (nested q1 ...) q etc1 etc ...)
(last-ec default (nested q1 ... q) etc1 etc ...) )
((last-ec default q1 q2 etc1 etc ...)
(last-ec default (nested q1 q2) etc1 etc ...) )
((last-ec default expression)
(last-ec default (nested) expression) )
((last-ec default qualifier expression)
(let ((result default))
(do-ec qualifier (set! result expression))
result ))))
; ==========================================================================
; The fundamental early-stopping comprehension first-ec
; ==========================================================================
(define-syntax first-ec
(syntax-rules (nested)
((first-ec default (nested q1 ...) q etc1 etc ...)
(first-ec default (nested q1 ... q) etc1 etc ...) )
((first-ec default q1 q2 etc1 etc ...)
(first-ec default (nested q1 q2) etc1 etc ...) )
((first-ec default expression)
(first-ec default (nested) expression) )
((first-ec default qualifier expression)
(let ((result default) (stop #f))
(ec-guarded-do-ec
stop
(nested qualifier)
(begin (set! result expression)
(set! stop #t) ))
result ))))
; (ec-guarded-do-ec stop (nested q ...) cmd)
; constructs (do-ec q ... cmd) where the generators gen in q ... are
; replaced by (\:until gen stop).
(define-syntax ec-guarded-do-ec
(syntax-rules (nested if not and or begin)
((ec-guarded-do-ec stop (nested (nested q1 ...) q2 ...) cmd)
(ec-guarded-do-ec stop (nested q1 ... q2 ...) cmd) )
((ec-guarded-do-ec stop (nested (if test) q ...) cmd)
(if test (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (not test) q ...) cmd)
(if (not test) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (and test ...) q ...) cmd)
(if (and test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (or test ...) q ...) cmd)
(if (or test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (begin etc ...) q ...) cmd)
(begin etc ... (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested gen q ...) cmd)
(do-ec
(\:until gen stop)
(ec-guarded-do-ec stop (nested q ...) cmd) ))
((ec-guarded-do-ec stop (nested) cmd)
(do-ec cmd) )))
; Alternative: Instead of modifying the generator with :until, it is
; possible to use call-with-current-continuation:
;
; (define-synatx first-ec
; ...same as above...
; ((first-ec default qualifier expression)
; (call-with-current-continuation
; (lambda (cc)
; (do-ec qualifier (cc expression))
; default ))) ))
;
; This is much simpler but not necessarily as efficient.
; ==========================================================================
; The early-stopping comprehensions any?-ec every?-ec
; ==========================================================================
(define-syntax any?-ec
(syntax-rules (nested)
((any?-ec (nested q1 ...) q etc1 etc ...)
(any?-ec (nested q1 ... q) etc1 etc ...) )
((any?-ec q1 q2 etc1 etc ...)
(any?-ec (nested q1 q2) etc1 etc ...) )
((any?-ec expression)
(any?-ec (nested) expression) )
((any?-ec qualifier expression)
(first-ec #f qualifier (if expression) #t) )))
(define-syntax every?-ec
(syntax-rules (nested)
((every?-ec (nested q1 ...) q etc1 etc ...)
(every?-ec (nested q1 ... q) etc1 etc ...) )
((every?-ec q1 q2 etc1 etc ...)
(every?-ec (nested q1 q2) etc1 etc ...) )
((every?-ec expression)
(every?-ec (nested) expression) )
((every?-ec qualifier expression)
(first-ec #t qualifier (if (not expression)) #f) )))
(define-library (srfi 42)
(export
\:
\:-dispatch-ref
\:-dispatch-set!
\:char-range
\:dispatched
\:do
\:generator-proc
\:integers
\:let
\:list
\:parallel
\:port
\:range
\:real-range
\:string
\:until
\:vector
\:while
any?-ec
append-ec
dispatch-union
do-ec
every?-ec
first-ec
fold-ec
fold3-ec
last-ec
list-ec
make-initial-\:-dispatch
max-ec
min-ec
product-ec
string-append-ec
string-ec
sum-ec
vector-ec
vector-of-length-ec
)
(import
(scheme base)
(scheme cxr)
(scheme read))
(include "42.body.scm"))
;;; "sort.scm" Defines: sorted?, merge, merge!, sort, sort!
;;; Author : Richard A. O'Keefe (based on Prolog code by D.H.D.Warren)
;;;
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Copyright (C) Aubrey Jaffer 2006. All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;; Updated: 11 June 1991
;;; Modified for scheme library: Aubrey Jaffer 19 Sept. 1991
;;; Updated: 19 June 1995
;;; (sort, sort!, sorted?): Generalized to strings by jaffer: 2003-09-09
;;; (sort, sort!, sorted?): Generalized to arrays by jaffer: 2003-10-04
;;; jaffer: 2006-10-08:
;;; (sort, sort!, sorted?, merge, merge!): Added optional KEY argument.
;;; jaffer: 2006-11-05:
;;; (sorted?, merge, merge!, sort, sort!): Call KEY arg at most once
;;; per element.
;;; (sorted? sequence less?)
;;; is true when sequence is a list (x0 x1 ... xm) or a vector #(x0 ... xm)
;;; such that for all 1 <= i <= m,
;;; (not (less? (list-ref list i) (list-ref list (- i 1)))).
;@
(define (sorted? seq less? . opt-key)
(define key (if (null? opt-key) values (car opt-key)))
(cond ((null? seq) #t)
((array? seq)
(let ((dimax (+ -1 (car (array-dimensions seq)))))
(or (<= dimax 1)
(let loop ((idx (+ -1 dimax))
(last (key (array-ref seq dimax))))
(or (negative? idx)
(let ((nxt (key (array-ref seq idx))))
(and (less? nxt last)
(loop (+ -1 idx) nxt))))))))
((null? (cdr seq)) #t)
(else
(let loop ((last (key (car seq)))
(next (cdr seq)))
(or (null? next)
(let ((nxt (key (car next))))
(and (not (less? nxt last))
(loop nxt (cdr next)))))))))
;;; (merge a b less?)
;;; takes two lists a and b such that (sorted? a less?) and (sorted? b less?)
;;; and returns a new list in which the elements of a and b have been stably
;;; interleaved so that (sorted? (merge a b less?) less?).
;;; Note: this does _not_ accept arrays. See below.
;@
(define (merge a b less? . opt-key)
(define key (if (null? opt-key) values (car opt-key)))
(cond ((null? a) b)
((null? b) a)
(else
(let loop ((x (car a)) (kx (key (car a))) (a (cdr a))
(y (car b)) (ky (key (car b))) (b (cdr b)))
;; The loop handles the merging of non-empty lists. It has
;; been written this way to save testing and car/cdring.
(if (less? ky kx)
(if (null? b)
(cons y (cons x a))
(cons y (loop x kx a (car b) (key (car b)) (cdr b))))
;; x <= y
(if (null? a)
(cons x (cons y b))
(cons x (loop (car a) (key (car a)) (cdr a) y ky b))))))))
(define (sort:merge! a b less? key)
(define (loop r a kcara b kcarb)
(cond ((less? kcarb kcara)
(set-cdr! r b)
(if (null? (cdr b))
(set-cdr! b a)
(loop b a kcara (cdr b) (key (cadr b)))))
(else ; (car a) <= (car b)
(set-cdr! r a)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) (key (cadr a)) b kcarb)))))
(cond ((null? a) b)
((null? b) a)
(else
(let ((kcara (key (car a)))
(kcarb (key (car b))))
(cond
((less? kcarb kcara)
(if (null? (cdr b))
(set-cdr! b a)
(loop b a kcara (cdr b) (key (cadr b))))
b)
(else ; (car a) <= (car b)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) (key (cadr a)) b kcarb))
a))))))
;;; takes two sorted lists a and b and smashes their cdr fields to form a
;;; single sorted list including the elements of both.
;;; Note: this does _not_ accept arrays.
;@
(define (merge! a b less? . opt-key)
(sort:merge! a b less? (if (null? opt-key) values (car opt-key))))
(define (sort:sort-list! seq less? key)
(define keyer (if key car values))
(define (step n)
(cond ((> n 2) (let* ((j (quotient n 2))
(a (step j))
(k (- n j))
(b (step k)))
(sort:merge! a b less? keyer)))
((= n 2) (let ((x (car seq))
(y (cadr seq))
(p seq))
(set! seq (cddr seq))
(cond ((less? (keyer y) (keyer x))
(set-car! p y)
(set-car! (cdr p) x)))
(set-cdr! (cdr p) '())
p))
((= n 1) (let ((p seq))
(set! seq (cdr seq))
(set-cdr! p '())
p))
(else '())))
(define (key-wrap! lst)
(cond ((null? lst))
(else (set-car! lst (cons (key (car lst)) (car lst)))
(key-wrap! (cdr lst)))))
(define (key-unwrap! lst)
(cond ((null? lst))
(else (set-car! lst (cdar lst))
(key-unwrap! (cdr lst)))))
(cond (key
(key-wrap! seq)
(set! seq (step (length seq)))
(key-unwrap! seq)
seq)
(else
(step (length seq)))))
(define (rank-1-array->list array)
(define dimensions (array-dimensions array))
(do ((idx (+ -1 (car dimensions)) (+ -1 idx))
(lst '() (cons (array-ref array idx) lst)))
((< idx 0) lst)))
;;; (sort! sequence less?)
;;; sorts the list, array, or string sequence destructively. It uses
;;; a version of merge-sort invented, to the best of my knowledge, by
;;; David H. D. Warren, and first used in the DEC-10 Prolog system.
;;; R. A. O'Keefe adapted it to work destructively in Scheme.
;;; A. Jaffer modified to always return the original list.
;@
(define (sort! seq less? . opt-key)
(define key (if (null? opt-key) #f (car opt-key)))
(cond ((array? seq)
(let ((dims (array-dimensions seq)))
(do ((sorted (sort:sort-list! (rank-1-array->list seq) less? key)
(cdr sorted))
(i 0 (+ i 1)))
((null? sorted) seq)
(array-set! seq (car sorted) i))))
(else ; otherwise, assume it is a list
(let ((ret (sort:sort-list! seq less? key)))
(if (not (eq? ret seq))
(do ((crt ret (cdr crt)))
((eq? (cdr crt) seq)
(set-cdr! crt ret)
(let ((scar (car seq)) (scdr (cdr seq)))
(set-car! seq (car ret)) (set-cdr! seq (cdr ret))
(set-car! ret scar) (set-cdr! ret scdr)))))
seq))))
;;; (sort sequence less?)
;;; sorts a array, string, or list non-destructively. It does this
;;; by sorting a copy of the sequence. My understanding is that the
;;; Standard says that the result of append is always "newly
;;; allocated" except for sharing structure with "the last argument",
;;; so (append x '()) ought to be a standard way of copying a list x.
;@
(define (sort seq less? . opt-key)
(define key (if (null? opt-key) #f (car opt-key)))
(cond ((array? seq)
(let ((dims (array-dimensions seq)))
(define newra (apply make-array seq dims))
(do ((sorted (sort:sort-list! (rank-1-array->list seq) less? key)
(cdr sorted))
(i 0 (+ i 1)))
((null? sorted) newra)
(array-set! newra (car sorted) i))))
(else (sort:sort-list! (append seq '()) less? key))))
; <PLAINTEXT>
; Eager Comprehensions in [outer..inner|expr]-Convention
; ======================================================
;
; sebastian.egner@philips.com, Eindhoven, The Netherlands, 26-Dec-2007
; Scheme R5RS (incl. macros), SRFI-23 (error).
;
; Loading the implementation into Scheme48 0.57:
; ,open srfi-23
; ,load ec.scm
;
; Loading the implementation into PLT/DrScheme 317:
; ; File > Open ... "ec.scm", click Execute
;
; Loading the implementation into SCM 5d7:
; (require 'macro) (require 'record)
; (load "ec.scm")
;
; Implementation comments:
; * All local (not exported) identifiers are named ec-<something>.
; * This implementation focuses on portability, performance,
; readability, and simplicity roughly in this order. Design
; decisions related to performance are taken for Scheme48.
; * Alternative implementations, Comments and Warnings are
; mentioned after the definition with a heading.
; ==========================================================================
; The fundamental comprehension do-ec
; ==========================================================================
;
; All eager comprehensions are reduced into do-ec and
; all generators are reduced to :do.
;
; We use the following short names for syntactic variables
; q - qualifier
; cc - current continuation, thing to call at the end;
; the CPS is (m (cc ...) arg ...) -> (cc ... expr ...)
; cmd - an expression being evaluated for its side-effects
; expr - an expression
; gen - a generator of an eager comprehension
; ob - outer binding
; oc - outer command
; lb - loop binding
; ne1? - not-end1? (before the payload)
; ib - inner binding
; ic - inner command
; ne2? - not-end2? (after the payload)
; ls - loop step
; etc - more arguments of mixed type
; (do-ec q ... cmd)
; handles nested, if/not/and/or, begin, :let, and calls generator
; macros in CPS to transform them into fully decorated :do.
; The code generation for a :do is delegated to do-ec:do.
(define-syntax do-ec
(syntax-rules (nested if not and or begin \:do let)
; explicit nesting -> implicit nesting
((do-ec (nested q ...) etc ...)
(do-ec q ... etc ...) )
; implicit nesting -> fold do-ec
((do-ec q1 q2 etc1 etc ...)
(do-ec q1 (do-ec q2 etc1 etc ...)) )
; no qualifiers at all -> evaluate cmd once
((do-ec cmd)
(begin cmd (if #f #f)) )
; now (do-ec q cmd) remains
; filter -> make conditional
((do-ec (if test) cmd)
(if test (do-ec cmd)) )
((do-ec (not test) cmd)
(if (not test) (do-ec cmd)) )
((do-ec (and test ...) cmd)
(if (and test ...) (do-ec cmd)) )
((do-ec (or test ...) cmd)
(if (or test ...) (do-ec cmd)) )
; begin -> make a sequence
((do-ec (begin etc ...) cmd)
(begin etc ... (do-ec cmd)) )
; fully decorated :do-generator -> delegate to do-ec:do
((do-ec (#\:do olet lbs ne1? ilet ne2? lss) cmd)
(do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss)) )
; anything else -> call generator-macro in CPS; reentry at (*)
((do-ec (g arg1 arg ...) cmd)
(g (do-ec:do cmd) arg1 arg ...) )))
; (do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss))
; generates code for a single fully decorated :do-generator
; with cmd as payload, taking care of special cases.
(define-syntax do-ec:do
(syntax-rules (#\:do let)
; reentry point (*) -> generate code
((do-ec:do cmd
(#\:do (let obs oc ...)
lbs
ne1?
(let ibs ic ...)
ne2?
(ls ...) ))
(ec-simplify
(let obs
oc ...
(let loop lbs
(ec-simplify
(if ne1?
(ec-simplify
(let ibs
ic ...
cmd
(ec-simplify
(if ne2?
(loop ls ...) )))))))))) ))
; (ec-simplify <expression>)
; generates potentially more efficient code for <expression>.
; The macro handles if, (begin <command>*), and (let () <command>*)
; and takes care of special cases.
(define-syntax ec-simplify
(syntax-rules (if not let begin)
; one- and two-sided if
; literal <test>
((ec-simplify (if #t consequent))
consequent )
((ec-simplify (if #f consequent))
(if #f #f) )
((ec-simplify (if #t consequent alternate))
consequent )
((ec-simplify (if #f consequent alternate))
alternate )
; (not (not <test>))
((ec-simplify (if (not (not test)) consequent))
(ec-simplify (if test consequent)) )
((ec-simplify (if (not (not test)) consequent alternate))
(ec-simplify (if test consequent alternate)) )
; (let () <command>*)
; empty <binding spec>*
((ec-simplify (let () command ...))
(ec-simplify (begin command ...)) )
; begin
; flatten use helper (ec-simplify 1 done to-do)
((ec-simplify (begin command ...))
(ec-simplify 1 () (command ...)) )
((ec-simplify 1 done ((begin to-do1 ...) to-do2 ...))
(ec-simplify 1 done (to-do1 ... to-do2 ...)) )
((ec-simplify 1 (done ...) (to-do1 to-do ...))
(ec-simplify 1 (done ... to-do1) (to-do ...)) )
; exit helper
((ec-simplify 1 () ())
(if #f #f) )
((ec-simplify 1 (command) ())
command )
((ec-simplify 1 (command1 command ...) ())
(begin command1 command ...) )
; anything else
((ec-simplify expression)
expression )))
; ==========================================================================
; The special generators :do, :let, :parallel, :while, and :until
; ==========================================================================
(define-syntax \:do
(syntax-rules ()
; full decorated -> continue with cc, reentry at (*)
((#\:do (cc ...) olet lbs ne1? ilet ne2? lss)
(cc ... (#\:do olet lbs ne1? ilet ne2? lss)) )
; short form -> fill in default values
((#\:do cc lbs ne1? lss)
(#\:do cc (let ()) lbs ne1? (let ()) #t lss) )))
(define-syntax \:let
(syntax-rules (index)
((\:let cc var (index i) expression)
(#\:do cc (let ((var expression) (i 0))) () #t (let ()) #f ()) )
((\:let cc var expression)
(#\:do cc (let ((var expression))) () #t (let ()) #f ()) )))
(define-syntax \:parallel
(syntax-rules (#\:do)
((\:parallel cc)
cc )
((\:parallel cc (g arg1 arg ...) gen ...)
(g (\:parallel-1 cc (gen ...)) arg1 arg ...) )))
; (\:parallel-1 cc (to-do ...) result [ next ] )
; iterates over to-do by converting the first generator into
; the :do-generator next and merging next into result.
(define-syntax \:parallel-1 ; used as
(syntax-rules (#\:do let)
; process next element of to-do, reentry at (**)
((\:parallel-1 cc ((g arg1 arg ...) gen ...) result)
(g (\:parallel-1 cc (gen ...) result) arg1 arg ...) )
; reentry point (**) -> merge next into result
((\:parallel-1
cc
gens
(#\:do (let (ob1 ...) oc1 ...)
(lb1 ...)
ne1?1
(let (ib1 ...) ic1 ...)
ne2?1
(ls1 ...) )
(#\:do (let (ob2 ...) oc2 ...)
(lb2 ...)
ne1?2
(let (ib2 ...) ic2 ...)
ne2?2
(ls2 ...) ))
(\:parallel-1
cc
gens
(#\:do (let (ob1 ... ob2 ...) oc1 ... oc2 ...)
(lb1 ... lb2 ...)
(and ne1?1 ne1?2)
(let (ib1 ... ib2 ...) ic1 ... ic2 ...)
(and ne2?1 ne2?2)
(ls1 ... ls2 ...) )))
; no more gens -> continue with cc, reentry at (*)
((\:parallel-1 (cc ...) () result)
(cc ... result) )))
(define-syntax \:while
(syntax-rules ()
((\:while cc (g arg1 arg ...) test)
(g (\:while-1 cc test) arg1 arg ...) )))
; (\:while-1 cc test (#\:do ...))
; modifies the fully decorated :do-generator such that it
; runs while test is a true value.
; The original implementation just replaced ne1? by
; (and ne1? test) as follows:
;
; (define-syntax \:while-1
; (syntax-rules (#\:do)
; ((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
; (#\:do cc olet lbs (and ne1? test) ilet ne2? lss) )))
;
; Bug #1:
; Unfortunately, this code is wrong because ne1? may depend
; in the inner bindings introduced in ilet, but ne1? is evaluated
; outside of the inner bindings. (Refer to the specification of
; :do to see the structure.)
; The problem manifests itself (as sunnan@handgranat.org
; observed, 25-Apr-2005) when the :list-generator is modified:
;
; (do-ec (\:while (\:list x '(1 2)) (= x 1)) (display x)).
;
; In order to generate proper code, we introduce temporary
; variables saving the values of the inner bindings. The inner
; bindings are executed in a new ne1?, which also evaluates ne1?
; outside the scope of the inner bindings, then the inner commands
; are executed (possibly changing the variables), and then the
; values of the inner bindings are saved and (and ne1? test) is
; returned. In the new ilet, the inner variables are bound and
; initialized and their values are restored. So we construct:
;
; (let (ob .. (ib-tmp #f) ...)
; oc ...
; (let loop (lb ...)
; (if (let (ne1?-value ne1?)
; (let ((ib-var ib-rhs) ...)
; ic ...
; (set! ib-tmp ib-var) ...)
; (and ne1?-value test))
; (let ((ib-var ib-tmp) ...)
; /payload/
; (if ne2?
; (loop ls ...) )))))
;
; Bug #2:
; Unfortunately, the above expansion is still incorrect (as Jens-Axel
; Soegaard pointed out, 4-Jun-2007) because ib-rhs are evaluated even
; if ne1?-value is #f, indicating that the loop has ended.
; The problem manifests itself in the following example:
;
; (do-ec (\:while (\:list x '(1)) #t) (display x))
;
; Which iterates :list beyond exhausting the list '(1).
;
; For the fix, we follow Jens-Axel's approach of guarding the evaluation
; of ib-rhs with a check on ne1?-value.
(define-syntax \:while-1
(syntax-rules (#\:do let)
((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(\:while-2 cc test () () () (#\:do olet lbs ne1? ilet ne2? lss)))))
(define-syntax \:while-2
(syntax-rules (#\:do let)
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do olet
lbs
ne1?
(let ((ib-var ib-rhs) ib ...) ic ...)
ne2?
lss))
(\:while-2 cc
test
(ib-let ... (ib-tmp #f))
(ib-save ... (ib-var ib-rhs))
(ib-restore ... (ib-var ib-tmp))
(#\:do olet
lbs
ne1?
(let (ib ...) ic ... (set! ib-tmp ib-var))
ne2?
lss)))
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do (let (ob ...) oc ...) lbs ne1? (let () ic ...) ne2? lss))
(#\:do cc
(let (ob ... ib-let ...) oc ...)
lbs
(let ((ne1?-value ne1?))
(and ne1?-value
(let (ib-save ...)
ic ...
test)))
(let (ib-restore ...))
ne2?
lss))))
(define-syntax \:until
(syntax-rules ()
((\:until cc (g arg1 arg ...) test)
(g (\:until-1 cc test) arg1 arg ...) )))
(define-syntax \:until-1
(syntax-rules (#\:do)
((\:until-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(#\:do cc olet lbs ne1? ilet (and ne2? (not test)) lss) )))
; ==========================================================================
; The typed generators :list :string :vector etc.
; ==========================================================================
(define-syntax \:list
(syntax-rules (index)
((\:list cc var (index i) arg ...)
(\:parallel cc (\:list var arg ...) (\:integers i)) )
((\:list cc var arg1 arg2 arg ...)
(\:list cc var (append arg1 arg2 arg ...)) )
((\:list cc var arg)
(#\:do cc
(let ())
((t arg))
(not (null? t))
(let ((var (car t))))
#t
((cdr t)) ))))
(define-syntax \:string
(syntax-rules (index)
((\:string cc var (index i) arg)
(#\:do cc
(let ((str arg) (len 0))
(set! len (string-length str)))
((i 0))
(< i len)
(let ((var (string-ref str i))))
#t
((+ i 1)) ))
((\:string cc var (index i) arg1 arg2 arg ...)
(\:string cc var (index i) (string-append arg1 arg2 arg ...)) )
((\:string cc var arg1 arg ...)
(\:string cc var (index i) arg1 arg ...) )))
; Alternative: An implementation in the style of :vector can also
; be used for :string. However, it is less interesting as the
; overhead of string-append is much less than for 'vector-append'.
(define-syntax \:vector
(syntax-rules (index)
((\:vector cc var arg)
(\:vector cc var (index i) arg) )
((\:vector cc var (index i) arg)
(#\:do cc
(let ((vec arg) (len 0))
(set! len (vector-length vec)))
((i 0))
(< i len)
(let ((var (vector-ref vec i))))
#t
((+ i 1)) ))
((\:vector cc var (index i) arg1 arg2 arg ...)
(\:parallel cc (\:vector cc var arg1 arg2 arg ...) (\:integers i)) )
((\:vector cc var arg1 arg2 arg ...)
(#\:do cc
(let ((vec #f)
(len 0)
(vecs (ec-:vector-filter (list arg1 arg2 arg ...))) ))
((k 0))
(if (< k len)
#t
(if (null? vecs)
#f
(begin (set! vec (car vecs))
(set! vecs (cdr vecs))
(set! len (vector-length vec))
(set! k 0)
#t )))
(let ((var (vector-ref vec k))))
#t
((+ k 1)) ))))
(define (ec-:vector-filter vecs)
(if (null? vecs)
'()
(if (zero? (vector-length (car vecs)))
(ec-:vector-filter (cdr vecs))
(cons (car vecs) (ec-:vector-filter (cdr vecs))) )))
; Alternative: A simpler implementation for :vector uses vector->list
; append and :list in the multi-argument case. Please refer to the
; 'design.scm' for more details.
(define-syntax \:integers
(syntax-rules (index)
((\:integers cc var (index i))
(#\:do cc ((var 0) (i 0)) #t ((+ var 1) (+ i 1))) )
((\:integers cc var)
(#\:do cc ((var 0)) #t ((+ var 1))) )))
(define-syntax \:range
(syntax-rules (index)
; handle index variable and add optional args
((\:range cc var (index i) arg1 arg ...)
(\:parallel cc (\:range var arg1 arg ...) (\:integers i)) )
((\:range cc var arg1)
(\:range cc var 0 arg1 1) )
((\:range cc var arg1 arg2)
(\:range cc var arg1 arg2 1) )
; special cases (partially evaluated by hand from general case)
((\:range cc var 0 arg2 1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var 0 arg2 -1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(> var b)
(let ())
#t
((- var 1)) ))
((\:range cc var arg1 arg2 1)
(#\:do cc
(let ((a arg1) (b arg2))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b 1 )) )
((var a))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var arg1 arg2 -1)
(#\:do cc
(let ((a arg1) (b arg2) (s -1) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b -1 )) )
((var a))
(> var b)
(let ())
#t
((- var 1)) ))
; the general case
((\:range cc var arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b)
(integer? s) (exact? s) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b s ))
(if (zero? s)
(error "step size must not be zero in :range") )
(set! stop (+ a (* (max 0 (ceiling (/ (- b a) s))) s))) )
((var a))
(not (= var stop))
(let ())
#t
((+ var s)) ))))
; Comment: The macro :range inserts some code to make sure the values
; are exact integers. This overhead has proven very helpful for
; saving users from themselves.
(define-syntax \:real-range
(syntax-rules (index)
; add optional args and index variable
((\:real-range cc var arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var (index i) arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var (index i) arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var arg1 arg2 arg3)
(\:real-range cc var (index i) arg1 arg2 arg3) )
; the fully qualified case
((\:real-range cc var (index i) arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (istop 0))
(if (not (and (real? a) (real? b) (real? s)))
(error "arguments of :real-range are not real" a b s) )
(if (and (exact? a) (or (not (exact? b)) (not (exact? s))))
(set! a (exact->inexact a)) )
(set! istop (/ (- b a) s)) )
((i 0))
(< i istop)
(let ((var (+ a (* s i)))))
#t
((+ i 1)) ))))
; Comment: The macro :real-range adapts the exactness of the start
; value in case any of the other values is inexact. This is a
; precaution to avoid (list-ec (\: x 0 3.0) x) => '(0 1.0 2.0).
(define-syntax \:char-range
(syntax-rules (index)
((\:char-range cc var (index i) arg1 arg2)
(\:parallel cc (\:char-range var arg1 arg2) (\:integers i)) )
((\:char-range cc var arg1 arg2)
(#\:do cc
(let ((imax (char->integer arg2))))
((i (char->integer arg1)))
(<= i imax)
(let ((var (integer->char i))))
#t
((+ i 1)) ))))
; Warning: There is no R5RS-way to implement the :char-range generator
; because the integers obtained by char->integer are not necessarily
; consecutive. We simply assume this anyhow for illustration.
(define-syntax \:port
(syntax-rules (index)
((\:port cc var (index i) arg1 arg ...)
(\:parallel cc (\:port var arg1 arg ...) (\:integers i)) )
((\:port cc var arg)
(\:port cc var arg read) )
((\:port cc var arg1 arg2)
(#\:do cc
(let ((port arg1) (read-proc arg2)))
((var (read-proc port)))
(not (eof-object? var))
(let ())
#t
((read-proc port)) ))))
; ==========================================================================
; The typed generator :dispatched and utilities for constructing dispatchers
; ==========================================================================
(define-syntax \:dispatched
(syntax-rules (index)
((\:dispatched cc var (index i) dispatch arg1 arg ...)
(\:parallel cc
(\:integers i)
(\:dispatched var dispatch arg1 arg ...) ))
((\:dispatched cc var dispatch arg1 arg ...)
(#\:do cc
(let ((d dispatch)
(args (list arg1 arg ...))
(g #f)
(empty (list #f)) )
(set! g (d args))
(if (not (procedure? g))
(error "unrecognized arguments in dispatching"
args
(d '()) )))
((var (g empty)))
(not (eq? var empty))
(let ())
#t
((g empty)) ))))
; Comment: The unique object empty is created as a newly allocated
; non-empty list. It is compared using eq? which distinguishes
; the object from any other object, according to R5RS 6.1.
(define-syntax \:generator-proc
(syntax-rules (#\:do let)
; call g with a variable, reentry at (**)
((\:generator-proc (g arg ...))
(g (\:generator-proc var) var arg ...) )
; reentry point (**) -> make the code from a single :do
((\:generator-proc
var
(#\:do (let obs oc ...)
((lv li) ...)
ne1?
(let ((i v) ...) ic ...)
ne2?
(ls ...)) )
(ec-simplify
(let obs
oc ...
(let ((lv li) ... (ne2 #t))
(ec-simplify
(let ((i #f) ...) ; v not yet valid
(lambda (empty)
(if (and ne1? ne2)
(ec-simplify
(begin
(set! i v) ...
ic ...
(let ((value var))
(ec-simplify
(if ne2?
(ec-simplify
(begin (set! lv ls) ...) )
(set! ne2 #f) ))
value )))
empty ))))))))
; silence warnings of some macro expanders
((\:generator-proc var)
(error "illegal macro call") )))
(define (dispatch-union d1 d2)
(lambda (args)
(let ((g1 (d1 args)) (g2 (d2 args)))
(if g1
(if g2
(if (null? args)
(append (if (list? g1) g1 (list g1))
(if (list? g2) g2 (list g2)) )
(error "dispatching conflict" args (d1 '()) (d2 '())) )
g1 )
(if g2 g2 #f) ))))
; ==========================================================================
; The dispatching generator :
; ==========================================================================
(define (make-initial-\:-dispatch)
(lambda (args)
(case (length args)
((0) 'SRFI42)
((1) (let ((a1 (car args)))
(cond
((list? a1)
(\:generator-proc (\:list a1)) )
((string? a1)
(\:generator-proc (\:string a1)) )
((vector? a1)
(\:generator-proc (\:vector a1)) )
((and (integer? a1) (exact? a1))
(\:generator-proc (\:range a1)) )
((real? a1)
(\:generator-proc (\:real-range a1)) )
((input-port? a1)
(\:generator-proc (\:port a1)) )
(else
#f ))))
((2) (let ((a1 (car args)) (a2 (cadr args)))
(cond
((and (list? a1) (list? a2))
(\:generator-proc (\:list a1 a2)) )
((and (string? a1) (string? a1))
(\:generator-proc (\:string a1 a2)) )
((and (vector? a1) (vector? a2))
(\:generator-proc (\:vector a1 a2)) )
((and (integer? a1) (exact? a1) (integer? a2) (exact? a2))
(\:generator-proc (\:range a1 a2)) )
((and (real? a1) (real? a2))
(\:generator-proc (\:real-range a1 a2)) )
((and (char? a1) (char? a2))
(\:generator-proc (\:char-range a1 a2)) )
((and (input-port? a1) (procedure? a2))
(\:generator-proc (\:port a1 a2)) )
(else
#f ))))
((3) (let ((a1 (car args)) (a2 (cadr args)) (a3 (caddr args)))
(cond
((and (list? a1) (list? a2) (list? a3))
(\:generator-proc (\:list a1 a2 a3)) )
((and (string? a1) (string? a1) (string? a3))
(\:generator-proc (\:string a1 a2 a3)) )
((and (vector? a1) (vector? a2) (vector? a3))
(\:generator-proc (\:vector a1 a2 a3)) )
((and (integer? a1) (exact? a1)
(integer? a2) (exact? a2)
(integer? a3) (exact? a3))
(\:generator-proc (\:range a1 a2 a3)) )
((and (real? a1) (real? a2) (real? a3))
(\:generator-proc (\:real-range a1 a2 a3)) )
(else
#f ))))
(else
(letrec ((every?
(lambda (pred args)
(if (null? args)
#t
(and (pred (car args))
(every? pred (cdr args)) )))))
(cond
((every? list? args)
(\:generator-proc (\:list (apply append args))) )
((every? string? args)
(\:generator-proc (\:string (apply string-append args))) )
((every? vector? args)
(\:generator-proc (\:list (apply append (map vector->list args)))) )
(else
#f )))))))
(define \\:-dispatch
(make-initial-\:-dispatch) )
(define (\\:-dispatch-ref)
\:-dispatch )
(define (\\:-dispatch-set! dispatch)
(if (not (procedure? dispatch))
(error "not a procedure" dispatch) )
(set! \:-dispatch dispatch) )
(define-syntax \:
(syntax-rules (index)
((\: cc var (index i) arg1 arg ...)
(\:dispatched cc var (index i) \:-dispatch arg1 arg ...) )
((\: cc var arg1 arg ...)
(\:dispatched cc var \:-dispatch arg1 arg ...) )))
; ==========================================================================
; The utility comprehensions fold-ec, fold3-ec
; ==========================================================================
(define-syntax fold3-ec
(syntax-rules (nested)
((fold3-ec x0 (nested q1 ...) q etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 ... q) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 q1 q2 etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 q2) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 expression f1 f2)
(fold3-ec x0 (nested) expression f1 f2) )
((fold3-ec x0 qualifier expression f1 f2)
(let ((result #f) (empty #t))
(do-ec qualifier
(let ((value expression)) ; don't duplicate
(if empty
(begin (set! result (f1 value))
(set! empty #f) )
(set! result (f2 value result)) )))
(if empty x0 result) ))))
(define-syntax fold-ec
(syntax-rules (nested)
((fold-ec x0 (nested q1 ...) q etc1 etc2 etc ...)
(fold-ec x0 (nested q1 ... q) etc1 etc2 etc ...) )
((fold-ec x0 q1 q2 etc1 etc2 etc ...)
(fold-ec x0 (nested q1 q2) etc1 etc2 etc ...) )
((fold-ec x0 expression f2)
(fold-ec x0 (nested) expression f2) )
((fold-ec x0 qualifier expression f2)
(let ((result x0))
(do-ec qualifier (set! result (f2 expression result)))
result ))))
; ==========================================================================
; The comprehensions list-ec string-ec vector-ec etc.
; ==========================================================================
(define-syntax list-ec
(syntax-rules ()
((list-ec etc1 etc ...)
(reverse (fold-ec '() etc1 etc ... cons)) )))
; Alternative: Reverse can safely be replaced by reverse! if you have it.
;
; Alternative: It is possible to construct the result in the correct order
; using set-cdr! to add at the tail. This removes the overhead of copying
; at the end, at the cost of more book-keeping.
(define-syntax append-ec
(syntax-rules ()
((append-ec etc1 etc ...)
(apply append (list-ec etc1 etc ...)) )))
(define-syntax string-ec
(syntax-rules ()
((string-ec etc1 etc ...)
(list->string (list-ec etc1 etc ...)) )))
; Alternative: For very long strings, the intermediate list may be a
; problem. A more space-aware implementation collect the characters
; in an intermediate list and when this list becomes too large it is
; converted into an intermediate string. At the end, the intermediate
; strings are concatenated with string-append.
(define-syntax string-append-ec
(syntax-rules ()
((string-append-ec etc1 etc ...)
(apply string-append (list-ec etc1 etc ...)) )))
(define-syntax vector-ec
(syntax-rules ()
((vector-ec etc1 etc ...)
(list->vector (list-ec etc1 etc ...)) )))
; Comment: A similar approach as for string-ec can be used for vector-ec.
; However, the space overhead for the intermediate list is much lower
; than for string-ec and as there is no vector-append, the intermediate
; vectors must be copied explicitly.
(define-syntax vector-of-length-ec
(syntax-rules (nested)
((vector-of-length-ec k (nested q1 ...) q etc1 etc ...)
(vector-of-length-ec k (nested q1 ... q) etc1 etc ...) )
((vector-of-length-ec k q1 q2 etc1 etc ...)
(vector-of-length-ec k (nested q1 q2) etc1 etc ...) )
((vector-of-length-ec k expression)
(vector-of-length-ec k (nested) expression) )
((vector-of-length-ec k qualifier expression)
(let ((len k))
(let ((vec (make-vector len))
(i 0) )
(do-ec qualifier
(if (< i len)
(begin (vector-set! vec i expression)
(set! i (+ i 1)) )
(error "vector is too short for the comprehension") ))
(if (= i len)
vec
(error "vector is too long for the comprehension") ))))))
(define-syntax sum-ec
(syntax-rules ()
((sum-ec etc1 etc ...)
(fold-ec (+) etc1 etc ... +) )))
(define-syntax product-ec
(syntax-rules ()
((product-ec etc1 etc ...)
(fold-ec (*) etc1 etc ... *) )))
(define-syntax min-ec
(syntax-rules ()
((min-ec etc1 etc ...)
(fold3-ec (min) etc1 etc ... min min) )))
(define-syntax max-ec
(syntax-rules ()
((max-ec etc1 etc ...)
(fold3-ec (max) etc1 etc ... max max) )))
(define-syntax last-ec
(syntax-rules (nested)
((last-ec default (nested q1 ...) q etc1 etc ...)
(last-ec default (nested q1 ... q) etc1 etc ...) )
((last-ec default q1 q2 etc1 etc ...)
(last-ec default (nested q1 q2) etc1 etc ...) )
((last-ec default expression)
(last-ec default (nested) expression) )
((last-ec default qualifier expression)
(let ((result default))
(do-ec qualifier (set! result expression))
result ))))
; ==========================================================================
; The fundamental early-stopping comprehension first-ec
; ==========================================================================
(define-syntax first-ec
(syntax-rules (nested)
((first-ec default (nested q1 ...) q etc1 etc ...)
(first-ec default (nested q1 ... q) etc1 etc ...) )
((first-ec default q1 q2 etc1 etc ...)
(first-ec default (nested q1 q2) etc1 etc ...) )
((first-ec default expression)
(first-ec default (nested) expression) )
((first-ec default qualifier expression)
(let ((result default) (stop #f))
(ec-guarded-do-ec
stop
(nested qualifier)
(begin (set! result expression)
(set! stop #t) ))
result ))))
; (ec-guarded-do-ec stop (nested q ...) cmd)
; constructs (do-ec q ... cmd) where the generators gen in q ... are
; replaced by (\:until gen stop).
(define-syntax ec-guarded-do-ec
(syntax-rules (nested if not and or begin)
((ec-guarded-do-ec stop (nested (nested q1 ...) q2 ...) cmd)
(ec-guarded-do-ec stop (nested q1 ... q2 ...) cmd) )
((ec-guarded-do-ec stop (nested (if test) q ...) cmd)
(if test (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (not test) q ...) cmd)
(if (not test) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (and test ...) q ...) cmd)
(if (and test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (or test ...) q ...) cmd)
(if (or test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (begin etc ...) q ...) cmd)
(begin etc ... (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested gen q ...) cmd)
(do-ec
(\:until gen stop)
(ec-guarded-do-ec stop (nested q ...) cmd) ))
((ec-guarded-do-ec stop (nested) cmd)
(do-ec cmd) )))
; Alternative: Instead of modifying the generator with :until, it is
; possible to use call-with-current-continuation:
;
; (define-synatx first-ec
; ...same as above...
; ((first-ec default qualifier expression)
; (call-with-current-continuation
; (lambda (cc)
; (do-ec qualifier (cc expression))
; default ))) ))
;
; This is much simpler but not necessarily as efficient.
; ==========================================================================
; The early-stopping comprehensions any?-ec every?-ec
; ==========================================================================
(define-syntax any?-ec
(syntax-rules (nested)
((any?-ec (nested q1 ...) q etc1 etc ...)
(any?-ec (nested q1 ... q) etc1 etc ...) )
((any?-ec q1 q2 etc1 etc ...)
(any?-ec (nested q1 q2) etc1 etc ...) )
((any?-ec expression)
(any?-ec (nested) expression) )
((any?-ec qualifier expression)
(first-ec #f qualifier (if expression) #t) )))
(define-syntax every?-ec
(syntax-rules (nested)
((every?-ec (nested q1 ...) q etc1 etc ...)
(every?-ec (nested q1 ... q) etc1 etc ...) )
((every?-ec q1 q2 etc1 etc ...)
(every?-ec (nested q1 q2) etc1 etc ...) )
((every?-ec expression)
(every?-ec (nested) expression) )
((every?-ec qualifier expression)
(first-ec #t qualifier (if (not expression)) #f) )))
;;;;;; SRFI 43: Vector library -*- Scheme -*-
;;;
;;; $Id: vector-lib.scm,v 1.7 2009/03/29 09:46:03 sperber Exp $
;;;
;;; Taylor Campbell wrote this code; he places it in the public domain.
;;; Will Clinger [wdc] made some corrections, also in the public domain.
;;; Copyright (C) Taylor Campbell (2003). All rights reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright (C) 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;; --------------------
;;; Exported procedure index
;;;
;;; * Constructors
;;; make-vector vector
;;; vector-unfold vector-unfold-right
;;; vector-copy vector-reverse-copy
;;; vector-append vector-concatenate
;;;
;;; * Predicates
;;; vector?
;;; vector-empty?
;;; vector=
;;;
;;; * Selectors
;;; vector-ref
;;; vector-length
;;;
;;; * Iteration
;;; vector-fold vector-fold-right
;;; vector-map vector-map!
;;; vector-for-each
;;; vector-count
;;;
;;; * Searching
;;; vector-index vector-skip
;;; vector-index-right vector-skip-right
;;; vector-binary-search
;;; vector-any vector-every
;;;
;;; * Mutators
;;; vector-set!
;;; vector-swap!
;;; vector-fill!
;;; vector-reverse!
;;; vector-copy! vector-reverse-copy!
;;; vector-reverse!
;;;
;;; * Conversion
;;; vector->list reverse-vector->list
;;; list->vector reverse-list->vector
;;; --------------------
;;; Commentary on efficiency of the code
;;; This code is somewhat tuned for efficiency. There are several
;;; internal routines that can be optimized greatly to greatly improve
;;; the performance of much of the library. These internal procedures
;;; are already carefully tuned for performance, and lambda-lifted by
;;; hand. Some other routines are lambda-lifted by hand, but only the
;;; loops are lambda-lifted, and only if some routine has two possible
;;; loops -- a fast path and an n-ary case --, whereas _all_ of the
;;; internal routines' loops are lambda-lifted so as to never cons a
;;; closure in their body (VECTOR-PARSE-START+END doesn't have a loop),
;;; even in Scheme systems that perform no loop optimization (which is
;;; most of them, unfortunately).
;;;
;;; Fast paths are provided for common cases in most of the loops in
;;; this library.
;;;
;;; All calls to primitive vector operations are protected by a prior
;;; type check; they can be safely converted to use unsafe equivalents
;;; of the operations, if available. Ideally, the compiler should be
;;; able to determine this, but the state of Scheme compilers today is
;;; not a happy one.
;;;
;;; Efficiency of the actual algorithms is a rather mundane point to
;;; mention; vector operations are rarely beyond being straightforward.
;;; --------------------
;;; Utilities
(define (nonneg-int? x)
(and (integer? x)
(not (negative? x))))
(define (between? x y z)
(and (< x y)
(<= y z)))
(define (unspecified-value) (if #f #f))
;++ This should be implemented more efficiently. It shouldn't cons a
;++ closure, and the cons cells used in the loops when using this could
;++ be reused.
(define (vectors-ref vectors i)
(map (lambda (v) (vector-ref v i)) vectors))
;;; --------------------
;;; Internal routines
;;; These should all be integrated, native, or otherwise optimized --
;;; they're used a _lot_ --. All of the loops and LETs inside loops
;;; are lambda-lifted by hand, just so as not to cons closures in the
;;; loops. (If your compiler can do better than that if they're not
;;; lambda-lifted, then lambda-drop (?) them.)
;;; (VECTOR-PARSE-START+END <vector> <arguments>
;;; <start-name> <end-name>
;;; <callee>)
;;; -> [start end]
;;; Return two values, composing a valid range within VECTOR, as
;;; extracted from ARGUMENTS or defaulted from VECTOR -- 0 for START
;;; and the length of VECTOR for END --; START-NAME and END-NAME are
;;; purely for error checking.
(define (vector-parse-start+end vec args start-name end-name callee)
(let ((len (vector-length vec)))
(cond ((null? args)
(values 0 len))
((null? (cdr args))
(check-indices vec
(car args) start-name
len end-name
callee))
((null? (cddr args))
(check-indices vec
(car args) start-name
(cadr args) end-name
callee))
(else
(error "too many arguments"
`(extra args were ,(cddr args))
`(while calling ,callee))))))
(define-syntax let-vector-start+end
(syntax-rules ()
((let-vector-start+end ?callee ?vec ?args (?start ?end)
?body1 ?body2 ...)
(let ((?vec (check-type vector? ?vec ?callee)))
(receive (?start ?end)
(vector-parse-start+end ?vec ?args '?start '?end
?callee)
?body1 ?body2 ...)))))
;;; (%SMALLEST-LENGTH <vector-list> <default-length> <callee>)
;;; -> exact, nonnegative integer
;;; Compute the smallest length of VECTOR-LIST. DEFAULT-LENGTH is
;;; the length that is returned if VECTOR-LIST is empty. Common use
;;; of this is in n-ary vector routines:
;;; (define (f vec . vectors)
;;; (let ((vec (check-type vector? vec f)))
;;; ...(%smallest-length vectors (vector-length vec) f)...))
;;; %SMALLEST-LENGTH takes care of the type checking -- which is what
;;; the CALLEE argument is for --; thus, the design is tuned for
;;; avoiding redundant type checks.
(define %smallest-length
(letrec ((loop (lambda (vector-list length callee)
(if (null? vector-list)
length
(loop (cdr vector-list)
(min (vector-length
(check-type vector?
(car vector-list)
callee))
length)
callee)))))
loop))
;;; (%VECTOR-REVERSE-COPY! <target> <tstart> <source> <sstart> <send>)
;;; Copy elements from SSTART to SEND from SOURCE to TARGET, in the
;;; reverse order.
(define %vector-reverse-copy!
(letrec ((loop (lambda (target source sstart i j)
(cond ((>= i sstart)
(vector-set! target j (vector-ref source i))
(loop target source sstart
(- i 1)
(+ j 1)))))))
(lambda (target tstart source sstart send)
(loop target source sstart
(- send 1)
tstart))))
;;; (%VECTOR-REVERSE! <vector>)
(define %vector-reverse!
(letrec ((loop (lambda (vec i j)
(cond ((<= i j)
(let ((v (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j v)
(loop vec (+ i 1) (- j 1))))))))
(lambda (vec start end)
(loop vec start (- end 1)))))
;;; (%VECTOR-FOLD1 <kons> <knil> <vector>) -> knil'
;;; (KONS <index> <knil> <elt>) -> knil'
(define %vector-fold1
(letrec ((loop (lambda (kons knil len vec i)
(if (= i len)
knil
(loop kons
(kons i knil (vector-ref vec i))
len vec (+ i 1))))))
(lambda (kons knil len vec)
(loop kons knil len vec 0))))
;;; (%VECTOR-FOLD2+ <kons> <knil> <vector> ...) -> knil'
;;; (KONS <index> <knil> <elt> ...) -> knil'
(define %vector-fold2+
(letrec ((loop (lambda (kons knil len vectors i)
(if (= i len)
knil
(loop kons
(apply kons i knil
(vectors-ref vectors i))
len vectors (+ i 1))))))
(lambda (kons knil len vectors)
(loop kons knil len vectors 0))))
;;; (%VECTOR-MAP! <f> <target> <length> <vector>) -> target
;;; (F <index> <elt>) -> elt'
(define %vector-map1!
(letrec ((loop (lambda (f target vec i)
(if (zero? i)
target
(let ((j (- i 1)))
(vector-set! target j
(f j (vector-ref vec j)))
(loop f target vec j))))))
(lambda (f target vec len)
(loop f target vec len))))
;;; (%VECTOR-MAP2+! <f> <target> <vectors> <len>) -> target
;;; (F <index> <elt> ...) -> elt'
(define %vector-map2+!
(letrec ((loop (lambda (f target vectors i)
(if (zero? i)
target
(let ((j (- i 1)))
(vector-set! target j
(apply f j (vectors-ref vectors j)))
(loop f target vectors j))))))
(lambda (f target vectors len)
(loop f target vectors len))))
;;;;;;;;;;;;;;;;;;;;;;;; ***** vector-lib ***** ;;;;;;;;;;;;;;;;;;;;;;;
;;; --------------------
;;; Constructors
;;; (VECTOR-UNFOLD <f> <length> <initial-seed> ...) -> vector
;;; (F <index> <seed> ...) -> [elt seed' ...]
;;; The fundamental vector constructor. Creates a vector whose
;;; length is LENGTH and iterates across each index K between 0 and
;;; LENGTH, applying F at each iteration to the current index and the
;;; current seeds to receive N+1 values: first, the element to put in
;;; the Kth slot and then N new seeds for the next iteration.
(define vector-unfold
(letrec ((tabulate! ; Special zero-seed case.
(lambda (f vec i len)
(cond ((< i len)
(vector-set! vec i (f i))
(tabulate! f vec (+ i 1) len)))))
(unfold1! ; Fast path for one seed.
(lambda (f vec i len seed)
(if (< i len)
(receive (elt new-seed)
(f i seed)
(vector-set! vec i elt)
(unfold1! f vec (+ i 1) len new-seed)))))
(unfold2+! ; Slower variant for N seeds.
(lambda (f vec i len seeds)
(if (< i len)
(receive (elt . new-seeds)
(apply f i seeds)
(vector-set! vec i elt)
(unfold2+! f vec (+ i 1) len new-seeds))))))
(lambda (f len . initial-seeds)
(let ((f (check-type procedure? f vector-unfold))
(len (check-type nonneg-int? len vector-unfold)))
(let ((vec (make-vector len)))
(cond ((null? initial-seeds)
(tabulate! f vec 0 len))
((null? (cdr initial-seeds))
(unfold1! f vec 0 len (car initial-seeds)))
(else
(unfold2+! f vec 0 len initial-seeds)))
vec)))))
;;; (VECTOR-UNFOLD-RIGHT <f> <length> <initial-seed> ...) -> vector
;;; (F <seed> ...) -> [seed' ...]
;;; Like VECTOR-UNFOLD, but it generates elements from LENGTH to 0
;;; (still exclusive with LENGTH and inclusive with 0), not 0 to
;;; LENGTH as with VECTOR-UNFOLD.
(define vector-unfold-right
(letrec ((tabulate!
(lambda (f vec i)
(cond ((>= i 0)
(vector-set! vec i (f i))
(tabulate! f vec (- i 1))))))
(unfold1!
(lambda (f vec i seed)
(if (>= i 0)
(receive (elt new-seed)
(f i seed)
(vector-set! vec i elt)
(unfold1! f vec (- i 1) new-seed)))))
(unfold2+!
(lambda (f vec i seeds)
(if (>= i 0)
(receive (elt . new-seeds)
(apply f i seeds)
(vector-set! vec i elt)
(unfold2+! f vec (- i 1) new-seeds))))))
(lambda (f len . initial-seeds)
(let ((f (check-type procedure? f vector-unfold-right))
(len (check-type nonneg-int? len vector-unfold-right)))
(let ((vec (make-vector len))
(i (- len 1)))
(cond ((null? initial-seeds)
(tabulate! f vec i))
((null? (cdr initial-seeds))
(unfold1! f vec i (car initial-seeds)))
(else
(unfold2+! f vec i initial-seeds)))
vec)))))
;;; (VECTOR-REVERSE-COPY <vector> [<start> <end>]) -> vector
;;; Create a newly allocated vector whose elements are the reversed
;;; sequence of elements between START and END in VECTOR. START's
;;; default is 0; END's default is the length of VECTOR.
(define (vector-reverse-copy vec . maybe-start+end)
(let-vector-start+end vector-reverse-copy vec maybe-start+end
(start end)
(let ((new (make-vector (- end start))))
(%vector-reverse-copy! new 0 vec start end)
new)))
;;; (VECTOR-CONCATENATE <vector-list>) -> vector
;;; Concatenate the vectors in VECTOR-LIST. This is equivalent to
;;; (apply vector-append VECTOR-LIST)
;;; but VECTOR-APPEND tends to be implemented in terms of
;;; VECTOR-CONCATENATE, and some Schemes bork when the list to apply
;;; a function to is too long.
;;;
;;; Actually, they're both implemented in terms of an internal routine.
(define (vector-concatenate vector-list)
(vector-concatenate:aux vector-list vector-concatenate))
;;; Auxiliary for VECTOR-APPEND and VECTOR-CONCATENATE
(define vector-concatenate:aux
(letrec ((compute-length
(lambda (vectors len callee)
(if (null? vectors)
len
(let ((vec (check-type vector? (car vectors)
callee)))
(compute-length (cdr vectors)
(+ (vector-length vec) len)
callee)))))
(concatenate!
(lambda (vectors target to)
(if (null? vectors)
target
(let* ((vec1 (car vectors))
(len (vector-length vec1)))
(vector-copy! target to vec1 0 len)
(concatenate! (cdr vectors) target
(+ to len)))))))
(lambda (vectors callee)
(cond ((null? vectors) ;+++
(make-vector 0))
((null? (cdr vectors)) ;+++
;; Blech, we still have to allocate a new one.
(let* ((vec (check-type vector? (car vectors) callee))
(len (vector-length vec))
(new (make-vector len)))
(vector-copy! new 0 vec 0 len)
new))
(else
(let ((new-vector
(make-vector (compute-length vectors 0 callee))))
(concatenate! vectors new-vector 0)
new-vector))))))
;;; --------------------
;;; Predicates
;;; (VECTOR-EMPTY? <vector>) -> boolean
;;; Return #T if VECTOR has zero elements in it, i.e. VECTOR's length
;;; is 0, and #F if not.
(define (vector-empty? vec)
(let ((vec (check-type vector? vec vector-empty?)))
(zero? (vector-length vec))))
;;; (VECTOR= <elt=?> <vector> ...) -> boolean
;;; (ELT=? <value> <value>) -> boolean
;;; Determine vector equality generalized across element comparators.
;;; Vectors A and B are equal iff their lengths are the same and for
;;; each respective elements E_a and E_b (element=? E_a E_b) returns
;;; a true value. ELT=? is always applied to two arguments. Element
;;; comparison must be consistent wtih EQ?; that is, if (eq? E_a E_b)
;;; results in a true value, then (ELEMENT=? E_a E_b) must result in a
;;; true value. This may be exploited to avoid multiple unnecessary
;;; element comparisons. (This implementation does, but does not deal
;;; with the situation that ELEMENT=? is EQ? to avoid more unnecessary
;;; comparisons, but I believe this optimization is probably fairly
;;; insignificant.)
;;;
;;; If the number of vector arguments is zero or one, then #T is
;;; automatically returned. If there are N vector arguments,
;;; VECTOR_1 VECTOR_2 ... VECTOR_N, then VECTOR_1 & VECTOR_2 are
;;; compared; if they are equal, the vectors VECTOR_2 ... VECTOR_N
;;; are compared. The precise order in which ELT=? is applied is not
;;; specified.
(define (vector= elt=? . vectors)
(let ((elt=? (check-type procedure? elt=? vector=)))
(cond ((null? vectors)
#t)
((null? (cdr vectors))
(check-type vector? (car vectors) vector=)
#t)
(else
(let loop ((vecs vectors))
(let ((vec1 (check-type vector? (car vecs) vector=))
(vec2+ (cdr vecs)))
(or (null? vec2+)
(and (binary-vector= elt=? vec1 (car vec2+))
(loop vec2+)))))))))
(define (binary-vector= elt=? vector-a vector-b)
(or (eq? vector-a vector-b) ;+++
(let ((length-a (vector-length vector-a))
(length-b (vector-length vector-b)))
(letrec ((loop (lambda (i)
(or (= i length-a)
(and (< i length-b)
(test (vector-ref vector-a i)
(vector-ref vector-b i)
i)))))
(test (lambda (elt-a elt-b i)
(and (or (eq? elt-a elt-b) ;+++
(elt=? elt-a elt-b))
(loop (+ i 1))))))
(and (= length-a length-b)
(loop 0))))))
;;; --------------------
;;; Iteration
;;; (VECTOR-FOLD <kons> <initial-knil> <vector> ...) -> knil
;;; (KONS <knil> <elt> ...) -> knil' ; N vectors -> N+1 args
;;; The fundamental vector iterator. KONS is iterated over each
;;; index in all of the vectors in parallel, stopping at the end of
;;; the shortest; KONS is applied to an argument list of (list I
;;; STATE (vector-ref VEC I) ...), where STATE is the current state
;;; value -- the state value begins with KNIL and becomes whatever
;;; KONS returned at the respective iteration --, and I is the
;;; current index in the iteration. The iteration is strictly left-
;;; to-right.
;;; (vector-fold KONS KNIL (vector E_1 E_2 ... E_N))
;;; <=>
;;; (KONS (... (KONS (KONS KNIL E_1) E_2) ... E_N-1) E_N)
(define (vector-fold kons knil vec . vectors)
(let ((kons (check-type procedure? kons vector-fold))
(vec (check-type vector? vec vector-fold)))
(if (null? vectors)
(%vector-fold1 kons knil (vector-length vec) vec)
(%vector-fold2+ kons knil
(%smallest-length vectors
(vector-length vec)
vector-fold)
(cons vec vectors)))))
;;; (VECTOR-FOLD-RIGHT <kons> <initial-knil> <vector> ...) -> knil
;;; (KONS <knil> <elt> ...) -> knil' ; N vectors => N+1 args
;;; The fundamental vector recursor. Iterates in parallel across
;;; VECTOR ... right to left, applying KONS to the elements and the
;;; current state value; the state value becomes what KONS returns
;;; at each next iteration. KNIL is the initial state value.
;;; (vector-fold-right KONS KNIL (vector E_1 E_2 ... E_N))
;;; <=>
;;; (KONS (... (KONS (KONS KNIL E_N) E_N-1) ... E_2) E_1)
;;;
;;; Not implemented in terms of a more primitive operations that might
;;; called %VECTOR-FOLD-RIGHT due to the fact that it wouldn't be very
;;; useful elsewhere.
(define vector-fold-right
(letrec ((loop1 (lambda (kons knil vec i)
(if (negative? i)
knil
(loop1 kons (kons i knil (vector-ref vec i))
vec
(- i 1)))))
(loop2+ (lambda (kons knil vectors i)
(if (negative? i)
knil
(loop2+ kons
(apply kons i knil
(vectors-ref vectors i))
vectors
(- i 1))))))
(lambda (kons knil vec . vectors)
(let ((kons (check-type procedure? kons vector-fold-right))
(vec (check-type vector? vec vector-fold-right)))
(if (null? vectors)
(loop1 kons knil vec (- (vector-length vec) 1))
(loop2+ kons knil (cons vec vectors)
(- (%smallest-length vectors
(vector-length vec)
vector-fold-right)
1)))))))
;;; (VECTOR-MAP <f> <vector> ...) -> vector
;;; (F <elt> ...) -> value ; N vectors -> N args
;;; Constructs a new vector of the shortest length of the vector
;;; arguments. Each element at index I of the new vector is mapped
;;; from the old vectors by (F I (vector-ref VECTOR I) ...). The
;;; dynamic order of application of F is unspecified.
(define (vector-map f vec . vectors)
(let ((f (check-type procedure? f vector-map))
(vec (check-type vector? vec vector-map)))
(if (null? vectors)
(let ((len (vector-length vec)))
(%vector-map1! f (make-vector len) vec len))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-map)))
(%vector-map2+! f (make-vector len) (cons vec vectors)
len)))))
;;; (VECTOR-MAP! <f> <vector> ...) -> unspecified
;;; (F <elt> ...) -> element' ; N vectors -> N args
;;; Similar to VECTOR-MAP, but rather than mapping the new elements
;;; into a new vector, the new mapped elements are destructively
;;; inserted into the first vector. Again, the dynamic order of
;;; application of F is unspecified, so it is dangerous for F to
;;; manipulate the first VECTOR.
(define (vector-map! f vec . vectors)
(let ((f (check-type procedure? f vector-map!))
(vec (check-type vector? vec vector-map!)))
(if (null? vectors)
(%vector-map1! f vec vec (vector-length vec))
(%vector-map2+! f vec (cons vec vectors)
(%smallest-length vectors
(vector-length vec)
vector-map!)))
(unspecified-value)))
;;; (VECTOR-FOR-EACH <f> <vector> ...) -> unspecified
;;; (F <elt> ...) ; N vectors -> N args
;;; Simple vector iterator: applies F to each index in the range [0,
;;; LENGTH), where LENGTH is the length of the smallest vector
;;; argument passed, and the respective element at that index. In
;;; contrast with VECTOR-MAP, F is reliably applied to each
;;; subsequent elements, starting at index 0 from left to right, in
;;; the vectors.
(define vector-for-each
(letrec ((for-each1
(lambda (f vec i len)
(cond ((< i len)
(f i (vector-ref vec i))
(for-each1 f vec (+ i 1) len)))))
(for-each2+
(lambda (f vecs i len)
(cond ((< i len)
(apply f i (vectors-ref vecs i))
(for-each2+ f vecs (+ i 1) len))))))
(lambda (f vec . vectors)
(let ((f (check-type procedure? f vector-for-each))
(vec (check-type vector? vec vector-for-each)))
(if (null? vectors)
(for-each1 f vec 0 (vector-length vec))
(for-each2+ f (cons vec vectors) 0
(%smallest-length vectors
(vector-length vec)
vector-for-each)))))))
;;; (VECTOR-COUNT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer
;;; (PREDICATE? <index> <value> ...) ; N vectors -> N+1 args
;;; PREDICATE? is applied element-wise to the elements of VECTOR ...,
;;; and a count is tallied of the number of elements for which a
;;; true value is produced by PREDICATE?. This count is returned.
(define (vector-count pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-count))
(vec (check-type vector? vec vector-count)))
(if (null? vectors)
(%vector-fold1 (lambda (index count elt)
(if (pred? index elt)
(+ count 1)
count))
0
(vector-length vec)
vec)
(%vector-fold2+ (lambda (index count . elts)
(if (apply pred? index elts)
(+ count 1)
count))
0
(%smallest-length vectors
(vector-length vec)
vector-count)
(cons vec vectors)))))
;;; --------------------
;;; Searching
;;; (VECTOR-INDEX <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Search left-to-right across VECTOR ... in parallel, returning the
;;; index of the first set of values VALUE ... such that (PREDICATE?
;;; VALUE ...) returns a true value; if no such set of elements is
;;; reached, return #F.
(define (vector-index pred? vec . vectors)
(vector-index/skip pred? vec vectors vector-index))
;;; (VECTOR-SKIP <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; (vector-index (lambda elts (not (apply PREDICATE? elts)))
;;; VECTOR ...)
;;; Like VECTOR-INDEX, but find the index of the first set of values
;;; that do _not_ satisfy PREDICATE?.
(define (vector-skip pred? vec . vectors)
(vector-index/skip (lambda elts (not (apply pred? elts)))
vec vectors
vector-skip))
;;; Auxiliary for VECTOR-INDEX & VECTOR-SKIP
(define vector-index/skip
(letrec ((loop1 (lambda (pred? vec len i)
(cond ((= i len) #f)
((pred? (vector-ref vec i)) i)
(else (loop1 pred? vec len (+ i 1))))))
(loop2+ (lambda (pred? vectors len i)
(cond ((= i len) #f)
((apply pred? (vectors-ref vectors i)) i)
(else (loop2+ pred? vectors len
(+ i 1)))))))
(lambda (pred? vec vectors callee)
(let ((pred? (check-type procedure? pred? callee))
(vec (check-type vector? vec callee)))
(if (null? vectors)
(loop1 pred? vec (vector-length vec) 0)
(loop2+ pred? (cons vec vectors)
(%smallest-length vectors
(vector-length vec)
callee)
0))))))
;;; (VECTOR-INDEX-RIGHT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Right-to-left variant of VECTOR-INDEX.
(define (vector-index-right pred? vec . vectors)
(vector-index/skip-right pred? vec vectors vector-index-right))
;;; (VECTOR-SKIP-RIGHT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Right-to-left variant of VECTOR-SKIP.
(define (vector-skip-right pred? vec . vectors)
(vector-index/skip-right (lambda elts (not (apply pred? elts)))
vec vectors
vector-index-right))
(define vector-index/skip-right
(letrec ((loop1 (lambda (pred? vec i)
(cond ((negative? i) #f)
((pred? (vector-ref vec i)) i)
(else (loop1 pred? vec (- i 1))))))
(loop2+ (lambda (pred? vectors i)
(cond ((negative? i) #f)
((apply pred? (vectors-ref vectors i)) i)
(else (loop2+ pred? vectors (- i 1)))))))
(lambda (pred? vec vectors callee)
(let ((pred? (check-type procedure? pred? callee))
(vec (check-type vector? vec callee)))
(if (null? vectors)
(loop1 pred? vec (- (vector-length vec) 1))
(loop2+ pred? (cons vec vectors)
(- (%smallest-length vectors
(vector-length vec)
callee)
1)))))))
;;; (VECTOR-BINARY-SEARCH <vector> <value> <cmp> [<start> <end>])
;;; -> exact, nonnegative integer or #F
;;; (CMP <value1> <value2>) -> integer
;;; positive -> VALUE1 > VALUE2
;;; zero -> VALUE1 = VALUE2
;;; negative -> VALUE1 < VALUE2
;;; Perform a binary search through VECTOR for VALUE, comparing each
;;; element to VALUE with CMP.
(define (vector-binary-search vec value cmp . maybe-start+end)
(let ((cmp (check-type procedure? cmp vector-binary-search)))
(let-vector-start+end vector-binary-search vec maybe-start+end
(start end)
(let loop ((start start) (end end) (j #f))
(let ((i (quotient (+ start end) 2)))
(if (or (= start end) (and j (= i j)))
#f
(let ((comparison
(check-type integer?
(cmp (vector-ref vec i) value)
`(,cmp for ,vector-binary-search))))
(cond ((zero? comparison) i)
((positive? comparison) (loop start i i))
(else (loop i end i))))))))))
;;; (VECTOR-ANY <pred?> <vector> ...) -> value
;;; Apply PRED? to each parallel element in each VECTOR ...; if PRED?
;;; should ever return a true value, immediately stop and return that
;;; value; otherwise, when the shortest vector runs out, return #F.
;;; The iteration and order of application of PRED? across elements
;;; is of the vectors is strictly left-to-right.
(define vector-any
(letrec ((loop1 (lambda (pred? vec i len len-1)
(and (not (= i len))
(if (= i len-1)
(pred? (vector-ref vec i))
(or (pred? (vector-ref vec i))
(loop1 pred? vec (+ i 1)
len len-1))))))
(loop2+ (lambda (pred? vectors i len len-1)
(and (not (= i len))
(if (= i len-1)
(apply pred? (vectors-ref vectors i))
(or (apply pred? (vectors-ref vectors i))
(loop2+ pred? vectors (+ i 1)
len len-1)))))))
(lambda (pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-any))
(vec (check-type vector? vec vector-any)))
(if (null? vectors)
(let ((len (vector-length vec)))
(loop1 pred? vec 0 len (- len 1)))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-any)))
(loop2+ pred? (cons vec vectors) 0 len (- len 1))))))))
;;; (VECTOR-EVERY <pred?> <vector> ...) -> value
;;; Apply PRED? to each parallel value in each VECTOR ...; if PRED?
;;; should ever return #F, immediately stop and return #F; otherwise,
;;; if PRED? should return a true value for each element, stopping at
;;; the end of the shortest vector, return the last value that PRED?
;;; returned. In the case that there is an empty vector, return #T.
;;; The iteration and order of application of PRED? across elements
;;; is of the vectors is strictly left-to-right.
(define vector-every
(letrec ((loop1 (lambda (pred? vec i len len-1)
(or (= i len)
(if (= i len-1)
(pred? (vector-ref vec i))
(and (pred? (vector-ref vec i))
(loop1 pred? vec (+ i 1)
len len-1))))))
(loop2+ (lambda (pred? vectors i len len-1)
(or (= i len)
(if (= i len-1)
(apply pred? (vectors-ref vectors i))
(and (apply pred? (vectors-ref vectors i))
(loop2+ pred? vectors (+ i 1)
len len-1)))))))
(lambda (pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-every))
(vec (check-type vector? vec vector-every)))
(if (null? vectors)
(let ((len (vector-length vec)))
(loop1 pred? vec 0 len (- len 1)))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-every)))
(loop2+ pred? (cons vec vectors) 0 len (- len 1))))))))
;;; --------------------
;;; Mutators
;;; (VECTOR-SWAP! <vector> <index1> <index2>) -> unspecified
;;; Swap the values in the locations at INDEX1 and INDEX2.
(define (vector-swap! vec i j)
(let ((vec (check-type vector? vec vector-swap!)))
(let ((i (check-index vec i vector-swap!))
(j (check-index vec j vector-swap!)))
(let ((x (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j x)))))
;;; (VECTOR-REVERSE-COPY! <target> <tstart> <source> [<sstart> <send>])
;;; [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source).
(define (vector-reverse-copy! target tstart source . maybe-sstart+send)
(define (doit! sstart send source-length)
(let ((tstart (check-type nonneg-int? tstart vector-reverse-copy!))
(sstart (check-type nonneg-int? sstart vector-reverse-copy!))
(send (check-type nonneg-int? send vector-reverse-copy!)))
(cond ((and (eq? target source)
(or (between? sstart tstart send)
(between? tstart sstart
(+ tstart (- send sstart)))))
(error "vector range for self-copying overlaps"
vector-reverse-copy!
`(vector was ,target)
`(tstart was ,tstart)
`(sstart was ,sstart)
`(send was ,send)))
((and (<= 0 sstart send source-length)
(<= (+ tstart (- send sstart)) (vector-length target)))
(%vector-reverse-copy! target tstart source sstart send))
(else
(error "illegal arguments"
`(while calling ,vector-reverse-copy!)
`(target was ,target)
`(target-length was ,(vector-length target))
`(tstart was ,tstart)
`(source was ,source)
`(source-length was ,source-length)
`(sstart was ,sstart)
`(send was ,send))))))
(let ((n (vector-length source)))
(cond ((null? maybe-sstart+send)
(doit! 0 n n))
((null? (cdr maybe-sstart+send))
(doit! (car maybe-sstart+send) n n))
((null? (cddr maybe-sstart+send))
(doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n))
(else
(error "too many arguments"
vector-reverse-copy!
(cddr maybe-sstart+send))))))
;;; (VECTOR-REVERSE! <vector> [<start> <end>]) -> unspecified
;;; Destructively reverse the contents of the sequence of locations
;;; in VECTOR between START, whose default is 0, and END, whose
;;; default is the length of VECTOR.
(define (vector-reverse! vec . start+end)
(let-vector-start+end vector-reverse! vec start+end
(start end)
(%vector-reverse! vec start end)))
;;; --------------------
;;; Conversion
;;; (REVERSE-VECTOR->LIST <vector> [<start> <end>]) -> list
;;; Produce a list containing the elements in the locations between
;;; START, whose default is 0, and END, whose default is the length
;;; of VECTOR, from VECTOR, in reverse order.
(define (reverse-vector->list vec . maybe-start+end)
(let-vector-start+end reverse-vector->list vec maybe-start+end
(start end)
;(unfold (lambda (i) (= i end)) ; No SRFI 1.
; (lambda (i) (vector-ref vec i))
; (lambda (i) (+ i 1))
; start)
(do ((i start (+ i 1))
(result '() (cons (vector-ref vec i) result)))
((= i end) result))))
;;; (LIST->VECTOR <list> [<start> <end>]) -> vector
;;; [R5RS+] Produce a vector containing the elements in LIST, which
;;; must be a proper list, between START, whose default is 0, & END,
;;; whose default is the length of LIST. It is suggested that if the
;;; length of LIST is known in advance, the START and END arguments
;;; be passed, so that LIST->VECTOR need not call LENGTH to determine
;;; the the length.
;;;
;;; This implementation diverges on circular lists, unless LENGTH fails
;;; and causes - to fail as well. Given a LENGTH* that computes the
;;; length of a list's cycle, this wouldn't diverge, and would work
;;; great for circular lists.
(define list->vector
(case-lambda
((lst) (%list->vector lst))
((lst start) (list->vector lst start (length lst)))
((lst start end)
(let ((start (check-type nonneg-int? start list->vector))
(end (check-type nonneg-int? end list->vector)))
((lambda (f)
(vector-unfold f (- end start) (list-tail lst start)))
(lambda (index l)
(cond ((null? l)
(error "list was too short"
`(list was ,lst)
`(attempted end was ,end)
`(while calling ,list->vector)))
((pair? l)
(values (car l) (cdr l)))
(else
;; Make this look as much like what CHECK-TYPE
;; would report as possible.
(error "erroneous value"
;; We want SRFI 1's PROPER-LIST?, but it
;; would be a waste to link all of SRFI
;; 1 to this module for only the single
;; function PROPER-LIST?.
(list list? lst)
`(while calling
,list->vector))))))))))
;;; (REVERSE-LIST->VECTOR <list> [<start> <end>]) -> vector
;;; Produce a vector containing the elements in LIST, which must be a
;;; proper list, between START, whose default is 0, and END, whose
;;; default is the length of LIST, in reverse order. It is suggested
;;; that if the length of LIST is known in advance, the START and END
;;; arguments be passed, so that REVERSE-LIST->VECTOR need not call
;;; LENGTH to determine the the length.
;;;
;;; This also diverges on circular lists unless, again, LENGTH returns
;;; something that makes - bork.
(define reverse-list->vector
(case-lambda
((lst) (reverse-list->vector lst 0 (length lst)))
((lst start) (reverse-list->vector start (length lst)))
((lst start end)
(let ((start (check-type nonneg-int? start reverse-list->vector))
(end (check-type nonneg-int? end reverse-list->vector)))
((lambda (f)
(vector-unfold-right f (- end start) (list-tail lst start)))
(lambda (index l)
(cond ((null? l)
(error "list too short"
`(list was ,lst)
`(attempted end was ,end)
`(while calling ,reverse-list->vector)))
((pair? l)
(values (car l) (cdr l)))
(else
(error "erroneous value"
(list list? lst)
`(while calling ,reverse-list->vector))))))))))
(define-library (srfi 43)
(export
;; Constructors
vector-unfold vector-unfold-right
vector-reverse-copy
vector-concatenate
;; Predicates
vector-empty?
vector=
;; Iteration
vector-fold vector-fold-right
vector-map vector-map!
vector-for-each
vector-count
;; Searching
vector-index vector-index-right
vector-skip vector-skip-right
vector-binary-search
vector-any vector-every
;; Mutators
vector-swap!
vector-reverse!
vector-reverse-copy!
;; Conversion
reverse-vector->list
list->vector
reverse-list->vector
)
(import
(rename (scheme base) (list->vector %list->vector))
(scheme case-lambda)
(scheme cxr)
(srfi 8)
(srfi aux))
(begin
(define-aux-forms check-type let-optionals* #\:optional)
;; (CHECK-INDEX <vector> <index> <callee>) -> index
;; Ensure that INDEX is a valid index into VECTOR; if not, signal an
;; error stating that it is not and that this happened in a call to
;; CALLEE. Return INDEX when it is valid. (Note that this does NOT
;; check that VECTOR is indeed a vector.)
(define check-index
(if (debug-mode)
(lambda (vec index callee)
(let ((index (check-type integer? index callee)))
(cond ((< index 0)
(check-index vec
(error "vector index too low"
index
`(into vector ,vec)
`(while calling ,callee))
callee))
((>= index (vector-length vec))
(check-index vec
(error "vector index too high"
index
`(into vector ,vec)
`(while calling ,callee))
callee))
(else index))))
(lambda (vec index callee)
index)))
;; (CHECK-INDICES <vector>
;; <start> <start-name>
;; <end> <end-name>
;; <caller>) -> [start end]
;; Ensure that START and END are valid bounds of a range within
;; VECTOR; if not, signal an error stating that they are not, with
;; the message being informative about what the argument names were
;; called -- by using START-NAME & END-NAME --, and that it occurred
;; while calling CALLEE. Also ensure that VEC is in fact a vector.
;; Returns no useful value.
(define check-indices
(if (debug-mode)
(lambda (vec start start-name end end-name callee)
(let ((lose (lambda things
(apply error "vector range out of bounds"
(append things
`(vector was ,vec)
`(,start-name was ,start)
`(,end-name was ,end)
`(while calling ,callee)))))
(start (check-type integer? start callee))
(end (check-type integer? end callee)))
(cond ((> start end)
;; I'm not sure how well this will work. The intent is that
;; the programmer tells the debugger to proceed with both a
;; new START & a new END by returning multiple values
;; somewhere.
(receive (new-start new-end)
(lose `(,end-name < ,start-name))
(check-indices vec
new-start start-name
new-end end-name
callee)))
((< start 0)
(check-indices vec
(lose `(,start-name < 0))
start-name
end end-name
callee))
((>= start (vector-length vec))
(check-indices vec
(lose `(,start-name > len)
`(len was ,(vector-length vec)))
start-name
end end-name
callee))
((> end (vector-length vec))
(check-indices vec
start start-name
(lose `(,end-name > len)
`(len was ,(vector-length vec)))
end-name
callee))
(else
(values start end)))))
(lambda (vec start start-name end end-name callee)
(values start end))))
)
(include "43.body.scm"))
(define-library (srfi 95)
(export sorted? merge merge! sort sort!)
(import
(except (scheme base) equal?)
(srfi 63))
(include "95.body.scm"))
;;;;;; SRFI 43: Vector library -*- Scheme -*-
;;;
;;; $Id: vector-lib.scm,v 1.7 2009/03/29 09:46:03 sperber Exp $
;;;
;;; Taylor Campbell wrote this code; he places it in the public domain.
;;; Will Clinger [wdc] made some corrections, also in the public domain.
;;; Copyright (C) Taylor Campbell (2003). All rights reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;; --------------------
;;; Exported procedure index
;;;
;;; * Constructors
;;; make-vector vector
;;; vector-unfold vector-unfold-right
;;; vector-copy vector-reverse-copy
;;; vector-append vector-concatenate
;;;
;;; * Predicates
;;; vector?
;;; vector-empty?
;;; vector=
;;;
;;; * Selectors
;;; vector-ref
;;; vector-length
;;;
;;; * Iteration
;;; vector-fold vector-fold-right
;;; vector-map vector-map!
;;; vector-for-each
;;; vector-count
;;;
;;; * Searching
;;; vector-index vector-skip
;;; vector-index-right vector-skip-right
;;; vector-binary-search
;;; vector-any vector-every
;;;
;;; * Mutators
;;; vector-set!
;;; vector-swap!
;;; vector-fill!
;;; vector-reverse!
;;; vector-copy! vector-reverse-copy!
;;; vector-reverse!
;;;
;;; * Conversion
;;; vector->list reverse-vector->list
;;; list->vector reverse-list->vector
;;; --------------------
;;; Commentary on efficiency of the code
;;; This code is somewhat tuned for efficiency. There are several
;;; internal routines that can be optimized greatly to greatly improve
;;; the performance of much of the library. These internal procedures
;;; are already carefully tuned for performance, and lambda-lifted by
;;; hand. Some other routines are lambda-lifted by hand, but only the
;;; loops are lambda-lifted, and only if some routine has two possible
;;; loops -- a fast path and an n-ary case --, whereas _all_ of the
;;; internal routines' loops are lambda-lifted so as to never cons a
;;; closure in their body (VECTOR-PARSE-START+END doesn't have a loop),
;;; even in Scheme systems that perform no loop optimization (which is
;;; most of them, unfortunately).
;;;
;;; Fast paths are provided for common cases in most of the loops in
;;; this library.
;;;
;;; All calls to primitive vector operations are protected by a prior
;;; type check; they can be safely converted to use unsafe equivalents
;;; of the operations, if available. Ideally, the compiler should be
;;; able to determine this, but the state of Scheme compilers today is
;;; not a happy one.
;;;
;;; Efficiency of the actual algorithms is a rather mundane point to
;;; mention; vector operations are rarely beyond being straightforward.
;;; --------------------
;;; Utilities
;;; SRFI 8, too trivial to put in the dependencies list.
(define-syntax receive
(syntax-rules ()
((receive ?formals ?producer ?body1 ?body2 ...)
(call-with-values (lambda () ?producer)
(lambda ?formals ?body1 ?body2 ...)))))
;;; Not the best LET*-OPTIONALS, but not the worst, either. Use Olin's
;;; if it's available to you.
(define-syntax let*-optionals
(syntax-rules ()
((let*-optionals (?x ...) ((?var ?default) ...) ?body1 ?body2 ...)
(let ((args (?x ...)))
(let*-optionals args ((?var ?default) ...) ?body1 ?body2 ...)))
((let*-optionals ?args ((?var ?default) ...) ?body1 ?body2 ...)
(let*-optionals:aux ?args ?args ((?var ?default) ...)
?body1 ?body2 ...))))
(define-syntax let*-optionals:aux
(syntax-rules ()
((aux ?orig-args-var ?args-var () ?body1 ?body2 ...)
(if (null? ?args-var)
(let () ?body1 ?body2 ...)
(error "too many arguments" (length ?orig-args-var)
?orig-args-var)))
((aux ?orig-args-var ?args-var
((?var ?default) ?more ...)
?body1 ?body2 ...)
(if (null? ?args-var)
(let* ((?var ?default) ?more ...) ?body1 ?body2 ...)
(let ((?var (car ?args-var))
(new-args (cdr ?args-var)))
(let*-optionals:aux ?orig-args-var new-args
(?more ...)
?body1 ?body2 ...))))))
(define (nonneg-int? x)
(and (integer? x)
(not (negative? x))))
(define (between? x y z)
(and (< x y)
(<= y z)))
(define (unspecified-value) (if #f #f))
;++ This should be implemented more efficiently. It shouldn't cons a
;++ closure, and the cons cells used in the loops when using this could
;++ be reused.
(define (vectors-ref vectors i)
(map (lambda (v) (vector-ref v i)) vectors))
;;; --------------------
;;; Error checking
;;; Error signalling (not checking) is done in a way that tries to be
;;; as helpful to the person who gets the debugging prompt as possible.
;;; That said, error _checking_ tries to be as unredundant as possible.
;;; I don't use any sort of general condition mechanism; I use simply
;;; SRFI 23's ERROR, even in cases where it might be better to use such
;;; a general condition mechanism. Fix that when porting this to a
;;; Scheme implementation that has its own condition system.
;;; In argument checks, upon receiving an invalid argument, the checker
;;; procedure recursively calls itself, but in one of the arguments to
;;; itself is a call to ERROR; this mechanism is used in the hopes that
;;; the user may be thrown into a debugger prompt, proceed with another
;;; value, and let it be checked again.
;;; Type checking is pretty basic, but easily factored out and replaced
;;; with whatever your implementation's preferred type checking method
;;; is. I doubt there will be many other methods of index checking,
;;; though the index checkers might be better implemented natively.
;;; (CHECK-TYPE <type-predicate?> <value> <callee>) -> value
;;; Ensure that VALUE satisfies TYPE-PREDICATE?; if not, signal an
;;; error stating that VALUE did not satisfy TYPE-PREDICATE?, showing
;;; that this happened while calling CALLEE. Return VALUE if no
;;; error was signalled.
(define (check-type pred? value callee)
(if (pred? value)
value
;; Recur: when (or if) the user gets a debugger prompt, he can
;; proceed where the call to ERROR was with the correct value.
(check-type pred?
(error "erroneous value"
(list pred? value)
`(while calling ,callee))
callee)))
;;; (CHECK-INDEX <vector> <index> <callee>) -> index
;;; Ensure that INDEX is a valid index into VECTOR; if not, signal an
;;; error stating that it is not and that this happened in a call to
;;; CALLEE. Return INDEX when it is valid. (Note that this does NOT
;;; check that VECTOR is indeed a vector.)
(define (check-index vec index callee)
(let ((index (check-type integer? index callee)))
(cond ((< index 0)
(check-index vec
(error "vector index too low"
index
`(into vector ,vec)
`(while calling ,callee))
callee))
((>= index (vector-length vec))
(check-index vec
(error "vector index too high"
index
`(into vector ,vec)
`(while calling ,callee))
callee))
(else index))))
;;; (CHECK-INDICES <vector>
;;; <start> <start-name>
;;; <end> <end-name>
;;; <caller>) -> [start end]
;;; Ensure that START and END are valid bounds of a range within
;;; VECTOR; if not, signal an error stating that they are not, with
;;; the message being informative about what the argument names were
;;; called -- by using START-NAME & END-NAME --, and that it occurred
;;; while calling CALLEE. Also ensure that VEC is in fact a vector.
;;; Returns no useful value.
(define (check-indices vec start start-name end end-name callee)
(let ((lose (lambda things
(apply error "vector range out of bounds"
(append things
`(vector was ,vec)
`(,start-name was ,start)
`(,end-name was ,end)
`(while calling ,callee)))))
(start (check-type integer? start callee))
(end (check-type integer? end callee)))
(cond ((> start end)
;; I'm not sure how well this will work. The intent is that
;; the programmer tells the debugger to proceed with both a
;; new START & a new END by returning multiple values
;; somewhere.
(receive (new-start new-end)
(lose `(,end-name < ,start-name))
(check-indices vec
new-start start-name
new-end end-name
callee)))
((< start 0)
(check-indices vec
(lose `(,start-name < 0))
start-name
end end-name
callee))
((>= start (vector-length vec))
(check-indices vec
(lose `(,start-name > len)
`(len was ,(vector-length vec)))
start-name
end end-name
callee))
((> end (vector-length vec))
(check-indices vec
start start-name
(lose `(,end-name > len)
`(len was ,(vector-length vec)))
end-name
callee))
(else
(values start end)))))
;;; --------------------
;;; Internal routines
;;; These should all be integrated, native, or otherwise optimized --
;;; they're used a _lot_ --. All of the loops and LETs inside loops
;;; are lambda-lifted by hand, just so as not to cons closures in the
;;; loops. (If your compiler can do better than that if they're not
;;; lambda-lifted, then lambda-drop (?) them.)
;;; (VECTOR-PARSE-START+END <vector> <arguments>
;;; <start-name> <end-name>
;;; <callee>)
;;; -> [start end]
;;; Return two values, composing a valid range within VECTOR, as
;;; extracted from ARGUMENTS or defaulted from VECTOR -- 0 for START
;;; and the length of VECTOR for END --; START-NAME and END-NAME are
;;; purely for error checking.
(define (vector-parse-start+end vec args start-name end-name callee)
(let ((len (vector-length vec)))
(cond ((null? args)
(values 0 len))
((null? (cdr args))
(check-indices vec
(car args) start-name
len end-name
callee))
((null? (cddr args))
(check-indices vec
(car args) start-name
(cadr args) end-name
callee))
(else
(error "too many arguments"
`(extra args were ,(cddr args))
`(while calling ,callee))))))
(define-syntax let-vector-start+end
(syntax-rules ()
((let-vector-start+end ?callee ?vec ?args (?start ?end)
?body1 ?body2 ...)
(let ((?vec (check-type vector? ?vec ?callee)))
(receive (?start ?end)
(vector-parse-start+end ?vec ?args '?start '?end
?callee)
?body1 ?body2 ...)))))
;;; (%SMALLEST-LENGTH <vector-list> <default-length> <callee>)
;;; -> exact, nonnegative integer
;;; Compute the smallest length of VECTOR-LIST. DEFAULT-LENGTH is
;;; the length that is returned if VECTOR-LIST is empty. Common use
;;; of this is in n-ary vector routines:
;;; (define (f vec . vectors)
;;; (let ((vec (check-type vector? vec f)))
;;; ...(%smallest-length vectors (vector-length vec) f)...))
;;; %SMALLEST-LENGTH takes care of the type checking -- which is what
;;; the CALLEE argument is for --; thus, the design is tuned for
;;; avoiding redundant type checks.
(define %smallest-length
(letrec ((loop (lambda (vector-list length callee)
(if (null? vector-list)
length
(loop (cdr vector-list)
(min (vector-length
(check-type vector?
(car vector-list)
callee))
length)
callee)))))
loop))
;;; (%VECTOR-COPY! <target> <tstart> <source> <sstart> <send>)
;;; Copy elements at locations SSTART to SEND from SOURCE to TARGET,
;;; starting at TSTART in TARGET.
;;;
;;; Optimize this! Probably with some combination of:
;;; - Force it to be integrated.
;;; - Let it use unsafe vector element dereferencing routines: bounds
;;; checking already happens outside of it. (Or use a compiler
;;; that figures this out, but Olin Shivers' PhD thesis seems to
;;; have been largely ignored in actual implementations...)
;;; - Implement it natively as a VM primitive: the VM can undoubtedly
;;; perform much faster than it can make Scheme perform, even with
;;; bounds checking.
;;; - Implement it in assembly: you _want_ the fine control that
;;; assembly can give you for this.
;;; I already lambda-lift it by hand, but you should be able to make it
;;; even better than that.
(define %vector-copy!
(letrec ((loop/l->r (lambda (target source send i j)
(cond ((< i send)
(vector-set! target j
(vector-ref source i))
(loop/l->r target source send
(+ i 1) (+ j 1))))))
(loop/r->l (lambda (target source sstart i j)
(cond ((>= i sstart)
(vector-set! target j
(vector-ref source i))
(loop/r->l target source sstart
(- i 1) (- j 1)))))))
(lambda (target tstart source sstart send)
(if (> sstart tstart) ; Make sure we don't copy over
; ourselves.
(loop/l->r target source send sstart tstart)
(loop/r->l target source sstart (- send 1)
(+ -1 tstart send (- sstart)))))))
;;; (%VECTOR-REVERSE-COPY! <target> <tstart> <source> <sstart> <send>)
;;; Copy elements from SSTART to SEND from SOURCE to TARGET, in the
;;; reverse order.
(define %vector-reverse-copy!
(letrec ((loop (lambda (target source sstart i j)
(cond ((>= i sstart)
(vector-set! target j (vector-ref source i))
(loop target source sstart
(- i 1)
(+ j 1)))))))
(lambda (target tstart source sstart send)
(loop target source sstart
(- send 1)
tstart))))
;;; (%VECTOR-REVERSE! <vector>)
(define %vector-reverse!
(letrec ((loop (lambda (vec i j)
(cond ((<= i j)
(let ((v (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j v)
(loop vec (+ i 1) (- j 1))))))))
(lambda (vec start end)
(loop vec start (- end 1)))))
;;; (%VECTOR-FOLD1 <kons> <knil> <vector>) -> knil'
;;; (KONS <index> <knil> <elt>) -> knil'
(define %vector-fold1
(letrec ((loop (lambda (kons knil len vec i)
(if (= i len)
knil
(loop kons
(kons i knil (vector-ref vec i))
len vec (+ i 1))))))
(lambda (kons knil len vec)
(loop kons knil len vec 0))))
;;; (%VECTOR-FOLD2+ <kons> <knil> <vector> ...) -> knil'
;;; (KONS <index> <knil> <elt> ...) -> knil'
(define %vector-fold2+
(letrec ((loop (lambda (kons knil len vectors i)
(if (= i len)
knil
(loop kons
(apply kons i knil
(vectors-ref vectors i))
len vectors (+ i 1))))))
(lambda (kons knil len vectors)
(loop kons knil len vectors 0))))
;;; (%VECTOR-MAP! <f> <target> <length> <vector>) -> target
;;; (F <index> <elt>) -> elt'
(define %vector-map1!
(letrec ((loop (lambda (f target vec i)
(if (zero? i)
target
(let ((j (- i 1)))
(vector-set! target j
(f j (vector-ref vec j)))
(loop f target vec j))))))
(lambda (f target vec len)
(loop f target vec len))))
;;; (%VECTOR-MAP2+! <f> <target> <vectors> <len>) -> target
;;; (F <index> <elt> ...) -> elt'
(define %vector-map2+!
(letrec ((loop (lambda (f target vectors i)
(if (zero? i)
target
(let ((j (- i 1)))
(vector-set! target j
(apply f j (vectors-ref vectors j)))
(loop f target vectors j))))))
(lambda (f target vectors len)
(loop f target vectors len))))
;;;;;;;;;;;;;;;;;;;;;;;; ***** vector-lib ***** ;;;;;;;;;;;;;;;;;;;;;;;
;;; --------------------
;;; Constructors
;;; (MAKE-VECTOR <size> [<fill>]) -> vector
;;; [R5RS] Create a vector of length LENGTH. If FILL is present,
;;; initialize each slot in the vector with it; if not, the vector's
;;; initial contents are unspecified.
(define make-vector make-vector)
;;; (VECTOR <elt> ...) -> vector
;;; [R5RS] Create a vector containing ELEMENT ..., in order.
(define vector vector)
;;; This ought to be able to be implemented much more efficiently -- if
;;; we have the number of arguments available to us, we can create the
;;; vector without using LENGTH to determine the number of elements it
;;; should have.
;(define (vector . elements) (list->vector elements))
;;; (VECTOR-UNFOLD <f> <length> <initial-seed> ...) -> vector
;;; (F <index> <seed> ...) -> [elt seed' ...]
;;; The fundamental vector constructor. Creates a vector whose
;;; length is LENGTH and iterates across each index K between 0 and
;;; LENGTH, applying F at each iteration to the current index and the
;;; current seeds to receive N+1 values: first, the element to put in
;;; the Kth slot and then N new seeds for the next iteration.
(define vector-unfold
(letrec ((tabulate! ; Special zero-seed case.
(lambda (f vec i len)
(cond ((< i len)
(vector-set! vec i (f i))
(tabulate! f vec (+ i 1) len)))))
(unfold1! ; Fast path for one seed.
(lambda (f vec i len seed)
(if (< i len)
(receive (elt new-seed)
(f i seed)
(vector-set! vec i elt)
(unfold1! f vec (+ i 1) len new-seed)))))
(unfold2+! ; Slower variant for N seeds.
(lambda (f vec i len seeds)
(if (< i len)
(receive (elt . new-seeds)
(apply f i seeds)
(vector-set! vec i elt)
(unfold2+! f vec (+ i 1) len new-seeds))))))
(lambda (f len . initial-seeds)
(let ((f (check-type procedure? f vector-unfold))
(len (check-type nonneg-int? len vector-unfold)))
(let ((vec (make-vector len)))
(cond ((null? initial-seeds)
(tabulate! f vec 0 len))
((null? (cdr initial-seeds))
(unfold1! f vec 0 len (car initial-seeds)))
(else
(unfold2+! f vec 0 len initial-seeds)))
vec)))))
;;; (VECTOR-UNFOLD-RIGHT <f> <length> <initial-seed> ...) -> vector
;;; (F <seed> ...) -> [seed' ...]
;;; Like VECTOR-UNFOLD, but it generates elements from LENGTH to 0
;;; (still exclusive with LENGTH and inclusive with 0), not 0 to
;;; LENGTH as with VECTOR-UNFOLD.
(define vector-unfold-right
(letrec ((tabulate!
(lambda (f vec i)
(cond ((>= i 0)
(vector-set! vec i (f i))
(tabulate! f vec (- i 1))))))
(unfold1!
(lambda (f vec i seed)
(if (>= i 0)
(receive (elt new-seed)
(f i seed)
(vector-set! vec i elt)
(unfold1! f vec (- i 1) new-seed)))))
(unfold2+!
(lambda (f vec i seeds)
(if (>= i 0)
(receive (elt . new-seeds)
(apply f i seeds)
(vector-set! vec i elt)
(unfold2+! f vec (- i 1) new-seeds))))))
(lambda (f len . initial-seeds)
(let ((f (check-type procedure? f vector-unfold-right))
(len (check-type nonneg-int? len vector-unfold-right)))
(let ((vec (make-vector len))
(i (- len 1)))
(cond ((null? initial-seeds)
(tabulate! f vec i))
((null? (cdr initial-seeds))
(unfold1! f vec i (car initial-seeds)))
(else
(unfold2+! f vec i initial-seeds)))
vec)))))
;;; (VECTOR-COPY <vector> [<start> <end> <fill>]) -> vector
;;; Create a newly allocated vector containing the elements from the
;;; range [START,END) in VECTOR. START defaults to 0; END defaults
;;; to the length of VECTOR. END may be greater than the length of
;;; VECTOR, in which case the vector is enlarged; if FILL is passed,
;;; the new locations from which there is no respective element in
;;; VECTOR are filled with FILL.
(define (vector-copy vec . args)
(let ((vec (check-type vector? vec vector-copy)))
;; We can't use LET-VECTOR-START+END, because we have one more
;; argument, and we want finer control, too.
;;
;; Olin's implementation of LET*-OPTIONALS would prove useful here:
;; the built-in argument-checks-as-you-go-along produces almost
;; _exactly_ the same code as VECTOR-COPY:PARSE-ARGS.
(receive (start end fill)
(vector-copy:parse-args vec args)
(let ((new-vector (make-vector (- end start) fill)))
(%vector-copy! new-vector 0
vec start
(if (> end (vector-length vec))
(vector-length vec)
end))
new-vector))))
;;; Auxiliary for VECTOR-COPY.
;;; [wdc] Corrected to allow 0 <= start <= (vector-length vec).
(define (vector-copy:parse-args vec args)
(define (parse-args start end n fill)
(let ((start (check-type nonneg-int? start vector-copy))
(end (check-type nonneg-int? end vector-copy)))
(cond ((and (<= 0 start end)
(<= start n))
(values start end fill))
(else
(error "illegal arguments"
`(while calling ,vector-copy)
`(start was ,start)
`(end was ,end)
`(vector was ,vec))))))
(let ((n (vector-length vec)))
(cond ((null? args)
(parse-args 0 n n (unspecified-value)))
((null? (cdr args))
(parse-args (car args) n n (unspecified-value)))
((null? (cddr args))
(parse-args (car args) (cadr args) n (unspecified-value)))
((null? (cdddr args))
(parse-args (car args) (cadr args) n (caddr args)))
(else
(error "too many arguments"
vector-copy
(cdddr args))))))
;;; (VECTOR-REVERSE-COPY <vector> [<start> <end>]) -> vector
;;; Create a newly allocated vector whose elements are the reversed
;;; sequence of elements between START and END in VECTOR. START's
;;; default is 0; END's default is the length of VECTOR.
(define (vector-reverse-copy vec . maybe-start+end)
(let-vector-start+end vector-reverse-copy vec maybe-start+end
(start end)
(let ((new (make-vector (- end start))))
(%vector-reverse-copy! new 0 vec start end)
new)))
;;; (VECTOR-APPEND <vector> ...) -> vector
;;; Append VECTOR ... into a newly allocated vector and return that
;;; new vector.
(define (vector-append . vectors)
(vector-concatenate:aux vectors vector-append))
;;; (VECTOR-CONCATENATE <vector-list>) -> vector
;;; Concatenate the vectors in VECTOR-LIST. This is equivalent to
;;; (apply vector-append VECTOR-LIST)
;;; but VECTOR-APPEND tends to be implemented in terms of
;;; VECTOR-CONCATENATE, and some Schemes bork when the list to apply
;;; a function to is too long.
;;;
;;; Actually, they're both implemented in terms of an internal routine.
(define (vector-concatenate vector-list)
(vector-concatenate:aux vector-list vector-concatenate))
;;; Auxiliary for VECTOR-APPEND and VECTOR-CONCATENATE
(define vector-concatenate:aux
(letrec ((compute-length
(lambda (vectors len callee)
(if (null? vectors)
len
(let ((vec (check-type vector? (car vectors)
callee)))
(compute-length (cdr vectors)
(+ (vector-length vec) len)
callee)))))
(concatenate!
(lambda (vectors target to)
(if (null? vectors)
target
(let* ((vec1 (car vectors))
(len (vector-length vec1)))
(%vector-copy! target to vec1 0 len)
(concatenate! (cdr vectors) target
(+ to len)))))))
(lambda (vectors callee)
(cond ((null? vectors) ;+++
(make-vector 0))
((null? (cdr vectors)) ;+++
;; Blech, we still have to allocate a new one.
(let* ((vec (check-type vector? (car vectors) callee))
(len (vector-length vec))
(new (make-vector len)))
(%vector-copy! new 0 vec 0 len)
new))
(else
(let ((new-vector
(make-vector (compute-length vectors 0 callee))))
(concatenate! vectors new-vector 0)
new-vector))))))
;;; --------------------
;;; Predicates
;;; (VECTOR? <value>) -> boolean
;;; [R5RS] Return #T if VALUE is a vector and #F if not.
(define vector? vector?)
;;; (VECTOR-EMPTY? <vector>) -> boolean
;;; Return #T if VECTOR has zero elements in it, i.e. VECTOR's length
;;; is 0, and #F if not.
(define (vector-empty? vec)
(let ((vec (check-type vector? vec vector-empty?)))
(zero? (vector-length vec))))
;;; (VECTOR= <elt=?> <vector> ...) -> boolean
;;; (ELT=? <value> <value>) -> boolean
;;; Determine vector equality generalized across element comparators.
;;; Vectors A and B are equal iff their lengths are the same and for
;;; each respective elements E_a and E_b (element=? E_a E_b) returns
;;; a true value. ELT=? is always applied to two arguments. Element
;;; comparison must be consistent wtih EQ?; that is, if (eq? E_a E_b)
;;; results in a true value, then (ELEMENT=? E_a E_b) must result in a
;;; true value. This may be exploited to avoid multiple unnecessary
;;; element comparisons. (This implementation does, but does not deal
;;; with the situation that ELEMENT=? is EQ? to avoid more unnecessary
;;; comparisons, but I believe this optimization is probably fairly
;;; insignificant.)
;;;
;;; If the number of vector arguments is zero or one, then #T is
;;; automatically returned. If there are N vector arguments,
;;; VECTOR_1 VECTOR_2 ... VECTOR_N, then VECTOR_1 & VECTOR_2 are
;;; compared; if they are equal, the vectors VECTOR_2 ... VECTOR_N
;;; are compared. The precise order in which ELT=? is applied is not
;;; specified.
(define (vector= elt=? . vectors)
(let ((elt=? (check-type procedure? elt=? vector=)))
(cond ((null? vectors)
#t)
((null? (cdr vectors))
(check-type vector? (car vectors) vector=)
#t)
(else
(let loop ((vecs vectors))
(let ((vec1 (check-type vector? (car vecs) vector=))
(vec2+ (cdr vecs)))
(or (null? vec2+)
(and (binary-vector= elt=? vec1 (car vec2+))
(loop vec2+)))))))))
(define (binary-vector= elt=? vector-a vector-b)
(or (eq? vector-a vector-b) ;+++
(let ((length-a (vector-length vector-a))
(length-b (vector-length vector-b)))
(letrec ((loop (lambda (i)
(or (= i length-a)
(and (< i length-b)
(test (vector-ref vector-a i)
(vector-ref vector-b i)
i)))))
(test (lambda (elt-a elt-b i)
(and (or (eq? elt-a elt-b) ;+++
(elt=? elt-a elt-b))
(loop (+ i 1))))))
(and (= length-a length-b)
(loop 0))))))
;;; --------------------
;;; Selectors
;;; (VECTOR-REF <vector> <index>) -> value
;;; [R5RS] Return the value that the location in VECTOR at INDEX is
;;; mapped to in the store.
(define vector-ref vector-ref)
;;; (VECTOR-LENGTH <vector>) -> exact, nonnegative integer
;;; [R5RS] Return the length of VECTOR.
(define vector-length vector-length)
;;; --------------------
;;; Iteration
;;; (VECTOR-FOLD <kons> <initial-knil> <vector> ...) -> knil
;;; (KONS <knil> <elt> ...) -> knil' ; N vectors -> N+1 args
;;; The fundamental vector iterator. KONS is iterated over each
;;; index in all of the vectors in parallel, stopping at the end of
;;; the shortest; KONS is applied to an argument list of (list I
;;; STATE (vector-ref VEC I) ...), where STATE is the current state
;;; value -- the state value begins with KNIL and becomes whatever
;;; KONS returned at the respective iteration --, and I is the
;;; current index in the iteration. The iteration is strictly left-
;;; to-right.
;;; (vector-fold KONS KNIL (vector E_1 E_2 ... E_N))
;;; <=>
;;; (KONS (... (KONS (KONS KNIL E_1) E_2) ... E_N-1) E_N)
(define (vector-fold kons knil vec . vectors)
(let ((kons (check-type procedure? kons vector-fold))
(vec (check-type vector? vec vector-fold)))
(if (null? vectors)
(%vector-fold1 kons knil (vector-length vec) vec)
(%vector-fold2+ kons knil
(%smallest-length vectors
(vector-length vec)
vector-fold)
(cons vec vectors)))))
;;; (VECTOR-FOLD-RIGHT <kons> <initial-knil> <vector> ...) -> knil
;;; (KONS <knil> <elt> ...) -> knil' ; N vectors => N+1 args
;;; The fundamental vector recursor. Iterates in parallel across
;;; VECTOR ... right to left, applying KONS to the elements and the
;;; current state value; the state value becomes what KONS returns
;;; at each next iteration. KNIL is the initial state value.
;;; (vector-fold-right KONS KNIL (vector E_1 E_2 ... E_N))
;;; <=>
;;; (KONS (... (KONS (KONS KNIL E_N) E_N-1) ... E_2) E_1)
;;;
;;; Not implemented in terms of a more primitive operations that might
;;; called %VECTOR-FOLD-RIGHT due to the fact that it wouldn't be very
;;; useful elsewhere.
(define vector-fold-right
(letrec ((loop1 (lambda (kons knil vec i)
(if (negative? i)
knil
(loop1 kons (kons i knil (vector-ref vec i))
vec
(- i 1)))))
(loop2+ (lambda (kons knil vectors i)
(if (negative? i)
knil
(loop2+ kons
(apply kons i knil
(vectors-ref vectors i))
vectors
(- i 1))))))
(lambda (kons knil vec . vectors)
(let ((kons (check-type procedure? kons vector-fold-right))
(vec (check-type vector? vec vector-fold-right)))
(if (null? vectors)
(loop1 kons knil vec (- (vector-length vec) 1))
(loop2+ kons knil (cons vec vectors)
(- (%smallest-length vectors
(vector-length vec)
vector-fold-right)
1)))))))
;;; (VECTOR-MAP <f> <vector> ...) -> vector
;;; (F <elt> ...) -> value ; N vectors -> N args
;;; Constructs a new vector of the shortest length of the vector
;;; arguments. Each element at index I of the new vector is mapped
;;; from the old vectors by (F I (vector-ref VECTOR I) ...). The
;;; dynamic order of application of F is unspecified.
(define (vector-map f vec . vectors)
(let ((f (check-type procedure? f vector-map))
(vec (check-type vector? vec vector-map)))
(if (null? vectors)
(let ((len (vector-length vec)))
(%vector-map1! f (make-vector len) vec len))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-map)))
(%vector-map2+! f (make-vector len) (cons vec vectors)
len)))))
;;; (VECTOR-MAP! <f> <vector> ...) -> unspecified
;;; (F <elt> ...) -> element' ; N vectors -> N args
;;; Similar to VECTOR-MAP, but rather than mapping the new elements
;;; into a new vector, the new mapped elements are destructively
;;; inserted into the first vector. Again, the dynamic order of
;;; application of F is unspecified, so it is dangerous for F to
;;; manipulate the first VECTOR.
(define (vector-map! f vec . vectors)
(let ((f (check-type procedure? f vector-map!))
(vec (check-type vector? vec vector-map!)))
(if (null? vectors)
(%vector-map1! f vec vec (vector-length vec))
(%vector-map2+! f vec (cons vec vectors)
(%smallest-length vectors
(vector-length vec)
vector-map!)))
(unspecified-value)))
;;; (VECTOR-FOR-EACH <f> <vector> ...) -> unspecified
;;; (F <elt> ...) ; N vectors -> N args
;;; Simple vector iterator: applies F to each index in the range [0,
;;; LENGTH), where LENGTH is the length of the smallest vector
;;; argument passed, and the respective element at that index. In
;;; contrast with VECTOR-MAP, F is reliably applied to each
;;; subsequent elements, starting at index 0 from left to right, in
;;; the vectors.
(define vector-for-each
(letrec ((for-each1
(lambda (f vec i len)
(cond ((< i len)
(f i (vector-ref vec i))
(for-each1 f vec (+ i 1) len)))))
(for-each2+
(lambda (f vecs i len)
(cond ((< i len)
(apply f i (vectors-ref vecs i))
(for-each2+ f vecs (+ i 1) len))))))
(lambda (f vec . vectors)
(let ((f (check-type procedure? f vector-for-each))
(vec (check-type vector? vec vector-for-each)))
(if (null? vectors)
(for-each1 f vec 0 (vector-length vec))
(for-each2+ f (cons vec vectors) 0
(%smallest-length vectors
(vector-length vec)
vector-for-each)))))))
;;; (VECTOR-COUNT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer
;;; (PREDICATE? <index> <value> ...) ; N vectors -> N+1 args
;;; PREDICATE? is applied element-wise to the elements of VECTOR ...,
;;; and a count is tallied of the number of elements for which a
;;; true value is produced by PREDICATE?. This count is returned.
(define (vector-count pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-count))
(vec (check-type vector? vec vector-count)))
(if (null? vectors)
(%vector-fold1 (lambda (index count elt)
(if (pred? index elt)
(+ count 1)
count))
0
(vector-length vec)
vec)
(%vector-fold2+ (lambda (index count . elts)
(if (apply pred? index elts)
(+ count 1)
count))
0
(%smallest-length vectors
(vector-length vec)
vector-count)
(cons vec vectors)))))
;;; --------------------
;;; Searching
;;; (VECTOR-INDEX <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Search left-to-right across VECTOR ... in parallel, returning the
;;; index of the first set of values VALUE ... such that (PREDICATE?
;;; VALUE ...) returns a true value; if no such set of elements is
;;; reached, return #F.
(define (vector-index pred? vec . vectors)
(vector-index/skip pred? vec vectors vector-index))
;;; (VECTOR-SKIP <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; (vector-index (lambda elts (not (apply PREDICATE? elts)))
;;; VECTOR ...)
;;; Like VECTOR-INDEX, but find the index of the first set of values
;;; that do _not_ satisfy PREDICATE?.
(define (vector-skip pred? vec . vectors)
(vector-index/skip (lambda elts (not (apply pred? elts)))
vec vectors
vector-skip))
;;; Auxiliary for VECTOR-INDEX & VECTOR-SKIP
(define vector-index/skip
(letrec ((loop1 (lambda (pred? vec len i)
(cond ((= i len) #f)
((pred? (vector-ref vec i)) i)
(else (loop1 pred? vec len (+ i 1))))))
(loop2+ (lambda (pred? vectors len i)
(cond ((= i len) #f)
((apply pred? (vectors-ref vectors i)) i)
(else (loop2+ pred? vectors len
(+ i 1)))))))
(lambda (pred? vec vectors callee)
(let ((pred? (check-type procedure? pred? callee))
(vec (check-type vector? vec callee)))
(if (null? vectors)
(loop1 pred? vec (vector-length vec) 0)
(loop2+ pred? (cons vec vectors)
(%smallest-length vectors
(vector-length vec)
callee)
0))))))
;;; (VECTOR-INDEX-RIGHT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Right-to-left variant of VECTOR-INDEX.
(define (vector-index-right pred? vec . vectors)
(vector-index/skip-right pred? vec vectors vector-index-right))
;;; (VECTOR-SKIP-RIGHT <predicate?> <vector> ...)
;;; -> exact, nonnegative integer or #F
;;; (PREDICATE? <elt> ...) -> boolean ; N vectors -> N args
;;; Right-to-left variant of VECTOR-SKIP.
(define (vector-skip-right pred? vec . vectors)
(vector-index/skip-right (lambda elts (not (apply pred? elts)))
vec vectors
vector-index-right))
(define vector-index/skip-right
(letrec ((loop1 (lambda (pred? vec i)
(cond ((negative? i) #f)
((pred? (vector-ref vec i)) i)
(else (loop1 pred? vec (- i 1))))))
(loop2+ (lambda (pred? vectors i)
(cond ((negative? i) #f)
((apply pred? (vectors-ref vectors i)) i)
(else (loop2+ pred? vectors (- i 1)))))))
(lambda (pred? vec vectors callee)
(let ((pred? (check-type procedure? pred? callee))
(vec (check-type vector? vec callee)))
(if (null? vectors)
(loop1 pred? vec (- (vector-length vec) 1))
(loop2+ pred? (cons vec vectors)
(- (%smallest-length vectors
(vector-length vec)
callee)
1)))))))
;;; (VECTOR-BINARY-SEARCH <vector> <value> <cmp> [<start> <end>])
;;; -> exact, nonnegative integer or #F
;;; (CMP <value1> <value2>) -> integer
;;; positive -> VALUE1 > VALUE2
;;; zero -> VALUE1 = VALUE2
;;; negative -> VALUE1 < VALUE2
;;; Perform a binary search through VECTOR for VALUE, comparing each
;;; element to VALUE with CMP.
(define (vector-binary-search vec value cmp . maybe-start+end)
(let ((cmp (check-type procedure? cmp vector-binary-search)))
(let-vector-start+end vector-binary-search vec maybe-start+end
(start end)
(let loop ((start start) (end end) (j #f))
(let ((i (quotient (+ start end) 2)))
(if (or (= start end) (and j (= i j)))
#f
(let ((comparison
(check-type integer?
(cmp (vector-ref vec i) value)
`(,cmp for ,vector-binary-search))))
(cond ((zero? comparison) i)
((positive? comparison) (loop start i i))
(else (loop i end i))))))))))
;;; (VECTOR-ANY <pred?> <vector> ...) -> value
;;; Apply PRED? to each parallel element in each VECTOR ...; if PRED?
;;; should ever return a true value, immediately stop and return that
;;; value; otherwise, when the shortest vector runs out, return #F.
;;; The iteration and order of application of PRED? across elements
;;; is of the vectors is strictly left-to-right.
(define vector-any
(letrec ((loop1 (lambda (pred? vec i len len-1)
(and (not (= i len))
(if (= i len-1)
(pred? (vector-ref vec i))
(or (pred? (vector-ref vec i))
(loop1 pred? vec (+ i 1)
len len-1))))))
(loop2+ (lambda (pred? vectors i len len-1)
(and (not (= i len))
(if (= i len-1)
(apply pred? (vectors-ref vectors i))
(or (apply pred? (vectors-ref vectors i))
(loop2+ pred? vectors (+ i 1)
len len-1)))))))
(lambda (pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-any))
(vec (check-type vector? vec vector-any)))
(if (null? vectors)
(let ((len (vector-length vec)))
(loop1 pred? vec 0 len (- len 1)))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-any)))
(loop2+ pred? (cons vec vectors) 0 len (- len 1))))))))
;;; (VECTOR-EVERY <pred?> <vector> ...) -> value
;;; Apply PRED? to each parallel value in each VECTOR ...; if PRED?
;;; should ever return #F, immediately stop and return #F; otherwise,
;;; if PRED? should return a true value for each element, stopping at
;;; the end of the shortest vector, return the last value that PRED?
;;; returned. In the case that there is an empty vector, return #T.
;;; The iteration and order of application of PRED? across elements
;;; is of the vectors is strictly left-to-right.
(define vector-every
(letrec ((loop1 (lambda (pred? vec i len len-1)
(or (= i len)
(if (= i len-1)
(pred? (vector-ref vec i))
(and (pred? (vector-ref vec i))
(loop1 pred? vec (+ i 1)
len len-1))))))
(loop2+ (lambda (pred? vectors i len len-1)
(or (= i len)
(if (= i len-1)
(apply pred? (vectors-ref vectors i))
(and (apply pred? (vectors-ref vectors i))
(loop2+ pred? vectors (+ i 1)
len len-1)))))))
(lambda (pred? vec . vectors)
(let ((pred? (check-type procedure? pred? vector-every))
(vec (check-type vector? vec vector-every)))
(if (null? vectors)
(let ((len (vector-length vec)))
(loop1 pred? vec 0 len (- len 1)))
(let ((len (%smallest-length vectors
(vector-length vec)
vector-every)))
(loop2+ pred? (cons vec vectors) 0 len (- len 1))))))))
;;; --------------------
;;; Mutators
;;; (VECTOR-SET! <vector> <index> <value>) -> unspecified
;;; [R5RS] Assign the location at INDEX in VECTOR to VALUE.
(define vector-set! vector-set!)
;;; (VECTOR-SWAP! <vector> <index1> <index2>) -> unspecified
;;; Swap the values in the locations at INDEX1 and INDEX2.
(define (vector-swap! vec i j)
(let ((vec (check-type vector? vec vector-swap!)))
(let ((i (check-index vec i vector-swap!))
(j (check-index vec j vector-swap!)))
(let ((x (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j x)))))
;;; (VECTOR-FILL! <vector> <value> [<start> <end>]) -> unspecified
;;; [R5RS+] Fill the locations in VECTOR between START, whose default
;;; is 0, and END, whose default is the length of VECTOR, with VALUE.
;;;
;;; This one can probably be made really fast natively.
(define vector-fill!
(let ((%vector-fill! vector-fill!)) ; Take the native one, under
; the assumption that it's
; faster, so we can use it if
; there are no optional
; arguments.
(lambda (vec value . maybe-start+end)
(if (null? maybe-start+end)
(%vector-fill! vec value) ;+++
(let-vector-start+end vector-fill! vec maybe-start+end
(start end)
(do ((i start (+ i 1)))
((= i end))
(vector-set! vec i value)))))))
;;; (VECTOR-COPY! <target> <tstart> <source> [<sstart> <send>])
;;; -> unspecified
;;; Copy the values in the locations in [SSTART,SEND) from SOURCE to
;;; to TARGET, starting at TSTART in TARGET.
;;; [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source).
(define (vector-copy! target tstart source . maybe-sstart+send)
(define (doit! sstart send source-length)
(let ((tstart (check-type nonneg-int? tstart vector-copy!))
(sstart (check-type nonneg-int? sstart vector-copy!))
(send (check-type nonneg-int? send vector-copy!)))
(cond ((and (<= 0 sstart send source-length)
(<= (+ tstart (- send sstart)) (vector-length target)))
(%vector-copy! target tstart source sstart send))
(else
(error "illegal arguments"
`(while calling ,vector-copy!)
`(target was ,target)
`(target-length was ,(vector-length target))
`(tstart was ,tstart)
`(source was ,source)
`(source-length was ,source-length)
`(sstart was ,sstart)
`(send was ,send))))))
(let ((n (vector-length source)))
(cond ((null? maybe-sstart+send)
(doit! 0 n n))
((null? (cdr maybe-sstart+send))
(doit! (car maybe-sstart+send) n n))
((null? (cddr maybe-sstart+send))
(doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n))
(else
(error "too many arguments"
vector-copy!
(cddr maybe-sstart+send))))))
;;; (VECTOR-REVERSE-COPY! <target> <tstart> <source> [<sstart> <send>])
;;; [wdc] Corrected to allow 0 <= sstart <= send <= (vector-length source).
(define (vector-reverse-copy! target tstart source . maybe-sstart+send)
(define (doit! sstart send source-length)
(let ((tstart (check-type nonneg-int? tstart vector-reverse-copy!))
(sstart (check-type nonneg-int? sstart vector-reverse-copy!))
(send (check-type nonneg-int? send vector-reverse-copy!)))
(cond ((and (eq? target source)
(or (between? sstart tstart send)
(between? tstart sstart
(+ tstart (- send sstart)))))
(error "vector range for self-copying overlaps"
vector-reverse-copy!
`(vector was ,target)
`(tstart was ,tstart)
`(sstart was ,sstart)
`(send was ,send)))
((and (<= 0 sstart send source-length)
(<= (+ tstart (- send sstart)) (vector-length target)))
(%vector-reverse-copy! target tstart source sstart send))
(else
(error "illegal arguments"
`(while calling ,vector-reverse-copy!)
`(target was ,target)
`(target-length was ,(vector-length target))
`(tstart was ,tstart)
`(source was ,source)
`(source-length was ,source-length)
`(sstart was ,sstart)
`(send was ,send))))))
(let ((n (vector-length source)))
(cond ((null? maybe-sstart+send)
(doit! 0 n n))
((null? (cdr maybe-sstart+send))
(doit! (car maybe-sstart+send) n n))
((null? (cddr maybe-sstart+send))
(doit! (car maybe-sstart+send) (cadr maybe-sstart+send) n))
(else
(error "too many arguments"
vector-reverse-copy!
(cddr maybe-sstart+send))))))
;;; (VECTOR-REVERSE! <vector> [<start> <end>]) -> unspecified
;;; Destructively reverse the contents of the sequence of locations
;;; in VECTOR between START, whose default is 0, and END, whose
;;; default is the length of VECTOR.
(define (vector-reverse! vec . start+end)
(let-vector-start+end vector-reverse! vec start+end
(start end)
(%vector-reverse! vec start end)))
;;; --------------------
;;; Conversion
;;; (VECTOR->LIST <vector> [<start> <end>]) -> list
;;; [R5RS+] Produce a list containing the elements in the locations
;;; between START, whose default is 0, and END, whose default is the
;;; length of VECTOR, from VECTOR.
(define vector->list
(let ((%vector->list vector->list))
(lambda (vec . maybe-start+end)
(if (null? maybe-start+end) ; Oughta use CASE-LAMBDA.
(%vector->list vec) ;+++
(let-vector-start+end vector->list vec maybe-start+end
(start end)
;(unfold (lambda (i) ; No SRFI 1.
; (< i start))
; (lambda (i) (vector-ref vec i))
; (lambda (i) (- i 1))
; (- end 1))
(do ((i (- end 1) (- i 1))
(result '() (cons (vector-ref vec i) result)))
((< i start) result)))))))
;;; (REVERSE-VECTOR->LIST <vector> [<start> <end>]) -> list
;;; Produce a list containing the elements in the locations between
;;; START, whose default is 0, and END, whose default is the length
;;; of VECTOR, from VECTOR, in reverse order.
(define (reverse-vector->list vec . maybe-start+end)
(let-vector-start+end reverse-vector->list vec maybe-start+end
(start end)
;(unfold (lambda (i) (= i end)) ; No SRFI 1.
; (lambda (i) (vector-ref vec i))
; (lambda (i) (+ i 1))
; start)
(do ((i start (+ i 1))
(result '() (cons (vector-ref vec i) result)))
((= i end) result))))
;;; (LIST->VECTOR <list> [<start> <end>]) -> vector
;;; [R5RS+] Produce a vector containing the elements in LIST, which
;;; must be a proper list, between START, whose default is 0, & END,
;;; whose default is the length of LIST. It is suggested that if the
;;; length of LIST is known in advance, the START and END arguments
;;; be passed, so that LIST->VECTOR need not call LENGTH to determine
;;; the the length.
;;;
;;; This implementation diverges on circular lists, unless LENGTH fails
;;; and causes - to fail as well. Given a LENGTH* that computes the
;;; length of a list's cycle, this wouldn't diverge, and would work
;;; great for circular lists.
(define list->vector
(let ((%list->vector list->vector))
(lambda (lst . maybe-start+end)
;; Checking the type of a proper list is expensive, so we do it
;; amortizedly, or let %LIST->VECTOR or LIST-TAIL do it.
(if (null? maybe-start+end) ; Oughta use CASE-LAMBDA.
(%list->vector lst) ;+++
;; We can't use LET-VECTOR-START+END, because we're using the
;; bounds of a _list_, not a vector.
(let*-optionals maybe-start+end
((start 0)
(end (length lst))) ; Ugh -- LENGTH
(let ((start (check-type nonneg-int? start list->vector))
(end (check-type nonneg-int? end list->vector)))
((lambda (f)
(vector-unfold f (- end start) (list-tail lst start)))
(lambda (index l)
(cond ((null? l)
(error "list was too short"
`(list was ,lst)
`(attempted end was ,end)
`(while calling ,list->vector)))
((pair? l)
(values (car l) (cdr l)))
(else
;; Make this look as much like what CHECK-TYPE
;; would report as possible.
(error "erroneous value"
;; We want SRFI 1's PROPER-LIST?, but it
;; would be a waste to link all of SRFI
;; 1 to this module for only the single
;; function PROPER-LIST?.
(list list? lst)
`(while calling
,list->vector))))))))))))
;;; (REVERSE-LIST->VECTOR <list> [<start> <end>]) -> vector
;;; Produce a vector containing the elements in LIST, which must be a
;;; proper list, between START, whose default is 0, and END, whose
;;; default is the length of LIST, in reverse order. It is suggested
;;; that if the length of LIST is known in advance, the START and END
;;; arguments be passed, so that REVERSE-LIST->VECTOR need not call
;;; LENGTH to determine the the length.
;;;
;;; This also diverges on circular lists unless, again, LENGTH returns
;;; something that makes - bork.
(define (reverse-list->vector lst . maybe-start+end)
(let*-optionals maybe-start+end
((start 0)
(end (length lst))) ; Ugh -- LENGTH
(let ((start (check-type nonneg-int? start reverse-list->vector))
(end (check-type nonneg-int? end reverse-list->vector)))
((lambda (f)
(vector-unfold-right f (- end start) (list-tail lst start)))
(lambda (index l)
(cond ((null? l)
(error "list too short"
`(list was ,lst)
`(attempted end was ,end)
`(while calling ,reverse-list->vector)))
((pair? l)
(values (car l) (cdr l)))
(else
(error "erroneous value"
(list list? lst)
`(while calling ,reverse-list->vector)))))))))
;;; SPDX-FileCopyrightText: 2014 Taylan Kammer <taylan.kammer@gmail.com>
;;;
;;; SPDX-License-Identifier: MIT
(define-library (srfi 48)
(export format)
(import (rename (scheme base)
(exact inexact->exact)
(inexact exact->inexact))
(scheme char)
(scheme complex)
(rename (scheme write)
(write-shared write-with-shared-structure)))
(include "48.upstream.scm"))
;;; "sort.scm" Defines: sorted?, merge, merge!, sort, sort!
;;; Author : Richard A. O'Keefe (based on Prolog code by D.H.D.Warren)
;;; Copyright (C) Aubrey Jaffer 2006. All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
;;; Updated: 11 June 1991
;;; Modified for scheme library: Aubrey Jaffer 19 Sept. 1991
;;; Updated: 19 June 1995
;;; (sort, sort!, sorted?): Generalized to strings by jaffer: 2003-09-09
;;; (sort, sort!, sorted?): Generalized to arrays by jaffer: 2003-10-04
;;; jaffer: 2006-10-08:
;;; (sort, sort!, sorted?, merge, merge!): Added optional KEY argument.
;;; jaffer: 2006-11-05:
;;; (sorted?, merge, merge!, sort, sort!): Call KEY arg at most once
;;; per element.
(require 'array)
;;; (sorted? sequence less?)
;;; is true when sequence is a list (x0 x1 ... xm) or a vector #(x0 ... xm)
;;; such that for all 1 <= i <= m,
;;; (not (less? (list-ref list i) (list-ref list (- i 1)))).
;@
(define (sorted? seq less? . opt-key)
(define key (if (null? opt-key) identity (car opt-key)))
(cond ((null? seq) #t)
((array? seq)
(let ((dimax (+ -1 (car (array-dimensions seq)))))
(or (<= dimax 1)
(let loop ((idx (+ -1 dimax))
(last (key (array-ref seq dimax))))
(or (negative? idx)
(let ((nxt (key (array-ref seq idx))))
(and (less? nxt last)
(loop (+ -1 idx) nxt))))))))
((null? (cdr seq)) #t)
(else
(let loop ((last (key (car seq)))
(next (cdr seq)))
(or (null? next)
(let ((nxt (key (car next))))
(and (not (less? nxt last))
(loop nxt (cdr next)))))))))
;;; (merge a b less?)
;;; takes two lists a and b such that (sorted? a less?) and (sorted? b less?)
;;; and returns a new list in which the elements of a and b have been stably
;;; interleaved so that (sorted? (merge a b less?) less?).
;;; Note: this does _not_ accept arrays. See below.
;@
(define (merge a b less? . opt-key)
(define key (if (null? opt-key) identity (car opt-key)))
(cond ((null? a) b)
((null? b) a)
(else
(let loop ((x (car a)) (kx (key (car a))) (a (cdr a))
(y (car b)) (ky (key (car b))) (b (cdr b)))
;; The loop handles the merging of non-empty lists. It has
;; been written this way to save testing and car/cdring.
(if (less? ky kx)
(if (null? b)
(cons y (cons x a))
(cons y (loop x kx a (car b) (key (car b)) (cdr b))))
;; x <= y
(if (null? a)
(cons x (cons y b))
(cons x (loop (car a) (key (car a)) (cdr a) y ky b))))))))
(define (sort:merge! a b less? key)
(define (loop r a kcara b kcarb)
(cond ((less? kcarb kcara)
(set-cdr! r b)
(if (null? (cdr b))
(set-cdr! b a)
(loop b a kcara (cdr b) (key (cadr b)))))
(else ; (car a) <= (car b)
(set-cdr! r a)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) (key (cadr a)) b kcarb)))))
(cond ((null? a) b)
((null? b) a)
(else
(let ((kcara (key (car a)))
(kcarb (key (car b))))
(cond
((less? kcarb kcara)
(if (null? (cdr b))
(set-cdr! b a)
(loop b a kcara (cdr b) (key (cadr b))))
b)
(else ; (car a) <= (car b)
(if (null? (cdr a))
(set-cdr! a b)
(loop a (cdr a) (key (cadr a)) b kcarb))
a))))))
;;; takes two sorted lists a and b and smashes their cdr fields to form a
;;; single sorted list including the elements of both.
;;; Note: this does _not_ accept arrays.
;@
(define (merge! a b less? . opt-key)
(sort:merge! a b less? (if (null? opt-key) identity (car opt-key))))
(define (sort:sort-list! seq less? key)
(define keyer (if key car identity))
(define (step n)
(cond ((> n 2) (let* ((j (quotient n 2))
(a (step j))
(k (- n j))
(b (step k)))
(sort:merge! a b less? keyer)))
((= n 2) (let ((x (car seq))
(y (cadr seq))
(p seq))
(set! seq (cddr seq))
(cond ((less? (keyer y) (keyer x))
(set-car! p y)
(set-car! (cdr p) x)))
(set-cdr! (cdr p) '())
p))
((= n 1) (let ((p seq))
(set! seq (cdr seq))
(set-cdr! p '())
p))
(else '())))
(define (key-wrap! lst)
(cond ((null? lst))
(else (set-car! lst (cons (key (car lst)) (car lst)))
(key-wrap! (cdr lst)))))
(define (key-unwrap! lst)
(cond ((null? lst))
(else (set-car! lst (cdar lst))
(key-unwrap! (cdr lst)))))
(cond (key
(key-wrap! seq)
(set! seq (step (length seq)))
(key-unwrap! seq)
seq)
(else
(step (length seq)))))
(define (rank-1-array->list array)
(define dimensions (array-dimensions array))
(do ((idx (+ -1 (car dimensions)) (+ -1 idx))
(lst '() (cons (array-ref array idx) lst)))
((< idx 0) lst)))
;;; (sort! sequence less?)
;;; sorts the list, array, or string sequence destructively. It uses
;;; a version of merge-sort invented, to the best of my knowledge, by
;;; David H. D. Warren, and first used in the DEC-10 Prolog system.
;;; R. A. O'Keefe adapted it to work destructively in Scheme.
;;; A. Jaffer modified to always return the original list.
;@
(define (sort! seq less? . opt-key)
(define key (if (null? opt-key) #f (car opt-key)))
(cond ((array? seq)
(let ((dims (array-dimensions seq)))
(do ((sorted (sort:sort-list! (rank-1-array->list seq) less? key)
(cdr sorted))
(i 0 (+ i 1)))
((null? sorted) seq)
(array-set! seq (car sorted) i))))
(else ; otherwise, assume it is a list
(let ((ret (sort:sort-list! seq less? key)))
(if (not (eq? ret seq))
(do ((crt ret (cdr crt)))
((eq? (cdr crt) seq)
(set-cdr! crt ret)
(let ((scar (car seq)) (scdr (cdr seq)))
(set-car! seq (car ret)) (set-cdr! seq (cdr ret))
(set-car! ret scar) (set-cdr! ret scdr)))))
seq))))
;;; (sort sequence less?)
;;; sorts a array, string, or list non-destructively. It does this
;;; by sorting a copy of the sequence. My understanding is that the
;;; Standard says that the result of append is always "newly
;;; allocated" except for sharing structure with "the last argument",
;;; so (append x '()) ought to be a standard way of copying a list x.
;@
(define (sort seq less? . opt-key)
(define key (if (null? opt-key) #f (car opt-key)))
(cond ((array? seq)
(let ((dims (array-dimensions seq)))
(define newra (apply make-array seq dims))
(do ((sorted (sort:sort-list! (rank-1-array->list seq) less? key)
(cdr sorted))
(i 0 (+ i 1)))
((null? sorted) newra)
(array-set! newra (car sorted) i))))
(else (sort:sort-list! (append seq '()) less? key))))
;;; SPDX-FileCopyrightText: 2003 Kenneth A Dickey <ken.dickey@allvantage.com>
;;; SPDX-FileCopyrightText: 2017 Hamayama <hamay1010@gmail.com>
;;;
;;; SPDX-License-Identifier: MIT
;; IMPLEMENTATION DEPENDENT options
(define ascii-tab (integer->char 9)) ;; NB: assumes ASCII encoding
(define dont-print (if (eq? #t #f) 1))
;;(define DONT-PRINT (string->symbol ""))
;;(define DONT-PRINT (void))
;;(define DONT-PRINT #!void)
(define pretty-print write) ; ugly but permitted
;; (require 'srfi-38) ;; write-with-shared-structure
;; Following three procedures are used by format ~F .
;; 'inexact-number->string' determines whether output is fixed-point
;; notation or exponential notation. In the current definition,
;; the notation depends on the implementation of 'number->string'.
;; 'exact-number->string' is expected to output only numeric characters
;; (not including such as '#', 'e', '.', '/') if the input is an positive
;; integer or zero.
;; 'real-number->string' is used when the digits of ~F is not specified.
(define (inexact-number->string x) (number->string (exact->inexact x)))
(define (exact-number->string x) (number->string (inexact->exact x)))
(define (real-number->string x) (number->string x))
;; FORMAT
(define (format . args)
(cond
((null? args)
(error "FORMAT: required format-string argument is missing")
)
((string? (car args))
(apply format (cons #f args)))
((< (length args) 2)
(error (format #f "FORMAT: too few arguments ~s" (cons 'format args)))
)
(else
(let ( (output-port (car args))
(format-string (cadr args))
(args (cddr args))
)
(letrec ( (port
(cond ((output-port? output-port) output-port)
((eq? output-port #t) (current-output-port))
((eq? output-port #f) (open-output-string))
(else (error
(format #f "FORMAT: bad output-port argument: ~s"
output-port)))
) )
(return-value
(if (eq? output-port #f) ;; if format into a string
(lambda () (get-output-string port)) ;; then return the string
(lambda () dont-print)) ;; else do something harmless
)
)
(define (string-index str c)
(let ( (len (string-length str)) )
(let loop ( (i 0) )
(cond ((= i len) #f)
((eqv? c (string-ref str i)) i)
(else (loop (+ i 1)))))))
(define (string-grow str len char)
(let ( (off (- len (string-length str))) )
(if (positive? off)
(string-append (make-string off char) str)
str)))
(define (compose-with-digits digits pre-str frac-str exp-str)
(let ( (frac-len (string-length frac-str)) )
(cond
((< frac-len digits) ;; grow frac part, pad with zeros
(string-append pre-str "."
frac-str (make-string (- digits frac-len) #\0)
exp-str)
)
((= frac-len digits) ;; frac-part is exactly the right size
(string-append pre-str "."
frac-str
exp-str)
)
(else ;; must round to shrink it
(let* ( (minus-flag (and (> (string-length pre-str) 0)
(char=? (string-ref pre-str 0) #\-)))
(pre-str* (if minus-flag
(substring pre-str 1 (string-length pre-str))
pre-str))
(first-part (substring frac-str 0 digits))
(last-part (substring frac-str digits frac-len))
(temp-str
(string-grow
(exact-number->string
(round (string->number
(string-append pre-str* first-part "." last-part))))
digits
#\0))
(temp-len (string-length temp-str))
(new-pre (substring temp-str 0 (- temp-len digits)))
(new-frac (substring temp-str (- temp-len digits) temp-len))
)
(string-append
(if minus-flag "-" "")
(if (string=? new-pre "")
;; check if the system displays integer part of numbers
;; whose absolute value is 0 < x < 1.
(if (and (string=? pre-str* "")
(> digits 0)
(not (= (string->number new-frac) 0)))
"" "0")
new-pre)
"."
new-frac
exp-str)))
) ) )
(define (format-fixed number-or-string width digits) ; returns a string
(cond
((string? number-or-string)
(string-grow number-or-string width #\space)
)
((number? number-or-string)
(let ( (real (real-part number-or-string))
(imag (imag-part number-or-string))
)
(cond
((not (zero? imag))
(string-grow
(string-append (format-fixed real 0 digits)
(if (negative? imag) "" "+")
(format-fixed imag 0 digits)
"i")
width
#\space)
)
(digits
(let* ( (num-str (inexact-number->string real))
(dot-index (string-index num-str #\.))
(exp-index (string-index num-str #\e))
(length (string-length num-str))
(pre-string
(if dot-index
(substring num-str 0 dot-index)
(if exp-index
(substring num-str 0 exp-index)
num-str))
)
(exp-string
(if exp-index
(substring num-str exp-index length)
"")
)
(frac-string
(if dot-index
(if exp-index
(substring num-str (+ dot-index 1) exp-index)
(substring num-str (+ dot-index 1) length))
"")
)
)
;; check +inf.0, -inf.0, +nan.0, -nan.0
(if (string-index num-str #\n)
(string-grow num-str width #\space)
(string-grow
(compose-with-digits digits
pre-string
frac-string
exp-string)
width
#\space))
))
(else ;; no digits
(string-grow (real-number->string real) width #\space)))
))
(else
(error
(format "FORMAT: ~F requires a number or a string, got ~s" number-or-string)))
))
(define documentation-string
"(format [<port>] <format-string> [<arg>...]) -- <port> is #t, #f or an output-port
OPTION [MNEMONIC] DESCRIPTION -- Implementation Assumes ASCII Text Encoding
~H [Help] output this text
~A [Any] (display arg) for humans
~S [Slashified] (write arg) for parsers
~W [WriteCircular] like ~s but outputs circular and recursive data structures
~~ [tilde] output a tilde
~T [Tab] output a tab character
~% [Newline] output a newline character
~& [Freshline] output a newline character if the previous output was not a newline
~D [Decimal] the arg is a number which is output in decimal radix
~X [heXadecimal] the arg is a number which is output in hexdecimal radix
~O [Octal] the arg is a number which is output in octal radix
~B [Binary] the arg is a number which is output in binary radix
~w,dF [Fixed] the arg is a string or number which has width w and d digits after the decimal
~C [Character] charater arg is output by write-char
~_ [Space] a single space character is output
~Y [Yuppify] the list arg is pretty-printed to the output
~? [Indirection] recursive format: next 2 args are format-string and list of arguments
~K [Indirection] same as ~?
"
)
(define (require-an-arg args)
(if (null? args)
(error "FORMAT: too few arguments" ))
)
(define (format-help format-strg arglist)
(letrec (
(length-of-format-string (string-length format-strg))
(anychar-dispatch
(lambda (pos arglist last-was-newline)
(if (>= pos length-of-format-string)
arglist ; return unused args
(let ( (char (string-ref format-strg pos)) )
(cond
((eqv? char #\~)
(tilde-dispatch (+ pos 1) arglist last-was-newline))
(else
(write-char char port)
(anychar-dispatch (+ pos 1) arglist #f)
))
))
)) ; end anychar-dispatch
(has-newline?
(lambda (whatever last-was-newline)
(or (eqv? whatever #\newline)
(and (string? whatever)
(let ( (len (string-length whatever)) )
(if (zero? len)
last-was-newline
(eqv? #\newline (string-ref whatever (- len 1)))))))
)) ; end has-newline?
(tilde-dispatch
(lambda (pos arglist last-was-newline)
(cond
((>= pos length-of-format-string)
(write-char #\~ port) ; tilde at end of string is just output
arglist ; return unused args
)
(else
(case (char-upcase (string-ref format-strg pos))
((#\A) ; Any -- for humans
(require-an-arg arglist)
(let ( (whatever (car arglist)) )
(display whatever port)
(anychar-dispatch (+ pos 1)
(cdr arglist)
(has-newline? whatever last-was-newline))
))
((#\S) ; Slashified -- for parsers
(require-an-arg arglist)
(let ( (whatever (car arglist)) )
(write whatever port)
(anychar-dispatch (+ pos 1)
(cdr arglist)
(has-newline? whatever last-was-newline))
))
((#\W)
(require-an-arg arglist)
(let ( (whatever (car arglist)) )
(write-with-shared-structure whatever port) ;; srfi-38
(anychar-dispatch (+ pos 1)
(cdr arglist)
(has-newline? whatever last-was-newline))
))
((#\D) ; Decimal
(require-an-arg arglist)
(display (number->string (car arglist) 10) port)
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\X) ; HeXadecimal
(require-an-arg arglist)
(display (number->string (car arglist) 16) port)
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\O) ; Octal
(require-an-arg arglist)
(display (number->string (car arglist) 8) port)
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\B) ; Binary
(require-an-arg arglist)
(display (number->string (car arglist) 2) port)
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\C) ; Character
(require-an-arg arglist)
(write-char (car arglist) port)
(anychar-dispatch (+ pos 1) (cdr arglist) (eqv? (car arglist) #\newline))
)
((#\~) ; Tilde
(write-char #\~ port)
(anychar-dispatch (+ pos 1) arglist #f)
)
((#\%) ; Newline
(newline port)
(anychar-dispatch (+ pos 1) arglist #t)
)
((#\&) ; Freshline
(if (not last-was-newline) ;; (unless last-was-newline ..
(newline port))
(anychar-dispatch (+ pos 1) arglist #t)
)
((#\_) ; Space
(write-char #\space port)
(anychar-dispatch (+ pos 1) arglist #f)
)
((#\T) ; Tab -- IMPLEMENTATION DEPENDENT ENCODING
(write-char ascii-tab port)
(anychar-dispatch (+ pos 1) arglist #f)
)
((#\Y) ; Pretty-print
(pretty-print (car arglist) port) ;; IMPLEMENTATION DEPENDENT
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\F)
(require-an-arg arglist)
(display (format-fixed (car arglist) 0 #f) port)
(anychar-dispatch (+ pos 1) (cdr arglist) #f)
)
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) ;; gather "~w[,d]F" w and d digits
(let loop ( (index (+ pos 1))
(w-digits (list (string-ref format-strg pos)))
(d-digits '())
(in-width? #t)
)
(if (>= index length-of-format-string)
(error
(format "FORMAT: improper numeric format directive in ~s" format-strg))
(let ( (next-char (string-ref format-strg index)) )
(cond
((char-numeric? next-char)
(if in-width?
(loop (+ index 1)
(cons next-char w-digits)
d-digits
in-width?)
(loop (+ index 1)
w-digits
(cons next-char d-digits)
in-width?))
)
((char=? (char-upcase next-char) #\F)
(let ( (width (string->number (list->string (reverse w-digits))))
(digits (if (zero? (length d-digits))
#f
(string->number (list->string (reverse d-digits)))))
)
(display (format-fixed (car arglist) width digits) port)
(anychar-dispatch (+ index 1) (cdr arglist) #f))
)
((char=? next-char #\,)
(if in-width?
(loop (+ index 1)
w-digits
d-digits
#f)
(error
(format "FORMAT: too many commas in directive ~s" format-strg)))
)
(else
(error (format "FORMAT: ~~w.dF directive ill-formed in ~s" format-strg))))))
))
((#\? #\K) ; indirection -- take next arg as format string
(cond ; and following arg as list of format args
((< (length arglist) 2)
(error
(format "FORMAT: less arguments than specified for ~~?: ~s" arglist))
)
((not (string? (car arglist)))
(error
(format "FORMAT: ~~? requires a string: ~s" (car arglist)))
)
(else
(format-help (car arglist) (cadr arglist))
(anychar-dispatch (+ pos 1) (cddr arglist) #f)
)))
((#\H) ; Help
(display documentation-string port)
(anychar-dispatch (+ pos 1) arglist #t)
)
(else
(error (format "FORMAT: unknown tilde escape: ~s"
(string-ref format-strg pos))))
)))
)) ; end tilde-dispatch
) ; end letrec
; format-help main
(anychar-dispatch 0 arglist #f)
)) ; end format-help
; format main
(let ( (unused-args (format-help format-string args)) )
(if (not (null? unused-args))
(error
(format "FORMAT: unused arguments ~s" unused-args)))
(return-value))
)) ; end letrec, if
))) ; end format
;; Copyright (C) Taylan Ulrich Bayırlı/Kammer (2015). All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
(define-library (srfi 5)
(export (rename let+ let))
(import (scheme base))
(begin
(define-syntax let+
(syntax-rules ()
;; Unnamed, no rest args.
((_ ((var val) ...) body ...)
(let ((var val) ...) body ...))
;; Unnamed, with rest args.
((_ ((var val) spec ...) body ...)
(rest ((var val) spec ...) () () body ...))
;; Signature style, no rest args.
((_ (name (var val) ...) body ...)
(let name ((var val) ...) body ...))
;; Signature style, with rest args.
((_ (name (var val) spec ...) body ...)
(rest/named name ((var val) spec ...) () () body ...))
;; Named let, no rest args.
((_ name ((var val) ...) body ...)
(let name ((var val) ...) body ...))
;; Named let, with rest args.
((_ name ((var val) spec ...) body ...)
(rest/named name ((var val) spec ...) () () body ...))))
(define-syntax rest
(syntax-rules ()
((_ ((var val) spec ...) (var* ...) (val* ...) body ...)
(rest name (spec ...) (var var* ...) (val val* ...) body ...))
((_ (rest-var rest-val ...) (var ...) (val ...) body ...)
(let ((var val)
...
(rest-var (list rest-val ...)))
body ...))))
(define-syntax rest/named
(syntax-rules ()
((_ name ((var val) spec ...) (var* ...) (val* ...) body ...)
(rest/named name (spec ...) (var var* ...) (val val* ...) body ...))
((_ name (rest-var rest-val ...) (var ...) (val ...) body ...)
(letrec ((name (lambda (var ... . rest-var) body ...)))
(name val ... rest-val ...)))))
))
(define-library (srfi 51)
(export
rest-values
arg-and
arg-ands
err-and
err-ands
arg-or
arg-ors
err-or
err-ors
)
(import
(scheme base)
(srfi 1))
(include "51.upstream.scm"))
(define-library (srfi aux)
(import
(scheme base)
(scheme case-lambda)
(srfi 31))
(export
debug-mode
define/opt
lambda/opt
define-check-arg
)
(begin
(define debug-mode (make-parameter #f))
;; Emacs indentation help:
;; (put 'define/opt 'scheme-indent-function 1)
;; (put 'lambda/opt 'scheme-indent-function 1)
(define-syntax define/opt
(syntax-rules ()
((_ (name . args) . body)
(define name (lambda/opt args . body)))))
(define-syntax lambda/opt
(syntax-rules ()
((lambda* args . body)
(rec name (opt/split-args name () () args body)))))
(define-syntax opt/split-args
(syntax-rules ()
((_ name non-opts (opts ...) ((opt) . rest) body)
(opt/split-args name non-opts (opts ... (opt #f)) rest body))
((_ name non-opts (opts ...) ((opt def) . rest) body)
(opt/split-args name non-opts (opts ... (opt def)) rest body))
((_ name (non-opts ...) opts (non-opt . rest) body)
(opt/split-args name (non-opts ... non-opt) opts rest body))
;; Rest could be () or a rest-arg here; just propagate it.
((_ name non-opts opts rest body)
(opt/make-clauses name () rest non-opts opts body))))
(define-syntax opt/make-clauses
(syntax-rules ()
;; Handle special-case with no optargs.
((_ name () rest (taken ...) () body)
(lambda (taken ... . rest)
. body))
;; Add clause where no optargs are provided.
((_ name () rest (taken ...) ((opt def) ...) body)
(opt/make-clauses
name
(((taken ...)
(name taken ... def ...)))
rest
(taken ...)
((opt def) ...)
body))
;; Add clauses where 1 to n-1 optargs are provided
((_ name (clause ...) rest (taken ...) ((opt def) (opt* def*) ... x) body)
(opt/make-clauses
name
(clause
...
((taken ... opt)
(name taken ... opt def* ...)))
rest
(taken ... opt)
((opt* def*) ... x)
body))
;; Add clause where all optargs were given, and possibly more.
((_ name (clause ...) rest (taken ...) ((opt def)) body)
(case-lambda
clause
...
((taken ... opt . rest)
. body)))))
(define-syntax define-check-arg
(syntax-rules ()
((_ check-arg)
(define check-arg
(if (debug-mode)
(lambda (pred val proc)
(if (pred val)
val
(error "Type assertion failed:"
`(value ,val)
`(expected-type ,pred)
`(callee ,proc))))
(lambda (pred val proc)
val))))))
))
;;; Copyright (C) Joo ChurlSoo (2004). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define (rest-values rest . default)
(let* ((caller (if (or (null? default)
(boolean? (car default))
(integer? (car default))
(memq (car default) (list + -)))
'()
(if (string? rest) rest (list rest))))
(rest-list (if (null? caller) rest (car default)))
(rest-length (if (list? rest-list)
(length rest-list)
(if (string? caller)
(error caller rest-list 'rest-list
'(list? rest-list))
(apply error "bad rest list" rest-list 'rest-list
'(list? rest-list) caller))))
(default (if (null? caller) default (cdr default)))
(default-list (if (null? default) default (cdr default)))
(default-length (length default-list))
(number
(and (not (null? default))
(let ((option (car default)))
(or (and (integer? option)
(or (and (> rest-length (abs option))
(if (string? caller)
(error caller rest-list 'rest-list
`(<= (length rest-list)
,(abs option)))
(apply error "too many arguments"
rest-list 'rest-list
`(<= (length rest-list)
,(abs option))
caller)))
(and (> default-length (abs option))
(if (string? caller)
(error caller default-list
'default-list
`(<= (length default-list)
,(abs option)))
(apply error "too many defaults"
default-list 'default-list
`(<= (length default-list)
,(abs option))
caller)))
option))
(eq? option #t)
(and (not option) 'false)
(and (eq? option +) +)
(and (eq? option -) -)
(if (string? caller)
(error caller option 'option
'(or (boolean? option)
(integer? option)
(memq option (list + -))))
(apply error "bad optional argument" option 'option
'(or (boolean? option)
(integer? option)
(memq option (list + -)))
caller)))))))
(cond
((or (eq? #t number) (eq? 'false number))
(and (not (every pair? default-list))
(if (string? caller)
(error caller default-list 'default-list
'(every pair? default-list))
(apply error "bad default list" default-list 'default-list
'(every pair? default-list) caller)))
(let loop ((rest-list rest-list)
(default-list default-list)
(result '()))
(if (null? default-list)
(if (null? rest-list)
(apply values (reverse result))
(if (eq? #t number)
(if (string? caller)
(error caller rest-list 'rest-list '(null? rest-list))
(apply error "bad argument" rest-list 'rest-list
'(null? rest-list) caller))
(apply values (append-reverse result rest-list))))
(if (null? rest-list)
(apply values (append-reverse result (map car default-list)))
(let ((default (car default-list)))
(let lp ((rest rest-list)
(head '()))
(if (null? rest)
(loop (reverse head)
(cdr default-list)
(cons (car default) result))
(if (list? default)
(if (member (car rest) default)
(loop (append-reverse head (cdr rest))
(cdr default-list)
(cons (car rest) result))
(lp (cdr rest) (cons (car rest) head)))
(if ((cdr default) (car rest))
(loop (append-reverse head (cdr rest))
(cdr default-list)
(cons (car rest) result))
(lp (cdr rest) (cons (car rest) head)))))))))))
((or (and (integer? number) (> number 0))
(eq? number +))
(and (not (every pair? default-list))
(if (string? caller)
(error caller default-list 'default-list
'(every pair? default-list))
(apply error "bad default list" default-list 'default-list
'(every pair? default-list) caller)))
(let loop ((rest rest-list)
(default default-list))
(if (or (null? rest) (null? default))
(apply values
(if (> default-length rest-length)
(append rest-list
(map car (list-tail default-list rest-length)))
rest-list))
(let ((arg (car rest))
(par (car default)))
(if (list? par)
(if (member arg par)
(loop (cdr rest) (cdr default))
(if (string? caller)
(error caller arg 'arg `(member arg ,par))
(apply error "unmatched argument"
arg 'arg `(member arg ,par) caller)))
(if ((cdr par) arg)
(loop (cdr rest) (cdr default))
(if (string? caller)
(error caller arg 'arg `(,(cdr par) arg))
(apply error "incorrect argument"
arg 'arg `(,(cdr par) arg) caller))))))))
(else
(apply values (if (> default-length rest-length)
(append rest-list (list-tail default-list rest-length))
rest-list))))))
(define-syntax arg-and
(syntax-rules()
((arg-and arg (a1 a2 ...) ...)
(and (or (symbol? 'arg)
(error "bad syntax" 'arg '(symbol? 'arg)
'(arg-and arg (a1 a2 ...) ...)))
(or (a1 a2 ...)
(error "incorrect argument" arg 'arg '(a1 a2 ...)))
...))
((arg-and caller arg (a1 a2 ...) ...)
(and (or (symbol? 'arg)
(error "bad syntax" 'arg '(symbol? 'arg)
'(arg-and caller arg (a1 a2 ...) ...)))
(or (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))))
;; accessory macro for arg-ands
(define-syntax caller-arg-and
(syntax-rules()
((caller-arg-and caller arg (a1 a2 ...) ...)
(and (or (symbol? 'arg)
(error "bad syntax" 'arg '(symbol? 'arg)
'(caller-arg-and caller arg (a1 a2 ...) ...)))
(or (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))
((caller-arg-and null caller arg (a1 a2 ...) ...)
(and (or (symbol? 'arg)
(error "bad syntax" 'arg '(symbol? 'arg)
'(caller-arg-and caller arg (a1 a2 ...) ...)))
(or (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))))
(define-syntax arg-ands
(syntax-rules (common)
((arg-ands (a1 a2 ...) ...)
(and (arg-and a1 a2 ...) ...))
((arg-ands common caller (a1 a2 ...) ...)
(and (caller-arg-and caller a1 a2 ...) ...))))
(define-syntax arg-or
(syntax-rules()
((arg-or arg (a1 a2 ...) ...)
(or (and (not (symbol? 'arg))
(error "bad syntax" 'arg '(symbol? 'arg)
'(arg-or arg (a1 a2 ...) ...)))
(and (a1 a2 ...)
(error "incorrect argument" arg 'arg '(a1 a2 ...)))
...))
((arg-or caller arg (a1 a2 ...) ...)
(or (and (not (symbol? 'arg))
(error "bad syntax" 'arg '(symbol? 'arg)
'(arg-or caller arg (a1 a2 ...) ...)))
(and (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))))
;; accessory macro for arg-ors
(define-syntax caller-arg-or
(syntax-rules()
((caller-arg-or caller arg (a1 a2 ...) ...)
(or (and (not (symbol? 'arg))
(error "bad syntax" 'arg '(symbol? 'arg)
'(caller-arg-or caller arg (a1 a2 ...) ...)))
(and (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))
((caller-arg-or null caller arg (a1 a2 ...) ...)
(or (and (not (symbol? 'arg))
(error "bad syntax" 'arg '(symbol? 'arg)
'(caller-arg-or caller arg (a1 a2 ...) ...)))
(and (a1 a2 ...)
(if (string? caller)
(error caller arg 'arg '(a1 a2 ...))
(error "incorrect argument" arg 'arg '(a1 a2 ...) caller)))
...))))
(define-syntax arg-ors
(syntax-rules (common)
((arg-ors (a1 a2 ...) ...)
(or (arg-or a1 a2 ...) ...))
((arg-ors common caller (a1 a2 ...) ...)
(or (caller-arg-or caller a1 a2 ...) ...))))
(define-syntax err-and
(syntax-rules ()
((err-and err expression ...)
(and (or expression
(if (string? err)
(error err 'expression)
(error "false expression" 'expression err)))
...))))
(define-syntax err-ands
(syntax-rules ()
((err-ands (err expression ...) ...)
(and (err-and err expression ...)
...))))
(define-syntax err-or
(syntax-rules ()
((err-or err expression ...)
(or (and expression
(if (string? err)
(error err 'expression)
(error "true expression" 'expression err)))
...))))
(define-syntax err-ors
(syntax-rules ()
((err-ors (err expression ...) ...)
(or (err-or err expression ...)
...))))
;;; Copyright (C) Joo ChurlSoo (2004). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-syntax alet-cat* ; borrowed from SRFI-86
(syntax-rules ()
((alet-cat* z (a . e) bd ...)
(let ((y z))
(%alet-cat* y (a . e) bd ...)))))
(define-syntax %alet-cat* ; borrowed from SRFI-86
(syntax-rules ()
((%alet-cat* z ((n d t ...)) bd ...)
(let ((n (if (null? z)
d
(if (null? (cdr z))
(wow-cat-end z n t ...)
(error "cat: too many arguments" (cdr z))))))
bd ...))
((%alet-cat* z ((n d t ...) . e) bd ...)
(let ((n (if (null? z)
d
(wow-cat! z n d t ...))))
(%alet-cat* z e bd ...)))
((%alet-cat* z e bd ...)
(let ((e z)) bd ...))))
(define-syntax wow-cat! ; borrowed from SRFI-86
(syntax-rules ()
((wow-cat! z n d)
(let ((n (car z)))
(set! z (cdr z))
n))
((wow-cat! z n d t)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) n)
(let lp ((head (list n)) (tail (cdr z)))
(if (null? tail)
d
(let ((n (car tail)))
(if t
(begin (set! z (append (reverse head) (cdr tail))) n)
(lp (cons n head) (cdr tail)))))))))
((wow-cat! z n d t ts)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) ts)
(let lp ((head (list n)) (tail (cdr z)))
(if (null? tail)
d
(let ((n (car tail)))
(if t
(begin (set! z (append (reverse head) (cdr tail))) ts)
(lp (cons n head) (cdr tail)))))))))
((wow-cat! z n d t ts fs)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) ts)
(begin (set! z (cdr z)) fs))))))
(define-syntax wow-cat-end ; borrowed from SRFI-86
(syntax-rules ()
((wow-cat-end z n)
(car z))
((wow-cat-end z n t)
(let ((n (car z)))
(if t n (error "cat: too many argument" z))))
((wow-cat-end z n t ts)
(let ((n (car z)))
(if t ts (error "cat: too many argument" z))))
((wow-cat-end z n t ts fs)
(let ((n (car z)))
(if t ts fs)))))
(define (str-index str char)
(let ((len (string-length str)))
(let lp ((n 0))
(and (< n len)
(if (char=? char (string-ref str n))
n
(lp (+ n 1)))))))
(define (every? pred ls)
(let lp ((ls ls))
(or (null? ls)
(and (pred (car ls))
(lp (cdr ls))))))
(define (part pred ls)
(let lp ((ls ls) (true '()) (false '()))
(cond
((null? ls) (cons (reverse true) (reverse false)))
((pred (car ls)) (lp (cdr ls) (cons (car ls) true) false))
(else (lp (cdr ls) true (cons (car ls) false))))))
(define (e-mold num pre)
(let* ((str (number->string (inexact num)))
(e-index (str-index str #\e)))
(if e-index
(string-append (mold (substring str 0 e-index) pre)
(substring str e-index (string-length str)))
(mold str pre))))
(define (mold str pre)
(let ((ind (str-index str #\.)))
(if ind
(let ((d-len (- (string-length str) (+ ind 1))))
(cond
((= d-len pre) str)
((< d-len pre) (string-append str (make-string (- pre d-len) #\0)))
;;((char<? #\4 (string-ref str (+ 1 ind pre)))
;;(let ((com (expt 10 pre)))
;; (number->string (/ (round (* (string->number str) com)) com))))
((or (char<? #\5 (string-ref str (+ 1 ind pre)))
(and (char=? #\5 (string-ref str (+ 1 ind pre)))
(or (< (+ 1 pre) d-len)
(memv (string-ref str (+ ind (if (= 0 pre) -1 pre)))
'(#\1 #\3 #\5 #\7 #\9)))))
(apply
string
(let* ((minus (char=? #\- (string-ref str 0)))
(str (substring str (if minus 1 0) (+ 1 ind pre)))
(char-list
(reverse
(let lp ((index (- (string-length str) 1))
(raise #t))
(if (= -1 index)
(if raise '(#\1) '())
(let ((chr (string-ref str index)))
(if (char=? #\. chr)
(cons chr (lp (- index 1) raise))
(if raise
(if (char=? #\9 chr)
(cons #\0 (lp (- index 1) raise))
(cons (integer->char
(+ 1 (char->integer chr)))
(lp (- index 1) #f)))
(cons chr (lp (- index 1) raise))))))))))
(if minus (cons #\- char-list) char-list))))
(else
(substring str 0 (+ 1 ind pre)))))
(string-append str "." (make-string pre #\0)))))
(define (separate str sep num opt)
(let* ((len (string-length str))
(pos (if opt
(let ((pos (remainder (if (eq? opt 'minus) (- len 1) len)
num)))
(if (= 0 pos) num pos))
num)))
(apply string-append
(let loop ((ini 0)
(pos (if (eq? opt 'minus) (+ pos 1) pos)))
(if (< pos len)
(cons (substring str ini pos)
(cons sep (loop pos (+ pos num))))
(list (substring str ini len)))))))
(define (cat object . rest)
(let* ((str-rest (part string? rest))
(str-list (car str-rest))
(rest-list (cdr str-rest)))
(if (null? rest-list)
(apply string-append
(cond
((number? object) (number->string object))
((string? object) object)
((char? object) (string object))
((boolean? object) (if object "#t" "#f"))
((symbol? object) (symbol->string object))
(else
(get-output-string
(let ((str-port (open-output-string)))
(write object str-port)
str-port))))
str-list)
(alet-cat* rest-list
((width 0 (and (integer? width) (exact? width)))
(port #f (or (boolean? port) (output-port? port))
(if (eq? port #t) (current-output-port) port))
(char #\space (char? char))
(converter #f (and (pair? converter)
(procedure? (car converter))
(procedure? (cdr converter))))
(precision #f (and (integer? precision)
(inexact? precision)))
(sign #f (eq? 'sign sign))
(radix 'decimal
(memq radix '(decimal octal binary hexadecimal)))
(exactness #f (memq exactness '(exact inexact)))
(separator #f (and (list? separator)
(< 0 (length separator) 3)
(char? (car separator))
(or (null? (cdr separator))
(let ((n (cadr separator)))
(and (integer? n) (exact? n)
(< 0 n))))))
(writer #f (procedure? writer))
(pipe #f (and (list? pipe)
(not (null? pipe))
(every? procedure? pipe)))
(take #f (and (list? take)
(< 0 (length take) 3)
(every? (lambda (x)
(and (integer? x) (exact? x)))
take))))
(let* ((str
(cond
((and converter
((car converter) object))
(let* ((str ((cdr converter) object))
(pad (- (abs width) (string-length str))))
(cond
((<= pad 0) str)
((< 0 width) (string-append (make-string pad char) str))
(else (string-append str (make-string pad char))))))
((number? object)
(and (not (eq? radix 'decimal)) precision
(error "cat: non-decimal cannot have a decimal point"))
(and precision (< precision 0) (eq? exactness 'exact)
(error "cat: exact number cannot have a decimal point without exact sign"))
(let* ((exact-sign (and precision
(<= 0 precision)
(or (eq? exactness 'exact)
(and (exact? object)
(not (eq? exactness
'inexact))))
"#e"))
(inexact-sign (and (not (eq? radix 'decimal))
(or (and (inexact? object)
(not (eq? exactness
'exact)))
(eq? exactness 'inexact))
"#i"))
(radix-sign (cdr (assq radix
'((decimal . #f)
(octal . "#o")
(binary . "#b")
(hexadecimal . "#x")))))
(plus-sign (and sign (< 0 (real-part object)) "+"))
(exactness-sign (or exact-sign inexact-sign))
(str
(if precision
(let ((precision (exact
(abs precision)))
(imag (imag-part object)))
(if (= 0 imag)
(e-mold object precision)
(string-append
(e-mold (real-part object) precision)
(if (< 0 imag) "+" "")
(e-mold imag precision)
"i")))
(number->string
(cond
(inexact-sign (exact object))
(exactness
(if (eq? exactness 'exact)
(exact object)
(inexact object)))
(else object))
(cdr (assq radix '((decimal . 10)
(octal . 8)
(binary . 2)
(hexadecimal . 16)))))))
(str
(if (and separator
(not (or (and (eq? radix 'decimal)
(str-index str #\e))
(str-index str #\i)
(str-index str #\/))))
(let ((sep (string (car separator)))
(num (if (null? (cdr separator))
3 (cadr separator)))
(dot-index (str-index str #\.)))
(if dot-index
(string-append
(separate (substring str 0 dot-index)
sep num (if (< object 0)
'minus #t))
"."
(separate (substring
str (+ 1 dot-index)
(string-length str))
sep num #f))
(separate str sep num (if (< object 0)
'minus #t))))
str))
(pad (- (abs width)
(+ (string-length str)
(if exactness-sign 2 0)
(if radix-sign 2 0)
(if plus-sign 1 0))))
(pad (if (< 0 pad) pad 0)))
(if (< 0 width)
(if (char-numeric? char)
(if (< (real-part object) 0)
(string-append (or exactness-sign "")
(or radix-sign "")
"-"
(make-string pad char)
(substring str 1
(string-length
str)))
(string-append (or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
(make-string pad char)
str))
(string-append (make-string pad char)
(or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
str))
(string-append (or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
str
(make-string pad char)))))
(else
(let* ((str (cond
(writer (get-output-string
(let ((str-port
(open-output-string)))
(writer object str-port)
str-port)))
((string? object) object)
((char? object) (string object))
((boolean? object) (if object "#t" "#f"))
((symbol? object) (symbol->string object))
(else (get-output-string
(let ((str-port (open-output-string)))
(write object str-port)
str-port)))))
(str (if pipe
(let loop ((str ((car pipe) str))
(fns (cdr pipe)))
(if (null? fns)
str
(loop ((car fns) str)
(cdr fns))))
str))
(str
(if take
(let ((left (car take))
(right (if (null? (cdr take))
0 (cadr take)))
(len (string-length str)))
(define (substr str beg end)
(let ((end (cond
((< end 0) 0)
((< len end) len)
(else end)))
(beg (cond
((< beg 0) 0)
((< len beg) len)
(else beg))))
(if (and (= beg 0) (= end len))
str
(substring str beg end))))
(string-append
(if (< left 0)
(substr str (abs left) len)
(substr str 0 left))
(if (< right 0)
(substr str 0 (+ len right))
(substr str (- len right) len))))
str))
(pad (- (abs width) (string-length str))))
(cond
((<= pad 0) str)
((< 0 width) (string-append (make-string pad char) str))
(else (string-append str (make-string pad char))))))))
(str (apply string-append str str-list)))
(and port (display str port))
str)))))
;;; eof
(define-library (srfi 54)
(export cat)
(import
(scheme base)
(scheme char)
(scheme complex)
(scheme write)
(srfi 1))
(include "54.body.scm"))
;;; Copyright (C) Joo ChurlSoo (2004). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define (cat object . rest)
(let* ((str-rest (part string? rest))
(str-list (car str-rest))
(rest-list (cdr str-rest)))
(if (null? rest-list)
(apply string-append
(cond
((number? object) (number->string object))
((string? object) object)
((char? object) (string object))
((boolean? object) (if object "#t" "#f"))
((symbol? object) (symbol->string object))
(else
(get-output-string
(let ((str-port (open-output-string)))
(write object str-port)
str-port))))
str-list)
(alet-cat* rest-list
((width 0 (and (integer? width) (exact? width)))
(port #f (or (boolean? port) (output-port? port))
(if (eq? port #t) (current-output-port) port))
(char #\space (char? char))
(converter #f (and (pair? converter)
(procedure? (car converter))
(procedure? (cdr converter))))
(precision #f (and (integer? precision)
(inexact? precision)))
(sign #f (eq? 'sign sign))
(radix 'decimal
(memq radix '(decimal octal binary hexadecimal)))
(exactness #f (memq exactness '(exact inexact)))
(separator #f (and (list? separator)
(< 0 (length separator) 3)
(char? (car separator))
(or (null? (cdr separator))
(let ((n (cadr separator)))
(and (integer? n) (exact? n)
(< 0 n))))))
(writer #f (procedure? writer))
(pipe #f (and (list? pipe)
(not (null? pipe))
(every? procedure? pipe)))
(take #f (and (list? take)
(< 0 (length take) 3)
(every? (lambda (x)
(and (integer? x) (exact? x)))
take))))
(let* ((str
(cond
((and converter
((car converter) object))
(let* ((str ((cdr converter) object))
(pad (- (abs width) (string-length str))))
(cond
((<= pad 0) str)
((< 0 width) (string-append (make-string pad char) str))
(else (string-append str (make-string pad char))))))
((number? object)
(and (not (eq? radix 'decimal)) precision
(error "cat: non-decimal cannot have a decimal point"))
(and precision (< precision 0) (eq? exactness 'exact)
(error "cat: exact number cannot have a decimal point without exact sign"))
(let* ((exact-sign (and precision
(<= 0 precision)
(or (eq? exactness 'exact)
(and (exact? object)
(not (eq? exactness
'inexact))))
"#e"))
(inexact-sign (and (not (eq? radix 'decimal))
(or (and (inexact? object)
(not (eq? exactness
'exact)))
(eq? exactness 'inexact))
"#i"))
(radix-sign (cdr (assq radix
'((decimal . #f)
(octal . "#o")
(binary . "#b")
(hexadecimal . "#x")))))
(plus-sign (and sign (< 0 (real-part object)) "+"))
(exactness-sign (or exact-sign inexact-sign))
(str
(if precision
(let ((precision (inexact->exact
(abs precision)))
(imag (imag-part object)))
(if (= 0 imag)
(e-mold object precision)
(string-append
(e-mold (real-part object) precision)
(if (< 0 imag) "+" "")
(e-mold imag precision)
"i")))
(number->string
(cond
(inexact-sign (inexact->exact object))
(exactness
(if (eq? exactness 'exact)
(inexact->exact object)
(exact->inexact object)))
(else object))
(cdr (assq radix '((decimal . 10)
(octal . 8)
(binary . 2)
(hexadecimal . 16)))))))
(str
(if (and separator
(not (or (and (eq? radix 'decimal)
(str-index str #\e))
(str-index str #\i)
(str-index str #\/))))
(let ((sep (string (car separator)))
(num (if (null? (cdr separator))
3 (cadr separator)))
(dot-index (str-index str #\.)))
(if dot-index
(string-append
(separate (substring str 0 dot-index)
sep num (if (< object 0)
'minus #t))
"."
(separate (substring
str (+ 1 dot-index)
(string-length str))
sep num #f))
(separate str sep num (if (< object 0)
'minus #t))))
str))
(pad (- (abs width)
(+ (string-length str)
(if exactness-sign 2 0)
(if radix-sign 2 0)
(if plus-sign 1 0))))
(pad (if (< 0 pad) pad 0)))
(if (< 0 width)
(if (char-numeric? char)
(if (< (real-part object) 0)
(string-append (or exactness-sign "")
(or radix-sign "")
"-"
(make-string pad char)
(substring str 1
(string-length
str)))
(string-append (or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
(make-string pad char)
str))
(string-append (make-string pad char)
(or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
str))
(string-append (or exactness-sign "")
(or radix-sign "")
(or plus-sign "")
str
(make-string pad char)))))
(else
(let* ((str (cond
(writer (get-output-string
(let ((str-port
(open-output-string)))
(writer object str-port)
str-port)))
((string? object) object)
((char? object) (string object))
((boolean? object) (if object "#t" "#f"))
((symbol? object) (symbol->string object))
(else (get-output-string
(let ((str-port (open-output-string)))
(write object str-port)
str-port)))))
(str (if pipe
(let loop ((str ((car pipe) str))
(fns (cdr pipe)))
(if (null? fns)
str
(loop ((car fns) str)
(cdr fns))))
str))
(str
(if take
(let ((left (car take))
(right (if (null? (cdr take))
0 (cadr take)))
(len (string-length str)))
(define (substr str beg end)
(let ((end (cond
((< end 0) 0)
((< len end) len)
(else end)))
(beg (cond
((< beg 0) 0)
((< len beg) len)
(else beg))))
(if (and (= beg 0) (= end len))
str
(substring str beg end))))
(string-append
(if (< left 0)
(substr str (abs left) len)
(substr str 0 left))
(if (< right 0)
(substr str 0 (+ len right))
(substr str (- len right) len))))
str))
(pad (- (abs width) (string-length str))))
(cond
((<= pad 0) str)
((< 0 width) (string-append (make-string pad char) str))
(else (string-append str (make-string pad char))))))))
(str (apply string-append str str-list)))
(and port (display str port))
str)))))
(define-syntax alet-cat* ; borrowed from SRFI-86
(syntax-rules ()
((alet-cat* z (a . e) bd ...)
(let ((y z))
(%alet-cat* y (a . e) bd ...)))))
(define-syntax %alet-cat* ; borrowed from SRFI-86
(syntax-rules ()
((%alet-cat* z ((n d t ...)) bd ...)
(let ((n (if (null? z)
d
(if (null? (cdr z))
(wow-cat-end z n t ...)
(error "cat: too many arguments" (cdr z))))))
bd ...))
((%alet-cat* z ((n d t ...) . e) bd ...)
(let ((n (if (null? z)
d
(wow-cat! z n d t ...))))
(%alet-cat* z e bd ...)))
((%alet-cat* z e bd ...)
(let ((e z)) bd ...))))
(define-syntax wow-cat! ; borrowed from SRFI-86
(syntax-rules ()
((wow-cat! z n d)
(let ((n (car z)))
(set! z (cdr z))
n))
((wow-cat! z n d t)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) n)
(let lp ((head (list n)) (tail (cdr z)))
(if (null? tail)
d
(let ((n (car tail)))
(if t
(begin (set! z (append (reverse head) (cdr tail))) n)
(lp (cons n head) (cdr tail)))))))))
((wow-cat! z n d t ts)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) ts)
(let lp ((head (list n)) (tail (cdr z)))
(if (null? tail)
d
(let ((n (car tail)))
(if t
(begin (set! z (append (reverse head) (cdr tail))) ts)
(lp (cons n head) (cdr tail)))))))))
((wow-cat! z n d t ts fs)
(let ((n (car z)))
(if t
(begin (set! z (cdr z)) ts)
(begin (set! z (cdr z)) fs))))))
(define-syntax wow-cat-end ; borrowed from SRFI-86
(syntax-rules ()
((wow-cat-end z n)
(car z))
((wow-cat-end z n t)
(let ((n (car z)))
(if t n (error "cat: too many argument" z))))
((wow-cat-end z n t ts)
(let ((n (car z)))
(if t ts (error "cat: too many argument" z))))
((wow-cat-end z n t ts fs)
(let ((n (car z)))
(if t ts fs)))))
(define (str-index str char)
(let ((len (string-length str)))
(let lp ((n 0))
(and (< n len)
(if (char=? char (string-ref str n))
n
(lp (+ n 1)))))))
(define (every? pred ls)
(let lp ((ls ls))
(or (null? ls)
(and (pred (car ls))
(lp (cdr ls))))))
(define (part pred ls)
(let lp ((ls ls) (true '()) (false '()))
(cond
((null? ls) (cons (reverse true) (reverse false)))
((pred (car ls)) (lp (cdr ls) (cons (car ls) true) false))
(else (lp (cdr ls) true (cons (car ls) false))))))
(define (e-mold num pre)
(let* ((str (number->string (exact->inexact num)))
(e-index (str-index str #\e)))
(if e-index
(string-append (mold (substring str 0 e-index) pre)
(substring str e-index (string-length str)))
(mold str pre))))
(define (mold str pre)
(let ((ind (str-index str #\.)))
(if ind
(let ((d-len (- (string-length str) (+ ind 1))))
(cond
((= d-len pre) str)
((< d-len pre) (string-append str (make-string (- pre d-len) #\0)))
;;((char<? #\4 (string-ref str (+ 1 ind pre)))
;;(let ((com (expt 10 pre)))
;; (number->string (/ (round (* (string->number str) com)) com))))
((or (char<? #\5 (string-ref str (+ 1 ind pre)))
(and (char=? #\5 (string-ref str (+ 1 ind pre)))
(or (< (+ 1 pre) d-len)
(memv (string-ref str (+ ind (if (= 0 pre) -1 pre)))
'(#\1 #\3 #\5 #\7 #\9)))))
(apply
string
(let* ((minus (char=? #\- (string-ref str 0)))
(str (substring str (if minus 1 0) (+ 1 ind pre)))
(char-list
(reverse
(let lp ((index (- (string-length str) 1))
(raise #t))
(if (= -1 index)
(if raise '(#\1) '())
(let ((chr (string-ref str index)))
(if (char=? #\. chr)
(cons chr (lp (- index 1) raise))
(if raise
(if (char=? #\9 chr)
(cons #\0 (lp (- index 1) raise))
(cons (integer->char
(+ 1 (char->integer chr)))
(lp (- index 1) #f)))
(cons chr (lp (- index 1) raise))))))))))
(if minus (cons #\- char-list) char-list))))
(else
(substring str 0 (+ 1 ind pre)))))
(string-append str "." (make-string pre #\0)))))
(define (separate str sep num opt)
(let* ((len (string-length str))
(pos (if opt
(let ((pos (remainder (if (eq? opt 'minus) (- len 1) len)
num)))
(if (= 0 pos) num pos))
num)))
(apply string-append
(let loop ((ini 0)
(pos (if (eq? opt 'minus) (+ pos 1) pos)))
(if (< pos len)
(cons (substring str ini pos)
(cons sep (loop pos (+ pos num))))
(list (substring str ini len)))))))
;;; eof
(define-library (srfi 57)
(export
define-record-type
define-record-scheme
record-update
record-update!
record-compose
)
(import
(rename (scheme base) (define-record-type srfi-9:define-record-type))
(scheme case-lambda))
(include "57.upstream.scm"))
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(cond-expand
(chicken
(require-extension syntax-case))
(guile-2
(use-modules (srfi srfi-9)
;; In 2.0.9, srfi-34 and srfi-35 are not well integrated
;; with either Guile's native exceptions or R6RS exceptions.
;;(srfi srfi-34) (srfi srfi-35)
(srfi srfi-39)))
(guile
(use-modules (ice-9 syncase) (srfi srfi-9)
;;(srfi srfi-34) (srfi srfi-35) - not in Guile 1.6.7
(srfi srfi-39)))
(sisc
(require-extension (srfi 9 34 35 39)))
(kawa
(module-compile-options warn-undefined-variable\: #t
warn-invoke-unknown-method\: #t)
(provide 'srfi-64)
(provide 'testing)
(require 'srfi-34)
(require 'srfi-35))
(else ()
))
(cond-expand
(kawa
(define-syntax %test-export
(syntax-rules ()
((%test-export test-begin . other-names)
(module-export %test-begin . other-names)))))
(else
(define-syntax %test-export
(syntax-rules ()
((%test-export . names) (if #f #f))))))
;; List of exported names
(%test-export
test-begin ;; must be listed first, since in Kawa (at least) it is "magic".
test-end test-assert test-eqv test-eq test-equal
test-approximate test-assert test-error test-apply test-with-runner
test-match-nth test-match-all test-match-any test-match-name
test-skip test-expect-fail test-read-eval-string
test-runner-group-path test-group test-group-with-cleanup
test-result-ref test-result-set! test-result-clear test-result-remove
test-result-kind test-passed?
test-log-to-file
; Misc test-runner functions
test-runner? test-runner-reset test-runner-null
test-runner-simple test-runner-current test-runner-factory test-runner-get
test-runner-create test-runner-test-name
;; test-runner field setter and getter functions - see %test-record-define:
test-runner-pass-count test-runner-pass-count!
test-runner-fail-count test-runner-fail-count!
test-runner-xpass-count test-runner-xpass-count!
test-runner-xfail-count test-runner-xfail-count!
test-runner-skip-count test-runner-skip-count!
test-runner-group-stack test-runner-group-stack!
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
test-result-alist test-result-alist!
test-runner-aux-value test-runner-aux-value!
;; default/simple call-back functions, used in default test-runner,
;; but can be called to construct more complex ones.
test-on-group-begin-simple test-on-group-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
test-on-final-simple test-on-test-end-simple
test-on-final-simple)
(cond-expand
(srfi-9
(define-syntax %test-record-define
(syntax-rules ()
((%test-record-define alloc runner? (name index setter getter) ...)
(define-record-type test-runner
(alloc)
runner?
(name setter getter) ...)))))
(else
(define %test-runner-cookie (list "test-runner"))
(define-syntax %test-record-define
(syntax-rules ()
((%test-record-define alloc runner? (name index getter setter) ...)
(begin
(define (runner? obj)
(and (vector? obj)
(> (vector-length obj) 1)
(eq (vector-ref obj 0) %test-runner-cookie)))
(define (alloc)
(let ((runner (make-vector 23)))
(vector-set! runner 0 %test-runner-cookie)
runner))
(begin
(define (getter runner)
(vector-ref runner index)) ...)
(begin
(define (setter runner value)
(vector-set! runner index value)) ...)))))))
(%test-record-define
%test-runner-alloc test-runner?
;; Cumulate count of all tests that have passed and were expected to.
(pass-count 1 test-runner-pass-count test-runner-pass-count!)
(fail-count 2 test-runner-fail-count test-runner-fail-count!)
(xpass-count 3 test-runner-xpass-count test-runner-xpass-count!)
(xfail-count 4 test-runner-xfail-count test-runner-xfail-count!)
(skip-count 5 test-runner-skip-count test-runner-skip-count!)
(skip-list 6 %test-runner-skip-list %test-runner-skip-list!)
(fail-list 7 %test-runner-fail-list %test-runner-fail-list!)
;; Normally #t, except when in a test-apply.
(run-list 8 %test-runner-run-list %test-runner-run-list!)
(skip-save 9 %test-runner-skip-save %test-runner-skip-save!)
(fail-save 10 %test-runner-fail-save %test-runner-fail-save!)
(group-stack 11 test-runner-group-stack test-runner-group-stack!)
(on-test-begin 12 test-runner-on-test-begin test-runner-on-test-begin!)
(on-test-end 13 test-runner-on-test-end test-runner-on-test-end!)
;; Call-back when entering a group. Takes (runner suite-name count).
(on-group-begin 14 test-runner-on-group-begin test-runner-on-group-begin!)
;; Call-back when leaving a group.
(on-group-end 15 test-runner-on-group-end test-runner-on-group-end!)
;; Call-back when leaving the outermost group.
(on-final 16 test-runner-on-final test-runner-on-final!)
;; Call-back when expected number of tests was wrong.
(on-bad-count 17 test-runner-on-bad-count test-runner-on-bad-count!)
;; Call-back when name in test=end doesn't match test-begin.
(on-bad-end-name 18 test-runner-on-bad-end-name test-runner-on-bad-end-name!)
;; Cumulate count of all tests that have been done.
(total-count 19 %test-runner-total-count %test-runner-total-count!)
;; Stack (list) of (count-at-start . expected-count):
(count-list 20 %test-runner-count-list %test-runner-count-list!)
(result-alist 21 test-result-alist test-result-alist!)
;; Field can be used by test-runner for any purpose.
;; test-runner-simple uses it for a log file.
(aux-value 22 test-runner-aux-value test-runner-aux-value!)
)
(define (test-runner-reset runner)
(test-result-alist! runner '())
(test-runner-pass-count! runner 0)
(test-runner-fail-count! runner 0)
(test-runner-xpass-count! runner 0)
(test-runner-xfail-count! runner 0)
(test-runner-skip-count! runner 0)
(%test-runner-total-count! runner 0)
(%test-runner-count-list! runner '())
(%test-runner-run-list! runner #t)
(%test-runner-skip-list! runner '())
(%test-runner-fail-list! runner '())
(%test-runner-skip-save! runner '())
(%test-runner-fail-save! runner '())
(test-runner-group-stack! runner '()))
(define (test-runner-group-path runner)
(reverse (test-runner-group-stack runner)))
(define (%test-null-callback runner) #f)
(define (test-runner-null)
(let ((runner (%test-runner-alloc)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner (lambda (runner name count) #f))
(test-runner-on-group-end! runner %test-null-callback)
(test-runner-on-final! runner %test-null-callback)
(test-runner-on-test-begin! runner %test-null-callback)
(test-runner-on-test-end! runner %test-null-callback)
(test-runner-on-bad-count! runner (lambda (runner count expected) #f))
(test-runner-on-bad-end-name! runner (lambda (runner begin end) #f))
runner))
;; Not part of the specification. FIXME
;; Controls whether a log file is generated.
(define test-log-to-file #t)
(define (test-runner-simple)
(let ((runner (%test-runner-alloc)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-on-group-begin-simple)
(test-runner-on-group-end! runner test-on-group-end-simple)
(test-runner-on-final! runner test-on-final-simple)
(test-runner-on-test-begin! runner test-on-test-begin-simple)
(test-runner-on-test-end! runner test-on-test-end-simple)
(test-runner-on-bad-count! runner test-on-bad-count-simple)
(test-runner-on-bad-end-name! runner test-on-bad-end-name-simple)
runner))
(cond-expand
(srfi-39
(define test-runner-current (make-parameter #f))
(define test-runner-factory (make-parameter test-runner-simple)))
(else
(define %test-runner-current #f)
(define-syntax test-runner-current
(syntax-rules ()
((test-runner-current)
%test-runner-current)
((test-runner-current runner)
(set! %test-runner-current runner))))
(define %test-runner-factory test-runner-simple)
(define-syntax test-runner-factory
(syntax-rules ()
((test-runner-factory)
%test-runner-factory)
((test-runner-factory runner)
(set! %test-runner-factory runner))))))
;; A safer wrapper to test-runner-current.
(define (test-runner-get)
(let ((r (test-runner-current)))
(if (not r)
(cond-expand
(srfi-23 (error "test-runner not initialized - test-begin missing?"))
(else #t)))
r))
(define (%test-specifier-matches spec runner)
(spec runner))
(define (test-runner-create)
((test-runner-factory)))
(define (%test-any-specifier-matches list runner)
(let ((result #f))
(let loop ((l list))
(cond ((null? l) result)
(else
(if (%test-specifier-matches (car l) runner)
(set! result #t))
(loop (cdr l)))))))
;; Returns #f, #t, or 'xfail.
(define (%test-should-execute runner)
(let ((run (%test-runner-run-list runner)))
(cond ((or
(not (or (eqv? run #t)
(%test-any-specifier-matches run runner)))
(%test-any-specifier-matches
(%test-runner-skip-list runner)
runner))
(test-result-set! runner 'result-kind 'skip)
#f)
((%test-any-specifier-matches
(%test-runner-fail-list runner)
runner)
(test-result-set! runner 'result-kind 'xfail)
'xfail)
(else #t))))
(define (%test-begin suite-name count)
(if (not (test-runner-current))
(test-runner-current (test-runner-create)))
(let ((runner (test-runner-current)))
((test-runner-on-group-begin runner) runner suite-name count)
(%test-runner-skip-save! runner
(cons (%test-runner-skip-list runner)
(%test-runner-skip-save runner)))
(%test-runner-fail-save! runner
(cons (%test-runner-fail-list runner)
(%test-runner-fail-save runner)))
(%test-runner-count-list! runner
(cons (cons (%test-runner-total-count runner)
count)
(%test-runner-count-list runner)))
(test-runner-group-stack! runner (cons suite-name
(test-runner-group-stack runner)))))
(cond-expand
(kawa
;; Kawa has test-begin built in, implemented as:
;; (begin
;; (cond-expand (srfi-64 #!void) (else (require 'srfi-64)))
;; (%test-begin suite-name [count]))
;; This puts test-begin but only test-begin in the default environment.,
;; which makes normal test suites loadable without non-portable commands.
)
(else
(define-syntax test-begin
(syntax-rules ()
((test-begin suite-name)
(%test-begin suite-name #f))
((test-begin suite-name count)
(%test-begin suite-name count))))))
(define (test-on-group-begin-simple runner suite-name count)
(if (null? (test-runner-group-stack runner))
(begin
(display "%%%% Starting test ")
(display suite-name)
(if test-log-to-file
(let* ((log-file-name
(if (string? test-log-to-file) test-log-to-file
(string-append suite-name ".log")))
(log-file
(cond-expand (mzscheme
(open-output-file log-file-name 'truncate/replace))
(else (open-output-file log-file-name)))))
(display "%%%% Starting test " log-file)
(display suite-name log-file)
(newline log-file)
(test-runner-aux-value! runner log-file)
(display " (Writing full log to \"")
(display log-file-name)
(display "\")")))
(newline)))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(begin
(display "Group begin: " log)
(display suite-name log)
(newline log))))
#f)
(define (test-on-group-end-simple runner)
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(begin
(display "Group end: " log)
(display (car (test-runner-group-stack runner)) log)
(newline log))))
#f)
(define (%test-on-bad-count-write runner count expected-count port)
(display "*** Total number of tests was " port)
(display count port)
(display " but should be " port)
(display expected-count port)
(display ". ***" port)
(newline port)
(display "*** Discrepancy indicates testsuite error or exceptions. ***" port)
(newline port))
(define (test-on-bad-count-simple runner count expected-count)
(%test-on-bad-count-write runner count expected-count (current-output-port))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(%test-on-bad-count-write runner count expected-count log))))
(define (test-on-bad-end-name-simple runner begin-name end-name)
(let ((msg (string-append (%test-format-line runner) "test-end " begin-name
" does not match test-begin " end-name)))
(cond-expand
(srfi-23 (error msg))
(else (display msg) (newline)))))
(define (%test-final-report1 value label port)
(if (> value 0)
(begin
(display label port)
(display value port)
(newline port))))
(define (%test-final-report-simple runner port)
(%test-final-report1 (test-runner-pass-count runner)
"# of expected passes " port)
(%test-final-report1 (test-runner-xfail-count runner)
"# of expected failures " port)
(%test-final-report1 (test-runner-xpass-count runner)
"# of unexpected successes " port)
(%test-final-report1 (test-runner-fail-count runner)
"# of unexpected failures " port)
(%test-final-report1 (test-runner-skip-count runner)
"# of skipped tests " port))
(define (test-on-final-simple runner)
(%test-final-report-simple runner (current-output-port))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(%test-final-report-simple runner log))))
(define (%test-format-line runner)
(let* ((line-info (test-result-alist runner))
(source-file (assq 'source-file line-info))
(source-line (assq 'source-line line-info))
(file (if source-file (cdr source-file) "")))
(if source-line
(string-append file ":"
(number->string (cdr source-line)) ": ")
"")))
(define (%test-end suite-name line-info)
(let* ((r (test-runner-get))
(groups (test-runner-group-stack r))
(line (%test-format-line r)))
(test-result-alist! r line-info)
(if (null? groups)
(let ((msg (string-append line "test-end not in a group")))
(cond-expand
(srfi-23 (error msg))
(else (display msg) (newline)))))
(if (and suite-name (not (equal? suite-name (car groups))))
((test-runner-on-bad-end-name r) r suite-name (car groups)))
(let* ((count-list (%test-runner-count-list r))
(expected-count (cdar count-list))
(saved-count (caar count-list))
(group-count (- (%test-runner-total-count r) saved-count)))
(if (and expected-count
(not (= expected-count group-count)))
((test-runner-on-bad-count r) r group-count expected-count))
((test-runner-on-group-end r) r)
(test-runner-group-stack! r (cdr (test-runner-group-stack r)))
(%test-runner-skip-list! r (car (%test-runner-skip-save r)))
(%test-runner-skip-save! r (cdr (%test-runner-skip-save r)))
(%test-runner-fail-list! r (car (%test-runner-fail-save r)))
(%test-runner-fail-save! r (cdr (%test-runner-fail-save r)))
(%test-runner-count-list! r (cdr count-list))
(if (null? (test-runner-group-stack r))
((test-runner-on-final r) r)))))
(define-syntax test-group
(syntax-rules ()
((test-group suite-name . body)
(let ((r (test-runner-current)))
;; Ideally should also set line-number, if available.
(test-result-alist! r (list (cons 'test-name suite-name)))
(if (%test-should-execute r)
(dynamic-wind
(lambda () (test-begin suite-name))
(lambda () . body)
(lambda () (test-end suite-name))))))))
(define-syntax test-group-with-cleanup
(syntax-rules ()
((test-group-with-cleanup suite-name form cleanup-form)
(test-group suite-name
(dynamic-wind
(lambda () #f)
(lambda () form)
(lambda () cleanup-form))))
((test-group-with-cleanup suite-name cleanup-form)
(test-group-with-cleanup suite-name #f cleanup-form))
((test-group-with-cleanup suite-name form1 form2 form3 . rest)
(test-group-with-cleanup suite-name (begin form1 form2) form3 . rest))))
(define (test-on-test-begin-simple runner)
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(let* ((results (test-result-alist runner))
(source-file (assq 'source-file results))
(source-line (assq 'source-line results))
(source-form (assq 'source-form results))
(test-name (assq 'test-name results)))
(display "Test begin:" log)
(newline log)
(if test-name (%test-write-result1 test-name log))
(if source-file (%test-write-result1 source-file log))
(if source-line (%test-write-result1 source-line log))
(if source-form (%test-write-result1 source-form log))))))
(define-syntax test-result-ref
(syntax-rules ()
((test-result-ref runner pname)
(test-result-ref runner pname #f))
((test-result-ref runner pname default)
(let ((p (assq pname (test-result-alist runner))))
(if p (cdr p) default)))))
(define (test-on-test-end-simple runner)
(let ((log (test-runner-aux-value runner))
(kind (test-result-ref runner 'result-kind)))
(if (memq kind '(fail xpass))
(let* ((results (test-result-alist runner))
(source-file (assq 'source-file results))
(source-line (assq 'source-line results))
(test-name (assq 'test-name results)))
(if (or source-file source-line)
(begin
(if source-file (display (cdr source-file)))
(display ":")
(if source-line (display (cdr source-line)))
(display ": ")))
(display (if (eq? kind 'xpass) "XPASS" "FAIL"))
(if test-name
(begin
(display " ")
(display (cdr test-name))))
(newline)))
(if (output-port? log)
(begin
(display "Test end:" log)
(newline log)
(let loop ((list (test-result-alist runner)))
(if (pair? list)
(let ((pair (car list)))
;; Write out properties not written out by on-test-begin.
(if (not (memq (car pair)
'(test-name source-file source-line source-form)))
(%test-write-result1 pair log))
(loop (cdr list)))))))))
(define (%test-write-result1 pair port)
(display " " port)
(display (car pair) port)
(display ": " port)
(write (cdr pair) port)
(newline port))
(define (test-result-set! runner pname value)
(let* ((alist (test-result-alist runner))
(p (assq pname alist)))
(if p
(set-cdr! p value)
(test-result-alist! runner (cons (cons pname value) alist)))))
(define (test-result-clear runner)
(test-result-alist! runner '()))
(define (test-result-remove runner pname)
(let* ((alist (test-result-alist runner))
(p (assq pname alist)))
(if p
(test-result-alist! runner
(let loop ((r alist))
(if (eq? r p) (cdr r)
(cons (car r) (loop (cdr r)))))))))
(define (test-result-kind . rest)
(let ((runner (if (pair? rest) (car rest) (test-runner-current))))
(test-result-ref runner 'result-kind)))
(define (test-passed? . rest)
(let ((runner (if (pair? rest) (car rest) (test-runner-get))))
(memq (test-result-ref runner 'result-kind) '(pass xpass))))
(define (%test-report-result)
(let* ((r (test-runner-get))
(result-kind (test-result-kind r)))
(case result-kind
((pass)
(test-runner-pass-count! r (+ 1 (test-runner-pass-count r))))
((fail)
(test-runner-fail-count! r (+ 1 (test-runner-fail-count r))))
((xpass)
(test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r))))
((xfail)
(test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r))))
(else
(test-runner-skip-count! r (+ 1 (test-runner-skip-count r)))))
(%test-runner-total-count! r (+ 1 (%test-runner-total-count r)))
((test-runner-on-test-end r) r)))
(cond-expand
(guile
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(catch #t
(lambda () test-expression)
(lambda (key . args)
(test-result-set! (test-runner-current) 'actual-error
(cons key args))
#f))))))
(kawa
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(try-catch test-expression
(ex <java.lang.Throwable>
(test-result-set! (test-runner-current) 'actual-error ex)
#f))))))
(srfi-34
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(guard (err (else #f)) test-expression)))))
(chicken
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(condition-case test-expression (ex () #f))))))
(else
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
test-expression)))))
(cond-expand
((or kawa mzscheme)
(cond-expand
(mzscheme
(define-for-syntax (%test-syntax-file form)
(let ((source (syntax-source form)))
(cond ((string? source) file)
((path? source) (path->string source))
(else #f)))))
(kawa
(define (%test-syntax-file form)
(syntax-source form))))
(define (%test-source-line2 form)
(let* ((line (syntax-line form))
(file (%test-syntax-file form))
(line-pair (if line (list (cons 'source-line line)) '())))
(cons (cons 'source-form (syntax-object->datum form))
(if file (cons (cons 'source-file file) line-pair) line-pair)))))
(guile-2
(define (%test-source-line2 form)
(let* ((src-props (syntax-source form))
(file (and src-props (assq-ref src-props 'filename)))
(line (and src-props (assq-ref src-props 'line)))
(file-alist (if file
`((source-file . ,file))
'()))
(line-alist (if line
`((source-line . ,(+ line 1)))
'())))
(datum->syntax (syntax here)
`((source-form . ,(syntax->datum form))
,@file-alist
,@line-alist)))))
(else
(define (%test-source-line2 form)
'())))
(define (%test-on-test-begin r)
(%test-should-execute r)
((test-runner-on-test-begin r) r)
(not (eq? 'skip (test-result-ref r 'result-kind))))
(define (%test-on-test-end r result)
(test-result-set! r 'result-kind
(if (eq? (test-result-ref r 'result-kind) 'xfail)
(if result 'xpass 'xfail)
(if result 'pass 'fail))))
(define (test-runner-test-name runner)
(test-result-ref runner 'test-name ""))
(define-syntax %test-comp2body
(syntax-rules ()
((%test-comp2body r comp expected expr)
(let ()
(if (%test-on-test-begin r)
(let ((exp expected))
(test-result-set! r 'expected-value exp)
(let ((res (%test-evaluate-with-catch expr)))
(test-result-set! r 'actual-value res)
(%test-on-test-end r (comp exp res)))))
(%test-report-result)))))
(define (%test-approximate= error)
(lambda (value expected)
(let ((rval (real-part value))
(ival (imag-part value))
(rexp (real-part expected))
(iexp (imag-part expected)))
(and (>= rval (- rexp error))
(>= ival (- iexp error))
(<= rval (+ rexp error))
(<= ival (+ iexp error))))))
(define-syntax %test-comp1body
(syntax-rules ()
((%test-comp1body r expr)
(let ()
(if (%test-on-test-begin r)
(let ()
(let ((res (%test-evaluate-with-catch expr)))
(test-result-set! r 'actual-value res)
(%test-on-test-end r res))))
(%test-report-result)))))
(cond-expand
((or kawa mzscheme guile-2)
;; Should be made to work for any Scheme with syntax-case
;; However, I haven't gotten the quoting working. FIXME.
(define-syntax test-end
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac suite-name) line)
(syntax
(%test-end suite-name line)))
(((mac) line)
(syntax
(%test-end #f line))))))
(define-syntax test-assert
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname expr) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp1body r expr))))
(((mac expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp1body r expr)))))))
(define (%test-comp2 comp x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x)) comp) ()
(((mac tname expected expr) line comp)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp2body r comp expected expr))))
(((mac expected expr) line comp)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp2body r comp expected expr))))))
(define-syntax test-eqv
(lambda (x) (%test-comp2 (syntax eqv?) x)))
(define-syntax test-eq
(lambda (x) (%test-comp2 (syntax eq?) x)))
(define-syntax test-equal
(lambda (x) (%test-comp2 (syntax equal?) x)))
(define-syntax test-approximate ;; FIXME - needed for non-Kawa
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname expected expr error) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp2body r (%test-approximate= error) expected expr))))
(((mac expected expr error) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp2body r (%test-approximate= error) expected expr))))))))
(else
(define-syntax test-end
(syntax-rules ()
((test-end)
(%test-end #f '()))
((test-end suite-name)
(%test-end suite-name '()))))
(define-syntax test-assert
(syntax-rules ()
((test-assert tname test-expression)
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r '((test-name . tname)))
(%test-comp1body r test-expression)))
((test-assert test-expression)
(let* ((r (test-runner-get)))
(test-result-alist! r '())
(%test-comp1body r test-expression)))))
(define-syntax %test-comp2
(syntax-rules ()
((%test-comp2 comp tname expected expr)
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (list (cons 'test-name tname)))
(%test-comp2body r comp expected expr)))
((%test-comp2 comp expected expr)
(let* ((r (test-runner-get)))
(test-result-alist! r '())
(%test-comp2body r comp expected expr)))))
(define-syntax test-equal
(syntax-rules ()
((test-equal . rest)
(%test-comp2 equal? . rest))))
(define-syntax test-eqv
(syntax-rules ()
((test-eqv . rest)
(%test-comp2 eqv? . rest))))
(define-syntax test-eq
(syntax-rules ()
((test-eq . rest)
(%test-comp2 eq? . rest))))
(define-syntax test-approximate
(syntax-rules ()
((test-approximate tname expected expr error)
(%test-comp2 (%test-approximate= error) tname expected expr))
((test-approximate expected expr error)
(%test-comp2 (%test-approximate= error) expected expr))))))
(cond-expand
(guile
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(cond ((%test-on-test-begin r)
(let ((et etype))
(test-result-set! r 'expected-error et)
(%test-on-test-end r
(catch #t
(lambda ()
(test-result-set! r 'actual-value expr)
#f)
(lambda (key . args)
;; TODO: decide how to specify expected
;; error types for Guile.
(test-result-set! r 'actual-error
(cons key args))
#t)))
(%test-report-result))))))))
(mzscheme
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (with-handlers (((lambda (h) #t) (lambda (h) #t)))
(let ()
(test-result-set! r 'actual-value expr)
#f)))))))
(chicken
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (condition-case expr (ex () #t)))))))
(kawa
(define-syntax %test-error
(syntax-rules ()
((%test-error r #t expr)
(cond ((%test-on-test-begin r)
(test-result-set! r 'expected-error #t)
(%test-on-test-end r
(try-catch
(let ()
(test-result-set! r 'actual-value expr)
#f)
(ex <java.lang.Throwable>
(test-result-set! r 'actual-error ex)
#t)))
(%test-report-result))))
((%test-error r etype expr)
(if (%test-on-test-begin r)
(let ((et etype))
(test-result-set! r 'expected-error et)
(%test-on-test-end r
(try-catch
(let ()
(test-result-set! r 'actual-value expr)
#f)
(ex <java.lang.Throwable>
(test-result-set! r 'actual-error ex)
(cond ((and (instance? et <gnu.bytecode.ClassType>)
(gnu.bytecode.ClassType:isSubclass et <java.lang.Throwable>))
(instance? ex et))
(else #t)))))
(%test-report-result)))))))
((and srfi-34 srfi-35)
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (guard (ex ((condition-type? etype)
(and (condition? ex) (condition-has-type? ex etype)))
((procedure? etype)
(etype ex))
((equal? etype #t)
#t)
(else #t))
expr #f))))))
(srfi-34
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (guard (ex (else #t)) expr #f))))))
(else
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(begin
((test-runner-on-test-begin r) r)
(test-result-set! r 'result-kind 'skip)
(%test-report-result)))))))
(cond-expand
((or kawa mzscheme guile-2)
(define-syntax test-error
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname etype expr) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-error r etype expr))))
(((mac etype expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-error r etype expr))))
(((mac expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-error r #t expr))))))))
(else
(define-syntax test-error
(syntax-rules ()
((test-error name etype expr)
(let ((r (test-runner-get)))
(test-result-alist! r `((test-name . ,name)))
(%test-error r etype expr)))
((test-error etype expr)
(let ((r (test-runner-get)))
(test-result-alist! r '())
(%test-error r etype expr)))
((test-error expr)
(let ((r (test-runner-get)))
(test-result-alist! r '())
(%test-error r #t expr)))))))
(define (test-apply first . rest)
(if (test-runner? first)
(test-with-runner first (apply test-apply rest))
(let ((r (test-runner-current)))
(if r
(let ((run-list (%test-runner-run-list r)))
(cond ((null? rest)
(%test-runner-run-list! r (reverse run-list))
(first)) ;; actually apply procedure thunk
(else
(%test-runner-run-list!
r
(if (eq? run-list #t) (list first) (cons first run-list)))
(apply test-apply rest)
(%test-runner-run-list! r run-list))))
(let ((r (test-runner-create)))
(test-with-runner r (apply test-apply first rest))
((test-runner-on-final r) r))))))
(define-syntax test-with-runner
(syntax-rules ()
((test-with-runner runner form ...)
(let ((saved-runner (test-runner-current)))
(dynamic-wind
(lambda () (test-runner-current runner))
(lambda () form ...)
(lambda () (test-runner-current saved-runner)))))))
;;; Predicates
(define (%test-match-nth n count)
(let ((i 0))
(lambda (runner)
(set! i (+ i 1))
(and (>= i n) (< i (+ n count))))))
(define-syntax test-match-nth
(syntax-rules ()
((test-match-nth n)
(test-match-nth n 1))
((test-match-nth n count)
(%test-match-nth n count))))
(define (%test-match-all . pred-list)
(lambda (runner)
(let ((result #t))
(let loop ((l pred-list))
(if (null? l)
result
(begin
(if (not ((car l) runner))
(set! result #f))
(loop (cdr l))))))))
(define-syntax test-match-all
(syntax-rules ()
((test-match-all pred ...)
(%test-match-all (%test-as-specifier pred) ...))))
(define (%test-match-any . pred-list)
(lambda (runner)
(let ((result #f))
(let loop ((l pred-list))
(if (null? l)
result
(begin
(if ((car l) runner)
(set! result #t))
(loop (cdr l))))))))
(define-syntax test-match-any
(syntax-rules ()
((test-match-any pred ...)
(%test-match-any (%test-as-specifier pred) ...))))
;; Coerce to a predicate function:
(define (%test-as-specifier specifier)
(cond ((procedure? specifier) specifier)
((integer? specifier) (test-match-nth 1 specifier))
((string? specifier) (test-match-name specifier))
(else
(error "not a valid test specifier"))))
(define-syntax test-skip
(syntax-rules ()
((test-skip pred ...)
(let ((runner (test-runner-get)))
(%test-runner-skip-list! runner
(cons (test-match-all (%test-as-specifier pred) ...)
(%test-runner-skip-list runner)))))))
(define-syntax test-expect-fail
(syntax-rules ()
((test-expect-fail pred ...)
(let ((runner (test-runner-get)))
(%test-runner-fail-list! runner
(cons (test-match-all (%test-as-specifier pred) ...)
(%test-runner-fail-list runner)))))))
(define (test-match-name name)
(lambda (runner)
(equal? name (test-runner-test-name runner))))
(define (test-read-eval-string string)
(let* ((port (open-input-string string))
(form (read port)))
(if (eof-object? (read-char port))
(cond-expand
(guile (eval form (current-module)))
(else (eval form)))
(cond-expand
(srfi-23 (error "(not at eof)"))
(else "error")))))
(define-library (srfi 67)
(export
</<=?
</<?
<=/<=?
<=/<?
<=?
<?
=?
>/>=?
>/>?
>=/>=?
>=/>?
>=?
>?
boolean-compare
chain<=?
chain<?
chain=?
chain>=?
chain>?
char-compare
char-compare-ci
compare-by<
compare-by<=
compare-by=/<
compare-by=/>
compare-by>
compare-by>=
complex-compare
cond-compare
debug-compare
default-compare
if-not=?
if3
if<=?
if<?
if=?
if>=?
if>?
integer-compare
kth-largest
list-compare
list-compare-as-vector
max-compare
min-compare
not=?
number-compare
pair-compare
pair-compare-car
pair-compare-cdr
pairwise-not=?
rational-compare
real-compare
refine-compare
select-compare
symbol-compare
vector-compare
vector-compare-as-list
bytevector-compare
bytevector-compare-as-list
)
(import
(scheme base)
(scheme case-lambda)
(scheme char)
(scheme complex)
(srfi 27))
(include "67.upstream.scm")
(begin
(define (bytevector-compare bv1 bv2)
(let ((len1 (bytevector-length bv1))
(len2 (bytevector-length bv2)))
(cond
((< len1 len2) -1)
((> len1 len2) +1)
(else
(let lp ((i 0))
(if (= i len1)
0
(let ((b1 (bytevector-u8-ref bv1 i))
(b2 (bytevector-u8-ref bv2 i)))
(cond
((< b1 b2) -1)
((> b1 b2) +1)
(else
(lp (+ 1 i)))))))))))
(define (bytevector-compare-as-list bv1 bv2)
(let ((len1 (bytevector-length bv1))
(len2 (bytevector-length bv2)))
(let lp ((i 0))
(cond
((or (= i len1) (= i len2))
(cond ((< len1 len2) -1)
((> len1 len2) +1)
(else 0)))
(else
(let ((b1 (bytevector-u8-ref bv1 i))
(b2 (bytevector-u8-ref bv2 i)))
(cond
((< b1 b2) -1)
((> b1 b2) +1)
(else
(lp (+ 1 i))))))))))
))
; Copyright (c) 2005 Sebastian Egner and Jens Axel S{\o}gaard.
;
; Permission is hereby granted, free of charge, to any person obtaining
; a copy of this software and associated documentation files (the
; ``Software''), to deal in the Software without restriction, including
; without limitation the rights to use, copy, modify, merge, publish,
; distribute, sublicense, and/or sell copies of the Software, and to
; permit persons to whom the Software is furnished to do so, subject to
; the following conditions:
;
; The above copyright notice and this permission notice shall be
; included in all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;
; -----------------------------------------------------------------------
;
; Compare procedures SRFI (reference implementation)
; Sebastian.Egner@philips.com, Jensaxel@soegaard.net
; history of this file:
; SE, 14-Oct-2004: first version
; SE, 18-Oct-2004: 1st redesign: axioms for 'compare function'
; SE, 29-Oct-2004: 2nd redesign: higher order reverse/map/refine/unite
; SE, 2-Nov-2004: 3rd redesign: macros cond/refine-compare replace h.o.f's
; SE, 10-Nov-2004: (im,re) replaced by (re,im) in complex-compare
; SE, 11-Nov-2004: case-compare by case (not by cond); select-compare added
; SE, 12-Jan-2005: pair-compare-cdr
; SE, 15-Feb-2005: stricter typing for compare-<type>; pairwise-not=?
; SE, 16-Feb-2005: case-compare -> if-compare -> if3; <? </<? chain<? etc.
; JS, 24-Feb-2005: selection-compare added
; SE, 25-Feb-2005: selection-compare -> kth-largest modified; if<? etc.
; JS, 28-Feb-2005: kth-largest modified - is "stable" now
; SE, 28-Feb-2005: simplified pairwise-not=?/kth-largest; min/max debugged
; SE, 07-Apr-2005: compare-based type checks made explicit
; SE, 18-Apr-2005: added (rel? compare) and eq?-test
; SE, 16-May-2005: naming convention changed; compare-by< etc. optional x y
; =============================================================================
; Reference Implementation
; ========================
;
; in R5RS (including hygienic macros)
; + SRFI-16 (case-lambda)
; + SRFI-23 (error)
; + SRFI-27 (random-integer)
; Implementation remarks:
; * In general, the emphasis of this implementation is on correctness
; and portability, not on efficiency.
; * Variable arity procedures are expressed in terms of case-lambda
; in the hope that this will produce efficient code for the case
; where the arity is statically known at the call site.
; * In procedures that are required to type-check their arguments,
; we use (compare x x) for executing extra checks. This relies on
; the assumption that eq? is used to catch this case quickly.
; * Care has been taken to reference comparison procedures of R5RS
; only at the time the operations here are being defined. This
; makes it possible to redefine these operations, if need be.
; * For the sake of efficiency, some inlining has been done by hand.
; This is mainly expressed by macros producing defines.
; * Identifiers of the form compare:<something> are private.
;
; Hints for low-level implementation:
; * The basis of this SRFI are the atomic compare procedures,
; i.e. boolean-compare, char-compare, etc. and the conditionals
; if3, if=?, if<? etc., and default-compare. These should make
; optimal use of the available type information.
; * For the sake of speed, the reference implementation does not
; use a LET to save the comparison value c for the ERROR call.
; This can be fixed in a low-level implementation at no cost.
; * Type-checks based on (compare x x) are made explicit by the
; expression (compare:check result compare x ...).
; * Eq? should can used to speed up built-in compare procedures,
; but it can only be used after type-checking at least one of
; the arguments.
(define (compare:checked result compare . args)
(for-each (lambda (x) (compare x x)) args)
result)
; 3-sided conditional
(define-syntax if3
(syntax-rules ()
((if3 c less equal greater)
(case c
((-1) less)
(( 0) equal)
(( 1) greater)
(else (error "comparison value not in {-1,0,1}"))))))
; 2-sided conditionals for comparisons
(define-syntax compare:if-rel?
(syntax-rules ()
((compare:if-rel? c-cases a-cases c consequence)
(compare:if-rel? c-cases a-cases c consequence (if #f #f)))
((compare:if-rel? c-cases a-cases c consequence alternate)
(case c
(c-cases consequence)
(a-cases alternate)
(else (error "comparison value not in {-1,0,1}"))))))
(define-syntax if=?
(syntax-rules ()
((if=? arg ...)
(compare:if-rel? (0) (-1 1) arg ...))))
(define-syntax if<?
(syntax-rules ()
((if<? arg ...)
(compare:if-rel? (-1) (0 1) arg ...))))
(define-syntax if>?
(syntax-rules ()
((if>? arg ...)
(compare:if-rel? (1) (-1 0) arg ...))))
(define-syntax if<=?
(syntax-rules ()
((if<=? arg ...)
(compare:if-rel? (-1 0) (1) arg ...))))
(define-syntax if>=?
(syntax-rules ()
((if>=? arg ...)
(compare:if-rel? (0 1) (-1) arg ...))))
(define-syntax if-not=?
(syntax-rules ()
((if-not=? arg ...)
(compare:if-rel? (-1 1) (0) arg ...))))
; predicates from compare procedures
(define-syntax compare:define-rel?
(syntax-rules ()
((compare:define-rel? rel? if-rel?)
(define rel?
(case-lambda
(() (lambda (x y) (if-rel? (default-compare x y) #t #f)))
((compare) (lambda (x y) (if-rel? (compare x y) #t #f)))
((x y) (if-rel? (default-compare x y) #t #f))
((compare x y)
(if (procedure? compare)
(if-rel? (compare x y) #t #f)
(error "not a procedure (Did you mean rel/rel??): " compare))))))))
(compare:define-rel? =? if=?)
(compare:define-rel? <? if<?)
(compare:define-rel? >? if>?)
(compare:define-rel? <=? if<=?)
(compare:define-rel? >=? if>=?)
(compare:define-rel? not=? if-not=?)
; chains of length 3
(define-syntax compare:define-rel1/rel2?
(syntax-rules ()
((compare:define-rel1/rel2? rel1/rel2? if-rel1? if-rel2?)
(define rel1/rel2?
(case-lambda
(()
(lambda (x y z)
(if-rel1? (default-compare x y)
(if-rel2? (default-compare y z) #t #f)
(compare:checked #f default-compare z))))
((compare)
(lambda (x y z)
(if-rel1? (compare x y)
(if-rel2? (compare y z) #t #f)
(compare:checked #f compare z))))
((x y z)
(if-rel1? (default-compare x y)
(if-rel2? (default-compare y z) #t #f)
(compare:checked #f default-compare z)))
((compare x y z)
(if-rel1? (compare x y)
(if-rel2? (compare y z) #t #f)
(compare:checked #f compare z))))))))
(compare:define-rel1/rel2? </<? if<? if<?)
(compare:define-rel1/rel2? </<=? if<? if<=?)
(compare:define-rel1/rel2? <=/<? if<=? if<?)
(compare:define-rel1/rel2? <=/<=? if<=? if<=?)
(compare:define-rel1/rel2? >/>? if>? if>?)
(compare:define-rel1/rel2? >/>=? if>? if>=?)
(compare:define-rel1/rel2? >=/>? if>=? if>?)
(compare:define-rel1/rel2? >=/>=? if>=? if>=?)
; chains of arbitrary length
(define-syntax compare:define-chain-rel?
(syntax-rules ()
((compare:define-chain-rel? chain-rel? if-rel?)
(define chain-rel?
(case-lambda
((compare)
#t)
((compare x1)
(compare:checked #t compare x1))
((compare x1 x2)
(if-rel? (compare x1 x2) #t #f))
((compare x1 x2 x3)
(if-rel? (compare x1 x2)
(if-rel? (compare x2 x3) #t #f)
(compare:checked #f compare x3)))
((compare x1 x2 . x3+)
(if-rel? (compare x1 x2)
(let chain? ((head x2) (tail x3+))
(if (null? tail)
#t
(if-rel? (compare head (car tail))
(chain? (car tail) (cdr tail))
(apply compare:checked #f
compare (cdr tail)))))
(apply compare:checked #f compare x3+))))))))
(compare:define-chain-rel? chain=? if=?)
(compare:define-chain-rel? chain<? if<?)
(compare:define-chain-rel? chain>? if>?)
(compare:define-chain-rel? chain<=? if<=?)
(compare:define-chain-rel? chain>=? if>=?)
; pairwise inequality
(define pairwise-not=?
(let ((= =) (<= <=))
(case-lambda
((compare)
#t)
((compare x1)
(compare:checked #t compare x1))
((compare x1 x2)
(if-not=? (compare x1 x2) #t #f))
((compare x1 x2 x3)
(if-not=? (compare x1 x2)
(if-not=? (compare x2 x3)
(if-not=? (compare x1 x3) #t #f)
#f)
(compare:checked #f compare x3)))
((compare . x1+)
(let unequal? ((x x1+) (n (length x1+)) (unchecked? #t))
(if (< n 2)
(if (and unchecked? (= n 1))
(compare:checked #t compare (car x))
#t)
(let* ((i-pivot (random-integer n))
(x-pivot (list-ref x i-pivot)))
(let split ((i 0) (x x) (x< '()) (x> '()))
(if (null? x)
(and (unequal? x< (length x<) #f)
(unequal? x> (length x>) #f))
(if (= i i-pivot)
(split (+ i 1) (cdr x) x< x>)
(if3 (compare (car x) x-pivot)
(split (+ i 1) (cdr x) (cons (car x) x<) x>)
(if unchecked?
(apply compare:checked #f compare (cdr x))
#f)
(split (+ i 1) (cdr x) x< (cons (car x) x>)))))))))))))
; min/max
(define min-compare
(case-lambda
((compare x1)
(compare:checked x1 compare x1))
((compare x1 x2)
(if<=? (compare x1 x2) x1 x2))
((compare x1 x2 x3)
(if<=? (compare x1 x2)
(if<=? (compare x1 x3) x1 x3)
(if<=? (compare x2 x3) x2 x3)))
((compare x1 x2 x3 x4)
(if<=? (compare x1 x2)
(if<=? (compare x1 x3)
(if<=? (compare x1 x4) x1 x4)
(if<=? (compare x3 x4) x3 x4))
(if<=? (compare x2 x3)
(if<=? (compare x2 x4) x2 x4)
(if<=? (compare x3 x4) x3 x4))))
((compare x1 x2 . x3+)
(let min ((xmin (if<=? (compare x1 x2) x1 x2)) (xs x3+))
(if (null? xs)
xmin
(min (if<=? (compare xmin (car xs)) xmin (car xs))
(cdr xs)))))))
(define max-compare
(case-lambda
((compare x1)
(compare:checked x1 compare x1))
((compare x1 x2)
(if>=? (compare x1 x2) x1 x2))
((compare x1 x2 x3)
(if>=? (compare x1 x2)
(if>=? (compare x1 x3) x1 x3)
(if>=? (compare x2 x3) x2 x3)))
((compare x1 x2 x3 x4)
(if>=? (compare x1 x2)
(if>=? (compare x1 x3)
(if>=? (compare x1 x4) x1 x4)
(if>=? (compare x3 x4) x3 x4))
(if>=? (compare x2 x3)
(if>=? (compare x2 x4) x2 x4)
(if>=? (compare x3 x4) x3 x4))))
((compare x1 x2 . x3+)
(let max ((xmax (if>=? (compare x1 x2) x1 x2)) (xs x3+))
(if (null? xs)
xmax
(max (if>=? (compare xmax (car xs)) xmax (car xs))
(cdr xs)))))))
; kth-largest
(define kth-largest
(let ((= =) (< <))
(case-lambda
((compare k x0)
(case (modulo k 1)
((0) (compare:checked x0 compare x0))
(else (error "bad index" k))))
((compare k x0 x1)
(case (modulo k 2)
((0) (if<=? (compare x0 x1) x0 x1))
((1) (if<=? (compare x0 x1) x1 x0))
(else (error "bad index" k))))
((compare k x0 x1 x2)
(case (modulo k 3)
((0) (if<=? (compare x0 x1)
(if<=? (compare x0 x2) x0 x2)
(if<=? (compare x1 x2) x1 x2)))
((1) (if3 (compare x0 x1)
(if<=? (compare x1 x2)
x1
(if<=? (compare x0 x2) x2 x0))
(if<=? (compare x0 x2) x1 x0)
(if<=? (compare x0 x2)
x0
(if<=? (compare x1 x2) x2 x1))))
((2) (if<=? (compare x0 x1)
(if<=? (compare x1 x2) x2 x1)
(if<=? (compare x0 x2) x2 x0)))
(else (error "bad index" k))))
((compare k x0 . x1+) ; |x1+| >= 1
(if (not (and (integer? k) (exact? k)))
(error "bad index" k))
(let ((n (+ 1 (length x1+))))
(let kth ((k (modulo k n))
(n n) ; = |x|
(rev #t) ; are x<, x=, x> reversed?
(x (cons x0 x1+)))
(let ((pivot (list-ref x (random-integer n))))
(let split ((x x) (x< '()) (n< 0) (x= '()) (n= 0) (x> '()) (n> 0))
(if (null? x)
(cond
((< k n<)
(kth k n< (not rev) x<))
((< k (+ n< n=))
(if rev
(list-ref x= (- (- n= 1) (- k n<)))
(list-ref x= (- k n<))))
(else
(kth (- k (+ n< n=)) n> (not rev) x>)))
(if3 (compare (car x) pivot)
(split (cdr x) (cons (car x) x<) (+ n< 1) x= n= x> n>)
(split (cdr x) x< n< (cons (car x) x=) (+ n= 1) x> n>)
(split (cdr x) x< n< x= n= (cons (car x) x>) (+ n> 1))))))))))))
; compare functions from predicates
(define compare-by<
(case-lambda
((lt) (lambda (x y) (if (lt x y) -1 (if (lt y x) 1 0))))
((lt x y) (if (lt x y) -1 (if (lt y x) 1 0)))))
(define compare-by>
(case-lambda
((gt) (lambda (x y) (if (gt x y) 1 (if (gt y x) -1 0))))
((gt x y) (if (gt x y) 1 (if (gt y x) -1 0)))))
(define compare-by<=
(case-lambda
((le) (lambda (x y) (if (le x y) (if (le y x) 0 -1) 1)))
((le x y) (if (le x y) (if (le y x) 0 -1) 1))))
(define compare-by>=
(case-lambda
((ge) (lambda (x y) (if (ge x y) (if (ge y x) 0 1) -1)))
((ge x y) (if (ge x y) (if (ge y x) 0 1) -1))))
(define compare-by=/<
(case-lambda
((eq lt) (lambda (x y) (if (eq x y) 0 (if (lt x y) -1 1))))
((eq lt x y) (if (eq x y) 0 (if (lt x y) -1 1)))))
(define compare-by=/>
(case-lambda
((eq gt) (lambda (x y) (if (eq x y) 0 (if (gt x y) 1 -1))))
((eq gt x y) (if (eq x y) 0 (if (gt x y) 1 -1)))))
; refine and extend construction
(define-syntax refine-compare
(syntax-rules ()
((refine-compare)
0)
((refine-compare c1)
c1)
((refine-compare c1 c2 cs ...)
(if3 c1 -1 (refine-compare c2 cs ...) 1))))
(define-syntax select-compare
(syntax-rules (else)
((select-compare x y clause ...)
(let ((x-val x) (y-val y))
(select-compare (x-val y-val clause ...))))
; used internally: (select-compare (x y clause ...))
((select-compare (x y))
0)
((select-compare (x y (else c ...)))
(refine-compare c ...))
((select-compare (x y (t? c ...) clause ...))
(let ((t?-val t?))
(let ((tx (t?-val x)) (ty (t?-val y)))
(if tx
(if ty (refine-compare c ...) -1)
(if ty 1 (select-compare (x y clause ...)))))))))
(define-syntax cond-compare
(syntax-rules (else)
((cond-compare)
0)
((cond-compare (else cs ...))
(refine-compare cs ...))
((cond-compare ((tx ty) cs ...) clause ...)
(let ((tx-val tx) (ty-val ty))
(if tx-val
(if ty-val (refine-compare cs ...) -1)
(if ty-val 1 (cond-compare clause ...)))))))
; R5RS atomic types
(define-syntax compare:type-check
(syntax-rules ()
((compare:type-check type? type-name x)
(if (not (type? x))
(error (string-append "not " type-name ":") x)))
((compare:type-check type? type-name x y)
(begin (compare:type-check type? type-name x)
(compare:type-check type? type-name y)))))
(define-syntax compare:define-by=/<
(syntax-rules ()
((compare:define-by=/< compare = < type? type-name)
(define compare
(let ((= =) (< <))
(lambda (x y)
(if (type? x)
(if (eq? x y)
0
(if (type? y)
(if (= x y) 0 (if (< x y) -1 1))
(error (string-append "not " type-name ":") y)))
(error (string-append "not " type-name ":") x))))))))
(define (boolean-compare x y)
(compare:type-check boolean? "boolean" x y)
(if x (if y 0 1) (if y -1 0)))
(compare:define-by=/< char-compare char=? char<? char? "char")
(compare:define-by=/< char-compare-ci char-ci=? char-ci<? char? "char")
(compare:define-by=/< string-compare string=? string<? string? "string")
(compare:define-by=/< string-compare-ci string-ci=? string-ci<? string? "string")
(define (symbol-compare x y)
(compare:type-check symbol? "symbol" x y)
(string-compare (symbol->string x) (symbol->string y)))
(compare:define-by=/< integer-compare = < integer? "integer")
(compare:define-by=/< rational-compare = < rational? "rational")
(compare:define-by=/< real-compare = < real? "real")
(define (complex-compare x y)
(compare:type-check complex? "complex" x y)
(if (and (real? x) (real? y))
(real-compare x y)
(refine-compare (real-compare (real-part x) (real-part y))
(real-compare (imag-part x) (imag-part y)))))
(define (number-compare x y)
(compare:type-check number? "number" x y)
(complex-compare x y))
; R5RS compound data structures: dotted pair, list, vector
(define (pair-compare-car compare)
(lambda (x y)
(compare (car x) (car y))))
(define (pair-compare-cdr compare)
(lambda (x y)
(compare (cdr x) (cdr y))))
(define pair-compare
(case-lambda
; dotted pair
((pair-compare-car pair-compare-cdr x y)
(refine-compare (pair-compare-car (car x) (car y))
(pair-compare-cdr (cdr x) (cdr y))))
; possibly improper lists
((compare x y)
(cond-compare
(((null? x) (null? y)) 0)
(((pair? x) (pair? y)) (compare (car x) (car y))
(pair-compare compare (cdr x) (cdr y)))
(else (compare x y))))
; for convenience
((x y)
(pair-compare default-compare x y))))
(define list-compare
(case-lambda
((compare x y empty? head tail)
(cond-compare
(((empty? x) (empty? y)) 0)
(else (compare (head x) (head y))
(list-compare compare (tail x) (tail y) empty? head tail))))
; for convenience
(( x y empty? head tail)
(list-compare default-compare x y empty? head tail))
((compare x y )
(list-compare compare x y null? car cdr))
(( x y )
(list-compare default-compare x y null? car cdr))))
(define list-compare-as-vector
(case-lambda
((compare x y empty? head tail)
(refine-compare
(let compare-length ((x x) (y y))
(cond-compare
(((empty? x) (empty? y)) 0)
(else (compare-length (tail x) (tail y)))))
(list-compare compare x y empty? head tail)))
; for convenience
(( x y empty? head tail)
(list-compare-as-vector default-compare x y empty? head tail))
((compare x y )
(list-compare-as-vector compare x y null? car cdr))
(( x y )
(list-compare-as-vector default-compare x y null? car cdr))))
(define vector-compare
(let ((= =))
(case-lambda
((compare x y size ref)
(let ((n (size x)) (m (size y)))
(refine-compare
(integer-compare n m)
(let compare-rest ((i 0)) ; compare x[i..n-1] y[i..n-1]
(if (= i n)
0
(refine-compare (compare (ref x i) (ref y i))
(compare-rest (+ i 1))))))))
; for convenience
(( x y size ref)
(vector-compare default-compare x y size ref))
((compare x y )
(vector-compare compare x y vector-length vector-ref))
(( x y )
(vector-compare default-compare x y vector-length vector-ref)))))
(define vector-compare-as-list
(let ((= =))
(case-lambda
((compare x y size ref)
(let ((nx (size x)) (ny (size y)))
(let ((n (min nx ny)))
(let compare-rest ((i 0)) ; compare x[i..n-1] y[i..n-1]
(if (= i n)
(integer-compare nx ny)
(refine-compare (compare (ref x i) (ref y i))
(compare-rest (+ i 1))))))))
; for convenience
(( x y size ref)
(vector-compare-as-list default-compare x y size ref))
((compare x y )
(vector-compare-as-list compare x y vector-length vector-ref))
(( x y )
(vector-compare-as-list default-compare x y vector-length vector-ref)))))
; default compare
(define (default-compare x y)
(select-compare
x y
(null? 0)
(pair? (default-compare (car x) (car y))
(default-compare (cdr x) (cdr y)))
(boolean? (boolean-compare x y))
(char? (char-compare x y))
(string? (string-compare x y))
(symbol? (symbol-compare x y))
(number? (number-compare x y))
(vector? (vector-compare default-compare x y))
(else (error "unrecognized type in default-compare" x y))))
; Note that we pass default-compare to compare-{pair,vector} explictly.
; This makes sure recursion proceeds with this default-compare, which
; need not be the one in the lexical scope of compare-{pair,vector}.
; debug compare
(define (debug-compare c)
(define (checked-value c x y)
(let ((c-xy (c x y)))
(if (or (eqv? c-xy -1) (eqv? c-xy 0) (eqv? c-xy 1))
c-xy
(error "compare value not in {-1,0,1}" c-xy (list c x y)))))
(define (random-boolean)
(zero? (random-integer 2)))
(define q ; (u v w) such that u <= v, v <= w, and not u <= w
'#(
;x < y x = y x > y [x < z]
0 0 0 ; y < z
0 (z y x) (z y x) ; y = z
0 (z y x) (z y x) ; y > z
;x < y x = y x > y [x = z]
(y z x) (z x y) 0 ; y < z
(y z x) 0 (x z y) ; y = z
0 (y x z) (x z y) ; y > z
;x < y x = y x > y [x > z]
(x y z) (x y z) 0 ; y < z
(x y z) (x y z) 0 ; y = z
0 0 0 ; y > z
))
(let ((z? #f) (z #f)) ; stored element from previous call
(lambda (x y)
(let ((c-xx (checked-value c x x))
(c-yy (checked-value c y y))
(c-xy (checked-value c x y))
(c-yx (checked-value c y x)))
(if (not (zero? c-xx))
(error "compare error: not reflexive" c x))
(if (not (zero? c-yy))
(error "compare error: not reflexive" c y))
(if (not (zero? (+ c-xy c-yx)))
(error "compare error: not anti-symmetric" c x y))
(if z?
(let ((c-xz (checked-value c x z))
(c-zx (checked-value c z x))
(c-yz (checked-value c y z))
(c-zy (checked-value c z y)))
(if (not (zero? (+ c-xz c-zx)))
(error "compare error: not anti-symmetric" c x z))
(if (not (zero? (+ c-yz c-zy)))
(error "compare error: not anti-symmetric" c y z))
(let ((ijk (vector-ref q (+ c-xy (* 3 c-yz) (* 9 c-xz) 13))))
(if (list? ijk)
(apply error
"compare error: not transitive"
c
(map (lambda (i) (case i ((x) x) ((y) y) ((z) z)))
ijk)))))
(set! z? #t))
(set! z (if (random-boolean) x y)) ; randomized testing
c-xy))))
;;; Copyright © Panu Kalliokoski (2005). All Rights Reserved.
;;; Made an R7RS library by Taylan Ulrich Bayırlı/Kammer, Copyright © 2014.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define default-bound (make-parameter (- (expt 2 29) 3)))
(define (%string-hash s ch-conv bound)
(let ((hash 31)
(len (string-length s)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hash bound))
(set! hash (modulo (+ (* 37 hash)
(char->integer (ch-conv (string-ref s index))))
(default-bound))))))
(define string-hash
(case-lambda
((s) (string-hash s (default-bound)))
((s bound)
(%string-hash s (lambda (x) x) bound))))
(define string-ci-hash
(case-lambda
((s) (string-ci-hash s (default-bound)))
((s bound)
(%string-hash s char-downcase bound))))
(define symbol-hash
(case-lambda
((s) (symbol-hash s (default-bound)))
((s bound)
(%string-hash (symbol->string s) (lambda (x) x) bound))))
(define hash
(case-lambda
((obj) (hash obj (default-bound)))
((obj bound)
(cond ((integer? obj) (modulo obj bound))
((string? obj) (string-hash obj bound))
((symbol? obj) (symbol-hash obj bound))
((real? obj) (modulo (+ (numerator obj) (denominator obj)) bound))
((number? obj)
(modulo (+ (hash (real-part obj)) (* 3 (hash (imag-part obj))))
bound))
((char? obj) (modulo (char->integer obj) bound))
((vector? obj) (vector-hash obj bound))
((pair? obj) (modulo (+ (hash (car obj)) (* 3 (hash (cdr obj))))
bound))
((null? obj) 0)
((not obj) 0)
((procedure? obj) (error "hash: procedures cannot be hashed" obj))
(else 1)))))
(define hash-by-identity hash)
(define (vector-hash v bound)
(let ((hashvalue 571)
(len (vector-length v)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hashvalue bound))
(set! hashvalue (modulo (+ (* 257 hashvalue) (hash (vector-ref v index)))
(default-bound))))))
(define %make-hash-node cons)
(define %hash-node-set-value! set-cdr!)
(define %hash-node-key car)
(define %hash-node-value cdr)
(define-record-type <srfi-hash-table>
(%make-hash-table size hash compare associate entries)
hash-table?
(size hash-table-size hash-table-set-size!)
(hash hash-table-hash-function)
(compare hash-table-equivalence-function)
(associate hash-table-association-function)
(entries hash-table-entries hash-table-set-entries!))
(define default-table-size (make-parameter 64))
(define (appropriate-hash-function-for comparison)
(or (and (eq? comparison eq?) hash-by-identity)
(and (eq? comparison string=?) string-hash)
(and (eq? comparison string-ci=?) string-ci-hash)
hash))
(define make-hash-table
(case-lambda
(()
(make-hash-table equal?
(appropriate-hash-function-for equal?)
(default-table-size)))
((comparison)
(make-hash-table comparison
(appropriate-hash-function-for comparison)
(default-table-size)))
((comparison hash)
(make-hash-table comparison
hash
(default-table-size)))
((comparison hash size)
(let ((association (or (and (eq? comparison eq?) assq)
(and (eq? comparison eqv?) assv)
(and (eq? comparison equal?) assoc)
(rec (associate val alist)
(cond
((null? alist) #f)
((comparison val (caar alist)) (car alist))
(else (associate val (cdr alist))))))))
(%make-hash-table
0 hash comparison association (make-vector size '()))))))
(define (make-hash-table-maker comp hash)
(lambda args (apply make-hash-table (cons comp (cons hash args)))))
(define make-symbol-hash-table
(make-hash-table-maker eq? symbol-hash))
(define make-string-hash-table
(make-hash-table-maker string=? string-hash))
(define make-string-ci-hash-table
(make-hash-table-maker string-ci=? string-ci-hash))
(define make-integer-hash-table
(make-hash-table-maker = modulo))
(define (%hash-table-hash hash-table key)
((hash-table-hash-function hash-table)
key (vector-length (hash-table-entries hash-table))))
(define (%hash-table-find entries associate hash key)
(associate key (vector-ref entries hash)))
(define (%hash-table-add! entries hash key value)
(vector-set! entries hash
(cons (%make-hash-node key value)
(vector-ref entries hash))))
(define (%hash-table-delete! entries compare hash key)
(let ((entrylist (vector-ref entries hash)))
(cond ((null? entrylist) #f)
((compare key (caar entrylist))
(vector-set! entries hash (cdr entrylist)) #t)
(else
(let loop ((current (cdr entrylist)) (previous entrylist))
(cond ((null? current) #f)
((compare key (caar current))
(set-cdr! previous (cdr current)) #t)
(else (loop (cdr current) current))))))))
(define (%hash-table-walk proc entries)
(do ((index (- (vector-length entries) 1) (- index 1)))
((< index 0)) (for-each proc (vector-ref entries index))))
(define (%hash-table-maybe-resize! hash-table)
(let* ((old-entries (hash-table-entries hash-table))
(hash-length (vector-length old-entries)))
(if (> (hash-table-size hash-table) hash-length)
(let* ((new-length (* 2 hash-length))
(new-entries (make-vector new-length '()))
(hash (hash-table-hash-function hash-table)))
(%hash-table-walk
(lambda (node)
(%hash-table-add! new-entries
(hash (%hash-node-key node) new-length)
(%hash-node-key node) (%hash-node-value node)))
old-entries)
(hash-table-set-entries! hash-table new-entries)))))
(define (not-found-error key)
(lambda ()
(error "No value associated with key:" key)))
(define hash-table-ref
(case-lambda
((hash-table key) (hash-table-ref hash-table key (not-found-error key)))
((hash-table key default-thunk)
(cond ((%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key)
=> %hash-node-value)
(else (default-thunk))))))
(define (hash-table-ref/default hash-table key default)
(hash-table-ref hash-table key (lambda () default)))
(define (hash-table-set! hash-table key value)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node) (%hash-node-set-value! node value)))
(else (%hash-table-add! entries hash key value)
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))
(define hash-table-update!
(case-lambda
((hash-table key function)
(hash-table-update! hash-table key function (not-found-error key)))
((hash-table key function default-thunk)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node)
(%hash-node-set-value!
node (function (%hash-node-value node)))))
(else (%hash-table-add! entries hash key
(function (default-thunk)))
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))))
(define (hash-table-update!/default hash-table key function default)
(hash-table-update! hash-table key function (lambda () default)))
(define (hash-table-delete! hash-table key)
(if (%hash-table-delete! (hash-table-entries hash-table)
(hash-table-equivalence-function hash-table)
(%hash-table-hash hash-table key) key)
(hash-table-set-size! hash-table (- (hash-table-size hash-table) 1))))
(define (hash-table-exists? hash-table key)
(and (%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key) #t))
(define (hash-table-walk hash-table proc)
(%hash-table-walk
(lambda (node) (proc (%hash-node-key node) (%hash-node-value node)))
(hash-table-entries hash-table)))
(define (hash-table-fold hash-table f acc)
(hash-table-walk hash-table
(lambda (key value) (set! acc (f key value acc))))
acc)
(define (appropriate-size-for-alist alist)
(max (default-table-size) (* 2 (length alist))))
(define alist->hash-table
(case-lambda
((alist)
(alist->hash-table alist
equal?
(appropriate-hash-function-for equal?)
(appropriate-size-for-alist alist)))
((alist comparison)
(alist->hash-table alist
comparison
(appropriate-hash-function-for comparison)
(appropriate-size-for-alist alist)))
((alist comparison hash)
(alist->hash-table alist
comparison
hash
(appropriate-size-for-alist alist)))
((alist comparison hash size)
(let ((hash-table (make-hash-table comparison hash size)))
(for-each
(lambda (elem)
(hash-table-update!/default
hash-table (car elem) (lambda (x) x) (cdr elem)))
alist)
hash-table))))
(define (hash-table->alist hash-table)
(hash-table-fold hash-table
(lambda (key val acc) (cons (cons key val) acc)) '()))
(define (hash-table-copy hash-table)
(let ((new (make-hash-table (hash-table-equivalence-function hash-table)
(hash-table-hash-function hash-table)
(max (default-table-size)
(* 2 (hash-table-size hash-table))))))
(hash-table-walk hash-table
(lambda (key value) (hash-table-set! new key value)))
new))
(define (hash-table-merge! hash-table1 hash-table2)
(hash-table-walk
hash-table2
(lambda (key value) (hash-table-set! hash-table1 key value)))
hash-table1)
(define (hash-table-keys hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons key acc)) '()))
(define (hash-table-values hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons val acc)) '()))
(define-library (srfi 69)
(export
;; Type constructors and predicate
make-hash-table hash-table? alist->hash-table
;; Reflective queries
hash-table-equivalence-function hash-table-hash-function
;; Dealing with single elements
hash-table-ref hash-table-ref/default hash-table-set! hash-table-delete!
hash-table-exists? hash-table-update! hash-table-update!/default
;; Dealing with the whole contents
hash-table-size hash-table-keys hash-table-values hash-table-walk
hash-table-fold hash-table->alist hash-table-copy hash-table-merge!
;; Hashing
hash string-hash string-ci-hash hash-by-identity
)
(import
(scheme base)
(scheme case-lambda)
(scheme char)
(scheme complex)
(scheme cxr)
(srfi 1)
(srfi 31))
(include "69.body.scm"))
;;; Copyright © Panu Kalliokoski (2005). All Rights Reserved.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define *default-bound* (- (expt 2 29) 3))
(define (%string-hash s ch-conv bound)
(let ((hash 31)
(len (string-length s)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hash bound))
(set! hash (modulo (+ (* 37 hash)
(char->integer (ch-conv (string-ref s index))))
*default-bound*)))))
(define (string-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash s (lambda (x) x) bound)))
(define (string-ci-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash s char-downcase bound)))
(define (symbol-hash s . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(%string-hash (symbol->string s) (lambda (x) x) bound)))
(define (hash obj . maybe-bound)
(let ((bound (if (null? maybe-bound) *default-bound* (car maybe-bound))))
(cond ((integer? obj) (modulo obj bound))
((string? obj) (string-hash obj bound))
((symbol? obj) (symbol-hash obj bound))
((real? obj) (modulo (+ (numerator obj) (denominator obj)) bound))
((number? obj)
(modulo (+ (hash (real-part obj)) (* 3 (hash (imag-part obj))))
bound))
((char? obj) (modulo (char->integer obj) bound))
((vector? obj) (vector-hash obj bound))
((pair? obj) (modulo (+ (hash (car obj)) (* 3 (hash (cdr obj))))
bound))
((null? obj) 0)
((not obj) 0)
((procedure? obj) (error "hash: procedures cannot be hashed" obj))
(else 1))))
(define hash-by-identity hash)
(define (vector-hash v bound)
(let ((hashvalue 571)
(len (vector-length v)))
(do ((index 0 (+ index 1)))
((>= index len) (modulo hashvalue bound))
(set! hashvalue (modulo (+ (* 257 hashvalue) (hash (vector-ref v index)))
*default-bound*)))))
(define %make-hash-node cons)
(define %hash-node-set-value! set-cdr!)
(define %hash-node-key car)
(define %hash-node-value cdr)
(define-record-type <srfi-hash-table>
(%make-hash-table size hash compare associate entries)
hash-table?
(size hash-table-size hash-table-set-size!)
(hash hash-table-hash-function)
(compare hash-table-equivalence-function)
(associate hash-table-association-function)
(entries hash-table-entries hash-table-set-entries!))
(define *default-table-size* 64)
(define (appropriate-hash-function-for comparison)
(or (and (eq? comparison eq?) hash-by-identity)
(and (eq? comparison string=?) string-hash)
(and (eq? comparison string-ci=?) string-ci-hash)
hash))
(define (make-hash-table . args)
(let* ((comparison (if (null? args) equal? (car args)))
(hash
(if (or (null? args) (null? (cdr args)))
(appropriate-hash-function-for comparison) (cadr args)))
(size
(if (or (null? args) (null? (cdr args)) (null? (cddr args)))
*default-table-size* (caddr args)))
(association
(or (and (eq? comparison eq?) assq)
(and (eq? comparison eqv?) assv)
(and (eq? comparison equal?) assoc)
(letrec
((associate
(lambda (val alist)
(cond ((null? alist) #f)
((comparison val (caar alist)) (car alist))
(else (associate val (cdr alist)))))))
associate))))
(%make-hash-table 0 hash comparison association (make-vector size '()))))
(define (make-hash-table-maker comp hash)
(lambda args (apply make-hash-table (cons comp (cons hash args)))))
(define make-symbol-hash-table
(make-hash-table-maker eq? symbol-hash))
(define make-string-hash-table
(make-hash-table-maker string=? string-hash))
(define make-string-ci-hash-table
(make-hash-table-maker string-ci=? string-ci-hash))
(define make-integer-hash-table
(make-hash-table-maker = modulo))
(define (%hash-table-hash hash-table key)
((hash-table-hash-function hash-table)
key (vector-length (hash-table-entries hash-table))))
(define (%hash-table-find entries associate hash key)
(associate key (vector-ref entries hash)))
(define (%hash-table-add! entries hash key value)
(vector-set! entries hash
(cons (%make-hash-node key value)
(vector-ref entries hash))))
(define (%hash-table-delete! entries compare hash key)
(let ((entrylist (vector-ref entries hash)))
(cond ((null? entrylist) #f)
((compare key (caar entrylist))
(vector-set! entries hash (cdr entrylist)) #t)
(else
(let loop ((current (cdr entrylist)) (previous entrylist))
(cond ((null? current) #f)
((compare key (caar current))
(set-cdr! previous (cdr current)) #t)
(else (loop (cdr current) current))))))))
(define (%hash-table-walk proc entries)
(do ((index (- (vector-length entries) 1) (- index 1)))
((< index 0)) (for-each proc (vector-ref entries index))))
(define (%hash-table-maybe-resize! hash-table)
(let* ((old-entries (hash-table-entries hash-table))
(hash-length (vector-length old-entries)))
(if (> (hash-table-size hash-table) hash-length)
(let* ((new-length (* 2 hash-length))
(new-entries (make-vector new-length '()))
(hash (hash-table-hash-function hash-table)))
(%hash-table-walk
(lambda (node)
(%hash-table-add! new-entries
(hash (%hash-node-key node) new-length)
(%hash-node-key node) (%hash-node-value node)))
old-entries)
(hash-table-set-entries! hash-table new-entries)))))
(define (hash-table-ref hash-table key . maybe-default)
(cond ((%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key)
=> %hash-node-value)
((null? maybe-default)
(error "hash-table-ref: no value associated with" key))
(else ((car maybe-default)))))
(define (hash-table-ref/default hash-table key default)
(hash-table-ref hash-table key (lambda () default)))
(define (hash-table-set! hash-table key value)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node) (%hash-node-set-value! node value)))
(else (%hash-table-add! entries hash key value)
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))
(define (hash-table-update! hash-table key function . maybe-default)
(let ((hash (%hash-table-hash hash-table key))
(entries (hash-table-entries hash-table)))
(cond ((%hash-table-find entries
(hash-table-association-function hash-table)
hash key)
=> (lambda (node)
(%hash-node-set-value!
node (function (%hash-node-value node)))))
((null? maybe-default)
(error "hash-table-update!: no value exists for key" key))
(else (%hash-table-add! entries hash key
(function ((car maybe-default))))
(hash-table-set-size! hash-table
(+ 1 (hash-table-size hash-table)))
(%hash-table-maybe-resize! hash-table)))))
(define (hash-table-update!/default hash-table key function default)
(hash-table-update! hash-table key function (lambda () default)))
(define (hash-table-delete! hash-table key)
(if (%hash-table-delete! (hash-table-entries hash-table)
(hash-table-equivalence-function hash-table)
(%hash-table-hash hash-table key) key)
(hash-table-set-size! hash-table (- (hash-table-size hash-table) 1))))
(define (hash-table-exists? hash-table key)
(and (%hash-table-find (hash-table-entries hash-table)
(hash-table-association-function hash-table)
(%hash-table-hash hash-table key) key) #t))
(define (hash-table-walk hash-table proc)
(%hash-table-walk
(lambda (node) (proc (%hash-node-key node) (%hash-node-value node)))
(hash-table-entries hash-table)))
(define (hash-table-fold hash-table f acc)
(hash-table-walk hash-table
(lambda (key value) (set! acc (f key value acc))))
acc)
(define (alist->hash-table alist . args)
(let* ((comparison (if (null? args) equal? (car args)))
(hash
(if (or (null? args) (null? (cdr args)))
(appropriate-hash-function-for comparison) (cadr args)))
(size
(if (or (null? args) (null? (cdr args)) (null? (cddr args)))
(max *default-table-size* (* 2 (length alist))) (caddr args)))
(hash-table (make-hash-table comparison hash size)))
(for-each
(lambda (elem)
(hash-table-update!/default
hash-table (car elem) (lambda (x) x) (cdr elem)))
alist)
hash-table))
(define (hash-table->alist hash-table)
(hash-table-fold hash-table
(lambda (key val acc) (cons (cons key val) acc)) '()))
(define (hash-table-copy hash-table)
(let ((new (make-hash-table (hash-table-equivalence-function hash-table)
(hash-table-hash-function hash-table)
(max *default-table-size*
(* 2 (hash-table-size hash-table))))))
(hash-table-walk hash-table
(lambda (key value) (hash-table-set! new key value)))
new))
(define (hash-table-merge! hash-table1 hash-table2)
(hash-table-walk
hash-table2
(lambda (key value) (hash-table-set! hash-table1 key value)))
hash-table1)
(define (hash-table-keys hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons key acc)) '()))
(define (hash-table-values hash-table)
(hash-table-fold hash-table (lambda (key val acc) (cons val acc)) '()))
(define-library (srfi 71)
(export
(rename srfi-letrec* letrec*)
(rename srfi-letrec letrec)
(rename srfi-let* let*)
(rename srfi-let let)
uncons
uncons-2
uncons-3
uncons-4
uncons-cons
unlist
unvector
)
(import
(rename (scheme base)
(let r5rs-let)
(letrec r5rs-letrec))
(scheme cxr))
(include "71.upstream.scm"))
;;; Copyright (c) 2005 Sebastian Egner.
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the ``Software''), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;; THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
; Reference implementation of SRFI-71 (generic part)
; Sebastian.Egner@philips.com, 20-May-2005, PLT 208
;
; In order to avoid conflicts with the existing let etc.
; the macros defined here are called srfi-let etc.,
; and they are defined in terms of r5rs-let etc.
; It is up to the actual implementation to save let/*/rec
; in r5rs-let/*/rec first and redefine let/*/rec
; by srfi-let/*/rec then.
;
; There is also a srfi-letrec* being defined (in view of R6RS.)
;
; Macros used internally are named i:<something>.
;
; Abbreviations for macro arguments:
; bs - <binding spec>
; b - component of a binding spec (values, <variable>, or <expression>)
; v - <variable>
; vr - <variable> for rest list
; x - <expression>
; t - newly introduced temporary variable
; vx - (<variable> <expression>)
; rec - flag if letrec is produced (and not let)
; cwv - call-with-value skeleton of the form (x formals)
; (call-with-values (lambda () x) (lambda formals /payload/))
; where /payload/ is of the form (let (vx ...) body1 body ...).
;
; Remark (*):
; We bind the variables of a letrec to i:undefined since there is
; no portable (R5RS) way of binding a variable to a values that
; raises an error when read uninitialized.
(define i:undefined 'undefined)
(define-syntax srfi-letrec* ; -> srfi-letrec
(syntax-rules ()
((srfi-letrec* () body1 body ...)
(srfi-letrec () body1 body ...))
((srfi-letrec* (bs) body1 body ...)
(srfi-letrec (bs) body1 body ...))
((srfi-letrec* (bs1 bs2 bs ...) body1 body ...)
(srfi-letrec (bs1) (srfi-letrec* (bs2 bs ...) body1 body ...)))))
(define-syntax srfi-letrec ; -> i:let
(syntax-rules ()
((srfi-letrec ((b1 b2 b ...) ...) body1 body ...)
(i:let "bs" #t () () (body1 body ...) ((b1 b2 b ...) ...)))))
(define-syntax srfi-let* ; -> srfi-let
(syntax-rules ()
((srfi-let* () body1 body ...)
(srfi-let () body1 body ...))
((srfi-let* (bs) body1 body ...)
(srfi-let (bs) body1 body ...))
((srfi-let* (bs1 bs2 bs ...) body1 body ...)
(srfi-let (bs1) (srfi-let* (bs2 bs ...) body1 body ...)))))
(define-syntax srfi-let ; -> i:let or i:named-let
(syntax-rules ()
((srfi-let ((b1 b2 b ...) ...) body1 body ...)
(i:let "bs" #f () () (body1 body ...) ((b1 b2 b ...) ...)))
((srfi-let tag ((b1 b2 b ...) ...) body1 body ...)
(i:named-let tag () (body1 body ...) ((b1 b2 b ...) ...)))))
(define-syntax i:let
(syntax-rules (values)
; (i:let "bs" rec (cwv ...) (vx ...) body (bs ...))
; processes the binding specs bs ... by adding call-with-values
; skeletons to cwv ... and bindings to vx ..., and afterwards
; wrapping the skeletons around the payload (let (vx ...) . body).
; no more bs to process -> wrap call-with-values skeletons
((i:let "bs" rec (cwv ...) vxs body ())
(i:let "wrap" rec vxs body cwv ...))
; recognize form1 without variable -> dummy binding for side-effects
((i:let "bs" rec cwvs (vx ...) body (((values) x) bs ...))
(i:let "bs" rec cwvs (vx ... (dummy (begin x #f))) body (bs ...)))
; recognize form1 with single variable -> just extend vx ...
((i:let "bs" rec cwvs (vx ...) body (((values v) x) bs ...))
(i:let "bs" rec cwvs (vx ... (v x)) body (bs ...)))
; recognize form1 without rest arg -> generate cwv
((i:let "bs" rec cwvs vxs body (((values v ...) x) bs ...))
(i:let "form1" rec cwvs vxs body (bs ...) (x ()) (values v ...)))
; recognize form1 with rest arg -> generate cwv
((i:let "bs" rec cwvs vxs body (((values . vs) x) bs ...))
(i:let "form1+" rec cwvs vxs body (bs ...) (x ()) (values . vs)))
; recognize form2 with single variable -> just extend vx ...
((i:let "bs" rec cwvs (vx ...) body ((v x) bs ...))
(i:let "bs" rec cwvs (vx ... (v x)) body (bs ...)))
; recognize form2 with >=2 variables -> transform to form1
((i:let "bs" rec cwvs vxs body ((b1 b2 b3 b ...) bs ...))
(i:let "form2" rec cwvs vxs body (bs ...) (b1 b2) (b3 b ...)))
; (i:let "form1" rec cwvs vxs body bss (x (t ...)) (values v1 v2 v ...))
; processes the variables in v1 v2 v ... adding them to (t ...)
; and producing a cwv when finished. There is not rest argument.
((i:let "form1" rec (cwv ...) vxs body bss (x ts) (values))
(i:let "bs" rec (cwv ... (x ts)) vxs body bss))
((i:let "form1" rec cwvs (vx ...) body bss (x (t ...)) (values v1 v ...))
(i:let "form1" rec cwvs (vx ... (v1 t1)) body bss (x (t ... t1)) (values v ...)))
; (i:let "form1+" rec cwvs vxs body bss (x (t ...)) (values v ... . vr))
; processes the variables in v ... . vr adding them to (t ...)
; and producing a cwv when finished. The rest arg is vr.
((i:let "form1+" rec cwvs (vx ...) body bss (x (t ...)) (values v1 v2 . vs))
(i:let "form1+" rec cwvs (vx ... (v1 t1)) body bss (x (t ... t1)) (values v2 . vs)))
((i:let "form1+" rec (cwv ...) (vx ...) body bss (x (t ...)) (values v1 . vr))
(i:let "bs" rec (cwv ... (x (t ... t1 . tr))) (vx ... (v1 t1) (vr tr)) body bss))
((i:let "form1+" rec (cwv ...) (vx ...) body bss (x ()) (values . vr))
(i:let "bs" rec (cwv ... (x tr)) (vx ... (vr tr)) body bss))
; (i:let "form2" rec cwvs vxs body bss (v ...) (b ... x))
; processes the binding items (b ... x) from form2 as in
; (v ... b ... x) into ((values v ... b ...) x), i.e. form1.
; Then call "bs" recursively.
((i:let "form2" rec cwvs vxs body (bs ...) (v ...) (x))
(i:let "bs" rec cwvs vxs body (((values v ...) x) bs ...)))
((i:let "form2" rec cwvs vxs body bss (v ...) (b1 b2 b ...))
(i:let "form2" rec cwvs vxs body bss (v ... b1) (b2 b ...)))
; (i:let "wrap" rec ((v x) ...) (body ...) cwv ...)
; wraps cwv ... around the payload generating the actual code.
; For letrec this is of course different than for let.
((i:let "wrap" #f vxs body)
(r5rs-let vxs . body))
((i:let "wrap" #f vxs body (x formals) cwv ...)
(call-with-values
(lambda () x)
(lambda formals (i:let "wrap" #f vxs body cwv ...))))
((i:let "wrap" #t vxs body)
(r5rs-letrec vxs . body))
((i:let "wrap" #t ((v t) ...) body cwv ...)
(r5rs-let ((v i:undefined) ...) ; (*)
(i:let "wraprec" ((v t) ...) body cwv ...)))
; (i:let "wraprec" ((v t) ...) body cwv ...)
; generate the inner code for a letrec. The variables v ...
; are the user-visible variables (bound outside), and t ...
; are the temporary variables bound by the cwv consumers.
((i:let "wraprec" ((v t) ...) (body ...))
(begin (set! v t) ... (r5rs-let () body ...)))
((i:let "wraprec" vxs body (x formals) cwv ...)
(call-with-values
(lambda () x)
(lambda formals (i:let "wraprec" vxs body cwv ...))))
))
(define-syntax i:named-let
(syntax-rules (values)
; (i:named-let tag (vx ...) body (bs ...))
; processes the binding specs bs ... by extracting the variable
; and expression, adding them to vx and turning the result into
; an ordinary named let.
((i:named-let tag vxs body ())
(r5rs-let tag vxs . body))
((i:named-let tag (vx ...) body (((values v) x) bs ...))
(i:named-let tag (vx ... (v x)) body (bs ...)))
((i:named-let tag (vx ...) body ((v x) bs ...))
(i:named-let tag (vx ... (v x)) body (bs ...)))))
; --- standard procedures ---
(define (uncons pair)
(values (car pair) (cdr pair)))
(define (uncons-2 list)
(values (car list) (cadr list) (cddr list)))
(define (uncons-3 list)
(values (car list) (cadr list) (caddr list) (cdddr list)))
(define (uncons-4 list)
(values (car list) (cadr list) (caddr list) (cadddr list) (cddddr list)))
(define (uncons-cons alist)
(values (caar alist) (cdar alist) (cdr alist)))
(define (unlist list)
(apply values list))
(define (unvector vector)
(apply values (vector->list vector)))
; --- standard macros ---
(define-syntax values->list
(syntax-rules ()
((values->list x)
(call-with-values (lambda () x) list))))
(define-syntax values->vector
(syntax-rules ()
((values->vector x)
(call-with-values (lambda () x) vector))))
(define-library (srfi 78)
(export
check
check-ec
check-report
check-set-mode!
check-reset!
check-passed?
)
(import
(scheme base)
(scheme cxr)
(scheme write)
(srfi 42))
(include "78.upstream.scm"))
; <PLAINTEXT>
; Copyright (c) 2005-2006 Sebastian Egner.
;
; Permission is hereby granted, free of charge, to any person obtaining
; a copy of this software and associated documentation files (the
; ``Software''), to deal in the Software without restriction, including
; without limitation the rights to use, copy, modify, merge, publish,
; distribute, sublicense, and/or sell copies of the Software, and to
; permit persons to whom the Software is furnished to do so, subject to
; the following conditions:
;
; The above copyright notice and this permission notice shall be
; included in all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;
; -----------------------------------------------------------------------
;
; Lightweight testing (reference implementation)
; ==============================================
;
; Sebastian.Egner@philips.com
; in R5RS + SRFI 23 (error) + SRFI 42 (comprehensions)
;
; history of this file:
; SE, 25-Oct-2004: first version based on code used in SRFIs 42 and 67
; SE, 19-Jan-2006: (arg ...) made optional in check-ec
;
; Naming convention "check:<identifier>" is used only internally.
; -- portability --
; PLT: (require (lib "23.ss" "srfi") (lib "42.ss" "srfi"))
; Scheme48: ,open srfi-23 srfi-42
; -- utilities --
(define check:write write)
; You can also use a pretty printer if you have one.
; However, the output might not improve for most cases
; because the pretty printers usually output a trailing
; newline.
; PLT: (require (lib "pretty.ss")) (define check:write pretty-print)
; Scheme48: ,open pp (define check:write p)
; -- mode --
(define check:mode #f)
(define (check-set-mode! mode)
(set! check:mode
(case mode
((off) 0)
((summary) 1)
((report-failed) 10)
((report) 100)
(else (error "unrecognized mode" mode)))))
(check-set-mode! 'report)
; -- state --
(define check:correct #f)
(define check:failed #f)
(define (check-reset!)
(set! check:correct 0)
(set! check:failed '()))
(define (check:add-correct!)
(set! check:correct (+ check:correct 1)))
(define (check:add-failed! expression actual-result expected-result)
(set! check:failed
(cons (list expression actual-result expected-result)
check:failed)))
(check-reset!)
; -- reporting --
(define (check:report-expression expression)
(newline)
(check:write expression)
(display " => "))
(define (check:report-actual-result actual-result)
(check:write actual-result)
(display " ; "))
(define (check:report-correct cases)
(display "correct")
(if (not (= cases 1))
(begin (display " (")
(display cases)
(display " cases checked)")))
(newline))
(define (check:report-failed expected-result)
(display "*** failed ***")
(newline)
(display " ; expected result: ")
(check:write expected-result)
(newline))
(define (check-report)
(if (>= check:mode 1)
(begin
(newline)
(display "; *** checks *** : ")
(display check:correct)
(display " correct, ")
(display (length check:failed))
(display " failed.")
(if (or (null? check:failed) (<= check:mode 1))
(newline)
(let* ((w (car (reverse check:failed)))
(expression (car w))
(actual-result (cadr w))
(expected-result (caddr w)))
(display " First failed example:")
(newline)
(check:report-expression expression)
(check:report-actual-result actual-result)
(check:report-failed expected-result))))))
(define (check-passed? expected-total-count)
(and (= (length check:failed) 0)
(= check:correct expected-total-count)))
; -- simple checks --
(define (check:proc expression thunk equal expected-result)
(case check:mode
((0) #f)
((1)
(let ((actual-result (thunk)))
(if (equal actual-result expected-result)
(check:add-correct!)
(check:add-failed! expression actual-result expected-result))))
((10)
(let ((actual-result (thunk)))
(if (equal actual-result expected-result)
(check:add-correct!)
(begin
(check:report-expression expression)
(check:report-actual-result actual-result)
(check:report-failed expected-result)
(check:add-failed! expression actual-result expected-result)))))
((100)
(check:report-expression expression)
(let ((actual-result (thunk)))
(check:report-actual-result actual-result)
(if (equal actual-result expected-result)
(begin (check:report-correct 1)
(check:add-correct!))
(begin (check:report-failed expected-result)
(check:add-failed! expression
actual-result
expected-result)))))
(else (error "unrecognized check:mode" check:mode)))
(if #f #f))
(define-syntax check
(syntax-rules (=>)
((check expr => expected)
(check expr (=> equal?) expected))
((check expr (=> equal) expected)
(if (>= check:mode 1)
(check:proc 'expr (lambda () expr) equal expected)))))
; -- parametric checks --
(define (check:proc-ec w)
(let ((correct? (car w))
(expression (cadr w))
(actual-result (caddr w))
(expected-result (cadddr w))
(cases (car (cddddr w))))
(if correct?
(begin (if (>= check:mode 100)
(begin (check:report-expression expression)
(check:report-actual-result actual-result)
(check:report-correct cases)))
(check:add-correct!))
(begin (if (>= check:mode 10)
(begin (check:report-expression expression)
(check:report-actual-result actual-result)
(check:report-failed expected-result)))
(check:add-failed! expression
actual-result
expected-result)))))
(define-syntax check-ec:make
(syntax-rules (=>)
((check-ec:make qualifiers expr (=> equal) expected (arg ...))
(if (>= check:mode 1)
(check:proc-ec
(let ((cases 0))
(let ((w (first-ec
#f
qualifiers
(\:let equal-pred equal)
(\:let expected-result expected)
(\:let actual-result
(let ((arg arg) ...) ; (*)
expr))
(begin (set! cases (+ cases 1)))
(if (not (equal-pred actual-result expected-result)))
(list (list 'let (list (list 'arg arg) ...) 'expr)
actual-result
expected-result
cases))))
(if w
(cons #f w)
(list #t
'(check-ec qualifiers
expr (=> equal)
expected (arg ...))
(if #f #f)
(if #f #f)
cases)))))))))
; (*) is a compile-time check that (arg ...) is a list
; of pairwise disjoint bound variables at this point.
(define-syntax check-ec
(syntax-rules (nested =>)
((check-ec expr => expected)
(check-ec:make (nested) expr (=> equal?) expected ()))
((check-ec expr (=> equal) expected)
(check-ec:make (nested) expr (=> equal) expected ()))
((check-ec expr => expected (arg ...))
(check-ec:make (nested) expr (=> equal?) expected (arg ...)))
((check-ec expr (=> equal) expected (arg ...))
(check-ec:make (nested) expr (=> equal) expected (arg ...)))
((check-ec qualifiers expr => expected)
(check-ec:make qualifiers expr (=> equal?) expected ()))
((check-ec qualifiers expr (=> equal) expected)
(check-ec:make qualifiers expr (=> equal) expected ()))
((check-ec qualifiers expr => expected (arg ...))
(check-ec:make qualifiers expr (=> equal?) expected (arg ...)))
((check-ec qualifiers expr (=> equal) expected (arg ...))
(check-ec:make qualifiers expr (=> equal) expected (arg ...)))
((check-ec (nested q1 ...) q etc ...)
(check-ec (nested q1 ... q) etc ...))
((check-ec q1 q2 etc ...)
(check-ec (nested q1 q2) etc ...))))
(import (scheme base)
(scheme eval)
(scheme file)
(srfi 1)
(srfi 48)
(srfi 64))
(test-runner-current (test-runner-simple "tests.log"))
(test-begin "SRFI")
(for-each
(lambda (n)
(let ((srfi-n (string->symbol (format #f "srfi-~s" n)))
(file-name (format #f "srfi-tests/srfi-~s.sld" n))
(test-name (format #f "SRFI-~s" n)))
(when (file-exists? file-name)
(test-assert test-name
(guard (err (else #f))
(eval '(run-tests) (environment `(srfi-tests ,srfi-n))))))))
(iota 200))
(test-end "SRFI")
(test-exit)
;;; SRFI 13 string library reference implementation -*- Scheme -*-
;;; Olin Shivers 7/2000
;;;
;;; Copyright (c) 1988-1994 Massachusetts Institute of Technology.
;;; Copyright (c) 1998, 1999, 2000 Olin Shivers. All rights reserved.
;;; The details of the copyrights appear at the end of the file. Short
;;; summary: BSD-style open source.
;;; Exports:
;;; string-map string-map!
;;; string-fold string-unfold
;;; string-fold-right string-unfold-right
;;; string-tabulate string-for-each string-for-each-index
;;; string-every string-any
;;; string-hash string-hash-ci
;;; string-compare string-compare-ci
;;; string= string< string> string<= string>= string<>
;;; string-ci= string-ci< string-ci> string-ci<= string-ci>= string-ci<>
;;; string-downcase string-upcase string-titlecase
;;; string-downcase! string-upcase! string-titlecase!
;;; string-take string-take-right
;;; string-drop string-drop-right
;;; string-pad string-pad-right
;;; string-trim string-trim-right string-trim-both
;;; string-filter string-delete
;;; string-index string-index-right
;;; string-skip string-skip-right
;;; string-count
;;; string-prefix-length string-prefix-length-ci
;;; string-suffix-length string-suffix-length-ci
;;; string-prefix? string-prefix-ci?
;;; string-suffix? string-suffix-ci?
;;; string-contains string-contains-ci
;;; string-copy! substring/shared
;;; string-reverse string-reverse! reverse-list->string
;;; string-concatenate string-concatenate/shared string-concatenate-reverse
;;; string-append/shared
;;; xsubstring string-xcopy!
;;; string-null?
;;; string-join
;;; string-tokenize
;;; string-replace
;;;
;;; R5RS extended:
;;; string->list string-copy string-fill!
;;;
;;; R5RS re-exports:
;;; string? make-string string-length string-ref string-set!
;;;
;;; R5RS re-exports (also defined here but commented-out):
;;; string string-append list->string
;;;
;;; Low-level routines:
;;; make-kmp-restart-vector string-kmp-partial-search kmp-step
;;; string-parse-start+end
;;; string-parse-final-start+end
;;; let-string-start+end
;;; check-substring-spec
;;; substring-spec-ok?
;;; Imports
;;; This is a fairly large library. While it was written for portability, you
;;; must be aware of its dependencies in order to run it in a given scheme
;;; implementation. Here is a complete list of the dependencies it has and the
;;; assumptions it makes beyond stock R5RS Scheme:
;;;
;;; This code has the following non-R5RS dependencies:
;;; - (RECEIVE (var ...) mv-exp body ...) multiple-value binding macro;
;;;
;;; - Various imports from the char-set library for the routines that can
;;; take char-set arguments;
;;;
;;; - An n-ary ERROR procedure;
;;;
;;; - BITWISE-AND for the hash functions;
;;;
;;; - A simple CHECK-ARG procedure for checking parameter values; it is
;;; (lambda (pred val proc)
;;; (if (pred val) val (error "Bad arg" val pred proc)))
;;;
;;; - #\:OPTIONAL and LET-OPTIONALS* macros for parsing, defaulting &
;;; type-checking optional parameters from a rest argument;
;;;
;;; - CHAR-CASED? and CHAR-TITLECASE for the STRING-TITLECASE &
;;; STRING-TITLECASE! procedures. The former returns true iff a character is
;;; one that has case distinctions; in ASCII it returns true on a-z and A-Z.
;;; CHAR-TITLECASE is analagous to CHAR-UPCASE and CHAR-DOWNCASE. In ASCII &
;;; Latin-1, it is the same as CHAR-UPCASE.
;;;
;;; The code depends upon a small set of core string primitives from R5RS:
;;; MAKE-STRING STRING-REF STRING-SET! STRING? STRING-LENGTH SUBSTRING
;;; (Actually, SUBSTRING is not a primitive, but we assume that an
;;; implementation's native version is probably faster than one we could
;;; define, so we import it from R5RS.)
;;;
;;; The code depends upon a small set of R5RS character primitives:
;;; char? char=? char-ci=? char<? char-ci<?
;;; char-upcase char-downcase
;;; char->integer (for the hash functions)
;;;
;;; We assume the following:
;;; - CHAR-DOWNCASE o CHAR-UPCASE = CHAR-DOWNCASE
;;; - CHAR-CI=? is equivalent to
;;; (lambda (c1 c2) (char=? (char-downcase (char-upcase c1))
;;; (char-downcase (char-upcase c2))))
;;; - CHAR-UPCASE, CHAR-DOWNCASE and CHAR-TITLECASE are locale-insensitive
;;; and consistent with Unicode's 1-1 char-mapping spec.
;;; These things are typically true, but if not, you would need to modify
;;; the case-mapping and case-insensitive routines.
;;; Enough introductory blather. On to the source code. (But see the end of
;;; the file for further notes on porting & performance tuning.)
;;; Support for START/END substring specs
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This macro parses optional start/end arguments from arg lists, defaulting
;;; them to 0/(string-length s), and checks them for correctness.
(define-syntax let-string-start+end
(syntax-rules ()
((let-string-start+end (start end) proc s-exp args-exp body ...)
(receive (start end) (string-parse-final-start+end proc s-exp args-exp)
body ...))
((let-string-start+end (start end rest) proc s-exp args-exp body ...)
(receive (rest start end) (string-parse-start+end proc s-exp args-exp)
body ...))))
;;; This one parses out a *pair* of final start/end indices.
;;; Not exported; for internal use.
(define-syntax let-string-start+end2
(syntax-rules ()
((l-s-s+e2 (start1 end1 start2 end2) proc s1 s2 args body ...)
(let ((procv proc)) ; Make sure PROC is only evaluated once.
(let-string-start+end (start1 end1 rest) procv s1 args
(let-string-start+end (start2 end2) procv s2 rest
body ...))))))
;;; Returns three values: rest start end
(define (string-parse-start+end proc s args)
(if (not (string? s)) (error "Non-string value" proc s))
(let ((slen (string-length s)))
(if (pair? args)
(let ((start (car args))
(args (cdr args)))
(if (and (integer? start) (exact? start) (>= start 0))
(receive (end args)
(if (pair? args)
(let ((end (car args))
(args (cdr args)))
(if (and (integer? end) (exact? end) (<= end slen))
(values end args)
(error "Illegal substring END spec" proc end s)))
(values slen args))
(if (<= start end) (values args start end)
(error "Illegal substring START/END spec"
proc start end s)))
(error "Illegal substring START spec" proc start s)))
(values '() 0 slen))))
(define (string-parse-final-start+end proc s args)
(receive (rest start end) (string-parse-start+end proc s args)
(if (pair? rest) (error "Extra arguments to procedure" proc rest)
(values start end))))
(define (substring-spec-ok? s start end)
(and (string? s)
(integer? start)
(exact? start)
(integer? end)
(exact? end)
(<= 0 start)
(<= start end)
(<= end (string-length s))))
(define (check-substring-spec proc s start end)
(if (not (substring-spec-ok? s start end))
(error "Illegal substring spec." proc s start end)))
;;; Defined by R5RS, so commented out here.
;(define (string . chars)
; (let* ((len (length chars))
; (ans (make-string len)))
; (do ((i 0 (+ i 1))
; (chars chars (cdr chars)))
; ((>= i len))
; (string-set! ans i (car chars)))
; ans))
;
;(define (string . chars) (string-unfold null? car cdr chars))
;;; substring/shared S START [END]
;;; string-copy S [START END]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; All this goop is just arg parsing & checking surrounding a call to the
;;; actual primitive, %SUBSTRING/SHARED.
(define (substring/shared s start . maybe-end)
(check-arg string? s substring/shared)
(let ((slen (string-length s)))
(check-arg (lambda (start) (and (integer? start) (exact? start) (<= 0 start)))
start substring/shared)
(%substring/shared s start
(#\:optional maybe-end slen
(lambda (end) (and (integer? end)
(exact? end)
(<= start end)
(<= end slen)))))))
;;; Split out so that other routines in this library can avoid arg-parsing
;;; overhead for END parameter.
(define (%substring/shared s start end)
(if (and (zero? start) (= end (string-length s))) s
(substring s start end)))
(define (string-copy s . maybe-start+end)
(let-string-start+end (start end) string-copy s maybe-start+end
(substring s start end)))
;This library uses the R5RS SUBSTRING, but doesn't export it.
;Here is a definition, just for completeness.
;(define (substring s start end)
; (check-substring-spec substring s start end)
; (let* ((slen (- end start))
; (ans (make-string slen)))
; (do ((i 0 (+ i 1))
; (j start (+ j 1)))
; ((>= i slen) ans)
; (string-set! ans i (string-ref s j)))))
;;; Basic iterators and other higher-order abstractions
;;; (string-map proc s [start end])
;;; (string-map! proc s [start end])
;;; (string-fold kons knil s [start end])
;;; (string-fold-right kons knil s [start end])
;;; (string-unfold p f g seed [base make-final])
;;; (string-unfold-right p f g seed [base make-final])
;;; (string-for-each proc s [start end])
;;; (string-for-each-index proc s [start end])
;;; (string-every char-set/char/pred s [start end])
;;; (string-any char-set/char/pred s [start end])
;;; (string-tabulate proc len)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; You want compiler support for high-level transforms on fold and unfold ops.
;;; You'd at least like a lot of inlining for clients of these procedures.
;;; Don't hold your breath.
(define (string-map proc s . maybe-start+end)
(check-arg procedure? proc string-map)
(let-string-start+end (start end) string-map s maybe-start+end
(%string-map proc s start end)))
(define (%string-map proc s start end) ; Internal utility
(let* ((len (- end start))
(ans (make-string len)))
(do ((i (- end 1) (- i 1))
(j (- len 1) (- j 1)))
((< j 0))
(string-set! ans j (proc (string-ref s i))))
ans))
(define (string-map! proc s . maybe-start+end)
(check-arg procedure? proc string-map!)
(let-string-start+end (start end) string-map! s maybe-start+end
(%string-map! proc s start end)))
(define (%string-map! proc s start end)
(do ((i (- end 1) (- i 1)))
((< i start))
(string-set! s i (proc (string-ref s i)))))
(define (string-fold kons knil s . maybe-start+end)
(check-arg procedure? kons string-fold)
(let-string-start+end (start end) string-fold s maybe-start+end
(let lp ((v knil) (i start))
(if (< i end) (lp (kons (string-ref s i) v) (+ i 1))
v))))
(define (string-fold-right kons knil s . maybe-start+end)
(check-arg procedure? kons string-fold-right)
(let-string-start+end (start end) string-fold-right s maybe-start+end
(let lp ((v knil) (i (- end 1)))
(if (>= i start) (lp (kons (string-ref s i) v) (- i 1))
v))))
;;; (string-unfold p f g seed [base make-final])
;;; This is the fundamental constructor for strings.
;;; - G is used to generate a series of "seed" values from the initial seed:
;;; SEED, (G SEED), (G^2 SEED), (G^3 SEED), ...
;;; - P tells us when to stop -- when it returns true when applied to one
;;; of these seed values.
;;; - F maps each seed value to the corresponding character
;;; in the result string. These chars are assembled into the
;;; string in a left-to-right order.
;;; - BASE is the optional initial/leftmost portion of the constructed string;
;;; it defaults to the empty string "".
;;; - MAKE-FINAL is applied to the terminal seed value (on which P returns
;;; true) to produce the final/rightmost portion of the constructed string.
;;; It defaults to (LAMBDA (X) "").
;;;
;;; In other words, the following (simple, inefficient) definition holds:
;;; (define (string-unfold p f g seed base make-final)
;;; (string-append base
;;; (let recur ((seed seed))
;;; (if (p seed) (make-final seed)
;;; (string-append (string (f seed))
;;; (recur (g seed)))))))
;;;
;;; STRING-UNFOLD is a fairly powerful constructor -- you can use it to
;;; reverse a string, copy a string, convert a list to a string, read
;;; a port into a string, and so forth. Examples:
;;; (port->string port) =
;;; (string-unfold (compose eof-object? peek-char)
;;; read-char values port)
;;;
;;; (list->string lis) = (string-unfold null? car cdr lis)
;;;
;;; (tabulate-string f size) = (string-unfold (lambda (i) (= i size)) f add1 0)
;;; A problem with the following simple formulation is that it pushes one
;;; stack frame for every char in the result string -- an issue if you are
;;; using it to read a 100kchar string. So we don't use it -- but I include
;;; it to give a clear, straightforward description of what the function
;;; does.
;(define (string-unfold p f g seed base make-final)
; (let ((ans (let recur ((seed seed) (i (string-length base)))
; (if (p seed)
; (let* ((final (make-final seed))
; (ans (make-string (+ i (string-length final)))))
; (string-copy! ans i final)
; ans)
;
; (let* ((c (f seed))
; (s (recur (g seed) (+ i 1))))
; (string-set! s i c)
; s)))))
; (string-copy! ans 0 base)
; ans))
;;; The strategy is to allocate a series of chunks into which we stash the
;;; chars as we generate them. Chunk size goes up in powers of two starting
;;; with 40 and levelling out at 4k, i.e.
;;; 40 40 80 160 320 640 1280 2560 4096 4096 4096 4096 4096...
;;; This should work pretty well for short strings, 1-line (80 char) strings,
;;; and longer ones. When done, we allocate an answer string and copy the
;;; chars over from the chunk buffers.
(define (string-unfold p f g seed . base+make-final)
(check-arg procedure? p string-unfold)
(check-arg procedure? f string-unfold)
(check-arg procedure? g string-unfold)
(let-optionals* base+make-final
((base "" (string? base))
(make-final (lambda (x) "") (procedure? make-final)))
(let lp ((chunks '()) ; Previously filled chunks
(nchars 0) ; Number of chars in CHUNKS
(chunk (make-string 40)) ; Current chunk into which we write
(chunk-len 40)
(i 0) ; Number of chars written into CHUNK
(seed seed))
(let lp2 ((i i) (seed seed))
(if (not (p seed))
(let ((c (f seed))
(seed (g seed)))
(if (< i chunk-len)
(begin (string-set! chunk i c)
(lp2 (+ i 1) seed))
(let* ((nchars2 (+ chunk-len nchars))
(chunk-len2 (min 4096 nchars2))
(new-chunk (make-string chunk-len2)))
(string-set! new-chunk 0 c)
(lp (cons chunk chunks) (+ nchars chunk-len)
new-chunk chunk-len2 1 seed))))
;; We're done. Make the answer string & install the bits.
(let* ((final (make-final seed))
(flen (string-length final))
(base-len (string-length base))
(j (+ base-len nchars i))
(ans (make-string (+ j flen))))
(%string-copy! ans j final 0 flen) ; Install FINAL.
(let ((j (- j i)))
(%string-copy! ans j chunk 0 i) ; Install CHUNK[0,I).
(let lp ((j j) (chunks chunks)) ; Install CHUNKS.
(if (pair? chunks)
(let* ((chunk (car chunks))
(chunks (cdr chunks))
(chunk-len (string-length chunk))
(j (- j chunk-len)))
(%string-copy! ans j chunk 0 chunk-len)
(lp j chunks)))))
(%string-copy! ans 0 base 0 base-len) ; Install BASE.
ans))))))
(define (string-unfold-right p f g seed . base+make-final)
(let-optionals* base+make-final
((base "" (string? base))
(make-final (lambda (x) "") (procedure? make-final)))
(let lp ((chunks '()) ; Previously filled chunks
(nchars 0) ; Number of chars in CHUNKS
(chunk (make-string 40)) ; Current chunk into which we write
(chunk-len 40)
(i 40) ; Number of chars available in CHUNK
(seed seed))
(let lp2 ((i i) (seed seed)) ; Fill up CHUNK from right
(if (not (p seed)) ; to left.
(let ((c (f seed))
(seed (g seed)))
(if (> i 0)
(let ((i (- i 1)))
(string-set! chunk i c)
(lp2 i seed))
(let* ((nchars2 (+ chunk-len nchars))
(chunk-len2 (min 4096 nchars2))
(new-chunk (make-string chunk-len2))
(i (- chunk-len2 1)))
(string-set! new-chunk i c)
(lp (cons chunk chunks) (+ nchars chunk-len)
new-chunk chunk-len2 i seed))))
;; We're done. Make the answer string & install the bits.
(let* ((final (make-final seed))
(flen (string-length final))
(base-len (string-length base))
(chunk-used (- chunk-len i))
(j (+ base-len nchars chunk-used))
(ans (make-string (+ j flen))))
(%string-copy! ans 0 final 0 flen) ; Install FINAL.
(%string-copy! ans flen chunk i chunk-len); Install CHUNK[I,).
(let lp ((j (+ flen chunk-used)) ; Install CHUNKS.
(chunks chunks))
(if (pair? chunks)
(let* ((chunk (car chunks))
(chunks (cdr chunks))
(chunk-len (string-length chunk)))
(%string-copy! ans j chunk 0 chunk-len)
(lp (+ j chunk-len) chunks))
(%string-copy! ans j base 0 base-len))); Install BASE.
ans))))))
(define (string-for-each proc s . maybe-start+end)
(check-arg procedure? proc string-for-each)
(let-string-start+end (start end) string-for-each s maybe-start+end
(let lp ((i start))
(if (< i end)
(begin (proc (string-ref s i))
(lp (+ i 1)))))))
(define (string-for-each-index proc s . maybe-start+end)
(check-arg procedure? proc string-for-each-index)
(let-string-start+end (start end) string-for-each-index s maybe-start+end
(let lp ((i start))
(if (< i end) (begin (proc i) (lp (+ i 1)))))))
(define (string-every criterion s . maybe-start+end)
(let-string-start+end (start end) string-every s maybe-start+end
(cond ((char? criterion)
(let lp ((i start))
(or (>= i end)
(and (char=? criterion (string-ref s i))
(lp (+ i 1))))))
((char-set? criterion)
(let lp ((i start))
(or (>= i end)
(and (char-set-contains? criterion (string-ref s i))
(lp (+ i 1))))))
((procedure? criterion) ; Slightly funky loop so that
(or (= start end) ; final (PRED S[END-1]) call
(let lp ((i start)) ; is a tail call.
(let ((c (string-ref s i))
(i1 (+ i 1)))
(if (= i1 end) (criterion c) ; Tail call.
(and (criterion c) (lp i1)))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-every criterion)))))
(define (string-any criterion s . maybe-start+end)
(let-string-start+end (start end) string-any s maybe-start+end
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(or (char=? criterion (string-ref s i))
(lp (+ i 1))))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(or (char-set-contains? criterion (string-ref s i))
(lp (+ i 1))))))
((procedure? criterion) ; Slightly funky loop so that
(and (< start end) ; final (PRED S[END-1]) call
(let lp ((i start)) ; is a tail call.
(let ((c (string-ref s i))
(i1 (+ i 1)))
(if (= i1 end) (criterion c) ; Tail call
(or (criterion c) (lp i1)))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-any criterion)))))
(define (string-tabulate proc len)
(check-arg procedure? proc string-tabulate)
(check-arg (lambda (val) (and (integer? val) (exact? val) (<= 0 val)))
len string-tabulate)
(let ((s (make-string len)))
(do ((i (- len 1) (- i 1)))
((< i 0))
(string-set! s i (proc i)))
s))
;;; string-prefix-length[-ci] s1 s2 [start1 end1 start2 end2]
;;; string-suffix-length[-ci] s1 s2 [start1 end1 start2 end2]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Find the length of the common prefix/suffix.
;;; It is not required that the two substrings passed be of equal length.
;;; This was microcode in MIT Scheme -- a very tightly bummed primitive.
;;; %STRING-PREFIX-LENGTH is the core routine of all string-comparisons,
;;; so should be as tense as possible.
(define (%string-prefix-length s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
(if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
delta
(let lp ((i start1) (j start2)) ; Regular path
(if (or (>= i end1)
(not (char=? (string-ref s1 i)
(string-ref s2 j))))
(- i start1)
(lp (+ i 1) (+ j 1)))))))
(define (%string-suffix-length s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(start1 (- end1 delta)))
(if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
delta
(let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
(if (or (< i start1)
(not (char=? (string-ref s1 i)
(string-ref s2 j))))
(- (- end1 i) 1)
(lp (- i 1) (- j 1)))))))
(define (%string-prefix-length-ci s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(end1 (+ start1 delta)))
(if (and (eq? s1 s2) (= start1 start2)) ; EQ fast path
delta
(let lp ((i start1) (j start2)) ; Regular path
(if (or (>= i end1)
(not (char-ci=? (string-ref s1 i)
(string-ref s2 j))))
(- i start1)
(lp (+ i 1) (+ j 1)))))))
(define (%string-suffix-length-ci s1 start1 end1 s2 start2 end2)
(let* ((delta (min (- end1 start1) (- end2 start2)))
(start1 (- end1 delta)))
(if (and (eq? s1 s2) (= end1 end2)) ; EQ fast path
delta
(let lp ((i (- end1 1)) (j (- end2 1))) ; Regular path
(if (or (< i start1)
(not (char-ci=? (string-ref s1 i)
(string-ref s2 j))))
(- (- end1 i) 1)
(lp (- i 1) (- j 1)))))))
(define (string-prefix-length s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-prefix-length s1 s2 maybe-starts+ends
(%string-prefix-length s1 start1 end1 s2 start2 end2)))
(define (string-suffix-length s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-suffix-length s1 s2 maybe-starts+ends
(%string-suffix-length s1 start1 end1 s2 start2 end2)))
(define (string-prefix-length-ci s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-prefix-length-ci s1 s2 maybe-starts+ends
(%string-prefix-length-ci s1 start1 end1 s2 start2 end2)))
(define (string-suffix-length-ci s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-suffix-length-ci s1 s2 maybe-starts+ends
(%string-suffix-length-ci s1 start1 end1 s2 start2 end2)))
;;; string-prefix? s1 s2 [start1 end1 start2 end2]
;;; string-suffix? s1 s2 [start1 end1 start2 end2]
;;; string-prefix-ci? s1 s2 [start1 end1 start2 end2]
;;; string-suffix-ci? s1 s2 [start1 end1 start2 end2]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; These are all simple derivatives of the previous counting funs.
(define (string-prefix? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-prefix? s1 s2 maybe-starts+ends
(%string-prefix? s1 start1 end1 s2 start2 end2)))
(define (string-suffix? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-suffix? s1 s2 maybe-starts+ends
(%string-suffix? s1 start1 end1 s2 start2 end2)))
(define (string-prefix-ci? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-prefix-ci? s1 s2 maybe-starts+ends
(%string-prefix-ci? s1 start1 end1 s2 start2 end2)))
(define (string-suffix-ci? s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-suffix-ci? s1 s2 maybe-starts+ends
(%string-suffix-ci? s1 start1 end1 s2 start2 end2)))
;;; Here are the internal routines that do the real work.
(define (%string-prefix? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= (%string-prefix-length s1 start1 end1
s2 start2 end2)
len1))))
(define (%string-suffix? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= len1 (%string-suffix-length s1 start1 end1
s2 start2 end2)))))
(define (%string-prefix-ci? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= len1 (%string-prefix-length-ci s1 start1 end1
s2 start2 end2)))))
(define (%string-suffix-ci? s1 start1 end1 s2 start2 end2)
(let ((len1 (- end1 start1)))
(and (<= len1 (- end2 start2)) ; Quick check
(= len1 (%string-suffix-length-ci s1 start1 end1
s2 start2 end2)))))
;;; string-compare s1 s2 proc< proc= proc> [start1 end1 start2 end2]
;;; string-compare-ci s1 s2 proc< proc= proc> [start1 end1 start2 end2]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Primitive string-comparison functions.
;;; Continuation order is different from MIT Scheme.
;;; Continuations are applied to s1's mismatch index;
;;; in the case of equality, this is END1.
(define (%string-compare s1 start1 end1 s2 start2 end2
proc< proc= proc>)
(let ((size1 (- end1 start1))
(size2 (- end2 start2)))
(let ((match (%string-prefix-length s1 start1 end1 s2 start2 end2)))
(if (= match size1)
((if (= match size2) proc= proc<) end1)
((if (= match size2)
proc>
(if (char<? (string-ref s1 (+ start1 match))
(string-ref s2 (+ start2 match)))
proc< proc>))
(+ match start1))))))
(define (%string-compare-ci s1 start1 end1 s2 start2 end2
proc< proc= proc>)
(let ((size1 (- end1 start1))
(size2 (- end2 start2)))
(let ((match (%string-prefix-length-ci s1 start1 end1 s2 start2 end2)))
(if (= match size1)
((if (= match size2) proc= proc<) end1)
((if (= match size2) proc>
(if (char-ci<? (string-ref s1 (+ start1 match))
(string-ref s2 (+ start2 match)))
proc< proc>))
(+ start1 match))))))
(define (string-compare s1 s2 proc< proc= proc> . maybe-starts+ends)
(check-arg procedure? proc< string-compare)
(check-arg procedure? proc= string-compare)
(check-arg procedure? proc> string-compare)
(let-string-start+end2 (start1 end1 start2 end2)
string-compare s1 s2 maybe-starts+ends
(%string-compare s1 start1 end1 s2 start2 end2 proc< proc= proc>)))
(define (string-compare-ci s1 s2 proc< proc= proc> . maybe-starts+ends)
(check-arg procedure? proc< string-compare-ci)
(check-arg procedure? proc= string-compare-ci)
(check-arg procedure? proc> string-compare-ci)
(let-string-start+end2 (start1 end1 start2 end2)
string-compare-ci s1 s2 maybe-starts+ends
(%string-compare-ci s1 start1 end1 s2 start2 end2 proc< proc= proc>)))
;;; string= string<> string-ci= string-ci<>
;;; string< string> string-ci< string-ci>
;;; string<= string>= string-ci<= string-ci>=
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simple definitions in terms of the previous comparison funs.
;;; I sure hope the %STRING-COMPARE calls get integrated.
(define (string= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string= s1 s2 maybe-starts+ends
(and (= (- end1 start1) (- end2 start2)) ; Quick filter
(or (and (eq? s1 s2) (= start1 start2)) ; Fast path
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
values
(lambda (i) #f))))))
(define (string<> s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string<> s1 s2 maybe-starts+ends
(or (not (= (- end1 start1) (- end2 start2))) ; Fast path
(and (not (and (eq? s1 s2) (= start1 start2))) ; Quick filter
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
values
(lambda (i) #f)
values)))))
(define (string< s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string< s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(< end1 end2)
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
values
(lambda (i) #f)
(lambda (i) #f)))))
(define (string> s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string> s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(> end1 end2)
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
(lambda (i) #f)
values))))
(define (string<= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string<= s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(<= end1 end2)
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
values
values
(lambda (i) #f)))))
(define (string>= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string>= s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(>= end1 end2)
(%string-compare s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
values
values))))
(define (string-ci= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci= s1 s2 maybe-starts+ends
(and (= (- end1 start1) (- end2 start2)) ; Quick filter
(or (and (eq? s1 s2) (= start1 start2)) ; Fast path
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
values
(lambda (i) #f))))))
(define (string-ci<> s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci<> s1 s2 maybe-starts+ends
(or (not (= (- end1 start1) (- end2 start2))) ; Fast path
(and (not (and (eq? s1 s2) (= start1 start2))) ; Quick filter
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
values
(lambda (i) #f)
values)))))
(define (string-ci< s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci< s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(< end1 end2)
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
values
(lambda (i) #f)
(lambda (i) #f)))))
(define (string-ci> s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci> s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(> end1 end2)
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
(lambda (i) #f)
values))))
(define (string-ci<= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci<= s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(<= end1 end2)
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
values
values
(lambda (i) #f)))))
(define (string-ci>= s1 s2 . maybe-starts+ends)
(let-string-start+end2 (start1 end1 start2 end2)
string-ci>= s1 s2 maybe-starts+ends
(if (and (eq? s1 s2) (= start1 start2)) ; Fast path
(>= end1 end2)
(%string-compare-ci s1 start1 end1 s2 start2 end2 ; Real test
(lambda (i) #f)
values
values))))
;;; Hash
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Compute (c + 37 c + 37^2 c + ...) modulo BOUND, with sleaze thrown in
;;; to keep the intermediate values small. (We do the calculation with just
;;; enough bits to represent BOUND, masking off high bits at each step in
;;; calculation. If this screws up any important properties of the hash
;;; function I'd like to hear about it. -Olin)
;;;
;;; If you keep BOUND small enough, the intermediate calculations will
;;; always be fixnums. How small is dependent on the underlying Scheme system;
;;; we use a default BOUND of 2^22 = 4194304, which should hack it in
;;; Schemes that give you at least 29 signed bits for fixnums. The core
;;; calculation that you don't want to overflow is, worst case,
;;; (+ 65535 (* 37 (- bound 1)))
;;; where 65535 is the max character code. Choose the default BOUND to be the
;;; biggest power of two that won't cause this expression to fixnum overflow,
;;; and everything will be copacetic.
(define (%string-hash s char->int bound start end)
(let ((iref (lambda (s i) (char->int (string-ref s i))))
;; Compute a 111...1 mask that will cover BOUND-1:
(mask (let lp ((i #x10000)) ; Let's skip first 16 iterations, eh?
(if (>= i bound) (- i 1) (lp (+ i i))))))
(let lp ((i start) (ans 0))
(if (>= i end) (modulo ans bound)
(lp (+ i 1) (bitwise-and mask (+ (* 37 ans) (iref s i))))))))
(define (string-hash s . maybe-bound+start+end)
(let-optionals* maybe-bound+start+end ((bound 4194304 (and (integer? bound)
(exact? bound)
(<= 0 bound)))
rest)
(let ((bound (if (zero? bound) 4194304 bound))) ; 0 means default.
(let-string-start+end (start end) string-hash s rest
(%string-hash s char->integer bound start end)))))
(define (string-hash-ci s . maybe-bound+start+end)
(let-optionals* maybe-bound+start+end ((bound 4194304 (and (integer? bound)
(exact? bound)
(<= 0 bound)))
rest)
(let ((bound (if (zero? bound) 4194304 bound))) ; 0 means default.
(let-string-start+end (start end) string-hash-ci s rest
(%string-hash s (lambda (c) (char->integer (char-downcase c)))
bound start end)))))
;;; Case hacking
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; string-upcase s [start end]
;;; string-upcase! s [start end]
;;; string-downcase s [start end]
;;; string-downcase! s [start end]
;;;
;;; string-titlecase s [start end]
;;; string-titlecase! s [start end]
;;; Capitalize every contiguous alpha sequence: capitalise
;;; first char, lowercase rest.
(define (string-upcase s . maybe-start+end)
(let-string-start+end (start end) string-upcase s maybe-start+end
(%string-map char-upcase s start end)))
(define (string-upcase! s . maybe-start+end)
(let-string-start+end (start end) string-upcase! s maybe-start+end
(%string-map! char-upcase s start end)))
(define (string-downcase s . maybe-start+end)
(let-string-start+end (start end) string-downcase s maybe-start+end
(%string-map char-downcase s start end)))
(define (string-downcase! s . maybe-start+end)
(let-string-start+end (start end) string-downcase! s maybe-start+end
(%string-map! char-downcase s start end)))
(define (%string-titlecase! s start end)
(let lp ((i start))
(cond ((string-index s char-cased? i end) =>
(lambda (i)
(string-set! s i (char-titlecase (string-ref s i)))
(let ((i1 (+ i 1)))
(cond ((string-skip s char-cased? i1 end) =>
(lambda (j)
(string-downcase! s i1 j)
(lp (+ j 1))))
(else (string-downcase! s i1 end)))))))))
(define (string-titlecase! s . maybe-start+end)
(let-string-start+end (start end) string-titlecase! s maybe-start+end
(%string-titlecase! s start end)))
(define (string-titlecase s . maybe-start+end)
(let-string-start+end (start end) string-titlecase! s maybe-start+end
(let ((ans (substring s start end)))
(%string-titlecase! ans 0 (- end start))
ans)))
;;; Cutting & pasting strings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; string-take string nchars
;;; string-drop string nchars
;;;
;;; string-take-right string nchars
;;; string-drop-right string nchars
;;;
;;; string-pad string k [char start end]
;;; string-pad-right string k [char start end]
;;;
;;; string-trim string [char/char-set/pred start end]
;;; string-trim-right string [char/char-set/pred start end]
;;; string-trim-both string [char/char-set/pred start end]
;;;
;;; These trimmers invert the char-set meaning from MIT Scheme -- you
;;; say what you want to trim.
(define (string-take s n)
(check-arg string? s string-take)
(check-arg (lambda (val) (and (integer? n) (exact? n)
(<= 0 n (string-length s))))
n string-take)
(%substring/shared s 0 n))
(define (string-take-right s n)
(check-arg string? s string-take-right)
(let ((len (string-length s)))
(check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
n string-take-right)
(%substring/shared s (- len n) len)))
(define (string-drop s n)
(check-arg string? s string-drop)
(let ((len (string-length s)))
(check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
n string-drop)
(%substring/shared s n len)))
(define (string-drop-right s n)
(check-arg string? s string-drop-right)
(let ((len (string-length s)))
(check-arg (lambda (val) (and (integer? n) (exact? n) (<= 0 n len)))
n string-drop-right)
(%substring/shared s 0 (- len n))))
(define (string-trim s . criterion+start+end)
(let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
(let-string-start+end (start end) string-trim s rest
(cond ((string-skip s criterion start end) =>
(lambda (i) (%substring/shared s i end)))
(else "")))))
(define (string-trim-right s . criterion+start+end)
(let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
(let-string-start+end (start end) string-trim-right s rest
(cond ((string-skip-right s criterion start end) =>
(lambda (i) (%substring/shared s start (+ 1 i))))
(else "")))))
(define (string-trim-both s . criterion+start+end)
(let-optionals* criterion+start+end ((criterion char-set:whitespace) rest)
(let-string-start+end (start end) string-trim-both s rest
(cond ((string-skip s criterion start end) =>
(lambda (i)
(%substring/shared s i (+ 1 (string-skip-right s criterion i end)))))
(else "")))))
(define (string-pad-right s n . char+start+end)
(let-optionals* char+start+end ((char #\space (char? char)) rest)
(let-string-start+end (start end) string-pad-right s rest
(check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
n string-pad-right)
(let ((len (- end start)))
(if (<= n len)
(%substring/shared s start (+ start n))
(let ((ans (make-string n char)))
(%string-copy! ans 0 s start end)
ans))))))
(define (string-pad s n . char+start+end)
(let-optionals* char+start+end ((char #\space (char? char)) rest)
(let-string-start+end (start end) string-pad s rest
(check-arg (lambda (n) (and (integer? n) (exact? n) (<= 0 n)))
n string-pad)
(let ((len (- end start)))
(if (<= n len)
(%substring/shared s (- end n) end)
(let ((ans (make-string n char)))
(%string-copy! ans (- n len) s start end)
ans))))))
;;; Filtering strings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; string-delete char/char-set/pred string [start end]
;;; string-filter char/char-set/pred string [start end]
;;;
;;; If the criterion is a char or char-set, we scan the string twice with
;;; string-fold -- once to determine the length of the result string,
;;; and once to do the filtered copy.
;;; If the criterion is a predicate, we don't do this double-scan strategy,
;;; because the predicate might have side-effects or be very expensive to
;;; compute. So we preallocate a temp buffer pessimistically, and only do
;;; one scan over S. This is likely to be faster and more space-efficient
;;; than consing a list.
(define (string-delete criterion s . maybe-start+end)
(let-string-start+end (start end) string-delete s maybe-start+end
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c) i
(begin (string-set! temp i c)
(+ i 1))))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-set-contains? cset c)
i
(+ i 1)))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-set-contains? cset c)
i
(begin (string-set! ans i c)
(+ i 1))))
0 s start end)
ans))))
(define (string-filter criterion s . maybe-start+end)
(let-string-start+end (start end) string-filter s maybe-start+end
(if (procedure? criterion)
(let* ((slen (- end start))
(temp (make-string slen))
(ans-len (string-fold (lambda (c i)
(if (criterion c)
(begin (string-set! temp i c)
(+ i 1))
i))
0 s start end)))
(if (= ans-len slen) temp (substring temp 0 ans-len)))
(let* ((cset (cond ((char-set? criterion) criterion)
((char? criterion) (char-set criterion))
(else (error "string-delete criterion not predicate, char or char-set" criterion))))
(len (string-fold (lambda (c i) (if (char-set-contains? cset c)
(+ i 1)
i))
0 s start end))
(ans (make-string len)))
(string-fold (lambda (c i) (if (char-set-contains? cset c)
(begin (string-set! ans i c)
(+ i 1))
i))
0 s start end)
ans))))
;;; String search
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; string-index string char/char-set/pred [start end]
;;; string-index-right string char/char-set/pred [start end]
;;; string-skip string char/char-set/pred [start end]
;;; string-skip-right string char/char-set/pred [start end]
;;; string-count string char/char-set/pred [start end]
;;; There's a lot of replicated code here for efficiency.
;;; For example, the char/char-set/pred discrimination has
;;; been lifted above the inner loop of each proc.
(define (string-index str criterion . maybe-start+end)
(let-string-start+end (start end) string-index str maybe-start+end
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i)) i
(lp (+ i 1))))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-set-contains? criterion (string-ref str i)) i
(lp (+ i 1))))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) i
(lp (+ i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index criterion)))))
(define (string-index-right str criterion . maybe-start+end)
(let-string-start+end (start end) string-index-right str maybe-start+end
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i)) i
(lp (- i 1))))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-set-contains? criterion (string-ref str i)) i
(lp (- i 1))))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) i
(lp (- i 1))))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-index-right criterion)))))
(define (string-skip str criterion . maybe-start+end)
(let-string-start+end (start end) string-skip str maybe-start+end
(cond ((char? criterion)
(let lp ((i start))
(and (< i end)
(if (char=? criterion (string-ref str i))
(lp (+ i 1))
i))))
((char-set? criterion)
(let lp ((i start))
(and (< i end)
(if (char-set-contains? criterion (string-ref str i))
(lp (+ i 1))
i))))
((procedure? criterion)
(let lp ((i start))
(and (< i end)
(if (criterion (string-ref str i)) (lp (+ i 1))
i))))
(else (error "Second param is neither char-set, char, or predicate procedure."
string-skip criterion)))))
(define (string-skip-right str criterion . maybe-start+end)
(let-string-start+end (start end) string-skip-right str maybe-start+end
(cond ((char? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char=? criterion (string-ref str i))
(lp (- i 1))
i))))
((char-set? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (char-set-contains? criterion (string-ref str i))
(lp (- i 1))
i))))
((procedure? criterion)
(let lp ((i (- end 1)))
(and (>= i start)
(if (criterion (string-ref str i)) (lp (- i 1))
i))))
(else (error "CRITERION param is neither char-set or char."
string-skip-right criterion)))))
(define (string-count s criterion . maybe-start+end)
(let-string-start+end (start end) string-count s maybe-start+end
(cond ((char? criterion)
(do ((i start (+ i 1))
(count 0 (if (char=? criterion (string-ref s i))
(+ count 1)
count)))
((>= i end) count)))
((char-set? criterion)
(do ((i start (+ i 1))
(count 0 (if (char-set-contains? criterion (string-ref s i))
(+ count 1)
count)))
((>= i end) count)))
((procedure? criterion)
(do ((i start (+ i 1))
(count 0 (if (criterion (string-ref s i)) (+ count 1) count)))
((>= i end) count)))
(else (error "CRITERION param is neither char-set or char."
string-count criterion)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; string-fill! string char [start end]
;;;
;;; string-copy! to tstart from [fstart fend]
;;; Guaranteed to work, even if s1 eq s2.
(define (string-fill! s char . maybe-start+end)
(check-arg char? char string-fill!)
(let-string-start+end (start end) string-fill! s maybe-start+end
(do ((i (- end 1) (- i 1)))
((< i start))
(string-set! s i char))))
(define (string-copy! to tstart from . maybe-fstart+fend)
(let-string-start+end (fstart fend) string-copy! from maybe-fstart+fend
(check-arg integer? tstart string-copy!)
(check-substring-spec string-copy! to tstart (+ tstart (- fend fstart)))
(%string-copy! to tstart from fstart fend)))
;;; Library-internal routine
(define (%string-copy! to tstart from fstart fend)
(if (> fstart tstart)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i)))
(do ((i (- fend 1) (- i 1))
(j (+ -1 tstart (- fend fstart)) (- j 1)))
((< i fstart))
(string-set! to j (string-ref from i)))))
;;; Returns starting-position in STRING or #f if not true.
;;; This implementation is slow & simple. It is useful as a "spec" or for
;;; comparison testing with fancier implementations.
;;; See below for fast KMP version.
;(define (string-contains string substring . maybe-starts+ends)
; (let-string-start+end2 (start1 end1 start2 end2)
; string-contains string substring maybe-starts+ends
; (let* ((len (- end2 start2))
; (i-bound (- end1 len)))
; (let lp ((i start1))
; (and (< i i-bound)
; (if (string= string substring i (+ i len) start2 end2)
; i
; (lp (+ i 1))))))))
;;; Searching for an occurrence of a substring
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (string-contains text pattern . maybe-starts+ends)
(let-string-start+end2 (t-start t-end p-start p-end)
string-contains text pattern maybe-starts+ends
(%kmp-search pattern text char=? p-start p-end t-start t-end)))
(define (string-contains-ci text pattern . maybe-starts+ends)
(let-string-start+end2 (t-start t-end p-start p-end)
string-contains-ci text pattern maybe-starts+ends
(%kmp-search pattern text char-ci=? p-start p-end t-start t-end)))
;;; Knuth-Morris-Pratt string searching
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; See
;;; "Fast pattern matching in strings"
;;; SIAM J. Computing 6(2):323-350 1977
;;; D. E. Knuth, J. H. Morris and V. R. Pratt
;;; also described in
;;; "Pattern matching in strings"
;;; Alfred V. Aho
;;; Formal Language Theory - Perspectives and Open Problems
;;; Ronald V. Brook (editor)
;;; This algorithm is O(m + n) where m and n are the
;;; lengths of the pattern and string respectively
;;; KMP search source[start,end) for PATTERN. Return starting index of
;;; leftmost match or #f.
(define (%kmp-search pattern text c= p-start p-end t-start t-end)
(let ((plen (- p-end p-start))
(rv (make-kmp-restart-vector pattern c= p-start p-end)))
;; The search loop. TJ & PJ are redundant state.
(let lp ((ti t-start) (pi 0)
(tj (- t-end t-start)) ; (- tlen ti) -- how many chars left.
(pj plen)) ; (- plen pi) -- how many chars left.
(if (= pi plen)
(- ti plen) ; Win.
(and (<= pj tj) ; Lose.
(if (c= (string-ref text ti) ; Search.
(string-ref pattern (+ p-start pi)))
(lp (+ 1 ti) (+ 1 pi) (- tj 1) (- pj 1)) ; Advance.
(let ((pi (vector-ref rv pi))) ; Retreat.
(if (= pi -1)
(lp (+ ti 1) 0 (- tj 1) plen) ; Punt.
(lp ti pi tj (- plen pi))))))))))
;;; (make-kmp-restart-vector pattern [c= start end]) -> integer-vector
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Compute the KMP restart vector RV for string PATTERN. If
;;; we have matched chars 0..i-1 of PATTERN against a search string S, and
;;; PATTERN[i] doesn't match S[k], then reset i := RV[i], and try again to
;;; match S[k]. If RV[i] = -1, then punt S[k] completely, and move on to
;;; S[k+1] and PATTERN[0] -- no possible match of PAT[0..i] contains S[k].
;;;
;;; In other words, if you have matched the first i chars of PATTERN, but
;;; the i+1'th char doesn't match, RV[i] tells you what the next-longest
;;; prefix of PATTERN is that you have matched.
;;;
;;; - C= (default CHAR=?) is used to compare characters for equality.
;;; Pass in CHAR-CI=? for case-folded string search.
;;;
;;; - START & END restrict the pattern to the indicated substring; the
;;; returned vector will be of length END - START. The numbers stored
;;; in the vector will be values in the range [0,END-START) -- that is,
;;; they are valid indices into the restart vector; you have to add START
;;; to them to use them as indices into PATTERN.
;;;
;;; I've split this out as a separate function in case other constant-string
;;; searchers might want to use it.
;;;
;;; E.g.:
;;; a b d a b x
;;; #(-1 0 0 -1 1 2)
(define (make-kmp-restart-vector pattern . maybe-c=+start+end)
(let-optionals* maybe-c=+start+end
((c= char=? (procedure? c=))
((start end) (lambda (args)
(string-parse-start+end make-kmp-restart-vector
pattern args))))
(let* ((rvlen (- end start))
(rv (make-vector rvlen -1)))
(if (> rvlen 0)
(let ((rvlen-1 (- rvlen 1))
(c0 (string-ref pattern start)))
;; Here's the main loop. We have set rv[0] ... rv[i].
;; K = I + START -- it is the corresponding index into PATTERN.
(let lp1 ((i 0) (j -1) (k start))
(if (< i rvlen-1)
;; lp2 invariant:
;; pat[(k-j) .. k-1] matches pat[start .. start+j-1]
;; or j = -1.
(let lp2 ((j j))
(cond ((= j -1)
(let ((i1 (+ 1 i)))
(if (not (c= (string-ref pattern (+ k 1)) c0))
(vector-set! rv i1 0))
(lp1 i1 0 (+ k 1))))
;; pat[(k-j) .. k] matches pat[start..start+j].
((c= (string-ref pattern k) (string-ref pattern (+ j start)))
(let* ((i1 (+ 1 i))
(j1 (+ 1 j)))
(vector-set! rv i1 j1)
(lp1 i1 j1 (+ k 1))))
(else (lp2 (vector-ref rv j)))))))))
rv)))
;;; We've matched I chars from PAT. C is the next char from the search string.
;;; Return the new I after handling C.
;;;
;;; The pattern is (VECTOR-LENGTH RV) chars long, beginning at index PAT-START
;;; in PAT (PAT-START is usually 0). The I chars of the pattern we've matched
;;; are
;;; PAT[PAT-START .. PAT-START + I].
;;;
;;; It's *not* an oversight that there is no friendly error checking or
;;; defaulting of arguments. This is a low-level, inner-loop procedure
;;; that we want integrated/inlined into the point of call.
(define (kmp-step pat rv c i c= p-start)
(let lp ((i i))
(if (c= c (string-ref pat (+ i p-start))) ; Match =>
(+ i 1) ; Done.
(let ((i (vector-ref rv i))) ; Back up in PAT.
(if (= i -1) 0 ; Can't back up further.
(lp i)))))) ; Keep trying for match.
;;; Zip through S[start,end), looking for a match of PAT. Assume we've
;;; already matched the first I chars of PAT when we commence at S[start].
;;; - <0: If we find a match *ending* at index J, return -J.
;;; - >=0: If we get to the end of the S[start,end) span without finding
;;; a complete match, return the number of chars from PAT we'd matched
;;; when we ran off the end.
;;;
;;; This is useful for searching *across* buffers -- that is, when your
;;; input comes in chunks of text. We hand-integrate the KMP-STEP loop
;;; for speed.
(define (string-kmp-partial-search pat rv s i . c=+p-start+s-start+s-end)
(check-arg vector? rv string-kmp-partial-search)
(let-optionals* c=+p-start+s-start+s-end
((c= char=? (procedure? c=))
(p-start 0 (and (integer? p-start) (exact? p-start) (<= 0 p-start)))
((s-start s-end) (lambda (args)
(string-parse-start+end string-kmp-partial-search
s args))))
(let ((patlen (vector-length rv)))
(check-arg (lambda (i) (and (integer? i) (exact? i) (<= 0 i) (< i patlen)))
i string-kmp-partial-search)
;; Enough prelude. Here's the actual code.
(let lp ((si s-start) ; An index into S.
(vi i)) ; An index into RV.
(cond ((= vi patlen) (- si)) ; Win.
((= si s-end) vi) ; Ran off the end.
(else ; Match s[si] & loop.
(let ((c (string-ref s si)))
(lp (+ si 1)
(let lp2 ((vi vi)) ; This is just KMP-STEP.
(if (c= c (string-ref pat (+ vi p-start)))
(+ vi 1)
(let ((vi (vector-ref rv vi)))
(if (= vi -1) 0
(lp2 vi)))))))))))))
;;; Misc
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; (string-null? s)
;;; (string-reverse s [start end])
;;; (string-reverse! s [start end])
;;; (reverse-list->string clist)
;;; (string->list s [start end])
(define (string-null? s) (zero? (string-length s)))
(define (string-reverse s . maybe-start+end)
(let-string-start+end (start end) string-reverse s maybe-start+end
(let* ((len (- end start))
(ans (make-string len)))
(do ((i start (+ i 1))
(j (- len 1) (- j 1)))
((< j 0))
(string-set! ans j (string-ref s i)))
ans)))
(define (string-reverse! s . maybe-start+end)
(let-string-start+end (start end) string-reverse! s maybe-start+end
(do ((i (- end 1) (- i 1))
(j start (+ j 1)))
((<= i j))
(let ((ci (string-ref s i)))
(string-set! s i (string-ref s j))
(string-set! s j ci)))))
(define (reverse-list->string clist)
(let* ((len (length clist))
(s (make-string len)))
(do ((i (- len 1) (- i 1)) (clist clist (cdr clist)))
((not (pair? clist)))
(string-set! s i (car clist)))
s))
;(define (string->list s . maybe-start+end)
; (apply string-fold-right cons '() s maybe-start+end))
(define (string->list s . maybe-start+end)
(let-string-start+end (start end) string->list s maybe-start+end
(do ((i (- end 1) (- i 1))
(ans '() (cons (string-ref s i) ans)))
((< i start) ans))))
;;; Defined by R5RS, so commented out here.
;(define (list->string lis) (string-unfold null? car cdr lis))
;;; string-concatenate string-list -> string
;;; string-concatenate/shared string-list -> string
;;; string-append/shared s ... -> string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; STRING-APPEND/SHARED has license to return a string that shares storage
;;; with any of its arguments. In particular, if there is only one non-empty
;;; string amongst its parameters, it is permitted to return that string as
;;; its result. STRING-APPEND, by contrast, always allocates new storage.
;;;
;;; STRING-CONCATENATE & STRING-CONCATENATE/SHARED are passed a list of
;;; strings, which they concatenate into a result string. STRING-CONCATENATE
;;; always allocates a fresh string; STRING-CONCATENATE/SHARED may (or may
;;; not) return a result that shares storage with any of its arguments. In
;;; particular, if it is applied to a singleton list, it is permitted to
;;; return the car of that list as its value.
(define (string-append/shared . strings) (string-concatenate/shared strings))
(define (string-concatenate/shared strings)
(let lp ((strings strings) (nchars 0) (first #f))
(cond ((pair? strings) ; Scan the args, add up total
(let* ((string (car strings)) ; length, remember 1st
(tail (cdr strings)) ; non-empty string.
(slen (string-length string)))
(if (zero? slen)
(lp tail nchars first)
(lp tail (+ nchars slen) (or first strings)))))
((zero? nchars) "")
;; Just one non-empty string! Return it.
((= nchars (string-length (car first))) (car first))
(else (let ((ans (make-string nchars)))
(let lp ((strings first) (i 0))
(if (pair? strings)
(let* ((s (car strings))
(slen (string-length s)))
(%string-copy! ans i s 0 slen)
(lp (cdr strings) (+ i slen)))))
ans)))))
; Alas, Scheme 48's APPLY blows up if you have many, many arguments.
;(define (string-concatenate strings) (apply string-append strings))
;;; Here it is written out. I avoid using REDUCE to add up string lengths
;;; to avoid non-R5RS dependencies.
(define (string-concatenate strings)
(let* ((total (do ((strings strings (cdr strings))
(i 0 (+ i (string-length (car strings)))))
((not (pair? strings)) i)))
(ans (make-string total)))
(let lp ((i 0) (strings strings))
(if (pair? strings)
(let* ((s (car strings))
(slen (string-length s)))
(%string-copy! ans i s 0 slen)
(lp (+ i slen) (cdr strings)))))
ans))
;;; Defined by R5RS, so commented out here.
;(define (string-append . strings) (string-concatenate strings))
;;; string-concatenate-reverse string-list [final-string end] -> string
;;; string-concatenate-reverse/shared string-list [final-string end] -> string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Return
;;; (string-concatenate
;;; (reverse
;;; (cons (substring final-string 0 end) string-list)))
(define (string-concatenate-reverse string-list . maybe-final+end)
(let-optionals* maybe-final+end ((final "" (string? final))
(end (string-length final)
(and (integer? end)
(exact? end)
(<= 0 end (string-length final)))))
(let ((len (let lp ((sum 0) (lis string-list))
(if (pair? lis)
(lp (+ sum (string-length (car lis))) (cdr lis))
sum))))
(%finish-string-concatenate-reverse len string-list final end))))
(define (string-concatenate-reverse/shared string-list . maybe-final+end)
(let-optionals* maybe-final+end ((final "" (string? final))
(end (string-length final)
(and (integer? end)
(exact? end)
(<= 0 end (string-length final)))))
;; Add up the lengths of all the strings in STRING-LIST; also get a
;; pointer NZLIST into STRING-LIST showing where the first non-zero-length
;; string starts.
(let lp ((len 0) (nzlist #f) (lis string-list))
(if (pair? lis)
(let ((slen (string-length (car lis))))
(lp (+ len slen)
(if (or nzlist (zero? slen)) nzlist lis)
(cdr lis)))
(cond ((zero? len) (substring/shared final 0 end))
;; LEN > 0, so NZLIST is non-empty.
((and (zero? end) (= len (string-length (car nzlist))))
(car nzlist))
(else (%finish-string-concatenate-reverse len nzlist final end)))))))
(define (%finish-string-concatenate-reverse len string-list final end)
(let ((ans (make-string (+ end len))))
(%string-copy! ans len final 0 end)
(let lp ((i len) (lis string-list))
(if (pair? lis)
(let* ((s (car lis))
(lis (cdr lis))
(slen (string-length s))
(i (- i slen)))
(%string-copy! ans i s 0 slen)
(lp i lis))))
ans))
;;; string-replace s1 s2 start1 end1 [start2 end2] -> string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Replace S1[START1,END1) with S2[START2,END2).
(define (string-replace s1 s2 start1 end1 . maybe-start+end)
(check-substring-spec string-replace s1 start1 end1)
(let-string-start+end (start2 end2) string-replace s2 maybe-start+end
(let* ((slen1 (string-length s1))
(sublen2 (- end2 start2))
(alen (+ (- slen1 (- end1 start1)) sublen2))
(ans (make-string alen)))
(%string-copy! ans 0 s1 0 start1)
(%string-copy! ans start1 s2 start2 end2)
(%string-copy! ans (+ start1 sublen2) s1 end1 slen1)
ans)))
;;; string-tokenize s [token-set start end] -> list
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Break S up into a list of token strings, where a token is a maximal
;;; non-empty contiguous sequence of chars belonging to TOKEN-SET.
;;; (string-tokenize "hello, world") => ("hello," "world")
(define (string-tokenize s . token-chars+start+end)
(let-optionals* token-chars+start+end
((token-chars char-set:graphic (char-set? token-chars)) rest)
(let-string-start+end (start end) string-tokenize s rest
(let lp ((i end) (ans '()))
(cond ((and (< start i) (string-index-right s token-chars start i)) =>
(lambda (tend-1)
(let ((tend (+ 1 tend-1)))
(cond ((string-skip-right s token-chars start tend-1) =>
(lambda (tstart-1)
(lp tstart-1
(cons (substring s (+ 1 tstart-1) tend)
ans))))
(else (cons (substring s start tend) ans))))))
(else ans))))))
;;; xsubstring s from [to start end] -> string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; S is a string; START and END are optional arguments that demarcate
;;; a substring of S, defaulting to 0 and the length of S (e.g., the whole
;;; string). Replicate this substring up and down index space, in both the
;; positive and negative directions. For example, if S = "abcdefg", START=3,
;;; and END=6, then we have the conceptual bidirectionally-infinite string
;;; ... d e f d e f d e f d e f d e f d e f d e f ...
;;; ... -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 ...
;;; XSUBSTRING returns the substring of this string beginning at index FROM,
;;; and ending at TO (which defaults to FROM+(END-START)).
;;;
;;; You can use XSUBSTRING in many ways:
;;; - To rotate a string left: (xsubstring "abcdef" 2) => "cdefab"
;;; - To rotate a string right: (xsubstring "abcdef" -2) => "efabcd"
;;; - To replicate a string: (xsubstring "abc" 0 7) => "abcabca"
;;;
;;; Note that
;;; - The FROM/TO indices give a half-open range -- the characters from
;;; index FROM up to, but not including index TO.
;;; - The FROM/TO indices are not in terms of the index space for string S.
;;; They are in terms of the replicated index space of the substring
;;; defined by S, START, and END.
;;;
;;; It is an error if START=END -- although this is allowed by special
;;; dispensation when FROM=TO.
(define (xsubstring s from . maybe-to+start+end)
(check-arg (lambda (val) (and (integer? val) (exact? val)))
from xsubstring)
(receive (to start end)
(if (pair? maybe-to+start+end)
(let-string-start+end (start end) xsubstring s (cdr maybe-to+start+end)
(let ((to (car maybe-to+start+end)))
(check-arg (lambda (val) (and (integer? val)
(exact? val)
(<= from val)))
to xsubstring)
(values to start end)))
(let ((slen (string-length (check-arg string? s xsubstring))))
(values (+ from slen) 0 slen)))
(let ((slen (- end start))
(anslen (- to from)))
(cond ((zero? anslen) "")
((zero? slen) (error "Cannot replicate empty (sub)string"
xsubstring s from to start end))
((= 1 slen) ; Fast path for 1-char replication.
(make-string anslen (string-ref s start)))
;; Selected text falls entirely within one span.
((= (floor (/ from slen)) (floor (/ to slen)))
(substring s (+ start (modulo from slen))
(+ start (modulo to slen))))
;; Selected text requires multiple spans.
(else (let ((ans (make-string anslen)))
(%multispan-repcopy! ans 0 s from to start end)
ans))))))
;;; string-xcopy! target tstart s sfrom [sto start end] -> unspecific
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Exactly the same as xsubstring, but the extracted text is written
;;; into the string TARGET starting at index TSTART.
;;; This operation is not defined if (EQ? TARGET S) -- you cannot copy
;;; a string on top of itself.
(define (string-xcopy! target tstart s sfrom . maybe-sto+start+end)
(check-arg (lambda (val) (and (integer? val) (exact? val)))
sfrom string-xcopy!)
(receive (sto start end)
(if (pair? maybe-sto+start+end)
(let-string-start+end (start end) string-xcopy! s (cdr maybe-sto+start+end)
(let ((sto (car maybe-sto+start+end)))
(check-arg (lambda (val) (and (integer? val) (exact? val)))
sto string-xcopy!)
(values sto start end)))
(let ((slen (string-length s)))
(values (+ sfrom slen) 0 slen)))
(let* ((tocopy (- sto sfrom))
(tend (+ tstart tocopy))
(slen (- end start)))
(check-substring-spec string-xcopy! target tstart tend)
(cond ((zero? tocopy))
((zero? slen) (error "Cannot replicate empty (sub)string"
string-xcopy!
target tstart s sfrom sto start end))
((= 1 slen) ; Fast path for 1-char replication.
(string-fill! target (string-ref s start) tstart tend))
;; Selected text falls entirely within one span.
((= (floor (/ sfrom slen)) (floor (/ sto slen)))
(%string-copy! target tstart s
(+ start (modulo sfrom slen))
(+ start (modulo sto slen))))
;; Multi-span copy.
(else (%multispan-repcopy! target tstart s sfrom sto start end))))))
;;; This is the core copying loop for XSUBSTRING and STRING-XCOPY!
;;; Internal -- not exported, no careful arg checking.
(define (%multispan-repcopy! target tstart s sfrom sto start end)
(let* ((slen (- end start))
(i0 (+ start (modulo sfrom slen)))
(total-chars (- sto sfrom)))
;; Copy the partial span @ the beginning
(%string-copy! target tstart s i0 end)
(let* ((ncopied (- end i0)) ; We've copied this many.
(nleft (- total-chars ncopied)) ; # chars left to copy.
(nspans (quotient nleft slen))) ; # whole spans to copy
;; Copy the whole spans in the middle.
(do ((i (+ tstart ncopied) (+ i slen)) ; Current target index.
(nspans nspans (- nspans 1))) ; # spans to copy
((zero? nspans)
;; Copy the partial-span @ the end & we're done.
(%string-copy! target i s start (+ start (- total-chars (- i tstart)))))
(%string-copy! target i s start end))))); Copy a whole span.
;;; (string-join string-list [delimiter grammar]) => string
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Paste strings together using the delimiter string.
;;;
;;; (join-strings '("foo" "bar" "baz") ":") => "foo:bar:baz"
;;;
;;; DELIMITER defaults to a single space " "
;;; GRAMMAR is one of the symbols {prefix, infix, strict-infix, suffix}
;;; and defaults to 'infix.
;;;
;;; I could rewrite this more efficiently -- precompute the length of the
;;; answer string, then allocate & fill it in iteratively. Using
;;; STRING-CONCATENATE is less efficient.
(define (string-join strings . delim+grammar)
(let-optionals* delim+grammar ((delim " " (string? delim))
(grammar 'infix))
(let ((buildit (lambda (lis final)
(let recur ((lis lis))
(if (pair? lis)
(cons delim (cons (car lis) (recur (cdr lis))))
final)))))
(cond ((pair? strings)
(string-concatenate
(case grammar
((infix strict-infix)
(cons (car strings) (buildit (cdr strings) '())))
((prefix) (buildit strings '()))
((suffix)
(cons (car strings) (buildit (cdr strings) (list delim))))
(else (error "Illegal join grammar"
grammar string-join)))))
((not (null? strings))
(error "STRINGS parameter not list." strings string-join))
;; STRINGS is ()
((eq? grammar 'strict-infix)
(error "Empty list cannot be joined with STRICT-INFIX grammar."
string-join))
(else ""))))) ; Special-cased for infix grammar.
;;; Porting & performance-tuning notes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; See the section at the beginning of this file on external dependencies.
;;;
;;; The biggest issue with respect to porting is the LET-OPTIONALS* macro.
;;; There are many, many optional arguments in this library; the complexity
;;; of parsing, defaulting & type-testing these parameters is handled with the
;;; aid of this macro. There are about 15 uses of LET-OPTIONALS*. You can
;;; rewrite the uses, port the hairy macro definition (which is implemented
;;; using a Clinger-Rees low-level explicit-renaming macro system), or port
;;; the simple, high-level definition, which is less efficient.
;;;
;;; There is a fair amount of argument checking. This is, strictly speaking,
;;; unnecessary -- the actual body of the procedures will blow up if, say, a
;;; START/END index is improper. However, the error message will not be as
;;; good as if the error were caught at the "higher level." Also, a very, very
;;; smart Scheme compiler may be able to exploit having the type checks done
;;; early, so that the actual body of the procedures can assume proper values.
;;; This isn't likely; this kind of compiler technology isn't common any
;;; longer.
;;;
;;; The overhead of optional-argument parsing is irritating. The optional
;;; arguments must be consed into a rest list on entry, and then parsed out.
;;; Function call should be a matter of a few register moves and a jump; it
;;; should not involve heap allocation! Your Scheme system may have a superior
;;; non-R5RS optional-argument system that can eliminate this overhead. If so,
;;; then this is a prime candidate for optimising these procedures,
;;; *especially* the many optional START/END index parameters.
;;;
;;; Note that optional arguments are also a barrier to procedure integration.
;;; If your Scheme system permits you to specify alternate entry points
;;; for a call when the number of optional arguments is known in a manner
;;; that enables inlining/integration, this can provide performance
;;; improvements.
;;;
;;; There is enough *explicit* error checking that *all* string-index
;;; operations should *never* produce a bounds error. Period. Feel like
;;; living dangerously? *Big* performance win to be had by replacing
;;; STRING-REF's and STRING-SET!'s with unsafe equivalents in the loops.
;;; Similarly, fixnum-specific operators can speed up the arithmetic done on
;;; the index values in the inner loops. The only arguments that are not
;;; completely error checked are
;;; - string lists (complete checking requires time proportional to the
;;; length of the list)
;;; - procedure arguments, such as char->char maps & predicates.
;;; There is no way to check the range & domain of procedures in Scheme.
;;; Procedures that take these parameters cannot fully check their
;;; arguments. But all other types to all other procedures are fully
;;; checked.
;;;
;;; This does open up the alternate possibility of simply *removing* these
;;; checks, and letting the safe primitives raise the errors. On a dumb
;;; Scheme system, this would provide speed (by eliminating the redundant
;;; error checks) at the cost of error-message clarity.
;;;
;;; See the comments preceding the hash function code for notes on tuning
;;; the default bound so that the code never overflows your implementation's
;;; fixnum size into bignum calculation.
;;;
;;; In an interpreted Scheme, some of these procedures, or the internal
;;; routines with % prefixes, are excellent candidates for being rewritten
;;; in C. Consider STRING-HASH, %STRING-COMPARE, the
;;; %STRING-{SUF,PRE}FIX-LENGTH routines, STRING-COPY!, STRING-INDEX &
;;; STRING-SKIP (char-set & char cases), SUBSTRING and SUBSTRING/SHARED,
;;; %KMP-SEARCH, and %MULTISPAN-REPCOPY!.
;;;
;;; It would also be nice to have the ability to mark some of these
;;; routines as candidates for inlining/integration.
;;;
;;; All the %-prefixed routines in this source code are written
;;; to be called internally to this library. They do *not* perform
;;; friendly error checks on the inputs; they assume everything is
;;; proper. They also do not take optional arguments. These two properties
;;; save calling overhead and enable procedure integration -- but they
;;; are not appropriate for exported routines.
;;; Copyright details
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The prefix/suffix and comparison routines in this code had (extremely
;;; distant) origins in MIT Scheme's string lib, and was substantially
;;; reworked by Olin Shivers (shivers@ai.mit.edu) 9/98. As such, it is
;;; covered by MIT Scheme's open source copyright. See below for details.
;;;
;;; The KMP string-search code was influenced by implementations written
;;; by Stephen Bevan, Brian Dehneyer and Will Fitzgerald. However, this
;;; version was written from scratch by myself.
;;;
;;; The remainder of this code was written from scratch by myself for scsh.
;;; The scsh copyright is a BSD-style open source copyright. See below for
;;; details.
;;; -Olin Shivers
;;; MIT Scheme copyright terms
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This material was developed by the Scheme project at the Massachusetts
;;; Institute of Technology, Department of Electrical Engineering and
;;; Computer Science. Permission to copy and modify this software, to
;;; redistribute either the original software or a modified version, and
;;; to use this software for any purpose is granted, subject to the
;;; following restrictions and understandings.
;;;
;;; 1. Any copy made of this software must include this copyright notice
;;; in full.
;;;
;;; 2. Users of this software agree to make their best efforts (a) to
;;; return to the MIT Scheme project any improvements or extensions that
;;; they make, so that these may be included in future releases; and (b)
;;; to inform MIT of noteworthy uses of this software.
;;;
;;; 3. All materials developed as a consequence of the use of this
;;; software shall duly acknowledge such use, in accordance with the usual
;;; standards of acknowledging credit in academic research.
;;;
;;; 4. MIT has made no warrantee or representation that the operation of
;;; this software will be error-free, and MIT is under no obligation to
;;; provide any services, by way of maintenance, update, or otherwise.
;;;
;;; 5. In conjunction with products arising from the use of this material,
;;; there shall be no use of the name of the Massachusetts Institute of
;;; Technology nor of any adaptation thereof in any advertising,
;;; promotional, or sales literature without prior written consent from
;;; MIT in each case.
;;; Scsh copyright terms
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; 1. Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; 2. Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;; 3. The name of the authors may not be used to endorse or promote products
;;; derived from this software without specific prior written permission.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
;;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;;; IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
;;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(define-library (srfi 14)
(export
;; Predicates & comparison
char-set? char-set= char-set<= char-set-hash
;; Iterating over character sets
char-set-cursor char-set-ref char-set-cursor-next end-of-char-set?
char-set-fold char-set-unfold char-set-unfold!
char-set-for-each char-set-map
;; Creating character sets
char-set-copy char-set
list->char-set string->char-set
list->char-set! string->char-set!
char-set-filter ucs-range->char-set
char-set-filter! ucs-range->char-set!
->char-set
;; Querying character sets
char-set->list char-set->string
char-set-size char-set-count char-set-contains?
char-set-every char-set-any
;; Character-set algebra
char-set-adjoin char-set-delete
char-set-adjoin! char-set-delete!
char-set-complement char-set-union char-set-intersection
char-set-complement! char-set-union! char-set-intersection!
char-set-difference char-set-xor char-set-diff+intersection
char-set-difference! char-set-xor! char-set-diff+intersection!
;; Standard character sets
char-set:lower-case char-set:upper-case char-set:title-case
char-set:letter char-set:digit char-set:letter+digit
char-set:graphic char-set:printing char-set:whitespace
char-set:iso-control char-set:punctuation char-set:symbol
char-set:hex-digit char-set:blank char-set:ascii
char-set:empty char-set:full
)
(import
(scheme base)
(srfi 60)
(srfi aux))
(include "14.upstream.scm"))
;;; SRFI-14 character-sets library -*- Scheme -*-
;;;
;;; - Ported from MIT Scheme runtime by Brian D. Carlstrom.
;;; - Massively rehacked & extended by Olin Shivers 6/98.
;;; - Massively redesigned and rehacked 5/2000 during SRFI process.
;;; At this point, the code bears the following relationship to the
;;; MIT Scheme code: "This is my grandfather's axe. My father replaced
;;; the head, and I have replaced the handle." Nonetheless, we preserve
;;; the MIT Scheme copyright:
;;; Copyright (c) 1988-1995 Massachusetts Institute of Technology
;;; The MIT Scheme license is a "free software" license. See the end of
;;; this file for the tedious details.
;;; Exports:
;;; char-set? char-set= char-set<=
;;; char-set-hash
;;; char-set-cursor char-set-ref char-set-cursor-next end-of-char-set?
;;; char-set-fold char-set-unfold char-set-unfold!
;;; char-set-for-each char-set-map
;;; char-set-copy char-set
;;;
;;; list->char-set string->char-set
;;; list->char-set! string->char-set!
;;;
;;; filterchar-set ucs-range->char-set ->char-set
;;; filterchar-set! ucs-range->char-set!
;;;
;;; char-set->list char-set->string
;;;
;;; char-set-size char-set-count char-set-contains?
;;; char-set-every char-set-any
;;;
;;; char-set-adjoin char-set-delete
;;; char-set-adjoin! char-set-delete!
;;;
;;; char-set-complement char-set-union char-set-intersection
;;; char-set-complement! char-set-union! char-set-intersection!
;;;
;;; char-set-difference char-set-xor char-set-diff+intersection
;;; char-set-difference! char-set-xor! char-set-diff+intersection!
;;;
;;; char-set:lower-case char-set:upper-case char-set:title-case
;;; char-set:letter char-set:digit char-set:letter+digit
;;; char-set:graphic char-set:printing char-set:whitespace
;;; char-set:iso-control char-set:punctuation char-set:symbol
;;; char-set:hex-digit char-set:blank char-set:ascii
;;; char-set:empty char-set:full
;;; Imports
;;; This code has the following non-R5RS dependencies:
;;; - ERROR
;;; - %LATIN1->CHAR %CHAR->LATIN1
;;; - LET-OPTIONALS* and #\:OPTIONAL macros for parsing, checking & defaulting
;;; optional arguments from rest lists.
;;; - BITWISE-AND for CHAR-SET-HASH
;;; - The SRFI-19 DEFINE-RECORD-TYPE record macro
;;; - A simple CHECK-ARG procedure:
;;; (lambda (pred val caller) (if (not (pred val)) (error val caller)))
;;; This is simple code, not great code. Char sets are represented as 256-char
;;; strings. If char I is ASCII/Latin-1 0, then it isn't in the set; if char I
;;; is ASCII/Latin-1 1, then it is in the set.
;;; - Should be rewritten to use bit strings or byte vecs.
;;; - Is Latin-1 specific. Would certainly have to be rewritten for Unicode.
;;; See the end of the file for porting and performance-tuning notes.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-record-type \:char-set
(make-char-set s)
char-set?
(s char-set:s))
(define (%string-copy s) (substring s 0 (string-length s)))
;;; Parse, type-check & default a final optional BASE-CS parameter from
;;; a rest argument. Return a *fresh copy* of the underlying string.
;;; The default is the empty set. The PROC argument is to help us
;;; generate informative error exceptions.
(define (%default-base maybe-base proc)
(if (pair? maybe-base)
(let ((bcs (car maybe-base))
(tail (cdr maybe-base)))
(if (null? tail)
(if (char-set? bcs) (%string-copy (char-set:s bcs))
(error "BASE-CS parameter not a char-set" proc bcs))
(error "Expected final base char set -- too many parameters"
proc maybe-base)))
(make-string 256 (%latin1->char 0))))
;;; If CS is really a char-set, do CHAR-SET:S, otw report an error msg on
;;; behalf of our caller, PROC. This procedure exists basically to provide
;;; explicit error-checking & reporting.
(define (%char-set:s/check cs proc)
(let lp ((cs cs))
(if (char-set? cs) (char-set:s cs)
(lp (error "Not a char-set" cs proc)))))
;;; These internal functions hide a lot of the dependency on the
;;; underlying string representation of char sets. They should be
;;; inlined if possible.
(define (si=0? s i) (zero? (%char->latin1 (string-ref s i))))
(define (si=1? s i) (not (si=0? s i)))
(define c0 (%latin1->char 0))
(define c1 (%latin1->char 1))
(define (si s i) (%char->latin1 (string-ref s i)))
(define (%set0! s i) (string-set! s i c0))
(define (%set1! s i) (string-set! s i c1))
;;; These do various "s[i] := s[i] op val" operations -- see
;;; %CHAR-SET-ALGEBRA. They are used to implement the various
;;; set-algebra procedures.
(define (setv! s i v) (string-set! s i (%latin1->char v))) ; SET to a Value.
(define (%not! s i v) (setv! s i (- 1 v)))
(define (%and! s i v) (if (zero? v) (%set0! s i)))
(define (%or! s i v) (if (not (zero? v)) (%set1! s i)))
(define (%minus! s i v) (if (not (zero? v)) (%set0! s i)))
(define (%xor! s i v) (if (not (zero? v)) (setv! s i (- 1 (si s i)))))
(define (char-set-copy cs)
(make-char-set (%string-copy (%char-set:s/check cs char-set-copy))))
(define (char-set= . rest)
(or (null? rest)
(let* ((cs1 (car rest))
(rest (cdr rest))
(s1 (%char-set:s/check cs1 char-set=)))
(let lp ((rest rest))
(or (not (pair? rest))
(and (string=? s1 (%char-set:s/check (car rest) char-set=))
(lp (cdr rest))))))))
(define (char-set<= . rest)
(or (null? rest)
(let ((cs1 (car rest))
(rest (cdr rest)))
(let lp ((s1 (%char-set:s/check cs1 char-set<=)) (rest rest))
(or (not (pair? rest))
(let ((s2 (%char-set:s/check (car rest) char-set<=))
(rest (cdr rest)))
(if (eq? s1 s2) (lp s2 rest) ; Fast path
(let lp2 ((i 255)) ; Real test
(if (< i 0) (lp s2 rest)
(and (<= (si s1 i) (si s2 i))
(lp2 (- i 1))))))))))))
;;; Hash
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Compute (c + 37 c + 37^2 c + ...) modulo BOUND, with sleaze thrown in
;;; to keep the intermediate values small. (We do the calculation with just
;;; enough bits to represent BOUND, masking off high bits at each step in
;;; calculation. If this screws up any important properties of the hash
;;; function I'd like to hear about it. -Olin)
;;;
;;; If you keep BOUND small enough, the intermediate calculations will
;;; always be fixnums. How small is dependent on the underlying Scheme system;
;;; we use a default BOUND of 2^22 = 4194304, which should hack it in
;;; Schemes that give you at least 29 signed bits for fixnums. The core
;;; calculation that you don't want to overflow is, worst case,
;;; (+ 65535 (* 37 (- bound 1)))
;;; where 65535 is the max character code. Choose the default BOUND to be the
;;; biggest power of two that won't cause this expression to fixnum overflow,
;;; and everything will be copacetic.
(define (char-set-hash cs . maybe-bound)
(let* ((bound (#\:optional maybe-bound 4194304 (lambda (n) (and (integer? n)
(exact? n)
(<= 0 n)))))
(bound (if (zero? bound) 4194304 bound)) ; 0 means default.
(s (%char-set:s/check cs char-set-hash))
;; Compute a 111...1 mask that will cover BOUND-1:
(mask (let lp ((i #x10000)) ; Let's skip first 16 iterations, eh?
(if (>= i bound) (- i 1) (lp (+ i i))))))
(let lp ((i 255) (ans 0))
(if (< i 0) (modulo ans bound)
(lp (- i 1)
(if (si=0? s i) ans
(bitwise-and mask (+ (* 37 ans) i))))))))
(define (char-set-contains? cs char)
(si=1? (%char-set:s/check cs char-set-contains?)
(%char->latin1 (check-arg char? char char-set-contains?))))
(define (char-set-size cs)
(let ((s (%char-set:s/check cs char-set-size)))
(let lp ((i 255) (size 0))
(if (< i 0) size
(lp (- i 1) (+ size (si s i)))))))
(define (char-set-count pred cset)
(check-arg procedure? pred char-set-count)
(let ((s (%char-set:s/check cset char-set-count)))
(let lp ((i 255) (count 0))
(if (< i 0) count
(lp (- i 1)
(if (and (si=1? s i) (pred (%latin1->char i)))
(+ count 1)
count))))))
;;; -- Adjoin & delete
(define (%set-char-set set proc cs chars)
(let ((s (%string-copy (%char-set:s/check cs proc))))
(for-each (lambda (c) (set s (%char->latin1 c)))
chars)
(make-char-set s)))
(define (%set-char-set! set proc cs chars)
(let ((s (%char-set:s/check cs proc)))
(for-each (lambda (c) (set s (%char->latin1 c)))
chars))
cs)
(define (char-set-adjoin cs . chars)
(%set-char-set %set1! char-set-adjoin cs chars))
(define (char-set-adjoin! cs . chars)
(%set-char-set! %set1! char-set-adjoin! cs chars))
(define (char-set-delete cs . chars)
(%set-char-set %set0! char-set-delete cs chars))
(define (char-set-delete! cs . chars)
(%set-char-set! %set0! char-set-delete! cs chars))
;;; Cursors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Simple implementation. A cursors is an integer index into the
;;; mark vector, and -1 for the end-of-char-set cursor.
;;;
;;; If we represented char sets as a bit set, we could do the following
;;; trick to pick the lowest bit out of the set:
;;; (count-bits (xor (- cset 1) cset))
;;; (But first mask out the bits already scanned by the cursor first.)
(define (char-set-cursor cset)
(%char-set-cursor-next cset 256 char-set-cursor))
(define (end-of-char-set? cursor) (< cursor 0))
(define (char-set-ref cset cursor) (%latin1->char cursor))
(define (char-set-cursor-next cset cursor)
(check-arg (lambda (i) (and (integer? i) (exact? i) (<= 0 i 255))) cursor
char-set-cursor-next)
(%char-set-cursor-next cset cursor char-set-cursor-next))
(define (%char-set-cursor-next cset cursor proc) ; Internal
(let ((s (%char-set:s/check cset proc)))
(let lp ((cur cursor))
(let ((cur (- cur 1)))
(if (or (< cur 0) (si=1? s cur)) cur
(lp cur))))))
;;; -- for-each map fold unfold every any
(define (char-set-for-each proc cs)
(check-arg procedure? proc char-set-for-each)
(let ((s (%char-set:s/check cs char-set-for-each)))
(let lp ((i 255))
(cond ((>= i 0)
(if (si=1? s i) (proc (%latin1->char i)))
(lp (- i 1)))))))
(define (char-set-map proc cs)
(check-arg procedure? proc char-set-map)
(let ((s (%char-set:s/check cs char-set-map))
(ans (make-string 256 c0)))
(let lp ((i 255))
(cond ((>= i 0)
(if (si=1? s i)
(%set1! ans (%char->latin1 (proc (%latin1->char i)))))
(lp (- i 1)))))
(make-char-set ans)))
(define (char-set-fold kons knil cs)
(check-arg procedure? kons char-set-fold)
(let ((s (%char-set:s/check cs char-set-fold)))
(let lp ((i 255) (ans knil))
(if (< i 0) ans
(lp (- i 1)
(if (si=0? s i) ans
(kons (%latin1->char i) ans)))))))
(define (char-set-every pred cs)
(check-arg procedure? pred char-set-every)
(let ((s (%char-set:s/check cs char-set-every)))
(let lp ((i 255))
(or (< i 0)
(and (or (si=0? s i) (pred (%latin1->char i)))
(lp (- i 1)))))))
(define (char-set-any pred cs)
(check-arg procedure? pred char-set-any)
(let ((s (%char-set:s/check cs char-set-any)))
(let lp ((i 255))
(and (>= i 0)
(or (and (si=1? s i) (pred (%latin1->char i)))
(lp (- i 1)))))))
(define (%char-set-unfold! proc p f g s seed)
(check-arg procedure? p proc)
(check-arg procedure? f proc)
(check-arg procedure? g proc)
(let lp ((seed seed))
(cond ((not (p seed)) ; P says we are done.
(%set1! s (%char->latin1 (f seed))) ; Add (F SEED) to set.
(lp (g seed)))))) ; Loop on (G SEED).
(define (char-set-unfold p f g seed . maybe-base)
(let ((bs (%default-base maybe-base char-set-unfold)))
(%char-set-unfold! char-set-unfold p f g bs seed)
(make-char-set bs)))
(define (char-set-unfold! p f g seed base-cset)
(%char-set-unfold! char-set-unfold! p f g
(%char-set:s/check base-cset char-set-unfold!)
seed)
base-cset)
;;; list <--> char-set
(define (%list->char-set! chars s)
(for-each (lambda (char) (%set1! s (%char->latin1 char)))
chars))
(define (char-set . chars)
(let ((s (make-string 256 c0)))
(%list->char-set! chars s)
(make-char-set s)))
(define (list->char-set chars . maybe-base)
(let ((bs (%default-base maybe-base list->char-set)))
(%list->char-set! chars bs)
(make-char-set bs)))
(define (list->char-set! chars base-cs)
(%list->char-set! chars (%char-set:s/check base-cs list->char-set!))
base-cs)
(define (char-set->list cs)
(let ((s (%char-set:s/check cs char-set->list)))
(let lp ((i 255) (ans '()))
(if (< i 0) ans
(lp (- i 1)
(if (si=0? s i) ans
(cons (%latin1->char i) ans)))))))
;;; string <--> char-set
(define (%string->char-set! str bs proc)
(check-arg string? str proc)
(do ((i (- (string-length str) 1) (- i 1)))
((< i 0))
(%set1! bs (%char->latin1 (string-ref str i)))))
(define (string->char-set str . maybe-base)
(let ((bs (%default-base maybe-base string->char-set)))
(%string->char-set! str bs string->char-set)
(make-char-set bs)))
(define (string->char-set! str base-cs)
(%string->char-set! str (%char-set:s/check base-cs string->char-set!)
string->char-set!)
base-cs)
(define (char-set->string cs)
(let* ((s (%char-set:s/check cs char-set->string))
(ans (make-string (char-set-size cs))))
(let lp ((i 255) (j 0))
(if (< i 0) ans
(let ((j (if (si=0? s i) j
(begin (string-set! ans j (%latin1->char i))
(+ j 1)))))
(lp (- i 1) j))))))
;;; -- UCS-range -> char-set
(define (%ucs-range->char-set! lower upper error? bs proc)
(check-arg (lambda (x) (and (integer? x) (exact? x) (<= 0 x))) lower proc)
(check-arg (lambda (x) (and (integer? x) (exact? x) (<= lower x))) upper proc)
(if (and (< lower upper) (< 256 upper) error?)
(error "Requested UCS range contains unavailable characters -- this implementation only supports Latin-1"
proc lower upper))
(let lp ((i (- (min upper 256) 1)))
(cond ((<= lower i) (%set1! bs i) (lp (- i 1))))))
(define (ucs-range->char-set lower upper . rest)
(let-optionals* rest ((error? #f) rest)
(let ((bs (%default-base rest ucs-range->char-set)))
(%ucs-range->char-set! lower upper error? bs ucs-range->char-set)
(make-char-set bs))))
(define (ucs-range->char-set! lower upper error? base-cs)
(%ucs-range->char-set! lower upper error?
(%char-set:s/check base-cs ucs-range->char-set!)
ucs-range->char-set)
base-cs)
;;; -- predicate -> char-set
(define (%char-set-filter! pred ds bs proc)
(check-arg procedure? pred proc)
(let lp ((i 255))
(cond ((>= i 0)
(if (and (si=1? ds i) (pred (%latin1->char i)))
(%set1! bs i))
(lp (- i 1))))))
(define (char-set-filter predicate domain . maybe-base)
(let ((bs (%default-base maybe-base char-set-filter)))
(%char-set-filter! predicate
(%char-set:s/check domain char-set-filter!)
bs
char-set-filter)
(make-char-set bs)))
(define (char-set-filter! predicate domain base-cs)
(%char-set-filter! predicate
(%char-set:s/check domain char-set-filter!)
(%char-set:s/check base-cs char-set-filter!)
char-set-filter!)
base-cs)
;;; {string, char, char-set, char predicate} -> char-set
(define (->char-set x)
(cond ((char-set? x) x)
((string? x) (string->char-set x))
((char? x) (char-set x))
(else (error "->char-set: Not a charset, string or char." x))))
;;; Set algebra
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The exported ! procs are "linear update" -- allowed, but not required, to
;;; side-effect their first argument when computing their result. In other
;;; words, you must use them as if they were completely functional, just like
;;; their non-! counterparts, and you must additionally ensure that their
;;; first arguments are "dead" at the point of call. In return, we promise a
;;; more efficient result, plus allowing you to always assume char-sets are
;;; unchangeable values.
;;; Apply P to each index and its char code in S: (P I VAL).
;;; Used by the set-algebra ops.
(define (%string-iter p s)
(let lp ((i (- (string-length s) 1)))
(cond ((>= i 0)
(p i (%char->latin1 (string-ref s i)))
(lp (- i 1))))))
;;; String S represents some initial char-set. (OP s i val) does some
;;; kind of s[i] := s[i] op val update. Do
;;; S := S OP CSETi
;;; for all the char-sets in the list CSETS. The n-ary set-algebra ops
;;; all use this internal proc.
(define (%char-set-algebra s csets op proc)
(for-each (lambda (cset)
(let ((s2 (%char-set:s/check cset proc)))
(let lp ((i 255))
(cond ((>= i 0)
(op s i (si s2 i))
(lp (- i 1)))))))
csets))
;;; -- Complement
(define (char-set-complement cs)
(let ((s (%char-set:s/check cs char-set-complement))
(ans (make-string 256)))
(%string-iter (lambda (i v) (%not! ans i v)) s)
(make-char-set ans)))
(define (char-set-complement! cset)
(let ((s (%char-set:s/check cset char-set-complement!)))
(%string-iter (lambda (i v) (%not! s i v)) s))
cset)
;;; -- Union
(define (char-set-union! cset1 . csets)
(%char-set-algebra (%char-set:s/check cset1 char-set-union!)
csets %or! char-set-union!)
cset1)
(define (char-set-union . csets)
(if (pair? csets)
(let ((s (%string-copy (%char-set:s/check (car csets) char-set-union))))
(%char-set-algebra s (cdr csets) %or! char-set-union)
(make-char-set s))
(char-set-copy char-set:empty)))
;;; -- Intersection
(define (char-set-intersection! cset1 . csets)
(%char-set-algebra (%char-set:s/check cset1 char-set-intersection!)
csets %and! char-set-intersection!)
cset1)
(define (char-set-intersection . csets)
(if (pair? csets)
(let ((s (%string-copy (%char-set:s/check (car csets) char-set-intersection))))
(%char-set-algebra s (cdr csets) %and! char-set-intersection)
(make-char-set s))
(char-set-copy char-set:full)))
;;; -- Difference
(define (char-set-difference! cset1 . csets)
(%char-set-algebra (%char-set:s/check cset1 char-set-difference!)
csets %minus! char-set-difference!)
cset1)
(define (char-set-difference cs1 . csets)
(if (pair? csets)
(let ((s (%string-copy (%char-set:s/check cs1 char-set-difference))))
(%char-set-algebra s csets %minus! char-set-difference)
(make-char-set s))
(char-set-copy cs1)))
;;; -- Xor
(define (char-set-xor! cset1 . csets)
(%char-set-algebra (%char-set:s/check cset1 char-set-xor!)
csets %xor! char-set-xor!)
cset1)
(define (char-set-xor . csets)
(if (pair? csets)
(let ((s (%string-copy (%char-set:s/check (car csets) char-set-xor))))
(%char-set-algebra s (cdr csets) %xor! char-set-xor)
(make-char-set s))
(char-set-copy char-set:empty)))
;;; -- Difference & intersection
(define (%char-set-diff+intersection! diff int csets proc)
(for-each (lambda (cs)
(%string-iter (lambda (i v)
(if (not (zero? v))
(cond ((si=1? diff i)
(%set0! diff i)
(%set1! int i)))))
(%char-set:s/check cs proc)))
csets))
(define (char-set-diff+intersection! cs1 cs2 . csets)
(let ((s1 (%char-set:s/check cs1 char-set-diff+intersection!))
(s2 (%char-set:s/check cs2 char-set-diff+intersection!)))
(%string-iter (lambda (i v) (if (zero? v)
(%set0! s2 i)
(if (si=1? s2 i) (%set0! s1 i))))
s1)
(%char-set-diff+intersection! s1 s2 csets char-set-diff+intersection!))
(values cs1 cs2))
(define (char-set-diff+intersection cs1 . csets)
(let ((diff (string-copy (%char-set:s/check cs1 char-set-diff+intersection)))
(int (make-string 256 c0)))
(%char-set-diff+intersection! diff int csets char-set-diff+intersection)
(values (make-char-set diff) (make-char-set int))))
;;;; System character sets
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; These definitions are for Latin-1.
;;;
;;; If your Scheme implementation allows you to mark the underlying strings
;;; as immutable, you should do so -- it would be very, very bad if a client's
;;; buggy code corrupted these constants.
(define char-set:empty (char-set))
(define char-set:full (char-set-complement char-set:empty))
(define char-set:lower-case
(let* ((a-z (ucs-range->char-set #x61 #x7B))
(latin1 (ucs-range->char-set! #xdf #xf7 #t a-z))
(latin2 (ucs-range->char-set! #xf8 #x100 #t latin1)))
(char-set-adjoin! latin2 (%latin1->char #xb5))))
(define char-set:upper-case
(let ((A-Z (ucs-range->char-set #x41 #x5B)))
;; Add in the Latin-1 upper-case chars.
(ucs-range->char-set! #xd8 #xdf #t
(ucs-range->char-set! #xc0 #xd7 #t A-Z))))
(define char-set:title-case char-set:empty)
(define char-set:letter
(let ((u/l (char-set-union char-set:upper-case char-set:lower-case)))
(char-set-adjoin! u/l
(%latin1->char #xaa) ; FEMININE ORDINAL INDICATOR
(%latin1->char #xba)))) ; MASCULINE ORDINAL INDICATOR
(define char-set:digit (string->char-set "0123456789"))
(define char-set:hex-digit (string->char-set "0123456789abcdefABCDEF"))
(define char-set:letter+digit
(char-set-union char-set:letter char-set:digit))
(define char-set:punctuation
(let ((ascii (string->char-set "!\"#%&'()*,-./:;?@[\\]_{}"))
(latin-1-chars (map %latin1->char '(#xA1 ; INVERTED EXCLAMATION MARK
#xAB ; LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
#xAD ; SOFT HYPHEN
#xB7 ; MIDDLE DOT
#xBB ; RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
#xBF)))) ; INVERTED QUESTION MARK
(list->char-set! latin-1-chars ascii)))
(define char-set:symbol
(let ((ascii (string->char-set "$+<=>^`|~"))
(latin-1-chars (map %latin1->char '(#x00A2 ; CENT SIGN
#x00A3 ; POUND SIGN
#x00A4 ; CURRENCY SIGN
#x00A5 ; YEN SIGN
#x00A6 ; BROKEN BAR
#x00A7 ; SECTION SIGN
#x00A8 ; DIAERESIS
#x00A9 ; COPYRIGHT SIGN
#x00AC ; NOT SIGN
#x00AE ; REGISTERED SIGN
#x00AF ; MACRON
#x00B0 ; DEGREE SIGN
#x00B1 ; PLUS-MINUS SIGN
#x00B4 ; ACUTE ACCENT
#x00B6 ; PILCROW SIGN
#x00B8 ; CEDILLA
#x00D7 ; MULTIPLICATION SIGN
#x00F7)))) ; DIVISION SIGN
(list->char-set! latin-1-chars ascii)))
(define char-set:graphic
(char-set-union char-set:letter+digit char-set:punctuation char-set:symbol))
(define char-set:whitespace
(list->char-set (map %latin1->char '(#x09 ; HORIZONTAL TABULATION
#x0A ; LINE FEED
#x0B ; VERTICAL TABULATION
#x0C ; FORM FEED
#x0D ; CARRIAGE RETURN
#x20 ; SPACE
#xA0))))
(define char-set:printing (char-set-union char-set:whitespace char-set:graphic)) ; NO-BREAK SPACE
(define char-set:blank
(list->char-set (map %latin1->char '(#x09 ; HORIZONTAL TABULATION
#x20 ; SPACE
#xA0)))) ; NO-BREAK SPACE
(define char-set:iso-control
(ucs-range->char-set! #x7F #xA0 #t (ucs-range->char-set 0 32)))
(define char-set:ascii (ucs-range->char-set 0 128))
;;; Porting & performance-tuning notes
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; See the section at the beginning of this file on external dependencies.
;;;
;;; First and foremost, rewrite this code to use bit vectors of some sort.
;;; This will give big speedup and memory savings.
;;;
;;; - LET-OPTIONALS* macro.
;;; This is only used once. You can rewrite the use, port the hairy macro
;;; definition (which is implemented using a Clinger-Rees low-level
;;; explicit-renaming macro system), or port the simple, high-level
;;; definition, which is less efficient.
;;;
;;; - #\:OPTIONAL macro
;;; Very simply defined using an R5RS high-level macro.
;;;
;;; Implementations that can arrange for the base char sets to be immutable
;;; should do so. (E.g., Scheme 48 allows one to mark a string as immutable,
;;; which can be used to protect the underlying strings.) It would be very,
;;; very bad if a client's buggy code corrupted these constants.
;;;
;;; There is a fair amount of argument checking. This is, strictly speaking,
;;; unnecessary -- the actual body of the procedures will blow up if an
;;; illegal value is passed in. However, the error message will not be as good
;;; as if the error were caught at the "higher level." Also, a very, very
;;; smart Scheme compiler may be able to exploit having the type checks done
;;; early, so that the actual body of the procedures can assume proper values.
;;; This isn't likely; this kind of compiler technology isn't common any
;;; longer.
;;;
;;; The overhead of optional-argument parsing is irritating. The optional
;;; arguments must be consed into a rest list on entry, and then parsed out.
;;; Function call should be a matter of a few register moves and a jump; it
;;; should not involve heap allocation! Your Scheme system may have a superior
;;; non-R5RS optional-argument system that can eliminate this overhead. If so,
;;; then this is a prime candidate for optimising these procedures,
;;; *especially* the many optional BASE-CS parameters.
;;;
;;; Note that optional arguments are also a barrier to procedure integration.
;;; If your Scheme system permits you to specify alternate entry points
;;; for a call when the number of optional arguments is known in a manner
;;; that enables inlining/integration, this can provide performance
;;; improvements.
;;;
;;; There is enough *explicit* error checking that *all* internal operations
;;; should *never* produce a type or index-range error. Period. Feel like
;;; living dangerously? *Big* performance win to be had by replacing string
;;; and record-field accessors and setters with unsafe equivalents in the
;;; code. Similarly, fixnum-specific operators can speed up the arithmetic
;;; done on the index values in the inner loops. The only arguments that are
;;; not completely error checked are
;;; - string lists (complete checking requires time proportional to the
;;; length of the list)
;;; - procedure arguments, such as char->char maps & predicates.
;;; There is no way to check the range & domain of procedures in Scheme.
;;; Procedures that take these parameters cannot fully check their
;;; arguments. But all other types to all other procedures are fully
;;; checked.
;;;
;;; This does open up the alternate possibility of simply *removing* these
;;; checks, and letting the safe primitives raise the errors. On a dumb
;;; Scheme system, this would provide speed (by eliminating the redundant
;;; error checks) at the cost of error-message clarity.
;;;
;;; In an interpreted Scheme, some of these procedures, or the internal
;;; routines with % prefixes, are excellent candidates for being rewritten
;;; in C.
;;;
;;; It would also be nice to have the ability to mark some of these
;;; routines as candidates for inlining/integration.
;;;
;;; See the comments preceding the hash function code for notes on tuning
;;; the default bound so that the code never overflows your implementation's
;;; fixnum size into bignum calculation.
;;;
;;; All the %-prefixed routines in this source code are written
;;; to be called internally to this library. They do *not* perform
;;; friendly error checks on the inputs; they assume everything is
;;; proper. They also do not take optional arguments. These two properties
;;; save calling overhead and enable procedure integration -- but they
;;; are not appropriate for exported routines.
;;; Copyright notice
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Copyright (c) 1988-1995 Massachusetts Institute of Technology
;;;
;;; This material was developed by the Scheme project at the Massachusetts
;;; Institute of Technology, Department of Electrical Engineering and
;;; Computer Science. Permission to copy and modify this software, to
;;; redistribute either the original software or a modified version, and
;;; to use this software for any purpose is granted, subject to the
;;; following restrictions and understandings.
;;;
;;; 1. Any copy made of this software must include this copyright notice
;;; in full.
;;;
;;; 2. Users of this software agree to make their best efforts (a) to
;;; return to the MIT Scheme project any improvements or extensions that
;;; they make, so that these may be included in future releases; and (b)
;;; to inform MIT of noteworthy uses of this software.
;;;
;;; 3. All materials developed as a consequence of the use of this
;;; software shall duly acknowledge such use, in accordance with the usual
;;; standards of acknowledging credit in academic research.
;;;
;;; 4. MIT has made no warrantee or representation that the operation of
;;; this software will be error-free, and MIT is under no obligation to
;;; provide any services, by way of maintenance, update, or otherwise.
;;;
;;; 5. In conjunction with products arising from the use of this material,
;;; there shall be no use of the name of the Massachusetts Institute of
;;; Technology nor of any adaptation thereof in any advertising,
;;; promotional, or sales literature without prior written consent from
;;; MIT in each case.
(define-library (srfi test) ; -*- scheme -*-
(import (except (scheme base) cond)
(scheme write)
(srfi 61))
(begin
(display (cond
((values 0 1) (lambda (x y) #t)
=> list)))
(newline)))
(use-modules (srfi srfi-11))
(define (assert bool explanation)
(unless bool
(error explanation)))
(define (id= x y)
(and (identifier? x)
(identifier? y)
(free-identifier=? x y)))
(define-syntax uq
(syntax-rules ()
((uq . x) (syntax-error "Unquote used outside quasiquote."))))
(define-syntax uq-s
(syntax-rules ()
((uq-s . x) (syntax-error "Unquote-splicing used outside quasiquote."))))
(define-syntax qq
(lambda (stx)
(define (handle-node node level splicable?)
(if (zero? level)
(values 'one node)
(let ((node (syntax->datum node)))
(if (pair? node)
(handle-pair node level splicable?)
(handle-atom node level)))))
(define (handle-pair pair level splicable?)
(let ((car (datum->syntax stx (car pair)))
(cdr (datum->syntax stx (cdr pair))))
(cond
((id= car #'qq)
(handle-qq pair level))
((id= car #'uq)
(handle-uq pair level))
((and splicable? (id= car #'uq-s))
(handle-uq-s pair level))
(else
(let-values (((type car) (handle-node car level #t))
((_ cdr) (handle-node cdr level #f)))
(case type
((one)
(values 'one #`(cons #,car #,cdr)))
((many)
(values 'one #`(append #,car #,cdr)))))))))
(define (handle-qq qq-form level)
(assert (and (list? qq-form) (= 2 (length qq-form)))
"Quasiquote expects exactly one operand.")
(let ((operand (datum->syntax stx (cadr qq-form))))
(let-values (((_ val) (handle-node operand (+ level 1) #f)))
(values 'one #`(list 'qq #,val)))))
(define (handle-uq uq-form level)
(assert (and (list? uq-form) (= 2 (length uq-form)))
"Unquote expects exactly one operand.")
(let ((operand (datum->syntax stx (cadr uq-form))))
(let-values (((type val) (handle-node operand (- level 1) #t)))
(if (= level 1)
(values type val)
(case type
((one)
(values 'one #`(list 'uq #,val)))
((many)
(values 'one #`(apply list 'uq #,val))))))))
(define (handle-uq-s uq-s-form level)
(assert (and (list? uq-s-form) (= 2 (length uq-s-form)))
"Unquote-splicing expects exactly one operand.")
(let ((operand (datum->syntax stx (cadr uq-s-form))))
(let-values (((type val) (handle-node operand (- level 1) #t)))
(if (= 1 level)
(values 'many val)
(values 'one #`(list 'uq-s #,val))))))
(define (handle-atom atom level)
(let ((atom (datum->syntax stx atom)))
(values 'one #`(quote #,atom))))
(syntax-case stx ()
((qq operand)
(let-values (((_ val) (handle-node #'operand 1 #f)))
val))
((qq . x)
(error "Quasiquote expects exactly one operand.")))))
;;;; benchmark-suite/lib.scm --- generic support for benchmarking
;;;; Copyright (C) 2002, 2006, 2011, 2012 Free Software Foundation, Inc.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3, 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 Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this software; see the file COPYING.LESSER.
;;;; If not, write to the Free Software Foundation, Inc., 51 Franklin
;;;; Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (benchmark-suite lib)
#\use-module (srfi srfi-9)
#\export (;; Controlling the execution.
iteration-factor
scale-iterations
;; Running benchmarks.
run-benchmark
benchmark
;; Naming groups of benchmarks in a regular fashion.
with-benchmark-prefix with-benchmark-prefix*
current-benchmark-prefix format-benchmark-name
;; <benchmark-result> accessors
benchmark-result:name
benchmark-result:iterations
benchmark-result:real-time
benchmark-result:run-time
benchmark-result:gc-time
benchmark-result:core-time
;; Reporting results in various ways.
report current-reporter
register-reporter unregister-reporter reporter-registered?
make-log-reporter
full-reporter
user-reporter))
;;;; If you're using Emacs's Scheme mode:
;;;; (put 'with-benchmark-prefix 'scheme-indent-function 1)
;;;; (put 'benchmark 'scheme-indent-function 1)
;;;; CORE FUNCTIONS
;;;;
;;;; The function (run-benchmark name iterations thunk) is the heart of the
;;;; benchmarking environment. The first parameter NAME is a unique name for
;;;; the benchmark to be executed (for an explanation of this parameter see
;;;; below under ;;;; NAMES. The second parameter ITERATIONS is a positive
;;;; integer value that indicates how often the thunk shall be executed (for
;;;; an explanation of how iteration counts should be used, see below under
;;;; ;;;; ITERATION COUNTS). For example:
;;;;
;;;; (run-benchmark "small integer addition" 100000 (lambda () (+ 1 1)))
;;;;
;;;; This will run the function (lambda () (+ 1 1)) a 100000 times (the
;;;; iteration count can, however be scaled. See below for details). Some
;;;; different time data for running the thunk for the given number of
;;;; iterations is measured and reported.
;;;;
;;;; Convenience macro
;;;;
;;;; * (benchmark name iterations body) is a short form for
;;;; (run-benchmark name iterations (lambda () body))
;;;; NAMES
;;;;
;;;; Every benchmark in the benchmark suite has a unique name to be able to
;;;; compare the results of individual benchmarks across several runs of the
;;;; benchmark suite.
;;;;
;;;; A benchmark name is a list of printable objects. For example:
;;;; ("ports.scm" "file" "read and write back list of strings")
;;;; ("ports.scm" "pipe" "read")
;;;;
;;;; Benchmark names may contain arbitrary objects, but they always have
;;;; the following properties:
;;;; - Benchmark names can be compared with EQUAL?.
;;;; - Benchmark names can be reliably stored and retrieved with the standard
;;;; WRITE and READ procedures; doing so preserves their identity.
;;;;
;;;; For example:
;;;;
;;;; (benchmark "simple addition" 100000 (+ 2 2))
;;;;
;;;; In that case, the benchmark name is the list ("simple addition").
;;;;
;;;; The WITH-BENCHMARK-PREFIX syntax and WITH-BENCHMARK-PREFIX* procedure
;;;; establish a prefix for the names of all benchmarks whose results are
;;;; reported within their dynamic scope. For example:
;;;;
;;;; (begin
;;;; (with-benchmark-prefix "basic arithmetic"
;;;; (benchmark "addition" 100000 (+ 2 2))
;;;; (benchmark "subtraction" 100000 (- 4 2)))
;;;; (benchmark "multiplication" 100000 (* 2 2))))
;;;;
;;;; In that example, the three benchmark names are:
;;;; ("basic arithmetic" "addition"),
;;;; ("basic arithmetic" "subtraction"), and
;;;; ("multiplication").
;;;;
;;;; WITH-BENCHMARK-PREFIX can be nested. Each WITH-BENCHMARK-PREFIX
;;;; appends a new element to the current prefix:
;;;;
;;;; (with-benchmark-prefix "arithmetic"
;;;; (with-benchmark-prefix "addition"
;;;; (benchmark "integer" 100000 (+ 2 2))
;;;; (benchmark "complex" 100000 (+ 2+3i 4+5i)))
;;;; (with-benchmark-prefix "subtraction"
;;;; (benchmark "integer" 100000 (- 2 2))
;;;; (benchmark "complex" 100000 (- 2+3i 1+2i))))
;;;;
;;;; The four benchmark names here are:
;;;; ("arithmetic" "addition" "integer")
;;;; ("arithmetic" "addition" "complex")
;;;; ("arithmetic" "subtraction" "integer")
;;;; ("arithmetic" "subtraction" "complex")
;;;;
;;;; To print a name for a human reader, we DISPLAY its elements,
;;;; separated by ": ". So, the last set of benchmark names would be
;;;; reported as:
;;;;
;;;; arithmetic: addition: integer
;;;; arithmetic: addition: complex
;;;; arithmetic: subtraction: integer
;;;; arithmetic: subtraction: complex
;;;;
;;;; The Guile benchmarks use with-benchmark-prefix to include the name of
;;;; the source file containing the benchmark in the benchmark name, to
;;;; provide each file with its own namespace.
;;;; ITERATION COUNTS
;;;;
;;;; Every benchmark has to be given an iteration count that indicates how
;;;; often it should be executed. The reason is, that in most cases a single
;;;; execution of the benchmark code would not deliver usable timing results:
;;;; The resolution of the system time is not arbitrarily fine. Thus, some
;;;; benchmarks would be executed too quickly to be measured at all. A rule
;;;; of thumb is, that the longer a benchmark runs, the more exact is the
;;;; information about the execution time.
;;;;
;;;; However, execution time depends on several influences: First, the
;;;; machine you are running the benchmark on. Second, the compiler you use.
;;;; Third, which compiler options you use. Fourth, which version of guile
;;;; you are using. Fifth, which guile options you are using (for example if
;;;; you are using the debugging evaluator or not). There are even more
;;;; influences.
;;;;
;;;; For this reason, the same number of iterations for a single benchmark may
;;;; lead to completely different execution times in different
;;;; constellations. For someone working on a slow machine, the default
;;;; execution counts may lead to an inacceptable execution time of the
;;;; benchmark suite. For someone on a very fast machine, however, it may be
;;;; desireable to increase the number of iterations in order to increase the
;;;; accuracy of the time data.
;;;;
;;;; For this reason, the benchmark suite allows to scale the number of
;;;; executions by a global factor, stored in the exported variable
;;;; iteration-factor. The default for iteration-factor is 1. A number of 2
;;;; means, that all benchmarks are executed twice as often, which will also
;;;; roughly double the execution time for the benchmark suite. Similarly, if
;;;; iteration-factor holds a value of 0.5, only about half the execution time
;;;; will be required.
;;;;
;;;; It is probably a good idea to choose the iteration count for each
;;;; benchmark such that all benchmarks will take about the same time, for
;;;; example one second. To achieve this, the benchmark suite holds an empty
;;;; benchmark in the file 0-reference.bm named "reference benchmark for
;;;; iteration counts". It's iteration count is calibrated to make the
;;;; benchmark run about one second on Dirk's laptop :-) If you are adding
;;;; benchmarks to the suite, it would be nice if you could calibrate the
;;;; number of iterations such that each of your added benchmarks takes about
;;;; as long to run as the reference benchmark. But: Don't be too accurate
;;;; to figure out the correct iteration count.
;;;; REPORTERS
;;;;
;;;; A reporter is a function which we apply to each benchmark outcome.
;;;; Reporters can log results, print interesting results to the standard
;;;; output, collect statistics, etc.
;;;;
;;;; A reporter function takes the following arguments: NAME ITERATIONS
;;;; BEFORE AFTER GC-TIME. The argument NAME holds the name of the benchmark,
;;;; ITERATIONS holds the actual number of iterations that were performed.
;;;; BEFORE holds the result of the function (times) at the very beginning of
;;;; the excution of the benchmark, AFTER holds the result of the function
;;;; (times) after the execution of the benchmark. GC-TIME, finally, holds
;;;; the difference of calls to (gc-run-time) before and after the execution
;;;; of the benchmark.
;;;;
;;;; This library provides some standard reporters for logging results
;;;; to a file, reporting interesting results to the user, (FIXME: and
;;;; collecting totals).
;;;;
;;;; You can use the REGISTER-REPORTER function and friends to add whatever
;;;; reporting functions you like. See under ;;;; TIMING DATA to see how the
;;;; library helps you to extract relevant timing information from the values
;;;; ITERATIONS, BEFORE, AFTER and GC-TIME. If you don't register any
;;;; reporters, the library uses USER-REPORTER, which writes the most
;;;; interesting results to the standard output.
;;;; TIME CALCULATION
;;;;
;;;; The library uses the guile functions `get-internal-run-time',
;;;; `get-internal-real-time', and `gc-run-time' to determine the
;;;; execution time for a single benchmark. Based on these functions,
;;;; Guile makes a <benchmark-result>, a record containing the elapsed
;;;; run time, real time, gc time, and possibly other metrics. These
;;;; times include the time needed to executed the benchmark code
;;;; itself, but also the surrounding code that implements the loop to
;;;; run the benchmark code for the given number of times. This is
;;;; undesirable, since one would prefer to only get the timing data for
;;;; the benchmarking code.
;;;;
;;;; To cope with this, the benchmarking framework uses a trick: During
;;;; initialization of the library, the time for executing an empty
;;;; benchmark is measured and stored. This is an estimate for the time
;;;; needed by the benchmarking framework itself. For later benchmarks,
;;;; this time can then be subtracted from the measured execution times.
;;;; Note that for very short benchmarks, this may result in a negative
;;;; number.
;;;;
;;;; The benchmarking framework provides the following accessors for
;;;; <benchmark-result> values. Note that all time values are in
;;;; internal time units; divide by internal-time-units-per-second to
;;;; get seconds.
;;;;
;;;; benchmark-result:name : Return the name of the benchmark.
;;;;
;;;; benchmark-result:iterations : Return the number of iterations that
;;;; this benchmark ran for.
;;;;
;;;; benchmark-result:real-time : Return the clock time elapsed while
;;;; this benchmark executed.
;;;;
;;;; benchmark-result:run-time : Return the CPU time elapsed while this
;;;; benchmark executed, both in user and kernel space.
;;;;
;;;; benchmark-result:gc-time : Return the approximate amount of time
;;;; spent in garbage collection while this benchmark executed, both
;;;; in user and kernel space.
;;;;
;;;; benchmark-result:core-time : Like benchmark-result:run-time, but
;;;; also estimates the time spent by the framework for the number
;;;; of iterations, and subtracts off that time from the result.
;;;;
;;;; This module is used when benchmarking different Guiles, and so it
;;;; should run on all the Guiles of interest. Currently this set
;;;; includes Guile 1.8, so be careful with introducing features that
;;;; only Guile 2.0 supports.
;;;; MISCELLANEOUS
;;;;
(define-record-type <benchmark-result>
(make-benchmark-result name iterations real-time run-time gc-time)
benchmark-result?
(name benchmark-result:name)
(iterations benchmark-result:iterations)
(real-time benchmark-result:real-time)
(run-time benchmark-result:run-time)
(gc-time benchmark-result:gc-time))
;;; Perform a division and convert the result to inexact.
(define (->seconds time)
(/ time 1.0 internal-time-units-per-second))
;;; Scale the number of iterations according to the given scaling factor.
(define iteration-factor 1)
(define (scale-iterations iterations)
(let* ((i (inexact->exact (round (* iterations iteration-factor)))))
(if (< i 1) 1 i)))
;;; Parameters.
(cond-expand
(srfi-39 #t)
(else (use-modules (srfi srfi-39))))
;;;; CORE FUNCTIONS
;;;;
;;; The central routine for executing benchmarks.
;;; The idea is taken from Greg, the GNUstep regression test environment.
(define benchmark-running? (make-parameter #f))
(define (run-benchmark name iterations thunk)
(if (benchmark-running?)
(error "Nested calls to run-benchmark are not permitted."))
(if (not (and (integer? iterations) (exact? iterations)))
(error "Expected exact integral number of iterations"))
(parameterize ((benchmark-running? #t))
;; Warm up the benchmark first. This will resolve any toplevel-ref
;; forms.
(thunk)
(gc)
(let* ((before-gc-time (gc-run-time))
(before-real-time (get-internal-real-time))
(before-run-time (get-internal-run-time)))
(do ((i iterations (1- i)))
((zero? i))
(thunk))
(let ((after-run-time (get-internal-run-time))
(after-real-time (get-internal-real-time))
(after-gc-time (gc-run-time)))
(report (make-benchmark-result (full-name name) iterations
(- after-real-time before-real-time)
(- after-run-time before-run-time)
(- after-gc-time before-gc-time)))))))
;;; A short form for benchmarks.
(cond-expand
(guile-2
(define-syntax-rule (benchmark name iterations body body* ...)
(run-benchmark name iterations (lambda () body body* ...))))
(else
(defmacro benchmark (name iterations body . rest)
`(run-benchmark ,name ,iterations (lambda () ,body ,@rest)))))
;;;; BENCHMARK NAMES
;;;;
;;;; Turn a benchmark name into a nice human-readable string.
(define (format-benchmark-name name)
(string-join name ": "))
;;;; For a given benchmark-name, deliver the full name including all prefixes.
(define (full-name name)
(append (current-benchmark-prefix) (list name)))
;;; A parameter containing the current benchmark prefix, as a list.
(define current-benchmark-prefix
(make-parameter '()))
;;; Postpend PREFIX to the current name prefix while evaluting THUNK.
;;; The name prefix is only changed within the dynamic scope of the
;;; call to with-benchmark-prefix*. Return the value returned by THUNK.
(define (with-benchmark-prefix* prefix thunk)
(parameterize ((current-benchmark-prefix (full-name prefix)))
(thunk)))
;;; (with-benchmark-prefix PREFIX BODY ...)
;;; Postpend PREFIX to the current name prefix while evaluating BODY ...
;;; The name prefix is only changed within the dynamic scope of the
;;; with-benchmark-prefix expression. Return the value returned by the last
;;; BODY expression.
(cond-expand
(guile-2
(define-syntax-rule (with-benchmark-prefix prefix body body* ...)
(with-benchmark-prefix* prefix (lambda () body body* ...))))
(else
(defmacro with-benchmark-prefix (prefix . body)
`(with-benchmark-prefix* ,prefix (lambda () ,@body)))))
;;;; Benchmark results
;;;;
(define *calibration-result*
"<will be set during initialization>")
(define (benchmark-overhead iterations accessor)
(* (/ iterations 1.0 (benchmark-result:iterations *calibration-result*))
(accessor *calibration-result*)))
(define (benchmark-result:core-time result)
(- (benchmark-result:run-time result)
(benchmark-overhead (benchmark-result:iterations result)
benchmark-result:run-time)))
;;;; REPORTERS
;;;;
;;; The global set of reporters.
(define report-hook (make-hook 1))
(define (default-reporter result)
(if (hook-empty? report-hook)
(user-reporter result)
(run-hook report-hook result)))
(define current-reporter
(make-parameter default-reporter))
(define (register-reporter reporter)
(add-hook! report-hook reporter))
(define (unregister-reporter reporter)
(remove-hook! report-hook reporter))
;;; Return true iff REPORTER is in the current set of reporter functions.
(define (reporter-registered? reporter)
(if (memq reporter (hook->list report-hook)) #t #f))
;;; Send RESULT to all currently registered reporter functions.
(define (report result)
((current-reporter) result))
;;;; Some useful standard reporters:
;;;; Log reporters write all benchmark results to a given log file.
;;;; Full reporters write all benchmark results to the standard output.
;;;; User reporters write some interesting results to the standard output.
;;; Display a single benchmark result to the given port
(define (print-result port result)
(let ((name (format-benchmark-name (benchmark-result:name result)))
(iterations (benchmark-result:iterations result))
(real-time (benchmark-result:real-time result))
(run-time (benchmark-result:run-time result))
(gc-time (benchmark-result:gc-time result))
(core-time (benchmark-result:core-time result)))
(write (list name iterations
'total (->seconds real-time)
'user (->seconds run-time)
'system 0
'frame (->seconds (- run-time core-time))
'benchmark (->seconds core-time)
'user/interp (->seconds (- run-time gc-time))
'bench/interp (->seconds (- core-time gc-time))
'gc (->seconds gc-time))
port)
(newline port)))
;;; Return a reporter procedure which prints all results to the file
;;; FILE, in human-readable form. FILE may be a filename, or a port.
(define (make-log-reporter file)
(let ((port (if (output-port? file) file
(open-output-file file))))
(lambda (result)
(print-result port result)
(force-output port))))
;;; A reporter that reports all results to the user.
(define (full-reporter result)
(print-result (current-output-port) result))
;;; Display interesting results of a single benchmark to the given port
(define (print-user-result port result)
(let ((name (format-benchmark-name (benchmark-result:name result)))
(iterations (benchmark-result:iterations result))
(real-time (benchmark-result:real-time result))
(run-time (benchmark-result:run-time result))
(gc-time (benchmark-result:gc-time result))
(core-time (benchmark-result:core-time result)))
(write (list name iterations
'real (->seconds real-time)
'real/iteration (->seconds (/ real-time iterations))
'run/iteration (->seconds (/ run-time iterations))
'core/iteration (->seconds (/ core-time iterations))
'gc (->seconds gc-time))
port)
(newline port)))
;;; A reporter that reports interesting results to the user.
(define (user-reporter result)
(print-user-result (current-output-port) result))
;;;; Initialize the benchmarking system:
;;;;
(define (calibrate-benchmark-framework)
(display ";; running guile version ")
(display (version))
(newline)
(display ";; calibrating the benchmarking framework...")
(newline)
(parameterize ((current-reporter
(lambda (result)
(set! *calibration-result* result)
(display ";; calibration: ")
(print-user-result (current-output-port) result))))
(benchmark "empty initialization benchmark" 10000000 #t)))
(calibrate-benchmark-framework)
;; -*- Scheme -*-
;;
;; A library of dumb functions that may be used to benchmark Guile-VM.
;; The comments are from Ludovic, a while ago. The speedups now are much
;; more significant (all over 2x, sometimes 8x).
(define (fibo x)
(if (or (= x 1) (= x 2))
1
(+ (fibo (- x 1))
(fibo (- x 2)))))
(define (g-c-d x y)
(if (= x y)
x
(if (< x y)
(g-c-d x (- y x))
(g-c-d (- x y) y))))
(define (loop n)
;; This one shows that procedure calls are no faster than within the
;; interpreter: the VM yields no performance improvement.
(if (= 0 n)
0
(loop (1- n))))
;; Disassembly of `loop'
;;
;; Disassembly of #<objcode b79bdf28>:
;; nlocs = 0 nexts = 0
;; 0 (make-int8 64) ;; 64
;; 2 (load-symbol "guile-user") ;; guile-user
;; 14 (list 0 1) ;; 1 element
;; 17 (load-symbol "loop") ;; loop
;; 23 (link-later)
;; 24 (vector 0 1) ;; 1 element
;; 27 (make-int8 0) ;; 0
;; 29 (load-symbol "n") ;; n
;; 32 (make-false) ;; #f
;; 33 (make-int8 0) ;; 0
;; 35 (list 0 3) ;; 3 elements
;; 38 (list 0 2) ;; 2 elements
;; 41 (list 0 1) ;; 1 element
;; 44 (make-int8 5) ;; 5
;; 46 (make-false) ;; #f
;; 47 (cons)
;; 48 (make-int8 18) ;; 18
;; 50 (make-false) ;; #f
;; 51 (cons)
;; 52 (make-int8 20) ;; 20
;; 54 (make-false) ;; #f
;; 55 (cons)
;; 56 (list 0 4) ;; 4 elements
;; 59 (load-program ##{66}#)
;; 81 (define "loop")
;; 87 (variable-set)
;; 88 (void)
;; 89 (return)
;; Bytecode ##{66}#\
;; 0 (make-int8 0) ;; 0
;; 2 (local-ref 0)
;; 4 (ee?)
;; 5 (br-if-not 0 3) ;; -> 11
;; 8 (make-int8 0) ;; 0
;; 10 (return)
;; 11 (toplevel-ref 0)
;; 13 (local-ref 0)
;; 15 (make-int8 1) ;; 1
;; 17 (sub)
;; 18 (tail-call 1)
(define (loopi n)
;; Same as `loop'.
(let loopi ((n n))
(if (= 0 n)
0
(loopi (1- n)))))
(define (do-loop n)
;; Same as `loop' using `do'.
(do ((i n (1- i)))
((= 0 i))
;; do nothing
))
(define (do-cons x)
;; This one shows that the built-in `cons' instruction yields a significant
;; improvement (speedup: 1.5).
(let loop ((x x)
(result '()))
(if (<= x 0)
result
(loop (1- x) (cons x result)))))
(define big-list (iota 500000))
(define (copy-list lst)
;; Speedup: 5.9.
(let loop ((lst lst)
(result '()))
(if (null? lst)
result
(loop (cdr lst)
(cons (car lst) result)))))
;; A simple interpreter vs. VM performance comparison tool
;;
(define-module (measure)
\:export (measure)
\:use-module (system vm vm)
\:use-module (system base compile)
\:use-module (system base language))
(define (time-for-eval sexp eval)
(let ((before (tms:utime (times))))
(eval sexp)
(let ((elapsed (- (tms:utime (times)) before)))
(format #t "elapsed time: ~a~%" elapsed)
elapsed)))
(define *scheme* (lookup-language 'scheme))
(define (measure . args)
(if (< (length args) 2)
(begin
(format #t "Usage: measure SEXP FILE-TO-LOAD...~%")
(format #t "~%")
(format #t "Example: measure '(loop 23424)' lib.scm~%~%")
(exit 1)))
(for-each load (cdr args))
(let* ((sexp (with-input-from-string (car args)
(lambda ()
(read))))
(eval-here (lambda (sexp) (eval sexp (current-module))))
(proc-name (car sexp))
(proc-source (procedure-source (eval proc-name (current-module))))
(% (format #t "proc: ~a~%source: ~a~%" proc-name proc-source))
(time-interpreted (time-for-eval sexp eval-here))
(& (if (defined? proc-name)
(eval `(set! ,proc-name #f) (current-module))
(format #t "unbound~%")))
(the-program (compile proc-source))
(time-compiled (time-for-eval `(,proc-name ,@(cdr sexp))
(lambda (sexp)
(eval `(begin
(define ,proc-name
,the-program)
,sexp)
(current-module))))))
(format #t "proc: ~a => ~a~%"
proc-name (eval proc-name (current-module)))
(format #t "interpreted: ~a~%" time-interpreted)
(format #t "compiled: ~a~%" time-compiled)
(format #t "speedup: ~a~%"
(exact->inexact (/ time-interpreted time-compiled)))
0))
(define main measure)
;;; guile-emacs.scm --- Guile Emacs interface
;; Copyright (C) 2001, 2010 Keisuke Nishida <kxn30@po.cwru.edu>
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
;;;; 02111-1307 USA
;;; Code:
(use-modules (ice-9 regex))
(use-modules (ice-9 channel))
(use-modules (ice-9 session))
(use-modules (ice-9 documentation))
;;;
;;; Emacs Lisp channel
;;;
(define (emacs-lisp-channel)
(define (native-type? x)
(or (integer? x) (symbol? x) (string? x) (pair? x) (vector? x)))
(define (emacs-lisp-print ch val)
(cond
((unspecified? val))
((eq? val #t) (channel-print-value ch 't))
((or (eq? val #f) (null? val)) (channel-print-value ch 'nil))
((native-type? val) (channel-print-value ch val))
(else (channel-print-token ch val))))
(channel-open (make-object-channel emacs-lisp-print)))
;;;
;;; Scheme channel
;;;
(define (emacs-scheme-channel)
(define (print ch val) (channel-print-value ch (object->string val)))
(channel-open (make-object-channel print)))
;;;
;;; for guile-import and guile-import-module
;;;
(define (guile-emacs-export-procedure name proc docs)
(define (procedure-args proc)
(let ((source (procedure-source proc)))
(if source
;; formals -> emacs args
(let loop ((formals (cadr source)))
(cond
((null? formals) '())
((symbol? formals) `(&rest ,formals))
(else (cons (car formals) (loop (cdr formals))))))
;; arity -> emacs args
(let* ((arity (procedure-minimum-arity proc))
(nreqs (car arity))
(nopts (cadr arity))
(restp (caddr arity)))
(define (nsyms n)
(if (= n 0) '() (cons (gensym "a") (nsyms (1- n)))))
(append! (nsyms nreqs)
(if (> nopts 0) (cons '&optional (nsyms nopts)) '())
(if restp (cons '&rest (nsyms 1)) '()))))))
(define (procedure-call name args)
(let ((restp (memq '&rest args))
(args (delq '&rest (delq '&optional args))))
(if restp
`('apply ',name ,@args)
`(',name ,@args))))
(let ((args (procedure-args proc))
(docs (and docs (object-documentation proc))))
`(defun ,name ,args
,@(if docs (list docs) '())
(guile-lisp-flat-eval ,@(procedure-call (procedure-name proc) args)))))
(define (guile-emacs-export proc-name func-name docs)
(let ((proc (module-ref (current-module) proc-name)))
(guile-emacs-export-procedure func-name proc docs)))
(define (guile-emacs-export-procedures module-name docs)
(define (module-public-procedures name)
(hash-fold (lambda (s v d)
(let ((val (variable-ref v)))
(if (procedure? val) (acons s val d) d)))
'() (module-obarray (resolve-interface name))))
`(progn ,@(map (lambda (n+p)
(guile-emacs-export-procedure (car n+p) (cdr n+p) docs))
(module-public-procedures module-name))))
;;;
;;; for guile-scheme-complete-symbol
;;;
(define (guile-emacs-complete-alist str)
(sort! (apropos-fold (lambda (module name val data)
(cons (list (symbol->string name)
(cond ((procedure? val) " <p>")
((macro? val) " <m>")
(else "")))
data))
'() (string-append "^" (regexp-quote str))
apropos-fold-all)
(lambda (p1 p2) (string<? (car p1) (car p2)))))
;;;
;;; for guile-scheme-apropos
;;;
(define (guile-emacs-apropos regexp)
(with-output-to-string (lambda () (apropos regexp))))
;;;
;;; for guile-scheme-describe
;;;
(define (guile-emacs-describe sym)
(object-documentation (eval sym (current-module))))
;;;
;;; Guile 1.4 compatibility
;;;
(define object->string
(if (defined? 'object->string)
object->string
(lambda (x) (format #f "~S" x))))
;;; guile-emacs.scm ends here
;;; examples/box-dynamic-module/box-mixed.scm -- Scheme module using some
;;; functionality from the shared library libbox-module, but do not
;;; export procedures from the module.
;;; Commentary:
;;; This is the Scheme module box-mixed. It uses some functionality
;;; from the shared library libbox-module, but does not export it.
;;; Code:
;;; Author: Thomas Wawrzinek
;;; Date: 2001-06-08
;;; Changed: 2001-06-14 by martin, some commenting, cleanup and integration.
(define-module (box-mixed))
;; First, load the library.
;;
(load-extension "libbox-module" "scm_init_box")
;; Create a list of boxes, each containing one element from ARGS.
;;
(define (make-box-list . args)
(map (lambda (el)
(let ((b (make-box)))
(box-set! b el) b))
args))
;; Map the procedure FUNC over all elements of LST, which must be a
;; list of boxes. The result is a list of freshly allocated boxes,
;; each containing the result of an application of FUNC.
(define (box-map func lst)
(map (lambda (el)
(let ((b (make-box)))
(box-set! b (func (box-ref el)))
b))
lst))
;; Export the procedures, so that they can be used by others.
;;
(export make-box-list box-map)
;;; End of file.
;;; examples/box-dynamic-module/box-module.scm -- Scheme module exporting
;;; some functionality from the shared library libbox-module.
;;; Commentary:
;;; This is the Scheme part of the dynamic library module (box-module).
;;; When you do a (use-modules (box-module)) in this directory,
;;; this file gets loaded and will load the compiled extension.
;;; Code:
;;; Author: Martin Grabmueller
;;; Date: 2001-06-06
(define-module (box-module))
;; First, load the library.
;;
(load-extension "libbox-module" "scm_init_box")
;; Then export the procedures which should be visible to module users.
;;
(export make-box box-ref box-set!)
;;; End of file.
;;; examples/modules/module-0.scm -- Module system demo.
;;; Commentary:
;;; Module 0 of the module demo program.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-29
;;; Code:
(define-module (module-0))
(export foo bar)
(define (foo)
(display "module-0 foo")
(newline))
(define (bar)
(display "module-0 bar")
(newline))
;;; End of file.
;;; examples/modules/module-1.scm -- Module system demo.
;;; Commentary:
;;; Module 1 of the module demo program.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-29
;;; Code:
(define-module (module-1))
(export foo bar)
(define (foo)
(display "module-1 foo")
(newline))
(define (bar)
(display "module-1 bar")
(newline))
;;; End of file.
;;; examples/modules/module-2.scm -- Module system demo.
;;; Commentary:
;;; Module 2 of the module demo program.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-29
;;; Code:
(define-module (module-2))
(export foo bar braz)
(define (foo)
(display "module-2 foo")
(newline))
(define (bar)
(display "module-2 bar")
(newline))
(define (braz)
(display "module-2 braz")
(newline))
;;; End of file.
;;; examples/safe/evil.scm -- Evil Scheme file to be run in a safe
;;; environment.
;;; Commentary:
;;; This is an example file to be evaluated by the `safe' program in
;;; this directory. This program, unlike the `untrusted.scm' (which
;;; is untrusted, but a really nice fellow though), tries to do evil
;;; things and will thus break in a safe environment.
;;;
;;; *Note* that the files in this directory are only suitable for
;;; demonstration purposes, if you have to implement safe evaluation
;;; mechanisms in important environments, you will have to do more
;;; than shown here -- for example disabling input/output operations.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-30
;;; Code:
(define passwd (open-input-file "/etc/passwd"))
(let lp ((ch (read-char passwd)))
(if (not (eof-object? ch))
(lp (read-char passwd))))
;;; End of file.
;;; examples/safe/untrusted.scm -- Scheme file to be run in a safe
;;; environment.
;;; Commentary:
;;; This is an example file to be evaluated by the `safe' program in
;;; this directory.
;;;
;;; *Note* that the files in this directory are only suitable for
;;; demonstration purposes, if you have to implement safe evaluation
;;; mechanisms in important environments, you will have to do more
;;; than shown here -- for example disabling input/output operations.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-30
;;; Code:
;; fact -- the everlasting factorial function...
;;
(define (fact n)
(if (< n 2)
1
(* n (fact (- n 1)))))
;; Display the factorial of 0..9 to the terminal.
;;
(do ((x 0 (+ x 1)))
((= x 11))
(display (fact x))
(newline))
;;; End of file.
;;; Commentary:
;;; This is the famous Hello-World-program, written for Guile.
;;;
;;; For an advanced version, see the script `hello' in the same
;;; directory.
;;; Author: Martin Grabmueller
;;; Date: 2001-05-29
;;; Code:
(display "Hello, World!")
(newline)
;;; End of file.
;;; Commentary:
;;; A simple debugging server that responds to all responses with a
;;; table containing the headers given in the request.
;;;
;;; As a novelty, this server uses a little micro-framework to build up
;;; the response as SXML. Instead of a string, the `respond' helper
;;; returns a procedure for the body, which allows the `(web server)'
;;; machinery to collect the output as a bytevector in the desired
;;; encoding, instead of building an intermediate output string.
;;;
;;; In the future this will also allow for chunked transfer-encoding,
;;; for HTTP/1.1 clients.
;;; Code:
(use-modules (web server)
(web request)
(web response)
(sxml simple))
(define html5-doctype "<!DOCTYPE html>\n")
(define default-title "Hello hello!")
(define* (templatize #\key (title "No title") (body '((p "No body"))))
`(html (head (title ,title))
(body ,@body)))
(define* (respond #\optional body #\key
(status 200)
(title default-title)
(doctype html5-doctype)
(content-type-params '((charset . "utf-8")))
(content-type 'text/html)
(extra-headers '())
(sxml (and body (templatize #\title title #\body body))))
(values (build-response
#\code status
#\headers `((content-type . (,content-type ,@content-type-params))
,@extra-headers))
(lambda (port)
(if sxml
(begin
(if doctype (display doctype port))
(sxml->xml sxml port))))))
(define (debug-page request body)
(respond `((h1 "hello world!")
(table
(tr (th "header") (th "value"))
,@(map (lambda (pair)
`(tr (td (tt ,(with-output-to-string
(lambda () (display (car pair))))))
(td (tt ,(with-output-to-string
(lambda ()
(write (cdr pair))))))))
(request-headers request))))))
(run-server debug-page)
;;; Commentary:
;;; A simple web server that responds to all requests with the eponymous
;;; string. Visit http://localhost:8080 to test.
;;; Code:
(use-modules (web server))
;; A handler receives two values as arguments: the request object, and
;; the request body. It returns two values also: the response object,
;; and the response body.
;;
;; In this simple example we don't actually access the request object,
;; but if we wanted to, we would use the procedures from the `(web
;; request)' module. If there is no body given in the request, the body
;; argument will be false.
;;
;; To create a response object, use the `build-response' procedure from
;; `(web response)'. Here we take advantage of a shortcut, in which we
;; return an alist of headers for the response instead of returning a
;; proper response object. In this case, a response object will be made
;; for us with a 200 OK status.
;;
(define (handler request body)
(values '((content-type . (text/plain)))
"Hello, World!"))
(run-server handler)
;;; Copyright (C) 2008, 2011 Free Software Foundation, Inc.
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public License
;;; as published by the Free Software Foundation; either version 3, 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 Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this software; see the file COPYING.LESSER. If
;;; not, write to the Free Software Foundation, Inc., 51 Franklin
;;; Street, Fifth Floor, Boston, MA 02110-1301 USA
(use-modules (ice-9 format)
(ice-9 rdelim)
(ice-9 regex)
(srfi srfi-1)
(srfi srfi-37)
(srfi srfi-39))
;;;
;;; Memory usage.
;;;
(define (memory-mappings pid)
"Return an list of alists, each of which contains information about a
memory mapping of process @var{pid}. This information is obtained by reading
@file{/proc/PID/smaps} on Linux. See `procs(5)' for details."
(define mapping-line-rx
;; As of Linux 2.6.32.28, an `smaps' line looks like this:
;; "00400000-00401000 r-xp 00000000 fe:00 108264 /home/ludo/soft/bin/guile"
(make-regexp
"^([[:xdigit:]]+)-([[:xdigit:]]+) ([rwx-]{3}[ps]) ([[:xdigit:]]+) [[:xdigit:]]{2}:[[:xdigit:]]{2} [0-9]+[[:blank:]]+(.*)$"))
(define rss-line-rx
(make-regexp
"^Rss:[[:blank:]]+([[:digit:]]+) kB$"))
(if (not (string-contains %host-type "-linux-"))
(error "this procedure only works on Linux-based systems" %host-type))
(with-input-from-port (open-input-file (format #f "/proc/~a/smaps" pid))
(lambda ()
(let loop ((line (read-line))
(result '()))
(if (eof-object? line)
(reverse result)
(cond ((regexp-exec mapping-line-rx line)
=>
(lambda (match)
(let ((mapping-start (string->number
(match:substring match 1)
16))
(mapping-end (string->number
(match:substring match 2)
16))
(access-bits (match:substring match 3))
(name (match:substring match 5)))
(loop (read-line)
(cons `((mapping-start . ,mapping-start)
(mapping-end . ,mapping-end)
(access-bits . ,access-bits)
(name . ,(if (string=? name "")
#f
name)))
result)))))
((regexp-exec rss-line-rx line)
=>
(lambda (match)
(let ((section+ (cons (cons 'rss
(string->number
(match:substring match 1)))
(car result))))
(loop (read-line)
(cons section+ (cdr result))))))
(else
(loop (read-line) result))))))))
(define (total-heap-size pid)
"Return a pair representing the total and RSS heap size of PID."
(define heap-or-anon-rx
(make-regexp "\\[(heap|anon)\\]"))
(define private-mapping-rx
(make-regexp "^[r-][w-][x-]p$"))
(fold (lambda (heap total+rss)
(let ((name (assoc-ref heap 'name))
(perm (assoc-ref heap 'access-bits)))
;; Include anonymous private mappings.
(if (or (and (not name)
(regexp-exec private-mapping-rx perm))
(and name
(regexp-exec heap-or-anon-rx name)))
(let ((start (assoc-ref heap 'mapping-start))
(end (assoc-ref heap 'mapping-end))
(rss (assoc-ref heap 'rss)))
(cons (+ (car total+rss) (- end start))
(+ (cdr total+rss) rss)))
total+rss)))
'(0 . 0)
(memory-mappings pid)))
(define (display-stats start end)
(define (->usecs sec+usecs)
(+ (* 1000000 (car sec+usecs))
(cdr sec+usecs)))
(let ((usecs (- (->usecs end) (->usecs start)))
(heap-size (total-heap-size (getpid)))
(gc-heap-size (assoc-ref (gc-stats) 'heap-size)))
(format #t "execution time: ~6,3f seconds~%"
(/ usecs 1000000.0))
(and gc-heap-size
(format #t "GC-reported heap size: ~8d B (~1,2f MiB)~%"
gc-heap-size
(/ gc-heap-size 1024.0 1024.0)))
(format #t "heap size: ~8d B (~1,2f MiB)~%"
(car heap-size)
(/ (car heap-size) 1024.0 1024.0))
(format #t "heap RSS: ~8d KiB (~1,2f MiB)~%"
(cdr heap-size)
(/ (cdr heap-size) 1024.0))
;; (system (format #f "cat /proc/~a/smaps" (getpid)))
;; (system (format #f "exmtool procs | grep -E '^(PID|~a)'" (getpid)))
))
;;;
;;; Larceny/Twobit benchmarking compability layer.
;;;
(define *iteration-count*
(make-parameter #f))
(define (run-benchmark name . args)
"A @code{run-benchmark} procedure compatible with Larceny's GC benchmarking
framework. See
@url{http://www.ccs.neu.edu/home/will/Twobit/benchmarksAbout.html} for
details."
(define %concise-invocation?
;; This procedure can be called with only two arguments, NAME and
;; RUN-MAKER.
(procedure? (car args)))
(let ((count (or (*iteration-count*)
(if %concise-invocation? 0 (car args))))
(run-maker (if %concise-invocation? (car args) (cadr args)))
(ok? (if %concise-invocation?
(lambda (result) #t)
(caddr args)))
(args (if %concise-invocation? '() (cdddr args))))
(let loop ((i 0))
(and (< i count)
(let ((result (apply run-maker args)))
(if (not (ok? result))
(begin
(format (current-output-port) "invalid result for `~A'~%"
name)
(exit 1)))
(loop (1+ i)))))))
(define (save-directory-excursion directory thunk)
(let ((previous-dir (getcwd)))
(dynamic-wind
(lambda ()
(chdir directory))
thunk
(lambda ()
(chdir previous-dir)))))
(define (load-larceny-benchmark file)
"Load the Larceny benchmark from @var{file}."
(let ((name (let ((base (basename file)))
(substring base 0 (or (string-rindex base #\.)
(string-length base)))))
(module (let ((m (make-module)))
(beautify-user-module! m)
(module-use! m (resolve-interface '(ice-9 syncase)))
m)))
(save-directory-excursion (dirname file)
(lambda ()
(save-module-excursion
(lambda ()
(set-current-module module)
(module-define! module 'run-benchmark run-benchmark)
(load (basename file))
;; Invoke the benchmark's entry point.
(let ((entry (module-ref (current-module)
(symbol-append (string->symbol name)
'-benchmark))))
(entry))))))))
;;;
;;; Option processing.
;;;
(define %options
(list (option '(#\h "help") #f #f
(lambda args
(show-help)
(exit 0)))
(option '(#\l "larceny") #f #f
(lambda (opt name arg result)
(alist-cons 'larceny? #t result)))
(option '(#\i "iterations") #t #f
(lambda (opt name arg result)
(alist-cons 'iterations (string->number arg) result)))))
(define (show-help)
(format #t "Usage: gc-profile [OPTIONS] FILE.SCM
Load FILE.SCM, a Guile Scheme source file, and report its execution time and
final heap usage.
-h, --help Show this help message
-l, --larceny Provide mechanisms compatible with the Larceny/Twobit
GC benchmark suite.
-i, --iterations=COUNT
Run the given benchmark COUNT times, regardless of the
iteration count passed to `run-benchmark' (for Larceny
benchmarks).
Report bugs to <bug-guile@gnu.org>.~%"))
(define (parse-args args)
(define (leave fmt . args)
(apply format (current-error-port) (string-append fmt "~%") args)
(exit 1))
(args-fold args %options
(lambda (opt name arg result)
(leave "~A: unrecognized option" opt))
(lambda (file result)
(if (pair? (assoc 'input result))
(leave "~a: only one input file at a time" file)
(alist-cons 'input file result)))
'()))
;;;
;;; Main program.
;;;
(define (main . args)
(let* ((options (parse-args args))
(prog (assoc-ref options 'input))
(load (if (assoc-ref options 'larceny?)
load-larceny-benchmark
load)))
(parameterize ((*iteration-count* (assoc-ref options 'iterations)))
(format #t "running `~a' with Guile ~a...~%" prog (version))
(let ((start (gettimeofday)))
(dynamic-wind
(lambda ()
#t)
(lambda ()
(set! quit (lambda args args))
(load prog))
(lambda ()
(let ((end (gettimeofday)))
(format #t "done~%")
(display-stats start end))))))))
; This is adapted from a benchmark written by John Ellis and Pete Kovac
; of Post Communications.
; It was modified by Hans Boehm of Silicon Graphics.
; It was translated into Scheme by William D Clinger of Northeastern Univ;
; the Scheme version uses (RUN-BENCHMARK <string> <thunk>)
; Last modified 30 May 1997.
;
; This is no substitute for real applications. No actual application
; is likely to behave in exactly this way. However, this benchmark was
; designed to be more representative of real applications than other
; Java GC benchmarks of which we are aware.
; It attempts to model those properties of allocation requests that
; are important to current GC techniques.
; It is designed to be used either to obtain a single overall performance
; number, or to give a more detailed estimate of how collector
; performance varies with object lifetimes. It prints the time
; required to allocate and collect balanced binary trees of various
; sizes. Smaller trees result in shorter object lifetimes. Each cycle
; allocates roughly the same amount of memory.
; Two data structures are kept around during the entire process, so
; that the measured performance is representative of applications
; that maintain some live in-memory data. One of these is a tree
; containing many pointers. The other is a large array containing
; double precision floating point numbers. Both should be of comparable
; size.
;
; The results are only really meaningful together with a specification
; of how much memory was used. It is possible to trade memory for
; better time performance. This benchmark should be run in a 32 MB
; heap, though we don't currently know how to enforce that uniformly.
; In the Java version, this routine prints the heap size and the amount
; of free memory. There is no portable way to do this in Scheme; each
; implementation needs its own version.
(use-modules (ice-9 syncase))
(define (PrintDiagnostics)
(display " Total memory available= ???????? bytes")
(display " Free memory= ???????? bytes")
(newline))
(define (run-benchmark str thu)
(display str)
(thu))
; Should we implement a Java class as procedures or hygienic macros?
; Take your pick.
(define-syntax let-class
(syntax-rules
()
;; Put this rule first to implement a class using procedures.
((let-class (((method . args) . method-body) ...) . body)
(let () (define (method . args) . method-body) ... . body))
;; Put this rule first to implement a class using hygienic macros.
((let-class (((method . args) . method-body) ...) . body)
(letrec-syntax ((method (syntax-rules () ((method . args) (begin . method-body))))
...)
. body))
))
(define (gcbench kStretchTreeDepth)
; Nodes used by a tree of a given size
(define (TreeSize i)
(- (expt 2 (+ i 1)) 1))
; Number of iterations to use for a given tree depth
(define (NumIters i)
(quotient (* 2 (TreeSize kStretchTreeDepth))
(TreeSize i)))
; Parameters are determined by kStretchTreeDepth.
; In Boehm's version the parameters were fixed as follows:
; public static final int kStretchTreeDepth = 18; // about 16Mb
; public static final int kLongLivedTreeDepth = 16; // about 4Mb
; public static final int kArraySize = 500000; // about 4Mb
; public static final int kMinTreeDepth = 4;
; public static final int kMaxTreeDepth = 16;
; In Larceny the storage numbers above would be 12 Mby, 3 Mby, 6 Mby.
(let* ((kLongLivedTreeDepth (- kStretchTreeDepth 2))
(kArraySize (* 4 (TreeSize kLongLivedTreeDepth)))
(kMinTreeDepth 4)
(kMaxTreeDepth kLongLivedTreeDepth))
; Elements 3 and 4 of the allocated vectors are useless.
(let-class (((make-node l r)
(let ((v (make-empty-node)))
(vector-set! v 0 l)
(vector-set! v 1 r)
v))
((make-empty-node) (make-vector 4 0))
((node.left node) (vector-ref node 0))
((node.right node) (vector-ref node 1))
((node.left-set! node x) (vector-set! node 0 x))
((node.right-set! node x) (vector-set! node 1 x)))
; Build tree top down, assigning to older objects.
(define (Populate iDepth thisNode)
(if (<= iDepth 0)
#f
(let ((iDepth (- iDepth 1)))
(node.left-set! thisNode (make-empty-node))
(node.right-set! thisNode (make-empty-node))
(Populate iDepth (node.left thisNode))
(Populate iDepth (node.right thisNode)))))
; Build tree bottom-up
(define (MakeTree iDepth)
(if (<= iDepth 0)
(make-empty-node)
(make-node (MakeTree (- iDepth 1))
(MakeTree (- iDepth 1)))))
(define (TimeConstruction depth)
(let ((iNumIters (NumIters depth)))
(display (string-append "Creating "
(number->string iNumIters)
" trees of depth "
(number->string depth)))
(newline)
(run-benchmark "GCBench: Top down construction"
(lambda ()
(do ((i 0 (+ i 1)))
((>= i iNumIters))
(Populate depth (make-empty-node)))))
(run-benchmark "GCBench: Bottom up construction"
(lambda ()
(do ((i 0 (+ i 1)))
((>= i iNumIters))
(MakeTree depth))))))
(define (main)
(display "Garbage Collector Test")
(newline)
(display (string-append
" Stretching memory with a binary tree of depth "
(number->string kStretchTreeDepth)))
(newline)
(run-benchmark "GCBench: Main"
(lambda ()
; Stretch the memory space quickly
(MakeTree kStretchTreeDepth)
; Create a long lived object
(display (string-append
" Creating a long-lived binary tree of depth "
(number->string kLongLivedTreeDepth)))
(newline)
(let ((longLivedTree (make-empty-node)))
(Populate kLongLivedTreeDepth longLivedTree)
; Create long-lived array, filling half of it
(display (string-append
" Creating a long-lived array of "
(number->string kArraySize)
" inexact reals"))
(newline)
(let ((array (make-vector kArraySize 0.0)))
(do ((i 0 (+ i 1)))
((>= i (quotient kArraySize 2)))
(vector-set! array i (/ 1.0 (exact->inexact i))))
(PrintDiagnostics)
(do ((d kMinTreeDepth (+ d 2)))
((> d kMaxTreeDepth))
(TimeConstruction d))
(if (or (eq? longLivedTree '())
(let ((n (min 1000
(- (quotient (vector-length array)
2)
1))))
(not (= (vector-ref array n)
(/ 1.0 (exact->inexact
n))))))
(begin (display "Failed") (newline)))
; fake reference to LongLivedTree
; and array
; to keep them from being optimized away
))))
(PrintDiagnostics))
(main))))
(define (gc-benchmark . rest)
(let ((k (if (null? rest) 18 (car rest))))
(display "The garbage collector should touch about ")
(display (expt 2 (- k 13)))
(display " megabytes of heap storage.")
(newline)
(display "The use of more or less memory will skew the results.")
(newline)
(run-benchmark (string-append "GCBench" (number->string k))
(lambda () (gcbench k)))))
(gc-benchmark )
(display (gc-stats))
(set! %load-path (cons (string-append (getenv "HOME") "/src/guile")
%load-path))
(load "../test-suite/guile-test")
(main `("guile-test"
"--test-suite" ,(string-append (getenv "HOME")
"/src/guile/test-suite/tests")
"--log-file" ",,test-suite.log"))
;
; GCOld.sch x.x 00/08/03
; translated from GCOld.java 2.0a 00/08/23
;
; Copyright 2000 Sun Microsystems, Inc. All rights reserved.
;
;
; Should be good enough for this benchmark.
(define (newRandom)
(letrec ((random14
(lambda (n)
(set! x (remainder (+ (* a x) c) m))
(remainder (quotient x 8) n)))
(a 701)
(x 1)
(c 743483)
(m 524288)
(loop
(lambda (q r n)
(if (zero? q)
(remainder r n)
(loop (quotient q 16384)
(+ (* 16384 r) (random14 16384))
n)))))
(lambda (n)
(if (and (exact? n) (integer? n) (< n 16384))
(random14 n)
(loop n (random14 16384) n)))))
; A TreeNode is a record with three fields: left, right, val.
; The left and right fields contain a TreeNode or 0, and the
; val field will contain the integer height of the tree.
(define-syntax newTreeNode
(syntax-rules ()
((newTreeNode left right val)
(vector left right val))
((newTreeNode)
(vector 0 0 0))))
(define-syntax TreeNode.left
(syntax-rules ()
((TreeNode.left node)
(vector-ref node 0))))
(define-syntax TreeNode.right
(syntax-rules ()
((TreeNode.right node)
(vector-ref node 1))))
(define-syntax TreeNode.val
(syntax-rules ()
((TreeNode.val node)
(vector-ref node 2))))
(define-syntax setf
(syntax-rules (TreeNode.left TreeNode.right TreeNode.val)
((setf (TreeNode.left node) x)
(vector-set! node 0 x))
((setf (TreeNode.right node) x)
(vector-set! node 1 x))
((setf (TreeNode.val node) x)
(vector-set! node 2 x))))
; Args:
; live-data-size: in megabytes.
; work: units of mutator non-allocation work per byte allocated,
; (in unspecified units. This will affect the promotion rate
; printed at the end of the run: more mutator work per step implies
; fewer steps per second implies fewer bytes promoted per second.)
; short/long ratio: ratio of short-lived bytes allocated to long-lived
; bytes allocated.
; pointer mutation rate: number of pointer mutations per step.
; steps: number of steps to do.
;
(define (GCOld size workUnits promoteRate ptrMutRate steps)
(define (println . args)
(for-each display args)
(newline))
; Rounds an inexact real to two decimal places.
(define (round2 x)
(/ (round (* 100.0 x)) 100.0))
; Returns the height of the given tree.
(define (height t)
(if (eqv? t 0)
0
(+ 1 (max (height (TreeNode.left t))
(height (TreeNode.right t))))))
; Returns the length of the shortest path in the given tree.
(define (shortestPath t)
(if (eqv? t 0)
0
(+ 1 (min (shortestPath (TreeNode.left t))
(shortestPath (TreeNode.right t))))))
; Returns the number of nodes in a balanced tree of the given height.
(define (heightToNodes h)
(- (expt 2 h) 1))
; Returns the height of the largest balanced tree
; that has no more than the given number of nodes.
(define (nodesToHeight nodes)
(do ((h 1 (+ h 1))
(n 1 (+ n n)))
((> (+ n n -1) nodes)
(- h 1))))
(let* (
; Constants.
(null 0) ; Java's null
(pathBits 65536) ; to generate 16 random bits
(MEG 1000000)
(INSIGNIFICANT 999) ; this many bytes don't matter
(bytes/word 4)
(bytes/node 20) ; bytes per tree node in typical JVM
(words/dead 100) ; size of young garbage objects
; Returns the number of bytes in a balanced tree of the given height.
(heightToBytes
(lambda (h)
(* bytes/node (heightToNodes h))))
; Returns the height of the largest balanced tree
; that occupies no more than the given number of bytes.
(bytesToHeight
(lambda (bytes)
(nodesToHeight (/ bytes bytes/node))))
(treeHeight 14)
(treeSize (heightToBytes treeHeight))
(msg1 "Usage: java GCOld <size> <work> <ratio> <mutation> <steps>")
(msg2 " where <size> is the live storage in megabytes")
(msg3 " <work> is the mutator work per step (arbitrary units)")
(msg4 " <ratio> is the ratio of short-lived to long-lived allocation")
(msg5 " <mutation> is the mutations per step")
(msg6 " <steps> is the number of steps")
; Counters (and global variables that discourage optimization).
(youngBytes 0)
(nodes 0)
(actuallyMut 0)
(mutatorSum 0)
(aexport '#())
; Global variables.
(trees '#())
(where 0)
(rnd (newRandom))
)
; Returns a newly allocated balanced binary tree of height h.
(define (makeTree h)
(if (zero? h)
null
(let ((res (newTreeNode)))
(set! nodes (+ nodes 1))
(setf (TreeNode.left res) (makeTree (- h 1)))
(setf (TreeNode.right res) (makeTree (- h 1)))
(setf (TreeNode.val res) h)
res)))
; Allocates approximately size megabytes of trees and stores
; them into a global array.
(define (init)
; Each tree will be about a megabyte.
(let ((ntrees (quotient (* size MEG) treeSize)))
(set! trees (make-vector ntrees null))
(println "Allocating " ntrees " trees.")
(println " (" (* ntrees treeSize) " bytes)")
(do ((i 0 (+ i 1)))
((>= i ntrees))
(vector-set! trees i (makeTree treeHeight))
(doYoungGenAlloc (* promoteRate ntrees treeSize) words/dead))
(println " (" nodes " nodes)")))
; Confirms that all trees are balanced and have the correct height.
(define (checkTrees)
(let ((ntrees (vector-length trees)))
(do ((i 0 (+ i 1)))
((>= i ntrees))
(let* ((t (vector-ref trees i))
(h1 (height t))
(h2 (shortestPath t)))
(if (or (not (= h1 treeHeight))
(not (= h2 treeHeight)))
(println "*****BUG: " h1 " " h2))))))
; Called only by replaceTree (below) and by itself.
(define (replaceTreeWork full partial dir)
(let ((canGoLeft (and (not (eq? (TreeNode.left full) null))
(> (TreeNode.val (TreeNode.left full))
(TreeNode.val partial))))
(canGoRight (and (not (eq? (TreeNode.right full) null))
(> (TreeNode.val (TreeNode.right full))
(TreeNode.val partial)))))
(cond ((and canGoLeft canGoRight)
(if dir
(replaceTreeWork (TreeNode.left full)
partial
(not dir))
(replaceTreeWork (TreeNode.right full)
partial
(not dir))))
((and (not canGoLeft) (not canGoRight))
(if dir
(setf (TreeNode.left full) partial)
(setf (TreeNode.right full) partial)))
((not canGoLeft)
(setf (TreeNode.left full) partial))
(else
(setf (TreeNode.right full) partial)))))
; Given a balanced tree full and a smaller balanced tree partial,
; replaces an appropriate subtree of full by partial, taking care
; to preserve the shape of the full tree.
(define (replaceTree full partial)
(let ((dir (zero? (modulo (TreeNode.val partial) 2))))
(set! actuallyMut (+ actuallyMut 1))
(replaceTreeWork full partial dir)))
; Allocates approximately n bytes of long-lived storage,
; replacing oldest existing long-lived storage.
(define (oldGenAlloc n)
(let ((full (quotient n treeSize))
(partial (modulo n treeSize)))
;(println "In oldGenAlloc, doing "
; full
; " full trees and one partial tree of size "
; partial)
(do ((i 0 (+ i 1)))
((>= i full))
(vector-set! trees where (makeTree treeHeight))
(set! where
(modulo (+ where 1) (vector-length trees))))
(let loop ((partial partial))
(if (> partial INSIGNIFICANT)
(let* ((h (bytesToHeight partial))
(newTree (makeTree h)))
(replaceTree (vector-ref trees where) newTree)
(set! where
(modulo (+ where 1) (vector-length trees)))
(loop (- partial (heightToBytes h))))))))
; Interchanges two randomly selected subtrees (of same size and depth).
(define (oldGenSwapSubtrees)
; Randomly pick:
; * two tree indices
; * A depth
; * A path to that depth.
(let* ((index1 (rnd (vector-length trees)))
(index2 (rnd (vector-length trees)))
(depth (rnd treeHeight))
(path (rnd pathBits))
(tn1 (vector-ref trees index1))
(tn2 (vector-ref trees index2)))
(do ((i 0 (+ i 1)))
((>= i depth))
(if (even? path)
(begin (set! tn1 (TreeNode.left tn1))
(set! tn2 (TreeNode.left tn2)))
(begin (set! tn1 (TreeNode.right tn1))
(set! tn2 (TreeNode.right tn2))))
(set! path (quotient path 2)))
(if (even? path)
(let ((tmp (TreeNode.left tn1)))
(setf (TreeNode.left tn1) (TreeNode.left tn2))
(setf (TreeNode.left tn2) tmp))
(let ((tmp (TreeNode.right tn1)))
(setf (TreeNode.right tn1) (TreeNode.right tn2))
(setf (TreeNode.right tn2) tmp)))
(set! actuallyMut (+ actuallyMut 2))))
; Update "n" old-generation pointers.
(define (oldGenMut n)
(do ((i 0 (+ i 1)))
((>= i (quotient n 2)))
(oldGenSwapSubtrees)))
; Does the amount of mutator work appropriate for n bytes of young-gen
; garbage allocation.
(define (doMutWork n)
(let ((limit (quotient (* workUnits n) 10)))
(do ((k 0 (+ k 1))
(sum 0 (+ sum 1)))
((>= k limit)
; We don't want dead code elimination to eliminate this loop.
(set! mutatorSum (+ mutatorSum sum))))))
; Allocate n bytes of young-gen garbage, in units of "nwords"
; words.
(define (doYoungGenAlloc n nwords)
(let ((nbytes (* nwords bytes/word)))
(do ((allocated 0 (+ allocated nbytes)))
((>= allocated n)
(set! youngBytes (+ youngBytes allocated)))
(set! aexport (make-vector nwords 0)))))
; Allocate "n" bytes of young-gen data; and do the
; corresponding amount of old-gen allocation and pointer
; mutation.
; oldGenAlloc may perform some mutations, so this code
; takes those mutations into account.
(define (doStep n)
(let ((mutations actuallyMut))
(doYoungGenAlloc n words/dead)
(doMutWork n)
; Now do old-gen allocation
(oldGenAlloc (quotient n promoteRate))
(oldGenMut (max 0 (- (+ mutations ptrMutRate) actuallyMut)))))
(println size " megabytes")
(println workUnits " work units per step.")
(println "promotion ratio is 1:" promoteRate)
(println "pointer mutation rate is " ptrMutRate)
(println steps " steps")
(init)
(checkTrees)
(set! youngBytes 0)
(set! nodes 0)
(println "Initialization complete...")
(run-benchmark "GCOld"
1
(lambda ()
(lambda ()
(do ((step 0 (+ step 1)))
((>= step steps))
(doStep MEG))))
(lambda (result) #t))
(checkTrees)
(println "Allocated " steps " Mb of young gen garbage")
(println " (actually allocated "
(round2 (/ youngBytes MEG))
" megabytes)")
(println "Promoted " (round2 (/ steps promoteRate)) " Mb")
(println " (actually promoted "
(round2 (/ (* nodes bytes/node) MEG))
" megabytes)")
(if (not (zero? ptrMutRate))
(println "Mutated " actuallyMut " pointers"))
; This output serves mainly to discourage optimization.
(+ mutatorSum (vector-length aexport))))
(define (gcold-benchmark . args)
(define gcold-iters 1)
(GCOld 25 0 10 10 gcold-iters))
(let loop ((i 10000000))
(and (> i 0)
(loop (1- i))))
;;; Copyright (C) 2008, 2009 Free Software Foundation, Inc.
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public License
;;; as published by the Free Software Foundation; either version 3, 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 Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this software; see the file COPYING.LESSER. If
;;; not, write to the Free Software Foundation, Inc., 51 Franklin
;;; Street, Fifth Floor, Boston, MA 02110-1301 USA
(use-modules (ice-9 rdelim)
(ice-9 popen)
(ice-9 regex)
(ice-9 format)
(ice-9 pretty-print)
(srfi srfi-1)
(srfi srfi-37))
;;;
;;; Running Guile.
;;;
(define (run-reference-guile env bench-dir profile-opts bench)
"Run the ``mainstream'' Guile, i.e., Guile 1.9 with its own GC."
(open-input-pipe (string-append
env " "
bench-dir "/gc-profile.scm " profile-opts
" \"" bench "\"")))
(define (run-bdwgc-guile env bench-dir profile-opts options bench)
"Run the Guile port to the Boehm-Demers-Weiser GC (BDW-GC)."
(let ((fsd (assoc-ref options 'free-space-divisor)))
(open-input-pipe (string-append env " "
"GC_FREE_SPACE_DIVISOR="
(number->string fsd)
(if (or (assoc-ref options 'incremental?)
(assoc-ref options 'generational?))
" GC_ENABLE_INCREMENTAL=yes"
"")
(if (assoc-ref options 'generational?)
" GC_PAUSE_TIME_TARGET=999999"
"")
(if (assoc-ref options 'parallel?)
"" ;; let it choose the number of procs
" GC_MARKERS=1")
" "
bench-dir "/gc-profile.scm " profile-opts
" \"" bench "\""))))
;;;
;;; Extracting performance results.
;;;
(define (grep regexp input)
"Read line by line from the @var{input} port and return all matches for
@var{regexp}."
(let ((regexp (if (string? regexp) (make-regexp regexp) regexp)))
(with-input-from-port input
(lambda ()
(let loop ((line (read-line))
(result '()))
(format #t "> ~A~%" line)
(if (eof-object? line)
(reverse result)
(cond ((regexp-exec regexp line)
=>
(lambda (match)
(loop (read-line)
(cons match result))))
(else
(loop (read-line) result)))))))))
(define (parse-result benchmark-output)
(let ((result (grep "^(execution time|heap size):[[:blank:]]+([0-9.]+)"
benchmark-output)))
(fold (lambda (match result)
(cond ((equal? (match:substring match 1) "execution time")
(cons (cons 'execution-time
(string->number (match:substring match 2)))
result))
((equal? (match:substring match 1) "heap size")
(cons (cons 'heap-size
(string->number (match:substring match 2)))
result))
(else
result)))
'()
result)))
(define (pretty-print-result benchmark reference bdwgc)
(define ref-heap (assoc-ref reference 'heap-size))
(define ref-time (assoc-ref reference 'execution-time))
(define (distance x1 y1 x2 y2)
;; Return the distance between (X1,Y1) and (X2,Y2). Y is the heap size,
;; in MiB and X is the execution time in seconds.
(let ((y1 (/ y1 (expt 2 20)))
(y2 (/ y2 (expt 2 20))))
(sqrt (+ (expt (- y1 y2) 2)
(expt (- x1 x2) 2)))))
(define (score time heap)
;; Return a score lower than +1.0. The score is positive if the
;; distance to the origin of (TIME,HEAP) is smaller than that of
;; (REF-TIME,REF-HEAP), negative otherwise.
;; heap ^ .
;; size | . worse
;; | . [-]
;; | .
;; | . . . .ref. . . .
;; | .
;; | [+] .
;; | better .
;; 0 +-------------------->
;; exec. time
(let ((ref-dist (distance ref-time ref-heap 0 0))
(dist (distance time heap 0 0)))
(/ (- ref-dist dist) ref-dist)))
(define (score-string time heap)
;; Return a string denoting a bar to illustrate the score of (TIME,HEAP)
;; relative to (REF-TIME,REF-HEAP).
(define %max-width 15)
(let ((s (score time heap)))
(make-string (inexact->exact (round (* (if (< s 0.0) (- s) s)
%max-width)))
(if (< s 0.0)
#\-
#\+))))
(define (print-line name result ref?)
(let ((name (string-pad-right name 23))
(time (assoc-ref result 'execution-time))
(heap (assoc-ref result 'heap-size)))
(format #t "~a ~6,2f (~,2fx) ~7,3f (~,2fx)~A~%"
name
(/ heap (expt 2.0 20)) (/ heap ref-heap 1.0)
time (/ time ref-time 1.0)
(if (not ref?)
(string-append " "
(score-string time heap))
""))))
(format #t "benchmark: `~a'~%" benchmark)
(format #t " heap size (MiB) execution time (s.)~%")
(print-line "Guile" reference #t)
(for-each (lambda (bdwgc)
(let ((name (format #f "BDW-GC, FSD=~a~a"
(assoc-ref bdwgc 'free-space-divisor)
(cond ((assoc-ref bdwgc 'incremental?)
" incr.")
((assoc-ref bdwgc 'generational?)
" gene.")
((assoc-ref bdwgc 'parallel?)
" paral.")
(else "")))))
(print-line name bdwgc #f)))
bdwgc))
(define (print-raw-result benchmark reference bdwgc)
(pretty-print `(,benchmark
(reference . ,reference)
(bdw-gc . ,bdwgc))))
;;;
;;; Option processing.
;;;
(define %options
(list (option '(#\h "help") #f #f
(lambda args
(show-help)
(exit 0)))
(option '(#\r "reference") #t #f
(lambda (opt name arg result)
(alist-cons 'reference-environment arg
(alist-delete 'reference-environment result
eq?))))
(option '(#\b "bdw-gc") #t #f
(lambda (opt name arg result)
(alist-cons 'bdwgc-environment arg
(alist-delete 'bdwgc-environment result
eq?))))
(option '(#\d "benchmark-dir") #t #f
(lambda (opt name arg result)
(alist-cons 'benchmark-directory arg
(alist-delete 'benchmark-directory result
eq?))))
(option '(#\p "profile-options") #t #f
(lambda (opt name arg result)
(let ((opts (assoc-ref result 'profile-options)))
(alist-cons 'profile-options
(string-append opts " " arg)
(alist-delete 'profile-options result
eq?)))))
(option '(#\l "log-file") #t #f
(lambda (opt name arg result)
(alist-cons 'log-port (open-output-file arg)
(alist-delete 'log-port result
eq?))))
(option '("raw") #f #f
(lambda (opt name arg result)
(alist-cons 'printer print-raw-result
(alist-delete 'printer result eq?))))
(option '("load-results") #f #f
(lambda (opt name arg result)
(alist-cons 'load-results? #t result)))))
(define %default-options
`((reference-environment . "GUILE=guile")
(benchmark-directory . "./gc-benchmarks")
(log-port . ,(current-output-port))
(profile-options . "")
(input . ())
(printer . ,pretty-print-result)))
(define (show-help)
(format #t "Usage: run-benchmark [OPTIONS] BENCHMARKS...
Run BENCHMARKS (a list of Scheme files) and display a performance
comparison of standard Guile (1.9) and the BDW-GC-based Guile.
-h, --help Show this help message
-r, --reference=ENV
-b, --bdw-gc=ENV
Use ENV as the environment necessary to run the
\"reference\" Guile (1.9) or the BDW-GC-based Guile,
respectively. At a minimum, ENV should define the
`GUILE' environment variable. For example:
--reference='GUILE=/foo/bar/guile LD_LIBRARY_PATH=/foo'
-p, --profile-options=OPTS
Pass OPTS as additional options for `gc-profile.scm'.
-l, --log-file=FILE
Save output to FILE instead of the standard output.
--raw Write benchmark results in raw (s-exp) format.
--load-results
Load raw (s-exp) results instead of actually running
the benchmarks.
-d, --benchmark-dir=DIR
Use DIR as the GC benchmark directory where `gc-profile.scm'
lives (it is automatically determined by default).
Report bugs to <bug-guile@gnu.org>.~%"))
(define (parse-args args)
(define (leave fmt . args)
(apply format (current-error-port) (string-append fmt "~%") args)
(exit 1))
(args-fold args %options
(lambda (opt name arg result)
(leave "~A: unrecognized option" opt))
(lambda (file result)
(let ((files (or (assoc-ref result 'input) '())))
(alist-cons 'input (cons file files)
(alist-delete 'input result eq?))))
%default-options))
;;;
;;; The main program.
;;;
(define (main . args)
(let* ((args (parse-args args))
(benchmark-files (assoc-ref args 'input)))
(let* ((log (assoc-ref args 'log-port))
(bench-dir (assoc-ref args 'benchmark-directory))
(ref-env (assoc-ref args 'reference-environment))
(bdwgc-env (or (assoc-ref args 'bdwgc-environment)
(string-append "GUILE=" bench-dir
"/../meta/guile")))
(prof-opts (assoc-ref args 'profile-options))
(print (assoc-ref args 'printer)))
(define (run benchmark)
(let ((ref (parse-result (run-reference-guile ref-env
bench-dir
prof-opts
benchmark)))
(bdwgc (map (lambda (fsd incremental?
generational? parallel?)
(let ((opts
(list
(cons 'free-space-divisor fsd)
(cons 'incremental? incremental?)
(cons 'generational? generational?)
(cons 'parallel? parallel?))))
(append opts
(parse-result
(run-bdwgc-guile bdwgc-env
bench-dir
prof-opts
opts
benchmark)))))
'( 3 6 9 3 3)
'(#f #f #f #t #f) ;; incremental
'(#f #f #f #f #t) ;; generational
'(#f #f #f #f #f)))) ;; parallel
`(,benchmark
(reference . ,ref)
(bdw-gc . ,bdwgc))))
(define (load-results file)
(with-input-from-file file
(lambda ()
(let loop ((results '()) (o (read)))
(if (eof-object? o)
(reverse results)
(loop (cons o results)
(read)))))))
(for-each (lambda (result)
(let ((benchmark (car result))
(ref (assoc-ref (cdr result) 'reference))
(bdwgc (assoc-ref (cdr result) 'bdw-gc)))
(with-output-to-port log
(lambda ()
(print benchmark ref bdwgc)
(newline)
(force-output)))))
(if (assoc-ref args 'load-results?)
(append-map load-results benchmark-files)
(map run benchmark-files))))))
;;; From from http://www.ccs.neu.edu/home/will/Twobit/KVW/string.txt .
; string test
; (try 100000)
(define s "abcdef")
(define (grow)
(set! s (string-append "123" s "456" s "789"))
(set! s (string-append
(substring s (quotient (string-length s) 2) (string-length s))
(substring s 0 (+ 1 (quotient (string-length s) 2)))))
s)
(define (trial n)
(do ((i 0 (+ i 1)))
((> (string-length s) n) (string-length s))
(grow)))
(define (try n)
(do ((i 0 (+ i 1)))
((>= i 10) (string-length s))
(set! s "abcdef")
(trial n)))
(try 50000000);;;; readline.scm --- support functions for command-line editing
;;;;
;;;; Copyright (C) 1997, 1999, 2000, 2001, 2002, 2006, 2009, 2010, 2011, 2014 Free Software Foundation, Inc.
;;;;
;;;; 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 3, 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 software; see the file COPYING. If not, write to
;;;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;;;; Boston, MA 02110-1301 USA
;;;;
;;;; Contributed by Daniel Risacher <risacher@worldnet.att.net>.
;;;; Extensions based upon code by
;;;; Andrew Archibald <aarchiba@undergrad.math.uwaterloo.ca>.
(define-module (ice-9 readline)
#\use-module (ice-9 session)
#\use-module (ice-9 regex)
#\use-module (ice-9 buffered-input)
#\no-backtrace
#\export (filename-completion-function
add-history
read-history
write-history
clear-history))
;;; Dynamically link the glue code for accessing the readline library,
;;; but only when it isn't already present.
(if (not (provided? 'readline))
(load-extension "libguilereadline-v-18" "scm_init_readline"))
(if (not (provided? 'readline))
(scm-error 'misc-error
#f
"readline is not provided in this Guile installation"
'()
'()))
;;; Run-time options
(export
readline-options
readline-enable
readline-disable)
(export-syntax
readline-set!)
(define-option-interface
(readline-options-interface
(readline-options readline-enable readline-disable)
(readline-set!)))
;;; MDJ 980513 <djurfeldt@nada.kth.se>:
;;; There should probably be low-level support instead of this code.
;;; Dirk:FIXME:: If the-readline-port, input-port or output-port are closed,
;;; guile will enter an endless loop or crash.
(define-once new-input-prompt "")
(define-once continuation-prompt "")
(define-once input-port (current-input-port))
(define-once output-port (current-output-port))
(define-once read-hook #f)
(define (make-readline-port)
(let ((history-buffer #f))
(make-line-buffered-input-port (lambda (continuation?)
;; When starting a new read, add
;; the previously read expression
;; to the history.
(if (and (not continuation?)
history-buffer)
(begin
(add-history history-buffer)
(set! history-buffer #f)))
;; Set up prompts and read a line.
(let* ((prompt (if continuation?
continuation-prompt
new-input-prompt))
(str (%readline (if (string? prompt)
prompt
(prompt))
input-port
output-port
read-hook)))
(or (eof-object? str)
(string=? str "")
(set! history-buffer
(if history-buffer
(string-append history-buffer
"\n"
str)
str)))
str)))))
;;; We only create one readline port. There's no point in having
;;; more, since they would all share the tty and history ---
;;; everything except the prompt. And don't forget the
;;; compile/load/run phase distinctions. Also, the readline library
;;; isn't reentrant.
(define-once the-readline-port #f)
(define-once history-variable "GUILE_HISTORY")
(define-once history-file
(string-append (or (getenv "HOME") ".") "/.guile_history"))
(define-public readline-port
(let ((do (lambda (r/w)
(if (memq 'history-file (readline-options-interface))
(r/w (or (getenv history-variable)
history-file))))))
(lambda ()
(if (not the-readline-port)
(begin
(do read-history)
(set! the-readline-port (make-readline-port))
(add-hook! exit-hook (lambda ()
(do write-history)
(clear-history)))))
the-readline-port)))
;;; The user might try to use readline in his programs. It then
;;; becomes very uncomfortable that the current-input-port is the
;;; readline port...
;;;
;;; Here, we detect this situation and replace it with the
;;; underlying port.
;;;
;;; %readline is the low-level readline procedure.
(define-public (readline . args)
(let ((prompt new-input-prompt)
(inp input-port))
(cond ((not (null? args))
(set! prompt (car args))
(set! args (cdr args))
(cond ((not (null? args))
(set! inp (car args))
(set! args (cdr args))))))
(apply %readline
prompt
(if (eq? inp the-readline-port)
input-port
inp)
args)))
(define-public (set-readline-prompt! p . rest)
(set! new-input-prompt p)
(if (not (null? rest))
(set! continuation-prompt (car rest))))
(define-public (set-readline-input-port! p)
(cond ((or (not (file-port? p)) (not (input-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file input port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-input-port!"
"Port not open: ~S" (list p) #f))
(else
(set! input-port p))))
(define-public (set-readline-output-port! p)
(cond ((or (not (file-port? p)) (not (output-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file output port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-output-port!"
"Port not open: ~S" (list p) #f))
(else
(set! output-port p))))
(define-public (set-readline-read-hook! h)
(set! read-hook h))
(define-public apropos-completion-function
(let ((completions '()))
(lambda (text cont?)
(if (not cont?)
(set! completions
(map symbol->string
(apropos-internal
(string-append "^" (regexp-quote text))))))
(if (null? completions)
#f
(let ((retval (car completions)))
(begin (set! completions (cdr completions))
retval))))))
(if (provided? 'regex)
(set! *readline-completion-function* apropos-completion-function))
(define-public (with-readline-completion-function completer thunk)
"With @var{completer} as readline completion function, call @var{thunk}."
(let ((old-completer *readline-completion-function*))
(dynamic-wind
(lambda ()
(set! *readline-completion-function* completer))
thunk
(lambda ()
(set! *readline-completion-function* old-completer)))))
(define-once readline-repl-reader
(let ((boot-9-repl-reader repl-reader))
(lambda* (repl-prompt #\optional (reader (fluid-ref current-reader)))
(let ((port (current-input-port)))
(if (eq? port (readline-port))
(let ((outer-new-input-prompt new-input-prompt)
(outer-continuation-prompt continuation-prompt)
(outer-read-hook read-hook))
(dynamic-wind
(lambda ()
(set-buffered-input-continuation?! port #f)
(set-readline-prompt! repl-prompt "... ")
(set-readline-read-hook! (lambda ()
(run-hook before-read-hook))))
(lambda () ((or reader read) port))
(lambda ()
(set-readline-prompt! outer-new-input-prompt
outer-continuation-prompt)
(set-readline-read-hook! outer-read-hook))))
(boot-9-repl-reader repl-prompt reader))))))
(define-public (activate-readline)
(if (isatty? (current-input-port))
(begin
(set-current-input-port (readline-port))
(set! repl-reader readline-repl-reader)
(set! (using-readline?) #t))))
(define-public (make-completion-function strings)
"Construct and return a completion function for a list of strings.
The returned function is suitable for passing to
@code{with-readline-completion-function. The argument @var{strings}
should be a list of strings, where each string is one of the possible
completions."
(letrec ((strs '())
(regexp #f)
(completer (lambda (text continue?)
(if continue?
(if (null? strs)
#f
(let ((str (car strs)))
(set! strs (cdr strs))
(if (string-match regexp str)
str
(completer text #t))))
(begin
(set! strs strings)
(set! regexp
(string-append "^" (regexp-quote text)))
(completer text #t))))))
completer))
;;; GDB debugging support for Guile.
;;;
;;; Copyright 2014, 2015 Free Software Foundation, Inc.
;;;
;;; 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 3 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, see <http://www.gnu.org/licenses/>.
(define-module (guile-gdb)
#\use-module (system base types)
#\use-module ((gdb) #\hide (symbol?))
#\use-module (gdb printing)
#\use-module (srfi srfi-11)
#\use-module (ice-9 match)
#\export (%gdb-memory-backend
display-vm-frames))
;;; Commentary:
;;;
;;; This file defines GDB extensions to pretty-print 'SCM' objects, and
;;; to walk Guile's virtual machine stack.
;;;
;;; This file is installed under a name that follows the convention that
;;; allows GDB to auto-load it anytime the user is debugging libguile
;;; (info "(gdb) objfile-gdbdotext file").
;;;
;;; Code:
(define (type-name-from-descriptor descriptor-array type-number)
"Return the name of the type TYPE-NUMBER as seen in DESCRIPTOR-ARRAY, or #f
if the information is not available."
(let ((descriptors (lookup-global-symbol descriptor-array)))
(and descriptors
(let ((code (type-code (symbol-type descriptors))))
(or (= TYPE_CODE_ARRAY code)
(= TYPE_CODE_PTR code)))
(let* ((type-descr (value-subscript (symbol-value descriptors)
type-number))
(name (value-field type-descr "name")))
(value->string name)))))
(define (scm-value->integer value)
"Return the integer value of VALUE, which is assumed to be a GDB value
corresponding to an 'SCM' object."
(let ((type (type-strip-typedefs (value-type value))))
(cond ((= (type-code type) TYPE_CODE_UNION)
;; SCM_DEBUG_TYPING_STRICTNESS = 2
(value->integer (value-field (value-field value "n")
"n")))
(else
;; SCM_DEBUG_TYPING_STRICTNESS = 1
(value->integer value)))))
(define %gdb-memory-backend
;; The GDB back-end to access the inferior's memory.
(let ((void* (type-pointer (lookup-type "void"))))
(define (dereference-word address)
;; Return the word at ADDRESS.
(value->integer
(value-dereference (value-cast (make-value address)
(type-pointer void*)))))
(define (open address size)
;; Return a port to the SIZE bytes starting at ADDRESS.
(if size
(open-memory #\start address #\size size)
(open-memory #\start address)))
(define (type-name kind number)
;; Return the type name of KIND type NUMBER.
(type-name-from-descriptor (case kind
((smob) "scm_smobs")
((port) "scm_ptobs"))
number))
(memory-backend dereference-word open type-name)))
;;;
;;; GDB pretty-printer registration.
;;;
(define (make-scm-pretty-printer-worker obj)
(define (list->iterator list)
(make-iterator list list
(let ((n 0))
(lambda (iter)
(match (iterator-progress iter)
(() (end-of-iteration))
((elt . list)
(set-iterator-progress! iter list)
(let ((name (format #f "[~a]" n)))
(set! n (1+ n))
(cons name (object->string elt)))))))))
(cond
((string? obj)
(make-pretty-printer-worker
"string" ; display hint
(lambda (printer) obj)
#f))
((and (array? obj)
(match (array-shape obj)
(((0 _)) #t)
(_ #f)))
(make-pretty-printer-worker
"array" ; display hint
(lambda (printer)
(let ((tag (array-type obj)))
(case tag
((#t) "#<vector>")
((b) "#<bitvector>")
(else (format #f "#<~avector>" tag)))))
(lambda (printer)
(list->iterator (array->list obj)))))
((inferior-struct? obj)
(make-pretty-printer-worker
"array" ; display hint
(lambda (printer)
(format #f "#<struct ~a>" (inferior-struct-name obj)))
(lambda (printer)
(list->iterator (inferior-struct-fields obj)))))
(else
(make-pretty-printer-worker
#f ; display hint
(lambda (printer)
(object->string obj))
#f))))
(define %scm-pretty-printer
(make-pretty-printer
"SCM"
(lambda (pp value)
(let ((name (type-name (value-type value))))
(and (and name (string=? name "SCM"))
(make-scm-pretty-printer-worker
(scm->object (scm-value->integer value) %gdb-memory-backend)))))))
(define* (register-pretty-printer #\optional objfile)
(prepend-pretty-printer! objfile %scm-pretty-printer))
(register-pretty-printer)
;;;
;;; VM stack walking.
;;;
(define (find-vm-engine-frame)
"Return the bottom-most frame containing a call to the VM engine."
(define (vm-engine-frame? frame)
(let ((sym (frame-function frame)))
(and sym
(member (symbol-name sym)
'("vm_debug_engine" "vm_regular_engine")))))
(let loop ((frame (newest-frame)))
(and frame
(if (vm-engine-frame? frame)
frame
(loop (frame-older frame))))))
(define (vm-stack-pointer)
"Return the current value of the VM stack pointer or #f."
(let ((frame (find-vm-engine-frame)))
(and frame
(frame-read-var frame "sp"))))
(define (vm-frame-pointer)
"Return the current value of the VM frame pointer or #f."
(let ((frame (find-vm-engine-frame)))
(and frame
(frame-read-var frame "fp"))))
(define* (display-vm-frames #\optional (port (current-output-port)))
"Display the VM frames on PORT."
(define (display-objects start end)
;; Display all the objects (arguments and local variables) located
;; between START and END.
(let loop ((number 0)
(address start))
(when (and (> start 0) (<= address end))
(let ((object (dereference-word %gdb-memory-backend address)))
;; TODO: Push onto GDB's value history.
(format port " slot ~a -> ~s~%"
number (scm->object object %gdb-memory-backend)))
(loop (+ 1 number) (+ address %word-size)))))
(let loop ((number 0)
(sp (value->integer (vm-stack-pointer)))
(fp (value->integer (vm-frame-pointer))))
(unless (zero? fp)
(let-values (((ra mvra link proc)
(vm-frame fp %gdb-memory-backend)))
(format port "#~a ~s~%" number (scm->object proc %gdb-memory-backend))
(display-objects fp sp)
(loop (+ 1 number) (- fp (* 5 %word-size)) link)))))
;; See libguile/frames.h.
(define* (vm-frame fp #\optional (backend %gdb-memory-backend))
"Return the components of the stack frame at FP."
(let ((caller (dereference-word backend (- fp %word-size)))
(ra (dereference-word backend (- fp (* 2 %word-size))))
(mvra (dereference-word backend (- fp (* 3 %word-size))))
(link (dereference-word backend (- fp (* 4 %word-size)))))
(values ra mvra link caller)))
;;; libguile-2.0-gdb.scm ends here
;;;; and-let-star.scm --- and-let* syntactic form (SRFI-2) for Guile
;;;;
;;;; Copyright (C) 1999, 2001, 2004, 2006, 2013,
;;;; 2015 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 and-let-star)
\:export-syntax (and-let*))
(define-syntax %and-let*
(lambda (form)
(syntax-case form ()
;; Handle zero-clauses special-case.
((_ orig-form () . body)
#'(begin #t . body))
;; Reduce clauses down to one regardless of body.
((_ orig-form ((var expr) rest . rest*) . body)
(identifier? #'var)
#'(let ((var expr))
(and var (%and-let* orig-form (rest . rest*) . body))))
((_ orig-form ((expr) rest . rest*) . body)
#'(and expr (%and-let* orig-form (rest . rest*) . body)))
((_ orig-form (var rest . rest*) . body)
(identifier? #'var)
#'(and var (%and-let* orig-form (rest . rest*) . body)))
;; Handle 1-clause cases without a body.
((_ orig-form ((var expr)))
(identifier? #'var)
#'expr)
((_ orig-form ((expr)))
#'expr)
((_ orig-form (var))
(identifier? #'var)
#'var)
;; Handle 1-clause cases with a body.
((_ orig-form ((var expr)) . body)
(identifier? #'var)
#'(let ((var expr))
(and var (begin . body))))
((_ orig-form ((expr)) . body)
#'(and expr (begin . body)))
((_ orig-form (var) . body)
(identifier? #'var)
#'(and var (begin . body)))
;; Handle bad clauses.
((_ orig-form (bad-clause . rest) . body)
(syntax-violation 'and-let* "Bad clause" #'orig-form #'bad-clause)))))
(define-syntax and-let*
(lambda (form)
(syntax-case form ()
((_ (c ...) body ...)
#`(%and-let* #,form (c ...) body ...)))))
(cond-expand-provide (current-module) '(srfi-2))
;;; installed-scm-file
;;;; Copyright (C) 1999, 2001, 2004, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define (array-shape a)
(map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
(array-dimensions a)))
;;;; binary-ports.scm --- Binary IO on ports
;;;; Copyright (C) 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;;;
;;; The I/O port API of the R6RS is provided by this module. In many areas
;;; it complements or refines Guile's own historical port API. For instance,
;;; it allows for binary I/O with bytevectors.
;;;
;;; Code:
(define-module (ice-9 binary-ports)
#\use-module (rnrs bytevectors)
#\export (eof-object
open-bytevector-input-port
make-custom-binary-input-port
get-u8
lookahead-u8
get-bytevector-n
get-bytevector-n!
get-bytevector-some
get-bytevector-all
get-string-n!
put-u8
put-bytevector
unget-bytevector
open-bytevector-output-port
make-custom-binary-output-port))
;; Note that this extension also defines %make-transcoded-port, which is
;; not exported but is used by (rnrs io ports).
(load-extension (string-append "libguile-" (effective-version))
"scm_init_r6rs_ports")
;;; -*- mode: scheme; coding: utf-8; -*-
;;;; Copyright (C) 1995-2014, 2016 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; This file is the first thing loaded into Guile. It adds many mundane
;;; definitions and a few that are interesting.
;;;
;;; The module system (hence the hierarchical namespace) are defined in this
;;; file.
;;;
;;; Code:
;; Before compiling, make sure any symbols are resolved in the (guile)
;; module, the primary location of those symbols, rather than in
;; (guile-user), the default module that we compile in.
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
;; Prevent this file being loaded more than once in a session. Just
;; doesn't make sense!
(if (current-module)
(error "re-loading ice-9/boot-9.scm not allowed"))
;;; {Error handling}
;;;
;; Define delimited continuation operators, and implement catch and throw in
;; terms of them.
(define make-prompt-tag
(lambda* (#\optional (stem "prompt"))
(gensym stem)))
(define default-prompt-tag
;; not sure if we should expose this to the user as a fluid
(let ((%default-prompt-tag (make-prompt-tag)))
(lambda ()
%default-prompt-tag)))
(define (call-with-prompt tag thunk handler)
(@prompt tag (thunk) handler))
(define (abort-to-prompt tag . args)
(@abort tag args))
;; Define catch and with-throw-handler, using some common helper routines and a
;; shared fluid. Hide the helpers in a lexical contour.
(define with-throw-handler #f)
(let ()
(define (default-exception-handler k . args)
(cond
((eq? k 'quit)
(primitive-exit (cond
((not (pair? args)) 0)
((integer? (car args)) (car args))
((not (car args)) 1)
(else 0))))
(else
(format (current-error-port) "guile: uncaught throw to ~a: ~a\n" k args)
(primitive-exit 1))))
(define %running-exception-handlers (make-fluid '()))
(define %exception-handler (make-fluid default-exception-handler))
(define (default-throw-handler prompt-tag catch-k)
(let ((prev (fluid-ref %exception-handler)))
(lambda (thrown-k . args)
(if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
(apply abort-to-prompt prompt-tag thrown-k args)
(apply prev thrown-k args)))))
(define (custom-throw-handler prompt-tag catch-k pre)
(let ((prev (fluid-ref %exception-handler)))
(lambda (thrown-k . args)
(if (or (eq? thrown-k catch-k) (eqv? catch-k #t))
(let ((running (fluid-ref %running-exception-handlers)))
(with-fluids ((%running-exception-handlers (cons pre running)))
(if (not (memq pre running))
(apply pre thrown-k args))
;; fall through
(if prompt-tag
(apply abort-to-prompt prompt-tag thrown-k args)
(apply prev thrown-k args))))
(apply prev thrown-k args)))))
(set! catch
(lambda* (k thunk handler #\optional pre-unwind-handler)
"Invoke @var{thunk} in the dynamic context of @var{handler} for
exceptions matching @var{key}. If thunk throws to the symbol
@var{key}, then @var{handler} is invoked this way:
@lisp
(handler key args ...)
@end lisp
@var{key} is a symbol or @code{#t}.
@var{thunk} takes no arguments. If @var{thunk} returns
normally, that is the return value of @code{catch}.
Handler is invoked outside the scope of its own @code{catch}.
If @var{handler} again throws to the same key, a new handler
from further up the call chain is invoked.
If the key is @code{#t}, then a throw to @emph{any} symbol will
match this call to @code{catch}.
If a @var{pre-unwind-handler} is given and @var{thunk} throws
an exception that matches @var{key}, Guile calls the
@var{pre-unwind-handler} before unwinding the dynamic state and
invoking the main @var{handler}. @var{pre-unwind-handler} should
be a procedure with the same signature as @var{handler}, that
is @code{(lambda (key . args))}. It is typically used to save
the stack at the point where the exception occurred, but can also
query other parts of the dynamic state at that point, such as
fluid values.
A @var{pre-unwind-handler} can exit either normally or non-locally.
If it exits normally, Guile unwinds the stack and dynamic context
and then calls the normal (third argument) handler. If it exits
non-locally, that exit determines the continuation."
(if (not (or (symbol? k) (eqv? k #t)))
(scm-error 'wrong-type-arg "catch"
"Wrong type argument in position ~a: ~a"
(list 1 k) (list k)))
(let ((tag (make-prompt-tag "catch")))
(call-with-prompt
tag
(lambda ()
(with-fluids
((%exception-handler
(if pre-unwind-handler
(custom-throw-handler tag k pre-unwind-handler)
(default-throw-handler tag k))))
(thunk)))
(lambda (cont k . args)
(apply handler k args))))))
(set! with-throw-handler
(lambda (k thunk pre-unwind-handler)
"Add @var{handler} to the dynamic context as a throw handler
for key @var{k}, then invoke @var{thunk}."
(if (not (or (symbol? k) (eqv? k #t)))
(scm-error 'wrong-type-arg "with-throw-handler"
"Wrong type argument in position ~a: ~a"
(list 1 k) (list k)))
(with-fluids ((%exception-handler
(custom-throw-handler #f k pre-unwind-handler)))
(thunk))))
(set! throw
(lambda (key . args)
"Invoke the catch form matching @var{key}, passing @var{args} to the
@var{handler}.
@var{key} is a symbol. It will match catches of the same symbol or of @code{#t}.
If there is no handler at all, Guile prints an error and then exits."
(if (not (symbol? key))
((fluid-ref %exception-handler) 'wrong-type-arg "throw"
"Wrong type argument in position ~a: ~a" (list 1 key) (list key))
(apply (fluid-ref %exception-handler) key args)))))
;;; Boot versions of `map' and `for-each', enough to get the expander
;;; running, and get the "map" used in eval.scm for with-fluids to work.
;;;
(define map
(case-lambda
((f l)
(let map1 ((l l))
(if (null? l)
'()
(cons (f (car l)) (map1 (cdr l))))))
((f l1 l2)
(let map2 ((l1 l1) (l2 l2))
(if (null? l1)
'()
(cons (f (car l1) (car l2))
(map2 (cdr l1) (cdr l2))))))
((f l1 . rest)
(let lp ((l1 l1) (rest rest))
(if (null? l1)
'()
(cons (apply f (car l1) (map car rest))
(lp (cdr l1) (map cdr rest))))))))
(define for-each
(case-lambda
((f l)
(let for-each1 ((l l))
(if (pair? l)
(begin
(f (car l))
(for-each1 (cdr l))))))
((f l1 l2)
(let for-each2 ((l1 l1) (l2 l2))
(if (pair? l1)
(begin
(f (car l1) (car l2))
(for-each2 (cdr l1) (cdr l2))))))
((f l1 . rest)
(let lp ((l1 l1) (rest rest))
(if (pair? l1)
(begin
(apply f (car l1) (map car rest))
(lp (cdr l1) (map cdr rest))))))))
;;; {R4RS compliance}
;;;
(primitive-load-path "ice-9/r4rs")
;;; {Simple Debugging Tools}
;;;
;; peek takes any number of arguments, writes them to the
;; current ouput port, and returns the last argument.
;; It is handy to wrap around an expression to look at
;; a value each time is evaluated, e.g.:
;;
;; (+ 10 (troublesome-fn))
;; => (+ 10 (pk 'troublesome-fn-returned (troublesome-fn)))
;;
(define (peek . stuff)
(newline)
(display ";;; ")
(write stuff)
(newline)
(car (last-pair stuff)))
(define pk peek)
(define (warn . stuff)
(with-output-to-port (current-warning-port)
(lambda ()
(newline)
(display ";;; WARNING ")
(display stuff)
(newline)
(car (last-pair stuff)))))
;;; {Features}
;;;
(define (provide sym)
(if (not (memq sym *features*))
(set! *features* (cons sym *features*))))
;; Return #t iff FEATURE is available to this Guile interpreter. In SLIB,
;; provided? also checks to see if the module is available. We should do that
;; too, but don't.
(define (provided? feature)
(and (memq feature *features*) #t))
;;; {Structs}
;;;
(define (make-struct/no-tail vtable . args)
(apply make-struct vtable 0 args))
;; Temporary definition used in the include-from-path expansion;
;; replaced later.
(define (absolute-file-name? file-name)
#t)
;;; {and-map and or-map}
;;;
;;; (and-map fn lst) is like (and (fn (car lst)) (fn (cadr lst)) (fn...) ...)
;;; (or-map fn lst) is like (or (fn (car lst)) (fn (cadr lst)) (fn...) ...)
;;;
;; and-map f l
;;
;; Apply f to successive elements of l until exhaustion or f returns #f.
;; If returning early, return #f. Otherwise, return the last value returned
;; by f. If f has never been called because l is empty, return #t.
;;
(define (and-map f lst)
(let loop ((result #t)
(l lst))
(and result
(or (and (null? l)
result)
(loop (f (car l)) (cdr l))))))
;; or-map f l
;;
;; Apply f to successive elements of l until exhaustion or while f returns #f.
;; If returning early, return the return value of f.
;;
(define (or-map f lst)
(let loop ((result #f)
(l lst))
(or result
(and (not (null? l))
(loop (f (car l)) (cdr l))))))
;; let format alias simple-format until the more complete version is loaded
(define format simple-format)
;; this is scheme wrapping the C code so the final pred call is a tail call,
;; per SRFI-13 spec
(define string-any
(lambda* (char_pred s #\optional (start 0) (end (string-length s)))
(if (and (procedure? char_pred)
(> end start)
(<= end (string-length s))) ;; let c-code handle range error
(or (string-any-c-code char_pred s start (1- end))
(char_pred (string-ref s (1- end))))
(string-any-c-code char_pred s start end))))
;; this is scheme wrapping the C code so the final pred call is a tail call,
;; per SRFI-13 spec
(define string-every
(lambda* (char_pred s #\optional (start 0) (end (string-length s)))
(if (and (procedure? char_pred)
(> end start)
(<= end (string-length s))) ;; let c-code handle range error
(and (string-every-c-code char_pred s start (1- end))
(char_pred (string-ref s (1- end))))
(string-every-c-code char_pred s start end))))
;; A variant of string-fill! that we keep for compatability
;;
(define (substring-fill! str start end fill)
(string-fill! str fill start end))
;; Define a minimal stub of the module API for psyntax, before modules
;; have booted.
(define (module-name x)
'(guile))
(define (module-add! module sym var)
(hashq-set! (%get-pre-modules-obarray) sym var))
(define (module-define! module sym val)
(let ((v (hashq-ref (%get-pre-modules-obarray) sym)))
(if v
(variable-set! v val)
(module-add! (current-module) sym (make-variable val)))))
(define (module-ref module sym)
(let ((v (module-variable module sym)))
(if v (variable-ref v) (error "badness!" (pk module) (pk sym)))))
(define module-generate-unique-id!
(let ((next-id 0))
(lambda (m)
(let ((i next-id))
(set! next-id (+ i 1))
i))))
(define module-gensym gensym)
(define (resolve-module . args)
#f)
;; API provided by psyntax
(define syntax-violation #f)
(define datum->syntax #f)
(define syntax->datum #f)
(define syntax-source #f)
(define identifier? #f)
(define generate-temporaries #f)
(define bound-identifier=? #f)
(define free-identifier=? #f)
;; $sc-dispatch is an implementation detail of psyntax. It is used by
;; expanded macros, to dispatch an input against a set of patterns.
(define $sc-dispatch #f)
;; Load it up!
(primitive-load-path "ice-9/psyntax-pp")
;; The binding for `macroexpand' has now been overridden, making psyntax the
;; expander now.
(define-syntax and
(syntax-rules ()
((_) #t)
((_ x) x)
;; Avoid ellipsis, which would lead to quadratic expansion time.
((_ x . y) (if x (and . y) #f))))
(define-syntax or
(syntax-rules ()
((_) #f)
((_ x) x)
;; Avoid ellipsis, which would lead to quadratic expansion time.
((_ x . y) (let ((t x)) (if t t (or . y))))))
(include-from-path "ice-9/quasisyntax")
(define-syntax-rule (when test stmt stmt* ...)
(if test (begin stmt stmt* ...)))
(define-syntax-rule (unless test stmt stmt* ...)
(if (not test) (begin stmt stmt* ...)))
(define-syntax cond
(lambda (whole-expr)
(define (fold f seed xs)
(let loop ((xs xs) (seed seed))
(if (null? xs) seed
(loop (cdr xs) (f (car xs) seed)))))
(define (reverse-map f xs)
(fold (lambda (x seed) (cons (f x) seed))
'() xs))
(syntax-case whole-expr ()
((_ clause clauses ...)
#`(begin
#,@(fold (lambda (clause-builder tail)
(clause-builder tail))
#'()
(reverse-map
(lambda (clause)
(define* (bad-clause #\optional (msg "invalid clause"))
(syntax-violation 'cond msg whole-expr clause))
(syntax-case clause (=> else)
((else e e* ...)
(lambda (tail)
(if (null? tail)
#'((begin e e* ...))
(bad-clause "else must be the last clause"))))
((else . _) (bad-clause))
((test => receiver)
(lambda (tail)
#`((let ((t test))
(if t
(receiver t)
#,@tail)))))
((test => receiver ...)
(bad-clause "wrong number of receiver expressions"))
((generator guard => receiver)
(lambda (tail)
#`((call-with-values (lambda () generator)
(lambda vals
(if (apply guard vals)
(apply receiver vals)
#,@tail))))))
((generator guard => receiver ...)
(bad-clause "wrong number of receiver expressions"))
((test)
(lambda (tail)
#`((let ((t test))
(if t t #,@tail)))))
((test e e* ...)
(lambda (tail)
#`((if test
(begin e e* ...)
#,@tail))))
(_ (bad-clause))))
#'(clause clauses ...))))))))
(define-syntax case
(lambda (whole-expr)
(define (fold f seed xs)
(let loop ((xs xs) (seed seed))
(if (null? xs) seed
(loop (cdr xs) (f (car xs) seed)))))
(define (fold2 f a b xs)
(let loop ((xs xs) (a a) (b b))
(if (null? xs) (values a b)
(call-with-values
(lambda () (f (car xs) a b))
(lambda (a b)
(loop (cdr xs) a b))))))
(define (reverse-map-with-seed f seed xs)
(fold2 (lambda (x ys seed)
(call-with-values
(lambda () (f x seed))
(lambda (y seed)
(values (cons y ys) seed))))
'() seed xs))
(syntax-case whole-expr ()
((_ expr clause clauses ...)
(with-syntax ((key #'key))
#`(let ((key expr))
#,@(fold
(lambda (clause-builder tail)
(clause-builder tail))
#'()
(reverse-map-with-seed
(lambda (clause seen)
(define* (bad-clause #\optional (msg "invalid clause"))
(syntax-violation 'case msg whole-expr clause))
(syntax-case clause ()
((test . rest)
(with-syntax
((clause-expr
(syntax-case #'rest (=>)
((=> receiver) #'(receiver key))
((=> receiver ...)
(bad-clause
"wrong number of receiver expressions"))
((e e* ...) #'(begin e e* ...))
(_ (bad-clause)))))
(syntax-case #'test (else)
((datums ...)
(let ((seen
(fold
(lambda (datum seen)
(define (warn-datum type)
((@ (system base message)
warning)
type
(append (source-properties datum)
(source-properties
(syntax->datum #'test)))
datum
(syntax->datum clause)
(syntax->datum whole-expr)))
(when (memv datum seen)
(warn-datum 'duplicate-case-datum))
(when (or (pair? datum) (array? datum))
(warn-datum 'bad-case-datum))
(cons datum seen))
seen
(map syntax->datum #'(datums ...)))))
(values (lambda (tail)
#`((if (memv key '(datums ...))
clause-expr
#,@tail)))
seen)))
(else (values (lambda (tail)
(if (null? tail)
#'(clause-expr)
(bad-clause
"else must be the last clause")))
seen))
(_ (bad-clause)))))
(_ (bad-clause))))
'() #'(clause clauses ...)))))))))
(define-syntax do
(syntax-rules ()
((do ((var init step ...) ...)
(test expr ...)
command ...)
(letrec
((loop
(lambda (var ...)
(if test
(begin
(if #f #f)
expr ...)
(begin
command
...
(loop (do "step" var step ...)
...))))))
(loop init ...)))
((do "step" x)
x)
((do "step" x y)
y)))
;; XXX FIXME: When 'call-with-values' is fixed to no longer do automatic
;; truncation of values (in 2.2 ?), then this hack can be removed.
(define (%define-values-arity-error)
(throw 'wrong-number-of-args
#f
"define-values: wrong number of return values returned by expression"
'()
#f))
(define-syntax define-values
(lambda (orig-form)
(syntax-case orig-form ()
((_ () expr)
;; XXX Work around the lack of hygienic top-level identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(define dummy
(call-with-values (lambda () expr)
(case-lambda
(() #f)
(_ (%define-values-arity-error)))))))
((_ (var) expr)
(identifier? #'var)
#`(define var
(call-with-values (lambda () expr)
(case-lambda
((v) v)
(_ (%define-values-arity-error))))))
((_ (var0 ... varn) expr)
(and-map identifier? #'(var0 ... varn))
;; XXX Work around the lack of hygienic toplevel identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(begin
;; Avoid mutating the user-visible variables
(define dummy
(call-with-values (lambda () expr)
(case-lambda
((var0 ... varn)
(list var0 ... varn))
(_ (%define-values-arity-error)))))
(define var0
(let ((v (car dummy)))
(set! dummy (cdr dummy))
v))
...
(define varn
(let ((v (car dummy)))
(set! dummy #f) ; blackhole dummy
v)))))
((_ var expr)
(identifier? #'var)
#'(define var
(call-with-values (lambda () expr)
list)))
((_ (var0 ... . varn) expr)
(and-map identifier? #'(var0 ... varn))
;; XXX Work around the lack of hygienic toplevel identifiers
(with-syntax (((dummy) (generate-temporaries '(dummy))))
#`(begin
;; Avoid mutating the user-visible variables
(define dummy
(call-with-values (lambda () expr)
(case-lambda
((var0 ... . varn)
(list var0 ... varn))
(_ (%define-values-arity-error)))))
(define var0
(let ((v (car dummy)))
(set! dummy (cdr dummy))
v))
...
(define varn
(let ((v (car dummy)))
(set! dummy #f) ; blackhole dummy
v))))))))
(define-syntax-rule (delay exp)
(make-promise (lambda () exp)))
(define-syntax current-source-location
(lambda (x)
(syntax-case x ()
((_)
(with-syntax ((s (datum->syntax x (syntax-source x))))
#''s)))))
;; We provide this accessor out of convenience. current-line and
;; current-column aren't so interesting, because they distort what they
;; are measuring; better to use syntax-source from a macro.
;;
(define-syntax current-filename
(lambda (x)
"A macro that expands to the current filename: the filename that
the (current-filename) form appears in. Expands to #f if this
information is unavailable."
(false-if-exception
(canonicalize-path (assq-ref (syntax-source x) 'filename)))))
(define-syntax-rule (define-once sym val)
(define sym
(if (module-locally-bound? (current-module) 'sym) sym val)))
;;; The real versions of `map' and `for-each', with cycle detection, and
;;; that use reverse! instead of recursion in the case of `map'.
;;;
(define map
(case-lambda
((f l)
(let map1 ((hare l) (tortoise l) (move? #f) (out '()))
(if (pair? hare)
(if move?
(if (eq? tortoise hare)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l) #f)
(map1 (cdr hare) (cdr tortoise) #f
(cons (f (car hare)) out)))
(map1 (cdr hare) tortoise #t
(cons (f (car hare)) out)))
(if (null? hare)
(reverse! out)
(scm-error 'wrong-type-arg "map" "Not a list: ~S"
(list l) #f)))))
((f l1 l2)
(let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
(cond
((pair? h1)
(cond
((not (pair? h2))
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
((not move?)
(map2 (cdr h1) (cdr h2) t1 t2 #t
(cons (f (car h1) (car h2)) out)))
((eq? t1 h1)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l1) #f))
((eq? t2 h2)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l2) #f))
(else
(map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
(cons (f (car h1) (car h2)) out)))))
((and (null? h1) (null? h2))
(reverse! out))
((null? h1)
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
(else
(scm-error 'wrong-type-arg "map"
"Not a list: ~S"
(list l1) #f)))))
((f l1 . rest)
(let ((len (length l1)))
(let mapn ((rest rest))
(or (null? rest)
(if (= (length (car rest)) len)
(mapn (cdr rest))
(scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
(list (car rest)) #f)))))
(let mapn ((l1 l1) (rest rest) (out '()))
(if (null? l1)
(reverse! out)
(mapn (cdr l1) (map cdr rest)
(cons (apply f (car l1) (map car rest)) out)))))))
(define map-in-order map)
(define for-each
(case-lambda
((f l)
(let for-each1 ((hare l) (tortoise l))
(if (pair? hare)
(begin
(f (car hare))
(let ((hare (cdr hare)))
(if (pair? hare)
(begin
(when (eq? tortoise hare)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l) #f))
(f (car hare))
(for-each1 (cdr hare) (cdr tortoise))))))
(if (not (null? hare))
(scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
(list l) #f)))))
((f l1 l2)
(let for-each2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f))
(cond
((and (pair? h1) (pair? h2))
(cond
((not move?)
(f (car h1) (car h2))
(for-each2 (cdr h1) (cdr h2) t1 t2 #t))
((eq? t1 h1)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l1) #f))
((eq? t2 h2)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l2) #f))
(else
(f (car h1) (car h2))
(for-each2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f))))
((if (null? h1)
(or (null? h2) (pair? h2))
(and (pair? h1) (null? h2)))
(if #f #f))
((list? h1)
(scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
(list h2) #f))
(else
(scm-error 'wrong-type-arg "for-each" "Unexpected tail: ~S"
(list h1) #f)))))
((f l1 . rest)
(let ((len (length l1)))
(let for-eachn ((rest rest))
(or (null? rest)
(if (= (length (car rest)) len)
(for-eachn (cdr rest))
(scm-error 'wrong-type-arg "for-each" "List of wrong length: ~S"
(list (car rest)) #f)))))
(let for-eachn ((l1 l1) (rest rest))
(if (pair? l1)
(begin
(apply f (car l1) (map car rest))
(for-eachn (cdr l1) (map cdr rest))))))))
;;;
;;; Enhanced file opening procedures
;;;
(define* (open-input-file
file #\key (binary #f) (encoding #f) (guess-encoding #f))
"Takes a string naming an existing file and returns an input port
capable of delivering characters from the file. If the file
cannot be opened, an error is signalled."
(open-file file (if binary "rb" "r")
#\encoding encoding
#\guess-encoding guess-encoding))
(define* (open-output-file file #\key (binary #f) (encoding #f))
"Takes a string naming an output file to be created and returns an
output port capable of writing characters to a new file by that
name. If the file cannot be opened, an error is signalled. If a
file with the given name already exists, the effect is unspecified."
(open-file file (if binary "wb" "w")
#\encoding encoding))
(define* (call-with-input-file
file proc #\key (binary #f) (encoding #f) (guess-encoding #f))
"PROC should be a procedure of one argument, and FILE should be a
string naming a file. The file must
already exist. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-input-file file
#\binary binary
#\encoding encoding
#\guess-encoding guess-encoding)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-input-port p)
(apply values vals)))))
(define* (call-with-output-file file proc #\key (binary #f) (encoding #f))
"PROC should be a procedure of one argument, and FILE should be a
string naming a file. The behaviour is unspecified if the file
already exists. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-output-file file #\binary binary #\encoding encoding)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-output-port p)
(apply values vals)))))
(define* (with-input-from-file
file thunk #\key (binary #f) (encoding #f) (guess-encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The file must already exist. The file is opened for
input, an input port connected to it is made
the default value returned by `current-input-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-input-file file
(lambda (p) (with-input-from-port p thunk))
#\binary binary
#\encoding encoding
#\guess-encoding guess-encoding))
(define* (with-output-to-file file thunk #\key (binary #f) (encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-output-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-output-to-port p thunk))
#\binary binary
#\encoding encoding))
(define* (with-error-to-file file thunk #\key (binary #f) (encoding #f))
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-error-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-error-to-port p thunk))
#\binary binary
#\encoding encoding))
;;;
;;; Extensible exception printing.
;;;
(define set-exception-printer! #f)
;; There is already a definition of print-exception from backtrace.c
;; that we will override.
(let ((exception-printers '()))
(define (print-location frame port)
(let ((source (and=> frame frame-source)))
;; source := (addr . (filename . (line . column)))
(if source
(let ((filename (or (cadr source) "<unnamed port>"))
(line (caddr source))
(col (cdddr source)))
(format port "~a:~a:~a: " filename (1+ line) col))
(format port "ERROR: "))))
(set! set-exception-printer!
(lambda (key proc)
(set! exception-printers (acons key proc exception-printers))))
(set! print-exception
(lambda (port frame key args)
(define (default-printer)
(format port "Throw to key `~a' with args `~s'." key args))
(if frame
(let ((proc (frame-procedure frame)))
(print-location frame port)
(format port "In procedure ~a:\n"
(or (false-if-exception (procedure-name proc))
proc))))
(print-location frame port)
(catch #t
(lambda ()
(let ((printer (assq-ref exception-printers key)))
(if printer
(printer port key args default-printer)
(default-printer))))
(lambda (k . args)
(format port "Error while printing exception.")))
(newline port)
(force-output port))))
;;;
;;; Printers for those keys thrown by Guile.
;;;
(let ()
(define (scm-error-printer port key args default-printer)
;; Abuse case-lambda as a pattern matcher, given that we don't have
;; ice-9 match at this point.
(apply (case-lambda
((subr msg args . rest)
(if subr
(format port "In procedure ~a: " subr))
(apply format port msg (or args '())))
(_ (default-printer)))
args))
(define (syntax-error-printer port key args default-printer)
(apply (case-lambda
((who what where form subform . extra)
(format port "Syntax error:\n")
(if where
(let ((file (or (assq-ref where 'filename) "unknown file"))
(line (and=> (assq-ref where 'line) 1+))
(col (assq-ref where 'column)))
(format port "~a:~a:~a: " file line col))
(format port "unknown location: "))
(if who
(format port "~a: " who))
(format port "~a" what)
(if subform
(format port " in subform ~s of ~s" subform form)
(if form
(format port " in form ~s" form))))
(_ (default-printer)))
args))
(define (keyword-error-printer port key args default-printer)
(let ((message (cadr args))
(faulty (car (cadddr args)))) ; I won't do it again, I promise.
(format port "~a: ~s" message faulty)))
(define (getaddrinfo-error-printer port key args default-printer)
(format port "In procedure getaddrinfo: ~a" (gai-strerror (car args))))
(set-exception-printer! 'goops-error scm-error-printer)
(set-exception-printer! 'host-not-found scm-error-printer)
(set-exception-printer! 'keyword-argument-error keyword-error-printer)
(set-exception-printer! 'misc-error scm-error-printer)
(set-exception-printer! 'no-data scm-error-printer)
(set-exception-printer! 'no-recovery scm-error-printer)
(set-exception-printer! 'null-pointer-error scm-error-printer)
(set-exception-printer! 'out-of-range scm-error-printer)
(set-exception-printer! 'program-error scm-error-printer)
(set-exception-printer! 'read-error scm-error-printer)
(set-exception-printer! 'regular-expression-syntax scm-error-printer)
(set-exception-printer! 'signal scm-error-printer)
(set-exception-printer! 'stack-overflow scm-error-printer)
(set-exception-printer! 'system-error scm-error-printer)
(set-exception-printer! 'try-again scm-error-printer)
(set-exception-printer! 'unbound-variable scm-error-printer)
(set-exception-printer! 'wrong-number-of-args scm-error-printer)
(set-exception-printer! 'wrong-type-arg scm-error-printer)
(set-exception-printer! 'syntax-error syntax-error-printer)
(set-exception-printer! 'getaddrinfo-error getaddrinfo-error-printer))
;;; {Defmacros}
;;;
(define-syntax define-macro
(lambda (x)
"Define a defmacro."
(syntax-case x ()
((_ (macro . args) doc body1 body ...)
(string? (syntax->datum #'doc))
#'(define-macro macro doc (lambda args body1 body ...)))
((_ (macro . args) body ...)
#'(define-macro macro #f (lambda args body ...)))
((_ macro transformer)
#'(define-macro macro #f transformer))
((_ macro doc transformer)
(or (string? (syntax->datum #'doc))
(not (syntax->datum #'doc)))
#'(define-syntax macro
(lambda (y)
doc
#((macro-type . defmacro)
(defmacro-args args))
(syntax-case y ()
((_ . args)
(let ((v (syntax->datum #'args)))
(datum->syntax y (apply transformer v)))))))))))
(define-syntax defmacro
(lambda (x)
"Define a defmacro, with the old lispy defun syntax."
(syntax-case x ()
((_ macro args doc body1 body ...)
(string? (syntax->datum #'doc))
#'(define-macro macro doc (lambda args body1 body ...)))
((_ macro args body ...)
#'(define-macro macro #f (lambda args body ...))))))
(provide 'defmacro)
;;; {Deprecation}
;;;
(define-syntax begin-deprecated
(lambda (x)
(syntax-case x ()
((_ form form* ...)
(if (include-deprecated-features)
#'(begin form form* ...)
#'(begin))))))
;;; {Trivial Functions}
;;;
(define (identity x) x)
(define (compose proc . rest)
"Compose PROC with the procedures in REST, such that the last one in
REST is applied first and PROC last, and return the resulting procedure.
The given procedures must have compatible arity."
(if (null? rest)
proc
(let ((g (apply compose rest)))
(lambda args
(call-with-values (lambda () (apply g args)) proc)))))
(define (negate proc)
"Return a procedure with the same arity as PROC that returns the `not'
of PROC's result."
(lambda args
(not (apply proc args))))
(define (const value)
"Return a procedure that accepts any number of arguments and returns
VALUE."
(lambda _
value))
(define (and=> value procedure)
"When VALUE is #f, return #f. Otherwise, return (PROC VALUE)."
(and value (procedure value)))
(define call/cc call-with-current-continuation)
(define-syntax false-if-exception
(syntax-rules ()
((false-if-exception expr)
(catch #t
(lambda () expr)
(lambda args #f)))
((false-if-exception expr #\warning template arg ...)
(catch #t
(lambda () expr)
(lambda (key . args)
(for-each (lambda (s)
(if (not (string-null? s))
(format (current-warning-port) ";;; ~a\n" s)))
(string-split
(call-with-output-string
(lambda (port)
(format port template arg ...)
(print-exception port #f key args)))
#\newline))
#f)))))
;;; {General Properties}
;;;
;; Properties are a lispy way to associate random info with random objects.
;; Traditionally properties are implemented as an alist or a plist actually
;; pertaining to the object in question.
;;
;; These "object properties" have the advantage that they can be associated with
;; any object, even if the object has no plist. Object properties are good when
;; you are extending pre-existing objects in unexpected ways. They also present
;; a pleasing, uniform procedure-with-setter interface. But if you have a data
;; type that always has properties, it's often still best to store those
;; properties within the object itself.
(define (make-object-property)
(define-syntax-rule (with-mutex lock exp)
(dynamic-wind (lambda () (lock-mutex lock))
(lambda () exp)
(lambda () (unlock-mutex lock))))
(let ((prop (make-weak-key-hash-table))
(lock (make-mutex)))
(make-procedure-with-setter
(lambda (obj) (with-mutex lock (hashq-ref prop obj)))
(lambda (obj val) (with-mutex lock (hashq-set! prop obj val))))))
;;; {Symbol Properties}
;;;
;;; Symbol properties are something you see in old Lisp code. In most current
;;; Guile code, symbols are not used as a data structure -- they are used as
;;; keys into other data structures.
(define (symbol-property sym prop)
(let ((pair (assoc prop (symbol-pref sym))))
(and pair (cdr pair))))
(define (set-symbol-property! sym prop val)
(let ((pair (assoc prop (symbol-pref sym))))
(if pair
(set-cdr! pair val)
(symbol-pset! sym (acons prop val (symbol-pref sym))))))
(define (symbol-property-remove! sym prop)
(let ((pair (assoc prop (symbol-pref sym))))
(if pair
(symbol-pset! sym (delq! pair (symbol-pref sym))))))
;;; {Arrays}
;;;
(define (array-shape a)
(map (lambda (ind) (if (number? ind) (list 0 (+ -1 ind)) ind))
(array-dimensions a)))
;;; {Keywords}
;;;
;;; It's much better if you can use lambda* / define*, of course.
(define (kw-arg-ref args kw)
(let ((rem (member kw args)))
(and rem (pair? (cdr rem)) (cadr rem))))
;;; {Structs}
;;;
(define (struct-layout s)
(struct-ref (struct-vtable s) vtable-index-layout))
;;; {Records}
;;;
;; Printing records: by default, records are printed as
;;
;; #<type-name field1: val1 field2: val2 ...>
;;
;; You can change that by giving a custom printing function to
;; MAKE-RECORD-TYPE (after the list of field symbols). This function
;; will be called like
;;
;; (<printer> object port)
;;
;; It should print OBJECT to PORT.
(define (inherit-print-state old-port new-port)
(if (get-print-state old-port)
(port-with-print-state new-port (get-print-state old-port))
new-port))
;; 0: type-name, 1: fields, 2: constructor
(define record-type-vtable
(let ((s (make-vtable (string-append standard-vtable-fields "prprpw")
(lambda (s p)
(display "#<record-type " p)
(display (record-type-name s) p)
(display ">" p)))))
(set-struct-vtable-name! s 'record-type)
s))
(define (record-type? obj)
(and (struct? obj) (eq? record-type-vtable (struct-vtable obj))))
(define* (make-record-type type-name fields #\optional printer)
;; Pre-generate constructors for nfields < 20.
(define-syntax make-constructor
(lambda (x)
(define *max-static-argument-count* 20)
(define (make-formals n)
(let lp ((i 0))
(if (< i n)
(cons (datum->syntax
x
(string->symbol
(string (integer->char (+ (char->integer #\a) i)))))
(lp (1+ i)))
'())))
(syntax-case x ()
((_ rtd exp) (not (identifier? #'exp))
#'(let ((n exp))
(make-constructor rtd n)))
((_ rtd nfields)
#`(case nfields
#,@(let lp ((n 0))
(if (< n *max-static-argument-count*)
(cons (with-syntax (((formal ...) (make-formals n))
(n n))
#'((n)
(lambda (formal ...)
(make-struct rtd 0 formal ...))))
(lp (1+ n)))
'()))
(else
(lambda args
(if (= (length args) nfields)
(apply make-struct rtd 0 args)
(scm-error 'wrong-number-of-args
(format #f "make-~a" type-name)
"Wrong number of arguments" '() #f)))))))))
(define (default-record-printer s p)
(display "#<" p)
(display (record-type-name (record-type-descriptor s)) p)
(let loop ((fields (record-type-fields (record-type-descriptor s)))
(off 0))
(cond
((not (null? fields))
(display " " p)
(display (car fields) p)
(display ": " p)
(display (struct-ref s off) p)
(loop (cdr fields) (+ 1 off)))))
(display ">" p))
(let ((rtd (make-struct record-type-vtable 0
(make-struct-layout
(apply string-append
(map (lambda (f) "pw") fields)))
(or printer default-record-printer)
type-name
(copy-tree fields))))
(struct-set! rtd (+ vtable-offset-user 2)
(make-constructor rtd (length fields)))
;; Temporary solution: Associate a name to the record type descriptor
;; so that the object system can create a wrapper class for it.
(set-struct-vtable-name! rtd (if (symbol? type-name)
type-name
(string->symbol type-name)))
rtd))
(define (record-type-name obj)
(if (record-type? obj)
(struct-ref obj vtable-offset-user)
(error 'not-a-record-type obj)))
(define (record-type-fields obj)
(if (record-type? obj)
(struct-ref obj (+ 1 vtable-offset-user))
(error 'not-a-record-type obj)))
(define* (record-constructor rtd #\optional field-names)
(if (not field-names)
(struct-ref rtd (+ 2 vtable-offset-user))
(primitive-eval
`(lambda ,field-names
(make-struct ',rtd 0 ,@(map (lambda (f)
(if (memq f field-names)
f
#f))
(record-type-fields rtd)))))))
(define (record-predicate rtd)
(lambda (obj) (and (struct? obj) (eq? rtd (struct-vtable obj)))))
(define (%record-type-error rtd obj) ;; private helper
(or (eq? rtd (record-type-descriptor obj))
(scm-error 'wrong-type-arg "%record-type-check"
"Wrong type record (want `~S'): ~S"
(list (record-type-name rtd) obj)
#f)))
(define (record-accessor rtd field-name)
(let ((pos (list-index (record-type-fields rtd) field-name)))
(if (not pos)
(error 'no-such-field field-name))
(lambda (obj)
(if (eq? (struct-vtable obj) rtd)
(struct-ref obj pos)
(%record-type-error rtd obj)))))
(define (record-modifier rtd field-name)
(let ((pos (list-index (record-type-fields rtd) field-name)))
(if (not pos)
(error 'no-such-field field-name))
(lambda (obj val)
(if (eq? (struct-vtable obj) rtd)
(struct-set! obj pos val)
(%record-type-error rtd obj)))))
(define (record? obj)
(and (struct? obj) (record-type? (struct-vtable obj))))
(define (record-type-descriptor obj)
(if (struct? obj)
(struct-vtable obj)
(error 'not-a-record obj)))
(provide 'record)
;;; {Booleans}
;;;
(define (->bool x) (not (not x)))
;;; {Symbols}
;;;
(define (symbol-append . args)
(string->symbol (apply string-append (map symbol->string args))))
(define (list->symbol . args)
(string->symbol (apply list->string args)))
(define (symbol . args)
(string->symbol (apply string args)))
;;; {Lists}
;;;
(define (list-index l k)
(let loop ((n 0)
(l l))
(and (not (null? l))
(if (eq? (car l) k)
n
(loop (+ n 1) (cdr l))))))
;; Load `posix.scm' even when not (provided? 'posix) so that we get the
;; `stat' accessors.
(primitive-load-path "ice-9/posix")
(if (provided? 'socket)
(primitive-load-path "ice-9/networking"))
;; For reference, Emacs file-exists-p uses stat in this same way.
(define file-exists?
(if (provided? 'posix)
(lambda (str)
(->bool (stat str #f)))
(lambda (str)
(let ((port (catch 'system-error (lambda () (open-file str OPEN_READ))
(lambda args #f))))
(if port (begin (close-port port) #t)
#f)))))
(define file-is-directory?
(if (provided? 'posix)
(lambda (str)
(eq? (stat:type (stat str)) 'directory))
(lambda (str)
(let ((port (catch 'system-error
(lambda () (open-file (string-append str "/.")
OPEN_READ))
(lambda args #f))))
(if port (begin (close-port port) #t)
#f)))))
(define (system-error-errno args)
(if (eq? (car args) 'system-error)
(car (list-ref args 4))
#f))
;;; {Error Handling}
;;;
(define error
(case-lambda
(()
(scm-error 'misc-error #f "?" #f #f))
((message . args)
(let ((msg (string-join (cons "~A" (make-list (length args) "~S")))))
(scm-error 'misc-error #f msg (cons message args) #f)))))
;;; {Time Structures}
;;;
(define (tm:sec obj) (vector-ref obj 0))
(define (tm:min obj) (vector-ref obj 1))
(define (tm:hour obj) (vector-ref obj 2))
(define (tm:mday obj) (vector-ref obj 3))
(define (tm:mon obj) (vector-ref obj 4))
(define (tm:year obj) (vector-ref obj 5))
(define (tm:wday obj) (vector-ref obj 6))
(define (tm:yday obj) (vector-ref obj 7))
(define (tm:isdst obj) (vector-ref obj 8))
(define (tm:gmtoff obj) (vector-ref obj 9))
(define (tm:zone obj) (vector-ref obj 10))
(define (set-tm:sec obj val) (vector-set! obj 0 val))
(define (set-tm:min obj val) (vector-set! obj 1 val))
(define (set-tm:hour obj val) (vector-set! obj 2 val))
(define (set-tm:mday obj val) (vector-set! obj 3 val))
(define (set-tm:mon obj val) (vector-set! obj 4 val))
(define (set-tm:year obj val) (vector-set! obj 5 val))
(define (set-tm:wday obj val) (vector-set! obj 6 val))
(define (set-tm:yday obj val) (vector-set! obj 7 val))
(define (set-tm:isdst obj val) (vector-set! obj 8 val))
(define (set-tm:gmtoff obj val) (vector-set! obj 9 val))
(define (set-tm:zone obj val) (vector-set! obj 10 val))
(define (tms:clock obj) (vector-ref obj 0))
(define (tms:utime obj) (vector-ref obj 1))
(define (tms:stime obj) (vector-ref obj 2))
(define (tms:cutime obj) (vector-ref obj 3))
(define (tms:cstime obj) (vector-ref obj 4))
;;; {File Descriptors and Ports}
;;;
(define file-position ftell)
(define* (file-set-position port offset #\optional (whence SEEK_SET))
(seek port offset whence))
(define (move->fdes fd/port fd)
(cond ((integer? fd/port)
(dup->fdes fd/port fd)
(close fd/port)
fd)
(else
(primitive-move->fdes fd/port fd)
(set-port-revealed! fd/port 1)
fd/port)))
(define (release-port-handle port)
(let ((revealed (port-revealed port)))
(if (> revealed 0)
(set-port-revealed! port (- revealed 1)))))
(define dup->port
(case-lambda
((port/fd mode)
(fdopen (dup->fdes port/fd) mode))
((port/fd mode new-fd)
(let ((port (fdopen (dup->fdes port/fd new-fd) mode)))
(set-port-revealed! port 1)
port))))
(define dup->inport
(case-lambda
((port/fd)
(dup->port port/fd "r"))
((port/fd new-fd)
(dup->port port/fd "r" new-fd))))
(define dup->outport
(case-lambda
((port/fd)
(dup->port port/fd "w"))
((port/fd new-fd)
(dup->port port/fd "w" new-fd))))
(define dup
(case-lambda
((port/fd)
(if (integer? port/fd)
(dup->fdes port/fd)
(dup->port port/fd (port-mode port/fd))))
((port/fd new-fd)
(if (integer? port/fd)
(dup->fdes port/fd new-fd)
(dup->port port/fd (port-mode port/fd) new-fd)))))
(define (duplicate-port port modes)
(dup->port port modes))
(define (fdes->inport fdes)
(let loop ((rest-ports (fdes->ports fdes)))
(cond ((null? rest-ports)
(let ((result (fdopen fdes "r")))
(set-port-revealed! result 1)
result))
((input-port? (car rest-ports))
(set-port-revealed! (car rest-ports)
(+ (port-revealed (car rest-ports)) 1))
(car rest-ports))
(else
(loop (cdr rest-ports))))))
(define (fdes->outport fdes)
(let loop ((rest-ports (fdes->ports fdes)))
(cond ((null? rest-ports)
(let ((result (fdopen fdes "w")))
(set-port-revealed! result 1)
result))
((output-port? (car rest-ports))
(set-port-revealed! (car rest-ports)
(+ (port-revealed (car rest-ports)) 1))
(car rest-ports))
(else
(loop (cdr rest-ports))))))
(define (port->fdes port)
(set-port-revealed! port (+ (port-revealed port) 1))
(fileno port))
(define (setenv name value)
(if value
(putenv (string-append name "=" value))
(putenv name)))
(define (unsetenv name)
"Remove the entry for NAME from the environment."
(putenv name))
;;; {Load Paths}
;;;
(let-syntax ((compile-time-case
(lambda (stx)
(syntax-case stx ()
((_ exp clauses ...)
(let ((val (primitive-eval (syntax->datum #'exp))))
(let next-clause ((clauses #'(clauses ...)))
(syntax-case clauses (else)
(()
(syntax-violation 'compile-time-case
"all clauses failed to match" stx))
(((else form ...))
#'(begin form ...))
((((k ...) form ...) clauses ...)
(if (memv val (syntax->datum #'(k ...)))
#'(begin form ...)
(next-clause #'(clauses ...))))))))))))
;; emacs: (put 'compile-time-case 'scheme-indent-function 1)
(compile-time-case (system-file-name-convention)
((posix)
(define (file-name-separator? c)
(char=? c #\/))
(define file-name-separator-string "/")
(define (absolute-file-name? file-name)
(string-prefix? "/" file-name)))
((windows)
(define (file-name-separator? c)
(or (char=? c #\/)
(char=? c #\\)))
(define file-name-separator-string "/")
(define (absolute-file-name? file-name)
(define (file-name-separator-at-index? idx)
(and (> (string-length file-name) idx)
(file-name-separator? (string-ref file-name idx))))
(define (unc-file-name?)
;; Universal Naming Convention (UNC) file-names start with \\,
;; and are always absolute. See:
;; http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
(and (file-name-separator-at-index? 0)
(file-name-separator-at-index? 1)))
(define (has-drive-specifier?)
(and (>= (string-length file-name) 2)
(let ((drive (string-ref file-name 0)))
(or (char<=? #\a drive #\z)
(char<=? #\A drive #\Z)))
(eqv? (string-ref file-name 1) #\:)))
(or (unc-file-name?)
(if (has-drive-specifier?)
(file-name-separator-at-index? 2)
(file-name-separator-at-index? 0)))))))
(define (in-vicinity vicinity file)
(let ((tail (let ((len (string-length vicinity)))
(if (zero? len)
#f
(string-ref vicinity (- len 1))))))
(string-append vicinity
(if (or (not tail) (file-name-separator? tail))
""
file-name-separator-string)
file)))
;;; {Help for scm_shell}
;;;
;;; The argument-processing code used by Guile-based shells generates
;;; Scheme code based on the argument list. This page contains help
;;; functions for the code it generates.
;;;
(define (command-line) (program-arguments))
;; This is mostly for the internal use of the code generated by
;; scm_compile_shell_switches.
(define (load-user-init)
(let* ((home (or (getenv "HOME")
(false-if-exception (passwd:dir (getpwuid (getuid))))
file-name-separator-string)) ;; fallback for cygwin etc.
(init-file (in-vicinity home ".guile")))
(if (file-exists? init-file)
(primitive-load init-file))))
;;; {The interpreter stack}
;;;
;; %stacks defined in stacks.c
(define (%start-stack tag thunk)
(let ((prompt-tag (make-prompt-tag "start-stack")))
(call-with-prompt
prompt-tag
(lambda ()
(with-fluids ((%stacks (acons tag prompt-tag
(or (fluid-ref %stacks) '()))))
(thunk)))
(lambda (k . args)
(%start-stack tag (lambda () (apply k args)))))))
(define-syntax-rule (start-stack tag exp)
(%start-stack tag (lambda () exp)))
;;; {Loading by paths}
;;;
;;; Load a Scheme source file named NAME, searching for it in the
;;; directories listed in %load-path, and applying each of the file
;;; name extensions listed in %load-extensions.
(define (load-from-path name)
(start-stack 'load-stack
(primitive-load-path name)))
(define-syntax-rule (add-to-load-path elt)
"Add ELT to Guile's load path, at compile-time and at run-time."
(eval-when (expand load eval)
(set! %load-path (cons elt (delete elt %load-path)))))
(define %load-verbosely #f)
(define (assert-load-verbosity v) (set! %load-verbosely v))
(define (%load-announce file)
(if %load-verbosely
(with-output-to-port (current-warning-port)
(lambda ()
(display ";;; ")
(display "loading ")
(display file)
(newline)
(force-output)))))
(set! %load-hook %load-announce)
;;; {Reader Extensions}
;;;
;;; Reader code for various "#c" forms.
;;;
(define read-eval? (make-fluid #f))
(read-hash-extend #\.
(lambda (c port)
(if (fluid-ref read-eval?)
(eval (read port) (interaction-environment))
(error
"#. read expansion found and read-eval? is #f."))))
;;; {Low Level Modules}
;;;
;;; These are the low level data structures for modules.
;;;
;;; Every module object is of the type 'module-type', which is a record
;;; consisting of the following members:
;;;
;;; - eval-closure: A deprecated field, to be removed in Guile 2.2.
;;;
;;; - obarray: a hash table that maps symbols to variable objects. In this
;;; hash table, the definitions are found that are local to the module (that
;;; is, not imported from other modules). When looking up bindings in the
;;; module, this hash table is searched first.
;;;
;;; - binder: either #f or a function taking a module and a symbol argument.
;;; If it is a function it is called after the obarray has been
;;; unsuccessfully searched for a binding. It then can provide bindings
;;; that would otherwise not be found locally in the module.
;;;
;;; - uses: a list of modules from which non-local bindings can be inherited.
;;; These modules are the third place queried for bindings after the obarray
;;; has been unsuccessfully searched and the binder function did not deliver
;;; a result either.
;;;
;;; - transformer: either #f or a function taking a scheme expression as
;;; delivered by read. If it is a function, it will be called to perform
;;; syntax transformations (e. g. makro expansion) on the given scheme
;;; expression. The output of the transformer function will then be passed
;;; to Guile's internal memoizer. This means that the output must be valid
;;; scheme code. The only exception is, that the output may make use of the
;;; syntax extensions provided to identify the modules that a binding
;;; belongs to.
;;;
;;; - name: the name of the module. This is used for all kinds of printing
;;; outputs. In certain places the module name also serves as a way of
;;; identification. When adding a module to the uses list of another
;;; module, it is made sure that the new uses list will not contain two
;;; modules of the same name.
;;;
;;; - kind: classification of the kind of module. The value is (currently?)
;;; only used for printing. It has no influence on how a module is treated.
;;; Currently the following values are used when setting the module kind:
;;; 'module, 'directory, 'interface, 'custom-interface. If no explicit kind
;;; is set, it defaults to 'module.
;;;
;;; - duplicates-handlers: a list of procedures that get called to make a
;;; choice between two duplicate bindings when name clashes occur. See the
;;; `duplicate-handlers' global variable below.
;;;
;;; - observers: a list of procedures that get called when the module is
;;; modified.
;;;
;;; - weak-observers: a weak-key hash table of procedures that get called
;;; when the module is modified. See `module-observe-weak' for details.
;;;
;;; In addition, the module may (must?) contain a binding for
;;; `%module-public-interface'. This variable should be bound to a module
;;; representing the exported interface of a module. See the
;;; `module-public-interface' and `module-export!' procedures.
;;;
;;; !!! warning: The interface to lazy binder procedures is going
;;; to be changed in an incompatible way to permit all the basic
;;; module ops to be virtualized.
;;;
;;; (make-module size use-list lazy-binding-proc) => module
;;; module-{obarray,uses,binder}[|-set!]
;;; (module? obj) => [#t|#f]
;;; (module-locally-bound? module symbol) => [#t|#f]
;;; (module-bound? module symbol) => [#t|#f]
;;; (module-symbol-locally-interned? module symbol) => [#t|#f]
;;; (module-symbol-interned? module symbol) => [#t|#f]
;;; (module-local-variable module symbol) => [#<variable ...> | #f]
;;; (module-variable module symbol) => [#<variable ...> | #f]
;;; (module-symbol-binding module symbol opt-value)
;;; => [ <obj> | opt-value | an error occurs ]
;;; (module-make-local-var! module symbol) => #<variable...>
;;; (module-add! module symbol var) => unspecified
;;; (module-remove! module symbol) => unspecified
;;; (module-for-each proc module) => unspecified
;;; (make-scm-module) => module ; a lazy copy of the symhash module
;;; (set-current-module module) => unspecified
;;; (current-module) => #<module...>
;;;
;;;
;;; {Printing Modules}
;;;
;; This is how modules are printed. You can re-define it.
(define (%print-module mod port)
(display "#<" port)
(display (or (module-kind mod) "module") port)
(display " " port)
(display (module-name mod) port)
(display " " port)
(display (number->string (object-address mod) 16) port)
(display ">" port))
(letrec-syntax
;; Locally extend the syntax to allow record accessors to be defined at
;; compile-time. Cache the rtd locally to the constructor, the getters and
;; the setters, in order to allow for redefinition of the record type; not
;; relevant in the case of modules, but perhaps if we make this public, it
;; could matter.
((define-record-type
(lambda (x)
(define (make-id scope . fragments)
(datum->syntax #'scope
(apply symbol-append
(map (lambda (x)
(if (symbol? x) x (syntax->datum x)))
fragments))))
(define (getter rtd type-name field slot)
#`(define #,(make-id rtd type-name '- field)
(let ((rtd #,rtd))
(lambda (#,type-name)
(if (eq? (struct-vtable #,type-name) rtd)
(struct-ref #,type-name #,slot)
(%record-type-error rtd #,type-name))))))
(define (setter rtd type-name field slot)
#`(define #,(make-id rtd 'set- type-name '- field '!)
(let ((rtd #,rtd))
(lambda (#,type-name val)
(if (eq? (struct-vtable #,type-name) rtd)
(struct-set! #,type-name #,slot val)
(%record-type-error rtd #,type-name))))))
(define (accessors rtd type-name fields n exp)
(syntax-case fields ()
(() exp)
(((field #\no-accessors) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
exp))
(((field #\no-setter) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(getter rtd type-name #'field n))))
(((field #\no-getter) field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(setter rtd type-name #'field n))))
((field field* ...) (identifier? #'field)
(accessors rtd type-name #'(field* ...) (1+ n)
#`(begin #,exp
#,(getter rtd type-name #'field n)
#,(setter rtd type-name #'field n))))))
(define (predicate rtd type-name fields exp)
(accessors
rtd type-name fields 0
#`(begin
#,exp
(define (#,(make-id rtd type-name '?) obj)
(and (struct? obj) (eq? (struct-vtable obj) #,rtd))))))
(define (field-list fields)
(syntax-case fields ()
(() '())
(((f . opts) . rest) (identifier? #'f)
(cons #'f (field-list #'rest)))
((f . rest) (identifier? #'f)
(cons #'f (field-list #'rest)))))
(define (constructor rtd type-name fields exp)
(let ((ctor (make-id rtd type-name '-constructor))
(args (field-list fields)))
(predicate rtd type-name fields
#`(begin #,exp
(define #,ctor
(let ((rtd #,rtd))
(lambda #,args
(make-struct rtd 0 #,@args))))
(struct-set! #,rtd (+ vtable-offset-user 2)
#,ctor)))))
(define (type type-name printer fields)
(define (make-layout)
(let lp ((fields fields) (slots '()))
(syntax-case fields ()
(() (datum->syntax #'here
(make-struct-layout
(apply string-append slots))))
((_ . rest) (lp #'rest (cons "pw" slots))))))
(let ((rtd (make-id type-name type-name '-type)))
(constructor rtd type-name fields
#`(begin
(define #,rtd
(make-struct record-type-vtable 0
'#,(make-layout)
#,printer
'#,type-name
'#,(field-list fields)))
(set-struct-vtable-name! #,rtd '#,type-name)))))
(syntax-case x ()
((_ type-name printer (field ...))
(type #'type-name #'printer #'(field ...)))))))
;; module-type
;;
;; A module is characterized by an obarray in which local symbols
;; are interned, a list of modules, "uses", from which non-local
;; bindings can be inherited, and an optional lazy-binder which
;; is a (CLOSURE module symbol) which, as a last resort, can provide
;; bindings that would otherwise not be found locally in the module.
;;
;; NOTE: If you change the set of fields or their order, you also need to
;; change the constants in libguile/modules.h.
;;
;; NOTE: The getter `module-transfomer' is defined libguile/modules.c.
;; NOTE: The getter `module-name' is defined later, due to boot reasons.
;; NOTE: The getter `module-public-interface' is used in libguile/modules.c.
;;
(define-record-type module
(lambda (obj port) (%print-module obj port))
(obarray
uses
binder
eval-closure
(transformer #\no-getter)
(name #\no-getter)
kind
duplicates-handlers
(import-obarray #\no-setter)
observers
(weak-observers #\no-setter)
version
submodules
submodule-binder
public-interface
filename
next-unique-id)))
;; make-module &opt size uses binder
;;
;; Create a new module, perhaps with a particular size of obarray,
;; initial uses list, or binding procedure.
;;
(define* (make-module #\optional (size 31) (uses '()) (binder #f))
(define %default-import-size
;; Typical number of imported bindings actually used by a module.
600)
(if (not (integer? size))
(error "Illegal size to make-module." size))
(if (not (and (list? uses)
(and-map module? uses)))
(error "Incorrect use list." uses))
(if (and binder (not (procedure? binder)))
(error
"Lazy-binder expected to be a procedure or #f." binder))
(module-constructor (make-hash-table size)
uses binder #f macroexpand
#f #f #f
(make-hash-table %default-import-size)
'()
(make-weak-key-hash-table 31) #f
(make-hash-table 7) #f #f #f 0))
;;; {Observer protocol}
;;;
(define (module-observe module proc)
(set-module-observers! module (cons proc (module-observers module)))
(cons module proc))
(define* (module-observe-weak module observer-id #\optional (proc observer-id))
;; Register PROC as an observer of MODULE under name OBSERVER-ID (which can
;; be any Scheme object). PROC is invoked and passed MODULE any time
;; MODULE is modified. PROC gets unregistered when OBSERVER-ID gets GC'd
;; (thus, it is never unregistered if OBSERVER-ID is an immediate value,
;; for instance).
;; The two-argument version is kept for backward compatibility: when called
;; with two arguments, the observer gets unregistered when closure PROC
;; gets GC'd (making it impossible to use an anonymous lambda for PROC).
(hashq-set! (module-weak-observers module) observer-id proc))
(define (module-unobserve token)
(let ((module (car token))
(id (cdr token)))
(if (integer? id)
(hash-remove! (module-weak-observers module) id)
(set-module-observers! module (delq1! id (module-observers module)))))
*unspecified*)
(define module-defer-observers #f)
(define module-defer-observers-mutex (make-mutex 'recursive))
(define module-defer-observers-table (make-hash-table))
(define (module-modified m)
(if module-defer-observers
(hash-set! module-defer-observers-table m #t)
(module-call-observers m)))
;;; This function can be used to delay calls to observers so that they
;;; can be called once only in the face of massive updating of modules.
;;;
(define (call-with-deferred-observers thunk)
(dynamic-wind
(lambda ()
(lock-mutex module-defer-observers-mutex)
(set! module-defer-observers #t))
thunk
(lambda ()
(set! module-defer-observers #f)
(hash-for-each (lambda (m dummy)
(module-call-observers m))
module-defer-observers-table)
(hash-clear! module-defer-observers-table)
(unlock-mutex module-defer-observers-mutex))))
(define (module-call-observers m)
(for-each (lambda (proc) (proc m)) (module-observers m))
;; We assume that weak observers don't (un)register themselves as they are
;; called since this would preclude proper iteration over the hash table
;; elements.
(hash-for-each (lambda (id proc) (proc m)) (module-weak-observers m)))
;;; {Module Searching in General}
;;;
;;; We sometimes want to look for properties of a symbol
;;; just within the obarray of one module. If the property
;;; holds, then it is said to hold ``locally'' as in, ``The symbol
;;; DISPLAY is locally rebound in the module `safe-guile'.''
;;;
;;;
;;; Other times, we want to test for a symbol property in the obarray
;;; of M and, if it is not found there, try each of the modules in the
;;; uses list of M. This is the normal way of testing for some
;;; property, so we state these properties without qualification as
;;; in: ``The symbol 'fnord is interned in module M because it is
;;; interned locally in module M2 which is a member of the uses list
;;; of M.''
;;;
;; module-search fn m
;;
;; return the first non-#f result of FN applied to M and then to
;; the modules in the uses of m, and so on recursively. If all applications
;; return #f, then so does this function.
;;
(define (module-search fn m v)
(define (loop pos)
(and (pair? pos)
(or (module-search fn (car pos) v)
(loop (cdr pos)))))
(or (fn m v)
(loop (module-uses m))))
;;; {Is a symbol bound in a module?}
;;;
;;; Symbol S in Module M is bound if S is interned in M and if the binding
;;; of S in M has been set to some well-defined value.
;;;
;; module-locally-bound? module symbol
;;
;; Is a symbol bound (interned and defined) locally in a given module?
;;
(define (module-locally-bound? m v)
(let ((var (module-local-variable m v)))
(and var
(variable-bound? var))))
;; module-bound? module symbol
;;
;; Is a symbol bound (interned and defined) anywhere in a given module
;; or its uses?
;;
(define (module-bound? m v)
(let ((var (module-variable m v)))
(and var
(variable-bound? var))))
;;; {Is a symbol interned in a module?}
;;;
;;; Symbol S in Module M is interned if S occurs in
;;; of S in M has been set to some well-defined value.
;;;
;;; It is possible to intern a symbol in a module without providing
;;; an initial binding for the corresponding variable. This is done
;;; with:
;;; (module-add! module symbol (make-undefined-variable))
;;;
;;; In that case, the symbol is interned in the module, but not
;;; bound there. The unbound symbol shadows any binding for that
;;; symbol that might otherwise be inherited from a member of the uses list.
;;;
(define (module-obarray-get-handle ob key)
((if (symbol? key) hashq-get-handle hash-get-handle) ob key))
(define (module-obarray-ref ob key)
((if (symbol? key) hashq-ref hash-ref) ob key))
(define (module-obarray-set! ob key val)
((if (symbol? key) hashq-set! hash-set!) ob key val))
(define (module-obarray-remove! ob key)
((if (symbol? key) hashq-remove! hash-remove!) ob key))
;; module-symbol-locally-interned? module symbol
;;
;; is a symbol interned (not neccessarily defined) locally in a given module
;; or its uses? Interned symbols shadow inherited bindings even if
;; they are not themselves bound to a defined value.
;;
(define (module-symbol-locally-interned? m v)
(not (not (module-obarray-get-handle (module-obarray m) v))))
;; module-symbol-interned? module symbol
;;
;; is a symbol interned (not neccessarily defined) anywhere in a given module
;; or its uses? Interned symbols shadow inherited bindings even if
;; they are not themselves bound to a defined value.
;;
(define (module-symbol-interned? m v)
(module-search module-symbol-locally-interned? m v))
;;; {Mapping modules x symbols --> variables}
;;;
;; module-local-variable module symbol
;; return the local variable associated with a MODULE and SYMBOL.
;;
;;; This function is very important. It is the only function that can
;;; return a variable from a module other than the mutators that store
;;; new variables in modules. Therefore, this function is the location
;;; of the "lazy binder" hack.
;;;
;;; If symbol is defined in MODULE, and if the definition binds symbol
;;; to a variable, return that variable object.
;;;
;;; If the symbols is not found at first, but the module has a lazy binder,
;;; then try the binder.
;;;
;;; If the symbol is not found at all, return #f.
;;;
;;; (This is now written in C, see `modules.c'.)
;;;
;;; {Mapping modules x symbols --> bindings}
;;;
;;; These are similar to the mapping to variables, except that the
;;; variable is dereferenced.
;;;
;; module-symbol-binding module symbol opt-value
;;
;; return the binding of a variable specified by name within
;; a given module, signalling an error if the variable is unbound.
;; If the OPT-VALUE is passed, then instead of signalling an error,
;; return OPT-VALUE.
;;
(define (module-symbol-local-binding m v . opt-val)
(let ((var (module-local-variable m v)))
(if (and var (variable-bound? var))
(variable-ref var)
(if (not (null? opt-val))
(car opt-val)
(error "Locally unbound variable." v)))))
;; module-symbol-binding module symbol opt-value
;;
;; return the binding of a variable specified by name within
;; a given module, signalling an error if the variable is unbound.
;; If the OPT-VALUE is passed, then instead of signalling an error,
;; return OPT-VALUE.
;;
(define (module-symbol-binding m v . opt-val)
(let ((var (module-variable m v)))
(if (and var (variable-bound? var))
(variable-ref var)
(if (not (null? opt-val))
(car opt-val)
(error "Unbound variable." v)))))
;;; {Adding Variables to Modules}
;;;
;; module-make-local-var! module symbol
;;
;; ensure a variable for V in the local namespace of M.
;; If no variable was already there, then create a new and uninitialzied
;; variable.
;;
;; This function is used in modules.c.
;;
(define (module-make-local-var! m v)
(or (let ((b (module-obarray-ref (module-obarray m) v)))
(and (variable? b)
(begin
;; Mark as modified since this function is called when
;; the standard eval closure defines a binding
(module-modified m)
b)))
;; Create a new local variable.
(let ((local-var (make-undefined-variable)))
(module-add! m v local-var)
local-var)))
;; module-ensure-local-variable! module symbol
;;
;; Ensure that there is a local variable in MODULE for SYMBOL. If
;; there is no binding for SYMBOL, create a new uninitialized
;; variable. Return the local variable.
;;
(define (module-ensure-local-variable! module symbol)
(or (module-local-variable module symbol)
(let ((var (make-undefined-variable)))
(module-add! module symbol var)
var)))
;; module-add! module symbol var
;;
;; ensure a particular variable for V in the local namespace of M.
;;
(define (module-add! m v var)
(if (not (variable? var))
(error "Bad variable to module-add!" var))
(if (not (symbol? v))
(error "Bad symbol to module-add!" v))
(module-obarray-set! (module-obarray m) v var)
(module-modified m))
;; module-remove!
;;
;; make sure that a symbol is undefined in the local namespace of M.
;;
(define (module-remove! m v)
(module-obarray-remove! (module-obarray m) v)
(module-modified m))
(define (module-clear! m)
(hash-clear! (module-obarray m))
(module-modified m))
;; MODULE-FOR-EACH -- exported
;;
;; Call PROC on each symbol in MODULE, with arguments of (SYMBOL VARIABLE).
;;
(define (module-for-each proc module)
(hash-for-each proc (module-obarray module)))
(define (module-map proc module)
(hash-map->list proc (module-obarray module)))
;; Submodules
;;
;; Modules exist in a separate namespace from values, because you generally do
;; not want the name of a submodule, which you might not even use, to collide
;; with local variables that happen to be named the same as the submodule.
;;
(define (module-ref-submodule module name)
(or (hashq-ref (module-submodules module) name)
(and (module-submodule-binder module)
((module-submodule-binder module) module name))))
(define (module-define-submodule! module name submodule)
(hashq-set! (module-submodules module) name submodule))
;; It used to be, however, that module names were also present in the
;; value namespace. When we enable deprecated code, we preserve this
;; legacy behavior.
;;
;; These shims are defined here instead of in deprecated.scm because we
;; need their definitions before loading other modules.
;;
(begin-deprecated
(define (module-ref-submodule module name)
(or (hashq-ref (module-submodules module) name)
(and (module-submodule-binder module)
((module-submodule-binder module) module name))
(let ((var (module-local-variable module name)))
(and var (variable-bound? var) (module? (variable-ref var))
(begin
(warn "module" module "not in submodules table")
(variable-ref var))))))
(define (module-define-submodule! module name submodule)
(let ((var (module-local-variable module name)))
(if (and var
(or (not (variable-bound? var))
(not (module? (variable-ref var)))))
(warn "defining module" module ": not overriding local definition" var)
(module-define! module name submodule)))
(hashq-set! (module-submodules module) name submodule)))
;;; {Module-based Loading}
;;;
(define (save-module-excursion thunk)
(let ((inner-module (current-module))
(outer-module #f))
(dynamic-wind (lambda ()
(set! outer-module (current-module))
(set-current-module inner-module)
(set! inner-module #f))
thunk
(lambda ()
(set! inner-module (current-module))
(set-current-module outer-module)
(set! outer-module #f)))))
;;; {MODULE-REF -- exported}
;;;
;; Returns the value of a variable called NAME in MODULE or any of its
;; used modules. If there is no such variable, then if the optional third
;; argument DEFAULT is present, it is returned; otherwise an error is signaled.
;;
(define (module-ref module name . rest)
(let ((variable (module-variable module name)))
(if (and variable (variable-bound? variable))
(variable-ref variable)
(if (null? rest)
(error "No variable named" name 'in module)
(car rest) ; default value
))))
;; MODULE-SET! -- exported
;;
;; Sets the variable called NAME in MODULE (or in a module that MODULE uses)
;; to VALUE; if there is no such variable, an error is signaled.
;;
(define (module-set! module name value)
(let ((variable (module-variable module name)))
(if variable
(variable-set! variable value)
(error "No variable named" name 'in module))))
;; MODULE-DEFINE! -- exported
;;
;; Sets the variable called NAME in MODULE to VALUE; if there is no such
;; variable, it is added first.
;;
(define (module-define! module name value)
(let ((variable (module-local-variable module name)))
(if variable
(begin
(variable-set! variable value)
(module-modified module))
(let ((variable (make-variable value)))
(module-add! module name variable)))))
;; MODULE-DEFINED? -- exported
;;
;; Return #t iff NAME is defined in MODULE (or in a module that MODULE
;; uses)
;;
(define (module-defined? module name)
(let ((variable (module-variable module name)))
(and variable (variable-bound? variable))))
;; MODULE-USE! module interface
;;
;; Add INTERFACE to the list of interfaces used by MODULE.
;;
(define (module-use! module interface)
(if (not (or (eq? module interface)
(memq interface (module-uses module))))
(begin
;; Newly used modules must be appended rather than consed, so that
;; `module-variable' traverses the use list starting from the first
;; used module.
(set-module-uses! module (append (module-uses module)
(list interface)))
(hash-clear! (module-import-obarray module))
(module-modified module))))
;; MODULE-USE-INTERFACES! module interfaces
;;
;; Same as MODULE-USE!, but only notifies module observers after all
;; interfaces are added to the inports list.
;;
(define (module-use-interfaces! module interfaces)
(let* ((cur (module-uses module))
(new (let lp ((in interfaces) (out '()))
(if (null? in)
(reverse out)
(lp (cdr in)
(let ((iface (car in)))
(if (or (memq iface cur) (memq iface out))
out
(cons iface out))))))))
(set-module-uses! module (append cur new))
(hash-clear! (module-import-obarray module))
(module-modified module)))
;;; {Recursive Namespaces}
;;;
;;; A hierarchical namespace emerges if we consider some module to be
;;; root, and submodules of that module to be nested namespaces.
;;;
;;; The routines here manage variable names in hierarchical namespace.
;;; Each variable name is a list of elements, looked up in successively nested
;;; modules.
;;;
;;; (nested-ref some-root-module '(foo bar baz))
;;; => <value of a variable named baz in the submodule bar of
;;; the submodule foo of some-root-module>
;;;
;;;
;;; There are:
;;;
;;; ;; a-root is a module
;;; ;; name is a list of symbols
;;;
;;; nested-ref a-root name
;;; nested-set! a-root name val
;;; nested-define! a-root name val
;;; nested-remove! a-root name
;;;
;;; These functions manipulate values in namespaces. For referencing the
;;; namespaces themselves, use the following:
;;;
;;; nested-ref-module a-root name
;;; nested-define-module! a-root name mod
;;;
;;; (current-module) is a natural choice for a root so for convenience there are
;;; also:
;;;
;;; local-ref name == nested-ref (current-module) name
;;; local-set! name val == nested-set! (current-module) name val
;;; local-define name val == nested-define! (current-module) name val
;;; local-remove name == nested-remove! (current-module) name
;;; local-ref-module name == nested-ref-module (current-module) name
;;; local-define-module! name m == nested-define-module! (current-module) name m
;;;
(define (nested-ref root names)
(if (null? names)
root
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-ref cur head #f)
(let ((cur (module-ref-submodule cur head)))
(and cur
(loop cur (car tail) (cdr tail))))))))
(define (nested-set! root names val)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-set! cur head val)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-define! root names val)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-define! cur head val)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-remove! root names)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-remove! cur head)
(let ((cur (module-ref-submodule cur head)))
(if (not cur)
(error "failed to resolve module" names)
(loop cur (car tail) (cdr tail)))))))
(define (nested-ref-module root names)
(let loop ((cur root)
(names names))
(if (null? names)
cur
(let ((cur (module-ref-submodule cur (car names))))
(and cur
(loop cur (cdr names)))))))
(define (nested-define-module! root names module)
(if (null? names)
(error "can't redefine root module" root module)
(let loop ((cur root)
(head (car names))
(tail (cdr names)))
(if (null? tail)
(module-define-submodule! cur head module)
(let ((cur (or (module-ref-submodule cur head)
(let ((m (make-module 31)))
(set-module-kind! m 'directory)
(set-module-name! m (append (module-name cur)
(list head)))
(module-define-submodule! cur head m)
m))))
(loop cur (car tail) (cdr tail)))))))
(define (local-ref names)
(nested-ref (current-module) names))
(define (local-set! names val)
(nested-set! (current-module) names val))
(define (local-define names val)
(nested-define! (current-module) names val))
(define (local-remove names)
(nested-remove! (current-module) names))
(define (local-ref-module names)
(nested-ref-module (current-module) names))
(define (local-define-module names mod)
(nested-define-module! (current-module) names mod))
;;; {The (guile) module}
;;;
;;; The standard module, which has the core Guile bindings. Also called the
;;; "root module", as it is imported by many other modules, but it is not
;;; necessarily the root of anything; and indeed, the module named '() might be
;;; better thought of as a root.
;;;
;; The root module uses the pre-modules-obarray as its obarray. This
;; special obarray accumulates all bindings that have been established
;; before the module system is fully booted.
;;
;; (The obarray continues to be used by code that has been closed over
;; before the module system has been booted.)
;;
(define the-root-module
(let ((m (make-module 0)))
(set-module-obarray! m (%get-pre-modules-obarray))
(set-module-name! m '(guile))
;; Inherit next-unique-id from preliminary stub of
;; %module-get-next-unique-id! defined above.
(set-module-next-unique-id! m (module-generate-unique-id! #f))
m))
;; The root interface is a module that uses the same obarray as the
;; root module. It does not allow new definitions, tho.
;;
(define the-scm-module
(let ((m (make-module 0)))
(set-module-obarray! m (%get-pre-modules-obarray))
(set-module-name! m '(guile))
(set-module-kind! m 'interface)
;; In Guile 1.8 and earlier M was its own public interface.
(set-module-public-interface! m m)
m))
(set-module-public-interface! the-root-module the-scm-module)
;; Now that we have a root module, even though modules aren't fully booted,
;; expand the definition of resolve-module.
;;
(define (resolve-module name . args)
(if (equal? name '(guile))
the-root-module
(error "unexpected module to resolve during module boot" name)))
(define (module-generate-unique-id! m)
(let ((i (module-next-unique-id m)))
(set-module-next-unique-id! m (+ i 1))
i))
;; Cheat. These bindings are needed by modules.c, but we don't want
;; to move their real definition here because that would be unnatural.
;;
(define define-module* #f)
(define process-use-modules #f)
(define module-export! #f)
(define default-duplicate-binding-procedures #f)
;; This boots the module system. All bindings needed by modules.c
;; must have been defined by now.
;;
(set-current-module the-root-module)
;; Now that modules are booted, give module-name its final definition.
;;
(define module-name
(let ((accessor (record-accessor module-type 'name)))
(lambda (mod)
(or (accessor mod)
(let ((name (list (gensym))))
;; Name MOD and bind it in the module root so that it's visible to
;; `resolve-module'. This is important as `psyntax' stores module
;; names and relies on being able to `resolve-module' them.
(set-module-name! mod name)
(nested-define-module! (resolve-module '() #f) name mod)
(accessor mod))))))
(define* (module-gensym #\optional (id " mg") (m (current-module)))
"Return a fresh symbol in the context of module M, based on ID (a
string or symbol). As long as M is a valid module, this procedure is
deterministic."
(define (->string number)
(number->string number 16))
(if m
(string->symbol
(string-append id "-"
(->string (hash (module-name m) most-positive-fixnum))
"-"
(->string (module-generate-unique-id! m))))
(gensym id)))
(define (make-modules-in module name)
(or (nested-ref-module module name)
(let ((m (make-module 31)))
(set-module-kind! m 'directory)
(set-module-name! m (append (module-name module) name))
(nested-define-module! module name m)
m)))
(define (beautify-user-module! module)
(let ((interface (module-public-interface module)))
(if (or (not interface)
(eq? interface module))
(let ((interface (make-module 31)))
(set-module-name! interface (module-name module))
(set-module-version! interface (module-version module))
(set-module-kind! interface 'interface)
(set-module-public-interface! module interface))))
(if (and (not (memq the-scm-module (module-uses module)))
(not (eq? module the-root-module)))
;; Import the default set of bindings (from the SCM module) in MODULE.
(module-use! module the-scm-module)))
(define (version-matches? version-ref target)
(define (sub-versions-match? v-refs t)
(define (sub-version-matches? v-ref t)
(let ((matches? (lambda (v) (sub-version-matches? v t))))
(cond
((number? v-ref) (eqv? v-ref t))
((list? v-ref)
(case (car v-ref)
((>=) (>= t (cadr v-ref)))
((<=) (<= t (cadr v-ref)))
((and) (and-map matches? (cdr v-ref)))
((or) (or-map matches? (cdr v-ref)))
((not) (not (matches? (cadr v-ref))))
(else (error "Invalid sub-version reference" v-ref))))
(else (error "Invalid sub-version reference" v-ref)))))
(or (null? v-refs)
(and (not (null? t))
(sub-version-matches? (car v-refs) (car t))
(sub-versions-match? (cdr v-refs) (cdr t)))))
(let ((matches? (lambda (v) (version-matches? v target))))
(or (null? version-ref)
(case (car version-ref)
((and) (and-map matches? (cdr version-ref)))
((or) (or-map matches? (cdr version-ref)))
((not) (not (matches? (cadr version-ref))))
(else (sub-versions-match? version-ref target))))))
(define (make-fresh-user-module)
(let ((m (make-module)))
(beautify-user-module! m)
m))
;; NOTE: This binding is used in libguile/modules.c.
;;
(define resolve-module
(let ((root (make-module)))
(set-module-name! root '())
;; Define the-root-module as '(guile).
(module-define-submodule! root 'guile the-root-module)
(lambda* (name #\optional (autoload #t) (version #f) #\key (ensure #t))
(let ((already (nested-ref-module root name)))
(cond
((and already
(or (not autoload) (module-public-interface already)))
;; A hit, a palpable hit.
(if (and version
(not (version-matches? version (module-version already))))
(error "incompatible module version already loaded" name))
already)
(autoload
;; Try to autoload the module, and recurse.
(try-load-module name version)
(resolve-module name #f #\ensure ensure))
(else
;; No module found (or if one was, it had no public interface), and
;; we're not autoloading. Make an empty module if #\ensure is true.
(or already
(and ensure
(make-modules-in root name)))))))))
(define (try-load-module name version)
(try-module-autoload name version))
(define (reload-module m)
"Revisit the source file corresponding to the module @var{m}."
(let ((f (module-filename m)))
(if f
(save-module-excursion
(lambda ()
;; Re-set the initial environment, as in try-module-autoload.
(set-current-module (make-fresh-user-module))
(primitive-load-path f)
m))
;; Though we could guess, we *should* know it.
(error "unknown file name for module" m))))
(define (purify-module! module)
"Removes bindings in MODULE which are inherited from the (guile) module."
(let ((use-list (module-uses module)))
(if (and (pair? use-list)
(eq? (car (last-pair use-list)) the-scm-module))
(set-module-uses! module (reverse (cdr (reverse use-list)))))))
;; Return a module that is an interface to the module designated by
;; NAME.
;;
;; `resolve-interface' takes four keyword arguments:
;;
;; #\select SELECTION
;;
;; SELECTION is a list of binding-specs to be imported; A binding-spec
;; is either a symbol or a pair of symbols (ORIG . SEEN), where ORIG
;; is the name in the used module and SEEN is the name in the using
;; module. Note that SEEN is also passed through RENAMER, below. The
;; default is to select all bindings. If you specify no selection but
;; a renamer, only the bindings that already exist in the used module
;; are made available in the interface. Bindings that are added later
;; are not picked up.
;;
;; #\hide BINDINGS
;;
;; BINDINGS is a list of bindings which should not be imported.
;;
;; #\prefix PREFIX
;;
;; PREFIX is a symbol that will be appended to each exported name.
;; The default is to not perform any renaming.
;;
;; #\renamer RENAMER
;;
;; RENAMER is a procedure that takes a symbol and returns its new
;; name. The default is not perform any renaming.
;;
;; Signal "no code for module" error if module name is not resolvable
;; or its public interface is not available. Signal "no binding"
;; error if selected binding does not exist in the used module.
;;
(define* (resolve-interface name #\key
(select #f)
(hide '())
(prefix #f)
(renamer (if prefix
(symbol-prefix-proc prefix)
identity))
version)
(let* ((module (resolve-module name #t version #\ensure #f))
(public-i (and module (module-public-interface module))))
(unless public-i
(error "no code for module" name))
(if (and (not select) (null? hide) (eq? renamer identity))
public-i
(let ((selection (or select (module-map (lambda (sym var) sym)
public-i)))
(custom-i (make-module 31)))
(set-module-kind! custom-i 'custom-interface)
(set-module-name! custom-i name)
;; XXX - should use a lazy binder so that changes to the
;; used module are picked up automatically.
(for-each (lambda (bspec)
(let* ((direct? (symbol? bspec))
(orig (if direct? bspec (car bspec)))
(seen (if direct? bspec (cdr bspec)))
(var (or (module-local-variable public-i orig)
(module-local-variable module orig)
(error
;; fixme: format manually for now
(simple-format
#f "no binding `~A' in module ~A"
orig name)))))
(if (memq orig hide)
(set! hide (delq! orig hide))
(module-add! custom-i
(renamer seen)
var))))
selection)
;; Check that we are not hiding bindings which don't exist
(for-each (lambda (binding)
(if (not (module-local-variable public-i binding))
(error
(simple-format
#f "no binding `~A' to hide in module ~A"
binding name))))
hide)
custom-i))))
(define (symbol-prefix-proc prefix)
(lambda (symbol)
(symbol-append prefix symbol)))
;; This function is called from "modules.c". If you change it, be
;; sure to update "modules.c" as well.
(define* (define-module* name
#\key filename pure version (duplicates '())
(imports '()) (exports '()) (replacements '())
(re-exports '()) (autoloads '()) transformer)
(define (list-of pred l)
(or (null? l)
(and (pair? l) (pred (car l)) (list-of pred (cdr l)))))
(define (valid-export? x)
(or (symbol? x) (and (pair? x) (symbol? (car x)) (symbol? (cdr x)))))
(define (valid-autoload? x)
(and (pair? x) (list-of symbol? (car x)) (list-of symbol? (cdr x))))
(define (resolve-imports imports)
(define (resolve-import import-spec)
(if (list? import-spec)
(apply resolve-interface import-spec)
(error "unexpected use-module specification" import-spec)))
(let lp ((imports imports) (out '()))
(cond
((null? imports) (reverse! out))
((pair? imports)
(lp (cdr imports)
(cons (resolve-import (car imports)) out)))
(else (error "unexpected tail of imports list" imports)))))
;; We could add a #\no-check arg, set by the define-module macro, if
;; these checks are taking too much time.
;;
(let ((module (resolve-module name #f)))
(beautify-user-module! module)
(if filename
(set-module-filename! module filename))
(if pure
(purify-module! module))
(if version
(begin
(if (not (list-of integer? version))
(error "expected list of integers for version"))
(set-module-version! module version)
(set-module-version! (module-public-interface module) version)))
(let ((imports (resolve-imports imports)))
(call-with-deferred-observers
(lambda ()
(if (pair? imports)
(module-use-interfaces! module imports))
(if (list-of valid-export? exports)
(if (pair? exports)
(module-export! module exports))
(error "expected exports to be a list of symbols or symbol pairs"))
(if (list-of valid-export? replacements)
(if (pair? replacements)
(module-replace! module replacements))
(error "expected replacements to be a list of symbols or symbol pairs"))
(if (list-of valid-export? re-exports)
(if (pair? re-exports)
(module-re-export! module re-exports))
(error "expected re-exports to be a list of symbols or symbol pairs"))
;; FIXME
(if (not (null? autoloads))
(apply module-autoload! module autoloads))
;; Wait until modules have been loaded to resolve duplicates
;; handlers.
(if (pair? duplicates)
(let ((handlers (lookup-duplicates-handlers duplicates)))
(set-module-duplicates-handlers! module handlers))))))
(if transformer
(if (and (pair? transformer) (list-of symbol? transformer))
(let ((iface (resolve-interface transformer))
(sym (car (last-pair transformer))))
(set-module-transformer! module (module-ref iface sym)))
(error "expected transformer to be a module name" transformer)))
(run-hook module-defined-hook module)
module))
;; `module-defined-hook' is a hook that is run whenever a new module
;; is defined. Its members are called with one argument, the new
;; module.
(define module-defined-hook (make-hook 1))
;;; {Autoload}
;;;
(define (make-autoload-interface module name bindings)
(let ((b (lambda (a sym definep)
(false-if-exception
(and (memq sym bindings)
(let ((i (module-public-interface (resolve-module name))))
(if (not i)
(error "missing interface for module" name))
(let ((autoload (memq a (module-uses module))))
;; Replace autoload-interface with actual interface if
;; that has not happened yet.
(if (pair? autoload)
(set-car! autoload i)))
(module-local-variable i sym)))
#\warning "Failed to autoload ~a in ~a:\n" sym name))))
(module-constructor (make-hash-table 0) '() b #f #f name 'autoload #f
(make-hash-table 0) '() (make-weak-value-hash-table 31) #f
(make-hash-table 0) #f #f #f 0)))
(define (module-autoload! module . args)
"Have @var{module} automatically load the module named @var{name} when one
of the symbols listed in @var{bindings} is looked up. @var{args} should be a
list of module-name/binding-list pairs, e.g., as in @code{(module-autoload!
module '(ice-9 q) '(make-q q-length))}."
(let loop ((args args))
(cond ((null? args)
#t)
((null? (cdr args))
(error "invalid name+binding autoload list" args))
(else
(let ((name (car args))
(bindings (cadr args)))
(module-use! module (make-autoload-interface module
name bindings))
(loop (cddr args)))))))
;;; {Autoloading modules}
;;;
;;; XXX FIXME autoloads-in-progress and autoloads-done
;;; are not handled in a thread-safe way.
(define autoloads-in-progress '())
;; This function is called from scm_load_scheme_module in
;; "deprecated.c". Please do not change its interface.
;;
(define* (try-module-autoload module-name #\optional version)
"Try to load a module of the given name. If it is not found, return
#f. Otherwise return #t. May raise an exception if a file is found,
but it fails to load."
(let* ((reverse-name (reverse module-name))
(name (symbol->string (car reverse-name)))
(dir-hint-module-name (reverse (cdr reverse-name)))
(dir-hint (apply string-append
(map (lambda (elt)
(string-append (symbol->string elt)
file-name-separator-string))
dir-hint-module-name))))
(resolve-module dir-hint-module-name #f)
(and (not (autoload-done-or-in-progress? dir-hint name))
(let ((didit #f))
(dynamic-wind
(lambda () (autoload-in-progress! dir-hint name))
(lambda ()
(with-fluids ((current-reader #f))
(save-module-excursion
(lambda ()
(define (call/ec proc)
(let ((tag (make-prompt-tag)))
(call-with-prompt
tag
(lambda ()
(proc (lambda () (abort-to-prompt tag))))
(lambda (k) (values)))))
;; The initial environment when loading a module is a fresh
;; user module.
(set-current-module (make-fresh-user-module))
;; Here we could allow some other search strategy (other than
;; primitive-load-path), for example using versions encoded
;; into the file system -- but then we would have to figure
;; out how to locate the compiled file, do auto-compilation,
;; etc. Punt for now, and don't use versions when locating
;; the file.
(call/ec
(lambda (abort)
(primitive-load-path (in-vicinity dir-hint name)
abort)
(set! didit #t)))))))
(lambda () (set-autoloaded! dir-hint name didit)))
didit))))
;;; {Dynamic linking of modules}
;;;
(define autoloads-done '((guile . guile)))
(define (autoload-done-or-in-progress? p m)
(let ((n (cons p m)))
(->bool (or (member n autoloads-done)
(member n autoloads-in-progress)))))
(define (autoload-done! p m)
(let ((n (cons p m)))
(set! autoloads-in-progress
(delete! n autoloads-in-progress))
(or (member n autoloads-done)
(set! autoloads-done (cons n autoloads-done)))))
(define (autoload-in-progress! p m)
(let ((n (cons p m)))
(set! autoloads-done
(delete! n autoloads-done))
(set! autoloads-in-progress (cons n autoloads-in-progress))))
(define (set-autoloaded! p m done?)
(if done?
(autoload-done! p m)
(let ((n (cons p m)))
(set! autoloads-done (delete! n autoloads-done))
(set! autoloads-in-progress (delete! n autoloads-in-progress)))))
;;; {Run-time options}
;;;
(define-syntax define-option-interface
(syntax-rules ()
((_ (interface (options enable disable) (option-set!)))
(begin
(define options
(case-lambda
(() (interface))
((arg)
(if (list? arg)
(begin (interface arg) (interface))
(for-each
(lambda (option)
(apply (lambda (name value documentation)
(display name)
(let ((len (string-length (symbol->string name))))
(when (< len 16)
(display #\tab)
(when (< len 8)
(display #\tab))))
(display #\tab)
(display value)
(display #\tab)
(display documentation)
(newline))
option))
(interface #t))))))
(define (enable . flags)
(interface (append flags (interface)))
(interface))
(define (disable . flags)
(let ((options (interface)))
(for-each (lambda (flag) (set! options (delq! flag options)))
flags)
(interface options)
(interface)))
(define-syntax-rule (option-set! opt val)
(eval-when (expand load eval)
(options (append (options) (list 'opt val)))))))))
(define-option-interface
(debug-options-interface
(debug-options debug-enable debug-disable)
(debug-set!)))
(define-option-interface
(read-options-interface
(read-options read-enable read-disable)
(read-set!)))
(define-option-interface
(print-options-interface
(print-options print-enable print-disable)
(print-set!)))
;;; {The Unspecified Value}
;;;
;;; Currently Guile represents unspecified values via one particular value,
;;; which may be obtained by evaluating (if #f #f). It would be nice in the
;;; future if we could replace this with a return of 0 values, though.
;;;
(define-syntax *unspecified*
(identifier-syntax (if #f #f)))
(define (unspecified? v) (eq? v *unspecified*))
;;; {Parameters}
;;;
(define <parameter>
;; Three fields: the procedure itself, the fluid, and the converter.
(make-struct <applicable-struct-vtable> 0 'pwprpr))
(set-struct-vtable-name! <parameter> '<parameter>)
(define* (make-parameter init #\optional (conv (lambda (x) x)))
"Make a new parameter.
A parameter is a dynamically bound value, accessed through a procedure.
To access the current value, apply the procedure with no arguments:
(define p (make-parameter 10))
(p) => 10
To provide a new value for the parameter in a dynamic extent, use
`parameterize':
(parameterize ((p 20))
(p)) => 20
(p) => 10
The value outside of the dynamic extent of the body is unaffected. To
update the current value, apply it to one argument:
(p 20) => 10
(p) => 20
As you can see, the call that updates a parameter returns its previous
value.
All values for the parameter are first run through the CONV procedure,
including INIT, the initial value. The default CONV procedure is the
identity procedure. CONV is commonly used to ensure some set of
invariants on the values that a parameter may have."
(let ((fluid (make-fluid (conv init))))
(make-struct <parameter> 0
(case-lambda
(() (fluid-ref fluid))
((x) (let ((prev (fluid-ref fluid)))
(fluid-set! fluid (conv x))
prev)))
fluid conv)))
(define* (fluid->parameter fluid #\optional (conv (lambda (x) x)))
"Make a parameter that wraps a fluid.
The value of the parameter will be the same as the value of the fluid.
If the parameter is rebound in some dynamic extent, perhaps via
`parameterize', the new value will be run through the optional CONV
procedure, as with any parameter. Note that unlike `make-parameter',
CONV is not applied to the initial value."
(make-struct <parameter> 0
(case-lambda
(() (fluid-ref fluid))
((x) (let ((prev (fluid-ref fluid)))
(fluid-set! fluid (conv x))
prev)))
fluid conv))
(define (parameter? x)
(and (struct? x) (eq? (struct-vtable x) <parameter>)))
(define (parameter-fluid p)
(if (parameter? p)
(struct-ref p 1)
(scm-error 'wrong-type-arg "parameter-fluid"
"Not a parameter: ~S" (list p) #f)))
(define (parameter-converter p)
(if (parameter? p)
(struct-ref p 2)
(scm-error 'wrong-type-arg "parameter-fluid"
"Not a parameter: ~S" (list p) #f)))
(define-syntax parameterize
(lambda (x)
(syntax-case x ()
((_ ((param value) ...) body body* ...)
(with-syntax (((p ...) (generate-temporaries #'(param ...))))
#'(let ((p param) ...)
(if (not (parameter? p))
(scm-error 'wrong-type-arg "parameterize"
"Not a parameter: ~S" (list p) #f))
...
(with-fluids (((struct-ref p 1) ((struct-ref p 2) value))
...)
body body* ...)))))))
;;;
;;; Current ports as parameters.
;;;
(let ()
(define-syntax-rule (port-parameterize! binding fluid predicate msg)
(begin
(set! binding (fluid->parameter (module-ref (current-module) 'fluid)
(lambda (x)
(if (predicate x) x
(error msg x)))))
(module-remove! (current-module) 'fluid)))
(port-parameterize! current-input-port %current-input-port-fluid
input-port? "expected an input port")
(port-parameterize! current-output-port %current-output-port-fluid
output-port? "expected an output port")
(port-parameterize! current-error-port %current-error-port-fluid
output-port? "expected an output port")
(port-parameterize! current-warning-port %current-warning-port-fluid
output-port? "expected an output port"))
;;;
;;; Languages.
;;;
;; The language can be a symbolic name or a <language> object from
;; (system base language).
;;
(define current-language (make-parameter 'scheme))
;;; {Running Repls}
;;;
(define *repl-stack* (make-fluid '()))
;; Programs can call `batch-mode?' to see if they are running as part of a
;; script or if they are running interactively. REPL implementations ensure that
;; `batch-mode?' returns #f during their extent.
;;
(define (batch-mode?)
(null? (fluid-ref *repl-stack*)))
;; Programs can re-enter batch mode, for example after a fork, by calling
;; `ensure-batch-mode!'. It's not a great interface, though; it would be better
;; to abort to the outermost prompt, and call a thunk there.
;;
(define (ensure-batch-mode!)
(set! batch-mode? (lambda () #t)))
(define (quit . args)
(apply throw 'quit args))
(define exit quit)
(define (gc-run-time)
(cdr (assq 'gc-time-taken (gc-stats))))
(define abort-hook (make-hook))
(define before-error-hook (make-hook))
(define after-error-hook (make-hook))
(define before-backtrace-hook (make-hook))
(define after-backtrace-hook (make-hook))
(define before-read-hook (make-hook))
(define after-read-hook (make-hook))
(define before-eval-hook (make-hook 1))
(define after-eval-hook (make-hook 1))
(define before-print-hook (make-hook 1))
(define after-print-hook (make-hook 1))
;;; This hook is run at the very end of an interactive session.
;;;
(define exit-hook (make-hook))
;;; The default repl-reader function. We may override this if we've
;;; the readline library.
(define repl-reader
(lambda* (prompt #\optional (reader (fluid-ref current-reader)))
(if (not (char-ready?))
(begin
(display (if (string? prompt) prompt (prompt)))
;; An interesting situation. The printer resets the column to
;; 0 by printing a newline, but we then advance it by printing
;; the prompt. However the port-column of the output port
;; does not typically correspond with the actual column on the
;; screen, because the input is echoed back! Since the
;; input is line-buffered and thus ends with a newline, the
;; output will really start on column zero. So, here we zero
;; it out. See bug 9664.
;;
;; Note that for similar reasons, the output-line will not
;; reflect the actual line on the screen. But given the
;; possibility of multiline input, the fix is not as
;; straightforward, so we don't bother.
;;
;; Also note that the readline implementation papers over
;; these concerns, because it's readline itself printing the
;; prompt, and not Guile.
(set-port-column! (current-output-port) 0)))
(force-output)
(run-hook before-read-hook)
((or reader read) (current-input-port))))
;;; {IOTA functions: generating lists of numbers}
;;;
(define (iota n)
(let loop ((count (1- n)) (result '()))
(if (< count 0) result
(loop (1- count) (cons count result)))))
;;; {While}
;;;
;;; with `continue' and `break'.
;;;
;; The inliner will remove the prompts at compile-time if it finds that
;; `continue' or `break' are not used.
;;
(define-syntax while
(lambda (x)
(syntax-case x ()
((while cond body ...)
#`(let ((break-tag (make-prompt-tag "break"))
(continue-tag (make-prompt-tag "continue")))
(call-with-prompt
break-tag
(lambda ()
(define-syntax #,(datum->syntax #'while 'break)
(lambda (x)
(syntax-case x ()
((_ arg (... ...))
#'(abort-to-prompt break-tag arg (... ...)))
(_
#'(lambda args
(apply abort-to-prompt break-tag args))))))
(let lp ()
(call-with-prompt
continue-tag
(lambda ()
(define-syntax #,(datum->syntax #'while 'continue)
(lambda (x)
(syntax-case x ()
((_)
#'(abort-to-prompt continue-tag))
((_ . args)
(syntax-violation 'continue "too many arguments" x))
(_
#'(lambda ()
(abort-to-prompt continue-tag))))))
(do () ((not cond) #f) body ...))
(lambda (k) (lp)))))
(lambda (k . args)
(if (null? args)
#t
(apply values args)))))))))
;;; {Module System Macros}
;;;
;; Return a list of expressions that evaluate to the appropriate
;; arguments for resolve-interface according to SPEC.
(eval-when (expand)
(if (memq 'prefix (read-options))
(error "boot-9 must be compiled with #:kw, not :kw")))
(define (keyword-like-symbol->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define-syntax define-module
(lambda (x)
(define (keyword-like? stx)
(let ((dat (syntax->datum stx)))
(and (symbol? dat)
(eqv? (string-ref (symbol->string dat) 0) #\:))))
(define (->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define (parse-iface args)
(let loop ((in args) (out '()))
(syntax-case in ()
(() (reverse! out))
;; The user wanted #\foo, but wrote :foo. Fix it.
((sym . in) (keyword-like? #'sym)
(loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
((kw . in) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#\renamer renamer . in)
(loop #'in (cons* #',renamer #\renamer out)))
((kw val . in)
(loop #'in (cons* #'val #'kw out))))))
(define (parse args imp exp rex rep aut)
;; Just quote everything except #\use-module and #\use-syntax. We
;; need to know about all arguments regardless since we want to turn
;; symbols that look like keywords into real keywords, and the
;; keyword args in a define-module form are not regular
;; (i.e. no-backtrace doesn't take a value).
(syntax-case args ()
(()
(let ((imp (if (null? imp) '() #`(#\imports `#,imp)))
(exp (if (null? exp) '() #`(#\exports '#,exp)))
(rex (if (null? rex) '() #`(#\re-exports '#,rex)))
(rep (if (null? rep) '() #`(#\replacements '#,rep)))
(aut (if (null? aut) '() #`(#\autoloads '#,aut))))
#`(#,@imp #,@exp #,@rex #,@rep #,@aut)))
;; The user wanted #\foo, but wrote :foo. Fix it.
((sym . args) (keyword-like? #'sym)
(parse #`(#,(->keyword (syntax->datum #'sym)) . args)
imp exp rex rep aut))
((kw . args) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#\no-backtrace . args)
;; Ignore this one.
(parse #'args imp exp rex rep aut))
((#\pure . args)
#`(#\pure #t . #,(parse #'args imp exp rex rep aut)))
((kw)
(syntax-violation 'define-module "keyword arg without value" x #'kw))
((#\version (v ...) . args)
#`(#\version '(v ...) . #,(parse #'args imp exp rex rep aut)))
((#\duplicates (d ...) . args)
#`(#\duplicates '(d ...) . #,(parse #'args imp exp rex rep aut)))
((#\filename f . args)
#`(#\filename 'f . #,(parse #'args imp exp rex rep aut)))
((#\use-module (name name* ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut))
((#\use-syntax (name name* ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
#`(#\transformer '(name name* ...)
. #,(parse #'args #`(#,@imp ((name name* ...))) exp rex rep aut)))
((#\use-module ((name name* ...) arg ...) . args)
(and (and-map symbol? (syntax->datum #'(name name* ...))))
(parse #'args
#`(#,@imp ((name name* ...) #,@(parse-iface #'(arg ...))))
exp rex rep aut))
((#\export (ex ...) . args)
(parse #'args imp #`(#,@exp ex ...) rex rep aut))
((#\export-syntax (ex ...) . args)
(parse #'args imp #`(#,@exp ex ...) rex rep aut))
((#\re-export (re ...) . args)
(parse #'args imp exp #`(#,@rex re ...) rep aut))
((#\re-export-syntax (re ...) . args)
(parse #'args imp exp #`(#,@rex re ...) rep aut))
((#\replace (r ...) . args)
(parse #'args imp exp rex #`(#,@rep r ...) aut))
((#\replace-syntax (r ...) . args)
(parse #'args imp exp rex #`(#,@rep r ...) aut))
((#\autoload name bindings . args)
(parse #'args imp exp rex rep #`(#,@aut name bindings)))
((kw val . args)
(syntax-violation 'define-module "unknown keyword or bad argument"
#'kw #'val))))
(syntax-case x ()
((_ (name name* ...) arg ...)
(and-map symbol? (syntax->datum #'(name name* ...)))
(with-syntax (((quoted-arg ...)
(parse #'(arg ...) '() '() '() '() '()))
;; Ideally the filename is either a string or #f;
;; this hack is to work around a case in which
;; port-filename returns a symbol (`socket') for
;; sockets.
(filename (let ((f (assq-ref (or (syntax-source x) '())
'filename)))
(and (string? f) f))))
#'(eval-when (expand load eval)
(let ((m (define-module* '(name name* ...)
#\filename filename quoted-arg ...)))
(set-current-module m)
m)))))))
;; The guts of the use-modules macro. Add the interfaces of the named
;; modules to the use-list of the current module, in order.
;; This function is called by "modules.c". If you change it, be sure
;; to change scm_c_use_module as well.
(define (process-use-modules module-interface-args)
(let ((interfaces (map (lambda (mif-args)
(or (apply resolve-interface mif-args)
(error "no such module" mif-args)))
module-interface-args)))
(call-with-deferred-observers
(lambda ()
(module-use-interfaces! (current-module) interfaces)))))
(define-syntax use-modules
(lambda (x)
(define (keyword-like? stx)
(let ((dat (syntax->datum stx)))
(and (symbol? dat)
(eqv? (string-ref (symbol->string dat) 0) #\:))))
(define (->keyword sym)
(symbol->keyword (string->symbol (substring (symbol->string sym) 1))))
(define (quotify-iface args)
(let loop ((in args) (out '()))
(syntax-case in ()
(() (reverse! out))
;; The user wanted #\foo, but wrote :foo. Fix it.
((sym . in) (keyword-like? #'sym)
(loop #`(#,(->keyword (syntax->datum #'sym)) . in) out))
((kw . in) (not (keyword? (syntax->datum #'kw)))
(syntax-violation 'define-module "expected keyword arg" x #'kw))
((#\renamer renamer . in)
(loop #'in (cons* #'renamer #\renamer out)))
((kw val . in)
(loop #'in (cons* #''val #'kw out))))))
(define (quotify specs)
(let lp ((in specs) (out '()))
(syntax-case in ()
(() (reverse out))
(((name name* ...) . in)
(and-map symbol? (syntax->datum #'(name name* ...)))
(lp #'in (cons #''((name name* ...)) out)))
((((name name* ...) arg ...) . in)
(and-map symbol? (syntax->datum #'(name name* ...)))
(with-syntax (((quoted-arg ...) (quotify-iface #'(arg ...))))
(lp #'in (cons #`(list '(name name* ...) quoted-arg ...)
out)))))))
(syntax-case x ()
((_ spec ...)
(with-syntax (((quoted-args ...) (quotify #'(spec ...))))
#'(eval-when (expand load eval)
(process-use-modules (list quoted-args ...))
*unspecified*))))))
(define-syntax-rule (use-syntax spec ...)
(begin
(eval-when (expand load eval)
(issue-deprecation-warning
"`use-syntax' is deprecated. Please contact guile-devel for more info."))
(use-modules spec ...)))
(include-from-path "ice-9/r6rs-libraries")
(define-syntax-rule (define-private foo bar)
(define foo bar))
(define-syntax define-public
(syntax-rules ()
((_ (name . args) . body)
(begin
(define (name . args) . body)
(export name)))
((_ name val)
(begin
(define name val)
(export name)))))
(define-syntax-rule (defmacro-public name args body ...)
(begin
(defmacro name args body ...)
(export-syntax name)))
;; And now for the most important macro.
(define-syntax-rule (lumbum formals body ...)
(lambda formals body ...))
;; Export a local variable
;; This function is called from "modules.c". If you change it, be
;; sure to update "modules.c" as well.
(define (module-export! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-ensure-local-variable! m internal-name)))
(module-add! public-i external-name var)))
names)))
(define (module-replace! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-ensure-local-variable! m internal-name)))
;; FIXME: use a bit on variables instead of object
;; properties.
(set-object-property! var 'replace #t)
(module-add! public-i external-name var)))
names)))
;; Export all local variables from a module
;;
(define (module-export-all! mod)
(define (fresh-interface!)
(let ((iface (make-module)))
(set-module-name! iface (module-name mod))
(set-module-version! iface (module-version mod))
(set-module-kind! iface 'interface)
(set-module-public-interface! mod iface)
iface))
(let ((iface (or (module-public-interface mod)
(fresh-interface!))))
(set-module-obarray! iface (module-obarray mod))))
;; Re-export a imported variable
;;
(define (module-re-export! m names)
(let ((public-i (module-public-interface m)))
(for-each (lambda (name)
(let* ((internal-name (if (pair? name) (car name) name))
(external-name (if (pair? name) (cdr name) name))
(var (module-variable m internal-name)))
(cond ((not var)
(error "Undefined variable:" internal-name))
((eq? var (module-local-variable m internal-name))
(error "re-exporting local variable:" internal-name))
(else
(module-add! public-i external-name var)))))
names)))
(define-syntax-rule (export name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-export! (current-module) '(name ...))))))
(define-syntax-rule (re-export name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-re-export! (current-module) '(name ...))))))
(define-syntax-rule (export! name ...)
(eval-when (expand load eval)
(call-with-deferred-observers
(lambda ()
(module-replace! (current-module) '(name ...))))))
(define-syntax-rule (export-syntax name ...)
(export name ...))
(define-syntax-rule (re-export-syntax name ...)
(re-export name ...))
;;; {Parameters}
;;;
(define* (make-mutable-parameter init #\optional (converter identity))
(let ((fluid (make-fluid (converter init))))
(case-lambda
(() (fluid-ref fluid))
((val) (fluid-set! fluid (converter val))))))
;;; {Handling of duplicate imported bindings}
;;;
;; Duplicate handlers take the following arguments:
;;
;; module importing module
;; name conflicting name
;; int1 old interface where name occurs
;; val1 value of binding in old interface
;; int2 new interface where name occurs
;; val2 value of binding in new interface
;; var previous resolution or #f
;; val value of previous resolution
;;
;; A duplicate handler can take three alternative actions:
;;
;; 1. return #f => leave responsibility to next handler
;; 2. exit with an error
;; 3. return a variable resolving the conflict
;;
(define duplicate-handlers
(let ((m (make-module 7)))
(define (check module name int1 val1 int2 val2 var val)
(scm-error 'misc-error
#f
"~A: `~A' imported from both ~A and ~A"
(list (module-name module)
name
(module-name int1)
(module-name int2))
#f))
(define (warn module name int1 val1 int2 val2 var val)
(format (current-warning-port)
"WARNING: ~A: `~A' imported from both ~A and ~A\n"
(module-name module)
name
(module-name int1)
(module-name int2))
#f)
(define (replace module name int1 val1 int2 val2 var val)
(let ((old (or (and var (object-property var 'replace) var)
(module-variable int1 name)))
(new (module-variable int2 name)))
(if (object-property old 'replace)
(and (or (eq? old new)
(not (object-property new 'replace)))
old)
(and (object-property new 'replace)
new))))
(define (warn-override-core module name int1 val1 int2 val2 var val)
(and (eq? int1 the-scm-module)
(begin
(format (current-warning-port)
"WARNING: ~A: imported module ~A overrides core binding `~A'\n"
(module-name module)
(module-name int2)
name)
(module-local-variable int2 name))))
(define (first module name int1 val1 int2 val2 var val)
(or var (module-local-variable int1 name)))
(define (last module name int1 val1 int2 val2 var val)
(module-local-variable int2 name))
(define (noop module name int1 val1 int2 val2 var val)
#f)
(set-module-name! m 'duplicate-handlers)
(set-module-kind! m 'interface)
(module-define! m 'check check)
(module-define! m 'warn warn)
(module-define! m 'replace replace)
(module-define! m 'warn-override-core warn-override-core)
(module-define! m 'first first)
(module-define! m 'last last)
(module-define! m 'merge-generics noop)
(module-define! m 'merge-accessors noop)
m))
(define (lookup-duplicates-handlers handler-names)
(and handler-names
(map (lambda (handler-name)
(or (module-symbol-local-binding
duplicate-handlers handler-name #f)
(error "invalid duplicate handler name:"
handler-name)))
(if (list? handler-names)
handler-names
(list handler-names)))))
(define default-duplicate-binding-procedures
(make-mutable-parameter #f))
(define default-duplicate-binding-handler
(make-mutable-parameter '(replace warn-override-core warn last)
(lambda (handler-names)
(default-duplicate-binding-procedures
(lookup-duplicates-handlers handler-names))
handler-names)))
;;; {`load'.}
;;;
;;; Load is tricky when combined with relative file names, compilation,
;;; and the file system. If a file name is relative, what is it
;;; relative to? The name of the source file at the time it was
;;; compiled? The name of the compiled file? What if both or either
;;; were installed? And how do you get that information? Tricky, I
;;; say.
;;;
;;; To get around all of this, we're going to do something nasty, and
;;; turn `load' into a macro. That way it can know the name of the
;;; source file with respect to which it was invoked, so it can resolve
;;; relative file names with respect to the original source file.
;;;
;;; There is an exception, and that is that if the source file was in
;;; the load path when it was compiled, instead of looking up against
;;; the absolute source location, we load-from-path against the relative
;;; source location.
;;;
(define %auto-compilation-options
;; Default `compile-file' option when auto-compiling.
'(#\warnings (unbound-variable arity-mismatch format
duplicate-case-datum bad-case-datum)))
(define* (load-in-vicinity dir file-name #\optional reader)
"Load source file FILE-NAME in vicinity of directory DIR. Use a
pre-compiled version of FILE-NAME when available, and auto-compile one
when none is available, reading FILE-NAME with READER."
;; The auto-compilation code will residualize a .go file in the cache
;; dir: by default, $HOME/.cache/guile/2.0/ccache/PATH.go. This
;; function determines the PATH to use as a key into the compilation
;; cache.
(define (canonical->suffix canon)
(cond
((and (not (string-null? canon))
(file-name-separator? (string-ref canon 0)))
canon)
((and (eq? (system-file-name-convention) 'windows)
(absolute-file-name? canon))
;; An absolute file name that doesn't start with a separator
;; starts with a drive component. Transform the drive component
;; to a file name element: c:\foo -> \c\foo.
(string-append file-name-separator-string
(substring canon 0 1)
(substring canon 2)))
(else canon)))
(define compiled-extension
;; File name extension of compiled files.
(cond ((or (null? %load-compiled-extensions)
(string-null? (car %load-compiled-extensions)))
(warn "invalid %load-compiled-extensions"
%load-compiled-extensions)
".go")
(else (car %load-compiled-extensions))))
(define (more-recent? stat1 stat2)
;; Return #t when STAT1 has an mtime greater than that of STAT2.
(or (> (stat:mtime stat1) (stat:mtime stat2))
(and (= (stat:mtime stat1) (stat:mtime stat2))
(>= (stat:mtimensec stat1)
(stat:mtimensec stat2)))))
(define (fallback-file-name canon-file-name)
;; Return the in-cache compiled file name for source file
;; CANON-FILE-NAME.
;; FIXME: would probably be better just to append
;; SHA1(canon-file-name) to the %compile-fallback-path, to avoid
;; deep directory stats.
(and %compile-fallback-path
(string-append %compile-fallback-path
(canonical->suffix canon-file-name)
compiled-extension)))
(define (compile file)
;; Compile source FILE, lazily loading the compiler.
((module-ref (resolve-interface '(system base compile))
'compile-file)
file
#\opts %auto-compilation-options
#\env (current-module)))
(define (load-thunk-from-file file)
(let ((objcode (resolve-interface '(system vm objcode)))
(program (resolve-interface '(system vm program))))
((module-ref program 'make-program)
((module-ref objcode 'load-objcode) file))))
;; Returns a thunk loaded from the .go file corresponding to `name'.
;; Does not search load paths, only the fallback path. If the .go
;; file is missing or out of date, and auto-compilation is enabled,
;; will try auto-compilation, just as primitive-load-path does
;; internally. primitive-load is unaffected. Returns #f if
;; auto-compilation failed or was disabled.
;;
;; NB: Unless we need to compile the file, this function should not
;; cause (system base compile) to be loaded up. For that reason
;; compiled-file-name partially duplicates functionality from (system
;; base compile).
(define (fresh-compiled-thunk name scmstat go-file-name)
;; Return GO-FILE-NAME after making sure that it contains a freshly
;; compiled version of source file NAME with stat SCMSTAT; return #f
;; on failure.
(false-if-exception
(let ((gostat (and (not %fresh-auto-compile)
(stat go-file-name #f))))
(if (and gostat (more-recent? gostat scmstat))
(load-thunk-from-file go-file-name)
(begin
(when gostat
(format (current-warning-port)
";;; note: source file ~a\n;;; newer than compiled ~a\n"
name go-file-name))
(cond
(%load-should-auto-compile
(%warn-auto-compilation-enabled)
(format (current-warning-port) ";;; compiling ~a\n" name)
(let ((cfn (compile name)))
(format (current-warning-port) ";;; compiled ~a\n" cfn)
(load-thunk-from-file cfn)))
(else #f)))))
#\warning "WARNING: compilation of ~a failed:\n" name))
(define (sans-extension file)
(let ((dot (string-rindex file #\.)))
(if dot
(substring file 0 dot)
file)))
(define (load-absolute abs-file-name)
;; Load from ABS-FILE-NAME, using a compiled file or auto-compiling
;; if needed.
(define scmstat
(false-if-exception
(stat abs-file-name)
#\warning "Stat of ~a failed:\n" abs-file-name))
(define (pre-compiled)
(or-map
(lambda (dir)
(or-map
(lambda (ext)
(let ((candidate (string-append (in-vicinity dir file-name) ext)))
(let ((gostat (stat candidate #f)))
(and gostat
(more-recent? gostat scmstat)
(false-if-exception
(load-thunk-from-file candidate)
#\warning "WARNING: failed to load compiled file ~a:\n"
candidate)))))
%load-compiled-extensions))
%load-compiled-path))
(define (fallback)
(and=> (false-if-exception (canonicalize-path abs-file-name))
(lambda (canon)
(and=> (fallback-file-name canon)
(lambda (go-file-name)
(fresh-compiled-thunk abs-file-name
scmstat
go-file-name))))))
(let ((compiled (and scmstat (or (pre-compiled) (fallback)))))
(if compiled
(begin
(if %load-hook
(%load-hook abs-file-name))
(compiled))
(start-stack 'load-stack
(primitive-load abs-file-name)))))
(save-module-excursion
(lambda ()
(with-fluids ((current-reader reader)
(%file-port-name-canonicalization 'relative))
(cond
((absolute-file-name? file-name)
(load-absolute file-name))
((absolute-file-name? dir)
(load-absolute (in-vicinity dir file-name)))
(else
(load-from-path (in-vicinity dir file-name))))))))
(define-syntax load
(make-variable-transformer
(lambda (x)
(let* ((src (syntax-source x))
(file (and src (assq-ref src 'filename)))
(dir (and (string? file) (dirname file))))
(syntax-case x ()
((_ arg ...)
#`(load-in-vicinity #,(or dir #'(getcwd)) arg ...))
(id
(identifier? #'id)
#`(lambda args
(apply load-in-vicinity #,(or dir #'(getcwd)) args))))))))
;;; {`cond-expand' for SRFI-0 support.}
;;;
;;; This syntactic form expands into different commands or
;;; definitions, depending on the features provided by the Scheme
;;; implementation.
;;;
;;; Syntax:
;;;
;;; <cond-expand>
;;; --> (cond-expand <cond-expand-clause>+)
;;; | (cond-expand <cond-expand-clause>* (else <command-or-definition>))
;;; <cond-expand-clause>
;;; --> (<feature-requirement> <command-or-definition>*)
;;; <feature-requirement>
;;; --> <feature-identifier>
;;; | (and <feature-requirement>*)
;;; | (or <feature-requirement>*)
;;; | (not <feature-requirement>)
;;; <feature-identifier>
;;; --> <a symbol which is the name or alias of a SRFI>
;;;
;;; Additionally, this implementation provides the
;;; <feature-identifier>s `guile' and `r5rs', so that programs can
;;; determine the implementation type and the supported standard.
;;;
;;; Remember to update the features list when adding more SRFIs.
;;;
(define %cond-expand-features
;; This should contain only features that are present in core Guile,
;; before loading any modules. Modular features are handled by
;; placing 'cond-expand-provide' in the relevant module.
'(guile
guile-2
r5rs
srfi-0 ;; cond-expand itself
srfi-4 ;; homogeneous numeric vectors
;; We omit srfi-6 because the 'open-input-string' etc in Guile
;; core are not conformant with SRFI-6; they expose details
;; of the binary I/O model and may fail to support some characters.
srfi-13 ;; string library
srfi-14 ;; character sets
srfi-16 ;; case-lambda
srfi-23 ;; `error` procedure
srfi-30 ;; nested multi-line comments
srfi-39 ;; parameterize
srfi-46 ;; basic syntax-rules extensions
srfi-55 ;; require-extension
srfi-61 ;; general cond clause
srfi-62 ;; s-expression comments
srfi-87 ;; => in case clauses
srfi-105 ;; curly infix expressions
))
;; This table maps module public interfaces to the list of features.
;;
(define %cond-expand-table (make-hash-table 31))
;; Add one or more features to the `cond-expand' feature list of the
;; module `module'.
;;
(define (cond-expand-provide module features)
(let ((mod (module-public-interface module)))
(and mod
(hashq-set! %cond-expand-table mod
(append (hashq-ref %cond-expand-table mod '())
features)))))
(define-syntax cond-expand
(lambda (x)
(define (module-has-feature? mod sym)
(or-map (lambda (mod)
(memq sym (hashq-ref %cond-expand-table mod '())))
(module-uses mod)))
(define (condition-matches? condition)
(syntax-case condition (and or not)
((and c ...)
(and-map condition-matches? #'(c ...)))
((or c ...)
(or-map condition-matches? #'(c ...)))
((not c)
(if (condition-matches? #'c) #f #t))
(c
(identifier? #'c)
(let ((sym (syntax->datum #'c)))
(if (memq sym %cond-expand-features)
#t
(module-has-feature? (current-module) sym))))))
(define (match clauses alternate)
(syntax-case clauses ()
(((condition form ...) . rest)
(if (condition-matches? #'condition)
#'(begin form ...)
(match #'rest alternate)))
(() (alternate))))
(syntax-case x (else)
((_ clause ... (else form ...))
(match #'(clause ...)
(lambda ()
#'(begin form ...))))
((_ clause ...)
(match #'(clause ...)
(lambda ()
(syntax-violation 'cond-expand "unfulfilled cond-expand" x)))))))
;; This procedure gets called from the startup code with a list of
;; numbers, which are the numbers of the SRFIs to be loaded on startup.
;;
(define (use-srfis srfis)
(process-use-modules
(map (lambda (num)
(list (list 'srfi (string->symbol
(string-append "srfi-" (number->string num))))))
srfis)))
;;; srfi-55: require-extension
;;;
(define-syntax require-extension
(lambda (x)
(syntax-case x (srfi)
((_ (srfi n ...))
(and-map integer? (syntax->datum #'(n ...)))
(with-syntax
(((srfi-n ...)
(map (lambda (n)
(datum->syntax x (symbol-append 'srfi- n)))
(map string->symbol
(map number->string (syntax->datum #'(n ...)))))))
#'(use-modules (srfi srfi-n) ...)))
((_ (type arg ...))
(identifier? #'type)
(syntax-violation 'require-extension "Not a recognized extension type"
x)))))
;;; Defining transparently inlinable procedures
;;;
(define-syntax define-inlinable
;; Define a macro and a procedure such that direct calls are inlined, via
;; the macro expansion, whereas references in non-call contexts refer to
;; the procedure. Inspired by the `define-integrable' macro by Dybvig et al.
(lambda (x)
;; Use a space in the prefix to avoid potential -Wunused-toplevel
;; warning
(define prefix (string->symbol "% "))
(define (make-procedure-name name)
(datum->syntax name
(symbol-append prefix (syntax->datum name)
'-procedure)))
(syntax-case x ()
((_ (name formals ...) body ...)
(identifier? #'name)
(with-syntax ((proc-name (make-procedure-name #'name))
((args ...) (generate-temporaries #'(formals ...))))
#`(begin
(define (proc-name formals ...)
(syntax-parameterize ((name (identifier-syntax proc-name)))
body ...))
(define-syntax-parameter name
(lambda (x)
(syntax-case x ()
((_ args ...)
#'((syntax-parameterize ((name (identifier-syntax proc-name)))
(lambda (formals ...)
body ...))
args ...))
((_ a (... ...))
(syntax-violation 'name "Wrong number of arguments" x))
(_
(identifier? x)
#'proc-name))))))))))
(define using-readline?
(let ((using-readline? (make-fluid)))
(make-procedure-with-setter
(lambda () (fluid-ref using-readline?))
(lambda (v) (fluid-set! using-readline? v)))))
;;; {Deprecated stuff}
;;;
(begin-deprecated
(module-use! the-scm-module (resolve-interface '(ice-9 deprecated))))
;;; SRFI-4 in the default environment. FIXME: we should figure out how
;;; to deprecate this.
;;;
;; FIXME:
(module-use! the-scm-module (resolve-interface '(srfi srfi-4)))
;;; A few identifiers that need to be defined in this file are really
;;; internal implementation details. We shove them off into internal
;;; modules, removing them from the (guile) module.
;;;
(define-module (system syntax))
(let ()
(define (steal-bindings! from to ids)
(for-each
(lambda (sym)
(let ((v (module-local-variable from sym)))
(module-remove! from sym)
(module-add! to sym v)))
ids)
(module-export! to ids))
(steal-bindings! the-root-module (resolve-module '(system syntax))
'(syntax-local-binding
syntax-module
syntax-locally-bound-identifiers
syntax-session-id)))
;;; Place the user in the guile-user module.
;;;
;; Set filename to #f to prevent reload.
(define-module (guile-user)
#\autoload (system base compile) (compile compile-file)
#\filename #f)
;; Remain in the `(guile)' module at compilation-time so that the
;; `-Wunused-toplevel' warning works as expected.
(eval-when (compile) (set-current-module the-root-module))
;;; boot-9.scm ends here
;;;; buffered-input.scm --- construct a port from a buffered input reader
;;;;
;;;; Copyright (C) 2001, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 buffered-input)
#\export (make-buffered-input-port
make-line-buffered-input-port
set-buffered-input-continuation?!))
;; @code{buffered-input-continuation?} is a property of the ports
;; created by @code{make-line-buffered-input-port} that stores the
;; read continuation flag for each such port.
(define buffered-input-continuation? (make-object-property))
(define (set-buffered-input-continuation?! port val)
"Set the read continuation flag for @var{port} to @var{val}.
See @code{make-buffered-input-port} for the meaning and use of this
flag."
(set! (buffered-input-continuation? port) val))
(define (make-buffered-input-port reader)
"Construct a line-buffered input port from the specified @var{reader}.
@var{reader} should be a procedure of one argument that somehow reads
a chunk of input and returns it as a string.
The port created by @code{make-buffered-input-port} does @emph{not}
interpolate any additional characters between the strings returned by
@var{reader}.
@var{reader} should take a boolean @var{continuation?} argument.
@var{continuation?} indicates whether @var{reader} is being called to
start a logically new read operation (in which case
@var{continuation?} is @code{#f}) or to continue a read operation for
which some input has already been read (in which case
@var{continuation?} is @code{#t}). Some @var{reader} implementations
use the @var{continuation?} argument to determine what prompt to
display to the user.
The new/continuation distinction is largely an application-level
concept: @code{set-buffered-input-continuation?!} allows an
application to specify when a read operation is considered to be new.
But note that if there is non-whitespace data already buffered in the
port when a new read operation starts, this data will be read before
the first call to @var{reader}, and so @var{reader} will be called
with @var{continuation?} set to @code{#t}."
(let ((read-string "")
(string-index 0))
(letrec ((get-character
(lambda ()
(if (< string-index (string-length read-string))
;; Read a char.
(let ((res (string-ref read-string string-index)))
(set! string-index (+ 1 string-index))
(if (not (char-whitespace? res))
(set! (buffered-input-continuation? port) #t))
res)
;; Fill the buffer.
(let ((x (reader (buffered-input-continuation? port))))
(cond
((eof-object? x)
;; Don't buffer the EOF object.
x)
(else
(set! read-string x)
(set! string-index 0)
(get-character)))))))
(input-waiting
(lambda ()
(- (string-length read-string) string-index)))
(port #f))
(set! port (make-soft-port (vector #f #f #f get-character #f input-waiting) "r"))
(set! (buffered-input-continuation? port) #f)
port)))
(define (make-line-buffered-input-port reader)
"Construct a line-buffered input port from the specified @var{reader}.
@var{reader} should be a procedure of one argument that somehow reads
a line of input and returns it as a string @emph{without} the
terminating newline character.
The port created by @code{make-line-buffered-input-port} automatically
interpolates a newline character after each string returned by
@var{reader}.
@var{reader} should take a boolean @var{continuation?} argument. For
the meaning and use of this argument, see
@code{make-buffered-input-port}."
(make-buffered-input-port (lambda (continuation?)
(let ((str (reader continuation?)))
(if (eof-object? str)
str
(string-append str "\n"))))))
;;; buffered-input.scm ends here
;;;; calling.scm --- Calling Conventions
;;;;
;;;; Copyright (C) 1995, 1996, 1997, 2000, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 calling)
\:export-syntax (with-excursion-function
with-getter-and-setter
with-getter
with-delegating-getter-and-setter
with-excursion-getter-and-setter
with-configuration-getter-and-setter
with-delegating-configuration-getter-and-setter
let-with-configuration-getter-and-setter))
;;;;
;;;
;;; This file contains a number of macros that support
;;; common calling conventions.
;;;
;;; with-excursion-function <vars> proc
;;; <vars> is an unevaluated list of names that are bound in the caller.
;;; proc is a procedure, called:
;;; (proc excursion)
;;;
;;; excursion is a procedure isolates all changes to <vars>
;;; in the dynamic scope of the call to proc. In other words,
;;; the values of <vars> are saved when proc is entered, and when
;;; proc returns, those values are restored. Values are also restored
;;; entering and leaving the call to proc non-locally, such as using
;;; call-with-current-continuation, error, or throw.
;;;
(defmacro with-excursion-function (vars proc)
`(,proc ,(excursion-function-syntax vars)))
;;; with-getter-and-setter <vars> proc
;;; <vars> is an unevaluated list of names that are bound in the caller.
;;; proc is a procedure, called:
;;; (proc getter setter)
;;;
;;; getter and setter are procedures used to access
;;; or modify <vars>.
;;;
;;; setter, called with keywords arguments, modifies the named
;;; values. If "foo" and "bar" are among <vars>, then:
;;;
;;; (setter :foo 1 :bar 2)
;;; == (set! foo 1 bar 2)
;;;
;;; getter, called with just keywords, returns
;;; a list of the corresponding values. For example,
;;; if "foo" and "bar" are among the <vars>, then
;;;
;;; (getter :foo :bar)
;;; => (<value-of-foo> <value-of-bar>)
;;;
;;; getter, called with no arguments, returns a list of all accepted
;;; keywords and the corresponding values. If "foo" and "bar" are
;;; the *only* <vars>, then:
;;;
;;; (getter)
;;; => (\:foo <value-of-bar> :bar <value-of-foo>)
;;;
;;; The unusual calling sequence of a getter supports too handy
;;; idioms:
;;;
;;; (apply setter (getter)) ;; save and restore
;;;
;;; (apply-to-args (getter :foo :bar) ;; fetch and bind
;;; (lambda (foo bar) ....))
;;;
;;; ;; [ "apply-to-args" is just like two-argument "apply" except that it
;;; ;; takes its arguments in a different order.
;;;
;;;
(defmacro with-getter-and-setter (vars proc)
`(,proc ,@ (getter-and-setter-syntax vars)))
;;; with-getter vars proc
;;; A short-hand for a call to with-getter-and-setter.
;;; The procedure is called:
;;; (proc getter)
;;;
(defmacro with-getter (vars proc)
`(,proc ,(car (getter-and-setter-syntax vars))))
;;; with-delegating-getter-and-setter <vars> get-delegate set-delegate proc
;;; Compose getters and setters.
;;;
;;; <vars> is an unevaluated list of names that are bound in the caller.
;;;
;;; get-delegate is called by the new getter to extend the set of
;;; gettable variables beyond just <vars>
;;; set-delegate is called by the new setter to extend the set of
;;; gettable variables beyond just <vars>
;;;
;;; proc is a procedure that is called
;;; (proc getter setter)
;;;
(defmacro with-delegating-getter-and-setter (vars get-delegate set-delegate proc)
`(,proc ,@ (delegating-getter-and-setter-syntax vars get-delegate set-delegate)))
;;; with-excursion-getter-and-setter <vars> proc
;;; <vars> is an unevaluated list of names that are bound in the caller.
;;; proc is called:
;;;
;;; (proc excursion getter setter)
;;;
;;; See also:
;;; with-getter-and-setter
;;; with-excursion-function
;;;
(defmacro with-excursion-getter-and-setter (vars proc)
`(,proc ,(excursion-function-syntax vars)
,@ (getter-and-setter-syntax vars)))
(define (excursion-function-syntax vars)
(let ((saved-value-names (map gensym vars))
(tmp-var-name (gensym "temp"))
(swap-fn-name (gensym "swap"))
(thunk-name (gensym "thunk")))
`(lambda (,thunk-name)
(letrec ((,tmp-var-name #f)
(,swap-fn-name
(lambda () ,@ (map (lambda (n sn)
`(begin (set! ,tmp-var-name ,n)
(set! ,n ,sn)
(set! ,sn ,tmp-var-name)))
vars saved-value-names)))
,@ (map (lambda (sn n) `(,sn ,n)) saved-value-names vars))
(dynamic-wind
,swap-fn-name
,thunk-name
,swap-fn-name)))))
(define (getter-and-setter-syntax vars)
(let ((args-name (gensym "args"))
(an-arg-name (gensym "an-arg"))
(new-val-name (gensym "new-value"))
(loop-name (gensym "loop"))
(kws (map symbol->keyword vars)))
(list `(lambda ,args-name
(let ,loop-name ((,args-name ,args-name))
(if (null? ,args-name)
,(if (null? kws)
''()
`(let ((all-vals (,loop-name ',kws)))
(let ,loop-name ((vals all-vals)
(kws ',kws))
(if (null? vals)
'()
`(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
(map (lambda (,an-arg-name)
(case ,an-arg-name
,@ (append
(map (lambda (kw v) `((,kw) ,v)) kws vars)
`((else (throw 'bad-get-option ,an-arg-name))))))
,args-name))))
`(lambda ,args-name
(let ,loop-name ((,args-name ,args-name))
(or (null? ,args-name)
(null? (cdr ,args-name))
(let ((,an-arg-name (car ,args-name))
(,new-val-name (cadr ,args-name)))
(case ,an-arg-name
,@ (append
(map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
`((else (throw 'bad-set-option ,an-arg-name)))))
(,loop-name (cddr ,args-name)))))))))
(define (delegating-getter-and-setter-syntax vars get-delegate set-delegate)
(let ((args-name (gensym "args"))
(an-arg-name (gensym "an-arg"))
(new-val-name (gensym "new-value"))
(loop-name (gensym "loop"))
(kws (map symbol->keyword vars)))
(list `(lambda ,args-name
(let ,loop-name ((,args-name ,args-name))
(if (null? ,args-name)
(append!
,(if (null? kws)
''()
`(let ((all-vals (,loop-name ',kws)))
(let ,loop-name ((vals all-vals)
(kws ',kws))
(if (null? vals)
'()
`(,(car kws) ,(car vals) ,@(,loop-name (cdr vals) (cdr kws)))))))
(,get-delegate))
(map (lambda (,an-arg-name)
(case ,an-arg-name
,@ (append
(map (lambda (kw v) `((,kw) ,v)) kws vars)
`((else (car (,get-delegate ,an-arg-name)))))))
,args-name))))
`(lambda ,args-name
(let ,loop-name ((,args-name ,args-name))
(or (null? ,args-name)
(null? (cdr ,args-name))
(let ((,an-arg-name (car ,args-name))
(,new-val-name (cadr ,args-name)))
(case ,an-arg-name
,@ (append
(map (lambda (kw v) `((,kw) (set! ,v ,new-val-name))) kws vars)
`((else (,set-delegate ,an-arg-name ,new-val-name)))))
(,loop-name (cddr ,args-name)))))))))
;;; with-configuration-getter-and-setter <vars-etc> proc
;;;
;;; Create a getter and setter that can trigger arbitrary computation.
;;;
;;; <vars-etc> is a list of variable specifiers, explained below.
;;; proc is called:
;;;
;;; (proc getter setter)
;;;
;;; Each element of the <vars-etc> list is of the form:
;;;
;;; (<var> getter-hook setter-hook)
;;;
;;; Both hook elements are evaluated; the variable name is not.
;;; Either hook may be #f or procedure.
;;;
;;; A getter hook is a thunk that returns a value for the corresponding
;;; variable. If omitted (#f is passed), the binding of <var> is
;;; returned.
;;;
;;; A setter hook is a procedure of one argument that accepts a new value
;;; for the corresponding variable. If omitted, the binding of <var>
;;; is simply set using set!.
;;;
(defmacro with-configuration-getter-and-setter (vars-etc proc)
`((lambda (simpler-get simpler-set body-proc)
(with-delegating-getter-and-setter ()
simpler-get simpler-set body-proc))
(lambda (kw)
(case kw
,@(map (lambda (v) `((,(symbol->keyword (car v)))
,(cond
((cadr v) => list)
(else `(list ,(car v))))))
vars-etc)))
(lambda (kw new-val)
(case kw
,@(map (lambda (v) `((,(symbol->keyword (car v)))
,(cond
((caddr v) => (lambda (proc) `(,proc new-val)))
(else `(set! ,(car v) new-val)))))
vars-etc)))
,proc))
(defmacro with-delegating-configuration-getter-and-setter (vars-etc delegate-get delegate-set proc)
`((lambda (simpler-get simpler-set body-proc)
(with-delegating-getter-and-setter ()
simpler-get simpler-set body-proc))
(lambda (kw)
(case kw
,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
,(cond
((cadr v) => list)
(else `(list ,(car v))))))
vars-etc)
`((else (,delegate-get kw))))))
(lambda (kw new-val)
(case kw
,@(append! (map (lambda (v) `((,(symbol->keyword (car v)))
,(cond
((caddr v) => (lambda (proc) `(,proc new-val)))
(else `(set! ,(car v) new-val)))))
vars-etc)
`((else (,delegate-set kw new-val))))))
,proc))
;;; let-configuration-getter-and-setter <vars-etc> proc
;;;
;;; This procedure is like with-configuration-getter-and-setter (q.v.)
;;; except that each element of <vars-etc> is:
;;;
;;; (<var> initial-value getter-hook setter-hook)
;;;
;;; Unlike with-configuration-getter-and-setter, let-configuration-getter-and-setter
;;; introduces bindings for the variables named in <vars-etc>.
;;; It is short-hand for:
;;;
;;; (let ((<var1> initial-value-1)
;;; (<var2> initial-value-2)
;;; ...)
;;; (with-configuration-getter-and-setter ((<var1> v1-get v1-set) ...) proc))
;;;
(defmacro let-with-configuration-getter-and-setter (vars-etc proc)
`(let ,(map (lambda (v) `(,(car v) ,(cadr v))) vars-etc)
(with-configuration-getter-and-setter ,(map (lambda (v) `(,(car v) ,(caddr v) ,(cadddr v))) vars-etc)
,proc)))
;;; Guile object channel
;; Copyright (C) 2001, 2006, 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; Now you can use Guile's modules in Emacs Lisp like this:
;;
;; (guile-import current-module)
;; (guile-import module-ref)
;;
;; (setq assq (module-ref (current-module) 'assq))
;; => ("<guile>" %%1%% . "#<primitive-procedure assq>")
;;
;; (guile-use-modules (ice-9 documentation))
;;
;; (object-documentation assq)
;; =>
;; " - primitive: assq key alist
;; - primitive: assv key alist
;; - primitive: assoc key alist
;; Fetches the entry in ALIST that is associated with KEY. To decide
;; whether the argument KEY matches a particular entry in ALIST,
;; `assq' compares keys with `eq?', `assv' uses `eqv?' and `assoc'
;; uses `equal?'. If KEY cannot be found in ALIST (according to
;; whichever equality predicate is in use), then `#f' is returned.
;; These functions return the entire alist entry found (i.e. both the
;; key and the value)."
;;
;; Probably we can use GTK in Emacs Lisp. Can anybody try it?
;;
;; I have also implemented Guile Scheme mode and Scheme Interaction mode.
;; Just put the following lines in your ~/.emacs:
;;
;; (require 'guile-scheme)
;; (setq initial-major-mode 'scheme-interaction-mode)
;;
;; Currently, the following commands are available:
;;
;; M-TAB guile-scheme-complete-symbol
;; M-C-x guile-scheme-eval-define
;; C-x C-e guile-scheme-eval-last-sexp
;; C-c C-b guile-scheme-eval-buffer
;; C-c C-r guile-scheme-eval-region
;; C-c : guile-scheme-eval-expression
;;
;; I'll write more commands soon, or if you want to hack, please take
;; a look at the following files:
;;
;; guile-core/ice-9/channel.scm ;; object channel
;; guile-core/emacs/guile.el ;; object adapter
;; guile-core/emacs/guile-emacs.scm ;; Guile <-> Emacs channels
;; guile-core/emacs/guile-scheme.el ;; Guile Scheme mode
;;
;; As always, there are more than one bugs ;)
;;; Code:
(define-module (ice-9 channel)
\:export (make-object-channel
channel-open
channel-print-value
channel-print-token))
;;;
;;; Channel type
;;;
(define channel-type
(make-record-type 'channel '(stdin stdout printer token-module)))
(define make-channel (record-constructor channel-type))
(define (make-object-channel printer)
(make-channel (current-input-port)
(current-output-port)
printer
(make-module)))
(define channel-stdin (record-accessor channel-type 'stdin))
(define channel-stdout (record-accessor channel-type 'stdout))
(define channel-printer (record-accessor channel-type 'printer))
(define channel-token-module (record-accessor channel-type 'token-module))
;;;
;;; Channel
;;;
(define (channel-open ch)
(let ((stdin (channel-stdin ch))
(stdout (channel-stdout ch))
(printer (channel-printer ch))
(token-module (channel-token-module ch)))
(let loop ()
(catch #t
(lambda ()
(channel:prompt stdout)
(let ((cmd (read stdin)))
(if (eof-object? cmd)
(throw 'quit)
(case cmd
((eval)
(module-use! (current-module) token-module)
(printer ch (eval (read stdin) (current-module))))
((destroy)
(let ((token (read stdin)))
(if (module-defined? token-module token)
(module-remove! token-module token)
(channel:error stdout "Invalid token: ~S" token))))
((quit)
(throw 'quit))
(else
(channel:error stdout "Unknown command: ~S" cmd)))))
(loop))
(lambda (key . args)
(case key
((quit) (throw 'quit))
(else
(format stdout "exception = ~S\n"
(list key (apply format #f (cadr args) (caddr args))))
(loop))))))))
(define (channel-print-value ch val)
(format (channel-stdout ch) "value = ~S\n" val))
(define (channel-print-token ch val)
(let* ((token (symbol-append (gensym "%%") '%%))
(pair (cons token (object->string val))))
(format (channel-stdout ch) "token = ~S\n" pair)
(module-define! (channel-token-module ch) token val)))
(define (channel:prompt port)
(display "channel> " port)
(force-output port))
(define (channel:error port msg . args)
(display "ERROR: " port)
(apply format port msg args)
(newline port))
;;;
;;; Guile 1.4 compatibility
;;;
(define guile:eval eval)
(define eval
(if (= (car (procedure-minimum-arity guile:eval)) 1)
(lambda (x e) (guile:eval x e))
guile:eval))
(define object->string
(if (defined? 'object->string)
object->string
(lambda (x) (format #f "~S" x))))
;;; channel.scm ends here
;;; Parsing Guile's command-line
;;; Copyright (C) 1994-1998, 2000-2016 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
;;;
;;; Please be careful not to load up other modules in this file, unless
;;; they are explicitly requested. Loading modules currently imposes a
;;; speed penalty of a few stats, an mmap, and some allocation, which
;;; can range from 1 to 20ms, depending on the state of your disk cache.
;;; Since `compile-shell-switches' is called even for the most transient
;;; of command-line programs, we need to keep it lean.
;;;
;;; Generally speaking, the goal is for Guile to boot and execute simple
;;; expressions like "1" within 20ms or less, measured using system time
;;; from the time of the `guile' invocation to exit.
;;;
(define-module (ice-9 command-line)
#\autoload (system vm vm) (set-default-vm-engine! set-vm-engine! the-vm)
#\export (compile-shell-switches
version-etc
*GPLv3+*
*LGPLv3+*
emit-bug-reporting-address))
;; An initial stab at i18n.
(define _ gettext)
(define *GPLv3+*
(_ "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."))
(define *LGPLv3+*
(_ "License LGPLv3+: GNU LGPL 3 or later <http://gnu.org/licenses/lgpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law."))
;; Display the --version information in the
;; standard way: command and package names, package version, followed
;; by a short license notice and a list of up to 10 author names.
;; If COMMAND_NAME is NULL, the PACKAGE is asumed to be the name of
;; the program. The formats are therefore:
;; PACKAGE VERSION
;; or
;; COMMAND_NAME (PACKAGE) VERSION.
;;
;; Based on the version-etc gnulib module.
;;
(define* (version-etc package version #\key
(port (current-output-port))
;; FIXME: authors
(copyright-year 2016)
(copyright-holder "Free Software Foundation, Inc.")
(copyright (format #f "Copyright (C) ~a ~a"
copyright-year copyright-holder))
(license *GPLv3+*)
command-name
packager packager-version)
(if command-name
(format port "~a (~a) ~a\n" command-name package version)
(format port "~a ~a\n" package version))
(if packager
(if packager-version
(format port (_ "Packaged by ~a (~a)\n") packager packager-version)
(format port (_ "Packaged by ~a\n") packager)))
(display copyright port)
(newline port)
(newline port)
(display license port)
(newline port))
;; Display the usual `Report bugs to' stanza.
;;
(define* (emit-bug-reporting-address package bug-address #\key
(port (current-output-port))
(url (string-append
"http://www.gnu.org/software/"
package
"/"))
packager packager-bug-address)
(format port (_ "\nReport bugs to: ~a\n") bug-address)
(if (and packager packager-bug-address)
(format port (_ "Report ~a bugs to: ~a\n") packager packager-bug-address))
(format port (_ "~a home page: <~a>\n") package url)
(format port
(_ "General help using GNU software: <http://www.gnu.org/gethelp/>\n")))
(define *usage*
(_ "Evaluate code with Guile, interactively or from a script.
[-s] FILE load source code from FILE, and exit
-c EXPR evalute expression EXPR, and exit
-- stop scanning arguments; run interactively
The above switches stop argument processing, and pass all
remaining arguments as the value of (command-line).
If FILE begins with `-' the -s switch is mandatory.
-L DIRECTORY add DIRECTORY to the front of the module load path
-C DIRECTORY like -L, but for compiled files
-x EXTENSION add EXTENSION to the front of the load extensions
-l FILE load source code from FILE
-e FUNCTION after reading script, apply FUNCTION to
command line arguments
--language=LANG change language; default: scheme
-ds do -s script at this point
--debug start with the \"debugging\" VM engine
--no-debug start with the normal VM engine (backtraces but
no breakpoints); default is --debug for interactive
use, but not for `-s' and `-c'.
--auto-compile compile source files automatically
--fresh-auto-compile invalidate auto-compilation cache
--no-auto-compile disable automatic source file compilation;
default is to enable auto-compilation of source
files.
--listen[=P] listen on a local port or a path for REPL clients;
if P is not given, the default is local port 37146
-q inhibit loading of user init file
--use-srfi=LS load SRFI modules for the SRFIs in LS,
which is a list of numbers like \"2,13,14\"
-h, --help display this help and exit
-v, --version display version information and exit
\\ read arguments from following script lines"))
(define* (shell-usage name fatal? #\optional fmt . args)
(let ((port (if fatal?
(current-error-port)
(current-output-port))))
(when fmt
(apply format port fmt args)
(newline port))
(format port (_ "Usage: ~a [OPTION]... [FILE]...\n") name)
(display *usage* port)
(newline port)
(emit-bug-reporting-address
"GNU Guile" "bug-guile@gnu.org"
#\port port
#\url "http://www.gnu.org/software/guile/"
#\packager (assq-ref %guile-build-info 'packager)
#\packager-bug-address
(assq-ref %guile-build-info 'packager-bug-address))
(if fatal?
(exit 1))))
;; Try to avoid loading (ice-9 eval-string) and (system base compile) if
;; possible.
(define (eval-string/lang str)
(case (current-language)
((scheme)
(call-with-input-string
str
(lambda (port)
(let lp ()
(let ((exp (read port)))
(if (not (eof-object? exp))
(begin
(eval exp (current-module))
(lp))))))))
(else
((module-ref (resolve-module '(ice-9 eval-string)) 'eval-string) str))))
(define (load/lang f)
(case (current-language)
((scheme)
(load-in-vicinity (getcwd) f))
(else
((module-ref (resolve-module '(system base compile)) 'compile-file)
f #\to 'value))))
(define* (compile-shell-switches args #\optional (usage-name "guile"))
(let ((arg0 "guile")
(script-cell #f)
(entry-point #f)
(user-load-path '())
(user-load-compiled-path '())
(user-extensions '())
(interactive? #t)
(inhibit-user-init? #f)
(turn-on-debugging? #f)
(turn-off-debugging? #f))
(define (error fmt . args)
(apply shell-usage usage-name #t
(string-append "error: " fmt "~%") args))
(define (parse args out)
(cond
((null? args)
(finish args out))
(else
(let ((arg (car args))
(args (cdr args)))
(cond
((not (string-prefix? "-" arg)) ; foo
;; If we specified the -ds option, script-cell is the cdr of
;; an expression like (load #f). We replace the car (i.e.,
;; the #f) with the script name.
(set! arg0 arg)
(set! interactive? #f)
(if script-cell
(begin
(set-car! script-cell arg0)
(finish args out))
(finish args
(cons `((@@ (ice-9 command-line) load/lang) ,arg0)
out))))
((string=? arg "-s") ; foo
(if (null? args)
(error "missing argument to `-s' switch"))
(set! arg0 (car args))
(set! interactive? #f)
(if script-cell
(begin
(set-car! script-cell arg0)
(finish (cdr args) out))
(finish (cdr args)
(cons `((@@ (ice-9 command-line) load/lang) ,arg0)
out))))
((string=? arg "-c") ; evaluate expr
(if (null? args)
(error "missing argument to `-c' switch"))
(set! interactive? #f)
(finish (cdr args)
(cons `((@@ (ice-9 command-line) eval-string/lang)
,(car args))
out)))
((string=? arg "--") ; end args go interactive
(finish args out))
((string=? arg "-l") ; load a file
(if (null? args)
(error "missing argument to `-l' switch"))
(parse (cdr args)
(cons `((@@ (ice-9 command-line) load/lang) ,(car args))
out)))
((string=? arg "-L") ; add to %load-path
(if (null? args)
(error "missing argument to `-L' switch"))
(set! user-load-path (cons (car args) user-load-path))
(parse (cdr args)
out))
((string=? arg "-C") ; add to %load-compiled-path
(if (null? args)
(error "missing argument to `-C' switch"))
(set! user-load-compiled-path
(cons (car args) user-load-compiled-path))
(parse (cdr args)
out))
((string=? arg "-x") ; add to %load-extensions
(if (null? args)
(error "missing argument to `-x' switch"))
(set! user-extensions (cons (car args) user-extensions))
(parse (cdr args)
out))
((string=? arg "-e") ; entry point
(if (null? args)
(error "missing argument to `-e' switch"))
(let* ((port (open-input-string (car args)))
(arg1 (read port))
(arg2 (read port)))
;; Recognize syntax of certain versions of guile 1.4 and
;; transform to (@ MODULE-NAME FUNC).
(set! entry-point
(cond
((not (eof-object? arg2))
`(@ ,arg1 ,arg2))
((and (pair? arg1)
(not (memq (car arg1) '(@ @@)))
(and-map symbol? arg1))
`(@ ,arg1 main))
(else
arg1))))
(parse (cdr args)
out))
((string-prefix? "--language=" arg) ; language
(parse args
(cons `(current-language
',(string->symbol
(substring arg (string-length "--language="))))
out)))
((string=? "--language" arg) ; language
(when (null? args)
(error "missing argument to `--language' option"))
(parse (cdr args)
(cons `(current-language ',(string->symbol (car args)))
out)))
((string=? arg "-ds") ; do script here
;; We put a dummy "load" expression, and let the -s put the
;; filename in.
(when script-cell
(error "the -ds switch may only be specified once"))
(set! script-cell (list #f))
(parse args
(acons '(@@ (ice-9 command-line) load/lang)
script-cell
out)))
((string=? arg "--debug")
(set! turn-on-debugging? #t)
(set! turn-off-debugging? #f)
(parse args out))
((string=? arg "--no-debug")
(set! turn-off-debugging? #t)
(set! turn-on-debugging? #f)
(parse args out))
;; Do auto-compile on/off now, because the form itself might
;; need this decision.
((string=? arg "--auto-compile")
(set! %load-should-auto-compile #t)
(parse args out))
((string=? arg "--fresh-auto-compile")
(set! %load-should-auto-compile #t)
(set! %fresh-auto-compile #t)
(parse args out))
((string=? arg "--no-auto-compile")
(set! %load-should-auto-compile #f)
(parse args out))
((string=? arg "-q") ; don't load user init
(set! inhibit-user-init? #t)
(parse args out))
((string-prefix? "--use-srfi=" arg)
(let ((srfis (map (lambda (x)
(let ((n (string->number x)))
(if (and n (exact? n) (integer? n) (>= n 0))
n
(error "invalid SRFI specification"))))
(string-split (substring arg 11) #\,))))
(if (null? srfis)
(error "invalid SRFI specification"))
(parse args
(cons `(use-srfis ',srfis) out))))
((string=? arg "--listen") ; start a repl server
(parse args
(cons '((@@ (system repl server) spawn-server)) out)))
((string-prefix? "--listen=" arg) ; start a repl server
(parse
args
(cons
(let ((where (substring arg 9)))
(cond
((string->number where) ; --listen=PORT
=> (lambda (port)
(if (and (integer? port) (exact? port) (>= port 0))
`((@@ (system repl server) spawn-server)
((@@ (system repl server) make-tcp-server-socket) #\port ,port))
(error "invalid port for --listen"))))
((string-prefix? "/" where) ; --listen=/PATH/TO/SOCKET
`((@@ (system repl server) spawn-server)
((@@ (system repl server) make-unix-domain-server-socket) #\path ,where)))
(else
(error "unknown argument to --listen"))))
out)))
((or (string=? arg "-h") (string=? arg "--help"))
(shell-usage usage-name #f)
(exit 0))
((or (string=? arg "-v") (string=? arg "--version"))
(version-etc "GNU Guile" (version)
#\license *LGPLv3+*
#\command-name "guile"
#\packager (assq-ref %guile-build-info 'packager)
#\packager-version
(assq-ref %guile-build-info 'packager-version))
(exit 0))
(else
(error "unrecognized switch ~a" arg)))))))
(define (finish args out)
;; Check to make sure the -ds got a -s.
(when (and script-cell (not (car script-cell)))
(error "the `-ds' switch requires the use of `-s' as well"))
;; Make any remaining arguments available to the
;; script/command/whatever.
(set-program-arguments (cons arg0 args))
;; If debugging was requested, or we are interactive and debugging
;; was not explicitly turned off, use the debug engine.
(if (or turn-on-debugging?
(and interactive? (not turn-off-debugging?)))
(begin
(set-default-vm-engine! 'debug)
(set-vm-engine! (the-vm) 'debug)))
;; Return this value.
`(;; It would be nice not to load up (ice-9 control), but the
;; default-prompt-handler is nontrivial.
(@ (ice-9 control) %)
(begin
;; If we didn't end with a -c or a -s and didn't supply a -q, load
;; the user's customization file.
,@(if (and interactive? (not inhibit-user-init?))
'((load-user-init))
'())
;; Use-specified extensions.
,@(map (lambda (ext)
`(set! %load-extensions (cons ,ext %load-extensions)))
user-extensions)
;; Add the user-specified load paths here, so they won't be in
;; effect during the loading of the user's customization file.
,@(map (lambda (path)
`(set! %load-path (cons ,path %load-path)))
user-load-path)
,@(map (lambda (path)
`(set! %load-compiled-path
(cons ,path %load-compiled-path)))
user-load-compiled-path)
;; Put accumulated actions in their correct order.
,@(reverse! out)
;; Handle the `-e' switch, if it was specified.
,@(if entry-point
`((,entry-point (command-line)))
'())
,(if interactive?
;; If we didn't end with a -c or a -s, start the
;; repl.
'((@ (ice-9 top-repl) top-repl))
;; Otherwise, after doing all the other actions
;; prescribed by the command line, quit.
'(quit)))))
(if (pair? args)
(begin
(set! arg0 (car args))
(let ((slash (string-rindex arg0 #\/)))
(set! usage-name
(if slash (substring arg0 (1+ slash)) arg0)))
(parse (cdr args) '()))
(parse args '()))))
;;;; common-list.scm --- COMMON LISP list functions for Scheme
;;;;
;;;; Copyright (C) 1995, 1996, 1997, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; These procedures are exported:
;; (adjoin e l)
;; (union l1 l2)
;; (intersection l1 l2)
;; (set-difference l1 l2)
;; (reduce-init p init l)
;; (reduce p l)
;; (some pred l . rest)
;; (every pred l . rest)
;; (notany pred . ls)
;; (notevery pred . ls)
;; (count-if pred l)
;; (find-if pred l)
;; (member-if pred l)
;; (remove-if pred l)
;; (remove-if-not pred l)
;; (delete-if! pred l)
;; (delete-if-not! pred l)
;; (butlast lst n)
;; (and? . args)
;; (or? . args)
;; (has-duplicates? lst)
;; (pick p l)
;; (pick-mappings p l)
;; (uniq l)
;;
;; See docstrings for each procedure for more info. See also module
;; `(srfi srfi-1)' for a complete list handling library.
;;; Code:
(define-module (ice-9 common-list)
\:export (adjoin union intersection set-difference reduce-init reduce
some every notany notevery count-if find-if member-if remove-if
remove-if-not delete-if! delete-if-not! butlast and? or?
has-duplicates? pick pick-mappings uniq))
;;"comlist.scm" Implementation of COMMON LISP list functions for Scheme
; Copyright (C) 1991, 1993, 1995 Aubrey Jaffer.
;
;Permission to copy this software, to redistribute it, and to use it
;for any purpose is granted, subject to the following restrictions and
;understandings.
;
;1. Any copy made of this software must include this copyright notice
;in full.
;
;2. I have made no warrantee or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
;3. In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(define (adjoin e l)
"Return list L, possibly with element E added if it is not already in L."
(if (memq e l) l (cons e l)))
(define (union l1 l2)
"Return a new list that is the union of L1 and L2.
Elements that occur in both lists occur only once in
the result list."
(cond ((null? l1) l2)
((null? l2) l1)
(else (union (cdr l1) (adjoin (car l1) l2)))))
(define (intersection l1 l2)
"Return a new list that is the intersection of L1 and L2.
Only elements that occur in both lists occur in the result list."
(if (null? l2) l2
(let loop ((l1 l1) (result '()))
(cond ((null? l1) (reverse! result))
((memv (car l1) l2) (loop (cdr l1) (cons (car l1) result)))
(else (loop (cdr l1) result))))))
(define (set-difference l1 l2)
"Return elements from list L1 that are not in list L2."
(let loop ((l1 l1) (result '()))
(cond ((null? l1) (reverse! result))
((memv (car l1) l2) (loop (cdr l1) result))
(else (loop (cdr l1) (cons (car l1) result))))))
(define (reduce-init p init l)
"Same as `reduce' except it implicitly inserts INIT at the start of L."
(if (null? l)
init
(reduce-init p (p init (car l)) (cdr l))))
(define (reduce p l)
"Combine all the elements of sequence L using a binary operation P.
The combination is left-associative. For example, using +, one can
add up all the elements. `reduce' allows you to apply a function which
accepts only two arguments to more than 2 objects. Functional
programmers usually refer to this as foldl."
(cond ((null? l) l)
((null? (cdr l)) (car l))
(else (reduce-init p (car l) (cdr l)))))
(define (some pred l . rest)
"PRED is a boolean function of as many arguments as there are list
arguments to `some', i.e., L plus any optional arguments. PRED is
applied to successive elements of the list arguments in order. As soon
as one of these applications returns a true value, return that value.
If no application returns a true value, return #f.
All the lists should have the same length."
(cond ((null? rest)
(let mapf ((l l))
(and (not (null? l))
(or (pred (car l)) (mapf (cdr l))))))
(else (let mapf ((l l) (rest rest))
(and (not (null? l))
(or (apply pred (car l) (map car rest))
(mapf (cdr l) (map cdr rest))))))))
(define (every pred l . rest)
"Return #t iff every application of PRED to L, etc., returns #t.
Analogous to `some' except it returns #t if every application of
PRED is #t and #f otherwise."
(cond ((null? rest)
(let mapf ((l l))
(or (null? l)
(and (pred (car l)) (mapf (cdr l))))))
(else (let mapf ((l l) (rest rest))
(or (null? l)
(and (apply pred (car l) (map car rest))
(mapf (cdr l) (map cdr rest))))))))
(define (notany pred . ls)
"Return #t iff every application of PRED to L, etc., returns #f.
Analogous to some but returns #t if no application of PRED returns a
true value or #f as soon as any one does."
(not (apply some pred ls)))
(define (notevery pred . ls)
"Return #t iff there is an application of PRED to L, etc., that returns #f.
Analogous to some but returns #t as soon as an application of PRED returns #f,
or #f otherwise."
(not (apply every pred ls)))
(define (count-if pred l)
"Return the number of elements in L for which (PRED element) returns true."
(let loop ((n 0) (l l))
(cond ((null? l) n)
((pred (car l)) (loop (+ n 1) (cdr l)))
(else (loop n (cdr l))))))
(define (find-if pred l)
"Search for the first element in L for which (PRED element) returns true.
If found, return that element, otherwise return #f."
(cond ((null? l) #f)
((pred (car l)) (car l))
(else (find-if pred (cdr l)))))
(define (member-if pred l)
"Return the first sublist of L for whose car PRED is true."
(cond ((null? l) #f)
((pred (car l)) l)
(else (member-if pred (cdr l)))))
(define (remove-if pred l)
"Remove all elements from L where (PRED element) is true.
Return everything that's left."
(let loop ((l l) (result '()))
(cond ((null? l) (reverse! result))
((pred (car l)) (loop (cdr l) result))
(else (loop (cdr l) (cons (car l) result))))))
(define (remove-if-not pred l)
"Remove all elements from L where (PRED element) is #f.
Return everything that's left."
(let loop ((l l) (result '()))
(cond ((null? l) (reverse! result))
((not (pred (car l))) (loop (cdr l) result))
(else (loop (cdr l) (cons (car l) result))))))
(define (delete-if! pred l)
"Destructive version of `remove-if'."
(let delete-if ((l l))
(cond ((null? l) '())
((pred (car l)) (delete-if (cdr l)))
(else
(set-cdr! l (delete-if (cdr l)))
l))))
(define (delete-if-not! pred l)
"Destructive version of `remove-if-not'."
(let delete-if-not ((l l))
(cond ((null? l) '())
((not (pred (car l))) (delete-if-not (cdr l)))
(else
(set-cdr! l (delete-if-not (cdr l)))
l))))
(define (butlast lst n)
"Return all but the last N elements of LST."
(letrec ((l (- (length lst) n))
(bl (lambda (lst n)
(cond ((null? lst) lst)
((positive? n)
(cons (car lst) (bl (cdr lst) (+ -1 n))))
(else '())))))
(bl lst (if (negative? n)
(error "negative argument to butlast" n)
l))))
(define (and? . args)
"Return #t iff all of ARGS are true."
(cond ((null? args) #t)
((car args) (apply and? (cdr args)))
(else #f)))
(define (or? . args)
"Return #t iff any of ARGS is true."
(cond ((null? args) #f)
((car args) #t)
(else (apply or? (cdr args)))))
(define (has-duplicates? lst)
"Return #t iff 2 members of LST are equal?, else #f."
(cond ((null? lst) #f)
((member (car lst) (cdr lst)) #t)
(else (has-duplicates? (cdr lst)))))
(define (pick p l)
"Apply P to each element of L, returning a list of elts
for which P returns a non-#f value."
(let loop ((s '())
(l l))
(cond
((null? l) s)
((p (car l)) (loop (cons (car l) s) (cdr l)))
(else (loop s (cdr l))))))
(define (pick-mappings p l)
"Apply P to each element of L, returning a list of the
non-#f return values of P."
(let loop ((s '())
(l l))
(cond
((null? l) s)
((p (car l)) => (lambda (mapping) (loop (cons mapping s) (cdr l))))
(else (loop s (cdr l))))))
(define (uniq l)
"Return a list containing elements of L, with duplicates removed."
(let loop ((acc '())
(l l))
(if (null? l)
(reverse! acc)
(loop (if (memq (car l) acc)
acc
(cons (car l) acc))
(cdr l)))))
;;; common-list.scm ends here
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(use-modules (language tree-il)
(language tree-il primitives)
(language tree-il canonicalize)
(srfi srfi-1)
(ice-9 pretty-print)
(system syntax))
;; Minimize a syntax-object such that it can no longer be used as the
;; first argument to 'datum->syntax', but is otherwise equivalent.
(define (squeeze-syntax-object! syn)
(define (ensure-list x) (if (vector? x) (vector->list x) x))
(let ((x (vector-ref syn 1))
(wrap (vector-ref syn 2))
(mod (vector-ref syn 3)))
(let ((marks (car wrap))
(subst (cdr wrap)))
(define (set-wrap! marks subst)
(vector-set! syn 2 (cons marks subst)))
(cond
((symbol? x)
(let loop ((marks marks) (subst subst))
(cond
((null? subst) (set-wrap! marks subst) syn)
((eq? 'shift (car subst)) (loop (cdr marks) (cdr subst)))
((find (lambda (entry) (and (eq? x (car entry))
(equal? marks (cadr entry))))
(apply map list (map ensure-list
(cdr (vector->list (car subst))))))
=> (lambda (entry)
(set-wrap! marks
(list (list->vector
(cons 'ribcage
(map vector entry)))))
syn))
(else (loop marks (cdr subst))))))
((or (pair? x) (vector? x))
syn)
(else x)))))
(define (squeeze-constant! x)
(define (syntax-object? x)
(and (vector? x)
(= 4 (vector-length x))
(eq? 'syntax-object (vector-ref x 0))))
(cond ((syntax-object? x)
(squeeze-syntax-object! x))
((pair? x)
(set-car! x (squeeze-constant! (car x)))
(set-cdr! x (squeeze-constant! (cdr x)))
x)
((vector? x)
(for-each (lambda (i)
(vector-set! x i (squeeze-constant! (vector-ref x i))))
(iota (vector-length x)))
x)
(else x)))
(define (squeeze-tree-il! x)
(post-order! (lambda (x)
(if (const? x)
(set! (const-exp x)
(squeeze-constant! (const-exp x))))
#f)
x))
;; Avoid gratuitous churn in psyntax-pp.scm due to the marks and labels
;; changing session identifiers.
(set! syntax-session-id (lambda () "*"))
(let ((source (list-ref (command-line) 1))
(target (list-ref (command-line) 2)))
(let ((in (open-input-file source))
(out (open-output-file (string-append target ".tmp"))))
(write '(eval-when (compile) (set-current-module (resolve-module '(guile))))
out)
(newline out)
(let loop ((x (read in)))
(if (eof-object? x)
(begin
(close-port out)
(close-port in))
(begin
(pretty-print (tree-il->scheme
(squeeze-tree-il!
(canonicalize!
(resolve-primitives!
(macroexpand x 'c '(compile load eval))
(current-module))))
(current-module)
(list #\avoid-lambda? #f
#\use-case? #f
#\strip-numeric-suffixes? #t
#\use-derived-syntax?
(and (pair? x)
(eq? 'let (car x)))))
out #\width 120 #\max-expr-width 70)
(newline out)
(loop (read in))))))
(system (format #f "mv -f ~s.tmp ~s" target target)))
;;; Beyond call/cc
;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (ice-9 control)
#\re-export (call-with-prompt abort-to-prompt
default-prompt-tag make-prompt-tag)
#\export (% abort shift reset shift* reset*
call-with-escape-continuation call/ec
let-escape-continuation let/ec))
(define (abort . args)
(apply abort-to-prompt (default-prompt-tag) args))
(define-syntax %
(syntax-rules ()
((_ expr)
(call-with-prompt (default-prompt-tag)
(lambda () expr)
default-prompt-handler))
((_ expr handler)
(call-with-prompt (default-prompt-tag)
(lambda () expr)
handler))
((_ tag expr handler)
(call-with-prompt tag
(lambda () expr)
handler))))
;; Each prompt tag has a type -- an expected set of arguments, and an unwritten
;; contract of what its handler will do on an abort. In the case of the default
;; prompt tag, we could choose to return values, exit nonlocally, or punt to the
;; user.
;;
;; We choose the latter, by requiring that the user return one value, a
;; procedure, to an abort to the prompt tag. That argument is then invoked with
;; the continuation as an argument, within a reinstated default prompt. In this
;; way the return value(s) from a default prompt are under the user's control.
(define (default-prompt-handler k proc)
(% (default-prompt-tag)
(proc k)
default-prompt-handler))
;; Kindly provided by Wolfgang J Moeller <wjm@heenes.com>, modelled
;; after the ones by Oleg Kiselyov in
;; http://okmij.org/ftp/Scheme/delim-control-n.scm, which are in the
;; public domain, as noted at the top of http://okmij.org/ftp/.
;;
(define-syntax-rule (reset . body)
(call-with-prompt (default-prompt-tag)
(lambda () . body)
(lambda (cont f) (f cont))))
(define-syntax-rule (shift var . body)
(abort-to-prompt (default-prompt-tag)
(lambda (cont)
((lambda (var) (reset . body))
(lambda vals (reset (apply cont vals)))))))
(define (reset* thunk)
(reset (thunk)))
(define (shift* fc)
(shift c (fc c)))
(define (call-with-escape-continuation proc)
"Call PROC with an escape continuation."
(let ((tag (list 'call/ec)))
(call-with-prompt tag
(lambda ()
(proc (lambda args
(apply abort-to-prompt tag args))))
(lambda (_ . args)
(apply values args)))))
(define call/ec call-with-escape-continuation)
(define-syntax-rule (let-escape-continuation k body ...)
"Bind K to an escape continuation within the lexical extent of BODY."
(let ((tag (list 'let/ec)))
(call-with-prompt tag
(lambda ()
(let ((k (lambda args
(apply abort-to-prompt tag args))))
body ...))
(lambda (_ . results)
(apply values results)))))
(define-syntax-rule (let/ec k body ...)
(let-escape-continuation k body ...))
;;; Copyright (C) 2010, 2013 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 curried-definitions)
#\replace ((cdefine . define)
(cdefine* . define*)
define-public
define*-public))
(define-syntax cdefine
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine head
(lambda rest body body* ...)))
((_ name val)
(define name val))))
(define-syntax cdefine*
(syntax-rules ()
((_ (head . rest) body body* ...)
(cdefine* head
(lambda* rest body body* ...)))
((_ name val)
(define* name val))))
(define-syntax define-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define-public head
(lambda rest body body* ...)))
((_ name val)
(begin
(define name val)
(export name)))))
(define-syntax define*-public
(syntax-rules ()
((_ (head . rest) body body* ...)
(define*-public head
(lambda* rest body body* ...)))
((_ name val)
(begin
(define* name val)
(export name)))))
;;;; Copyright (C) 1996, 1997, 1998, 1999, 2001, 2006, 2010 Free Software Foundation
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; The author can be reached at djurfeldt@nada.kth.se
;;;; Mikael Djurfeldt, SANS/NADA KTH, 10044 STOCKHOLM, SWEDEN
;;;;
(define-module (ice-9 debug))
(issue-deprecation-warning
"(ice-9 debug) is deprecated. Use (system vm trace) for tracing.")
;;;; Copyright (C) 2003, 2005, 2006, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 deprecated)
#\export (substring-move-left! substring-move-right!
dynamic-maybe-call dynamic-maybe-link
try-module-linked try-module-dynamic-link
list* feature? eval-case unmemoize-expr
$asinh
$acosh
$atanh
$sqrt
$abs
$exp
$expt
$log
$sin
$cos
$tan
$asin
$acos
$atan
$sinh
$cosh
$tanh
closure?
%nil
@bind
bad-throw
error-catching-loop
error-catching-repl
scm-style-repl
apply-to-args
has-suffix?
scheme-file-suffix
get-option
for-next-option
display-usage-report
transform-usage-lambda
collect
assert-repl-silence
assert-repl-print-unspecified
assert-repl-verbosity
set-repl-prompt!
set-batch-mode?!
repl
pre-unwind-handler-dispatch
default-pre-unwind-handler
handle-system-error
stack-saved?
the-last-stack
save-stack
named-module-use!
top-repl
turn-on-debugging
read-hash-procedures
process-define-module
fluid-let-syntax
set-system-module!
char-code-limit
generalized-vector?
generalized-vector-length
generalized-vector-ref
generalized-vector-set!
generalized-vector->list))
;;;; Deprecated definitions.
(define substring-move-left!
(lambda args
(issue-deprecation-warning
"`substring-move-left!' is deprecated. Use `substring-move!' instead.")
(apply substring-move! args)))
(define substring-move-right!
(lambda args
(issue-deprecation-warning
"`substring-move-right!' is deprecated. Use `substring-move!' instead.")
(apply substring-move! args)))
;; This method of dynamically linking Guile Extensions is deprecated.
;; Use `load-extension' explicitly from Scheme code instead.
(define (split-c-module-name str)
(let loop ((rev '())
(start 0)
(pos 0)
(end (string-length str)))
(cond
((= pos end)
(reverse (cons (string->symbol (substring str start pos)) rev)))
((eq? (string-ref str pos) #\space)
(loop (cons (string->symbol (substring str start pos)) rev)
(+ pos 1)
(+ pos 1)
end))
(else
(loop rev start (+ pos 1) end)))))
(define (convert-c-registered-modules dynobj)
(let ((res (map (lambda (c)
(list (split-c-module-name (car c)) (cdr c) dynobj))
(c-registered-modules))))
(c-clear-registered-modules)
res))
(define registered-modules '())
(define (register-modules dynobj)
(set! registered-modules
(append! (convert-c-registered-modules dynobj)
registered-modules)))
(define (warn-autoload-deprecation modname)
(issue-deprecation-warning
"Autoloading of compiled code modules is deprecated."
"Write a Scheme file instead that uses `load-extension'.")
(issue-deprecation-warning
(simple-format #f "(You just autoloaded module ~S.)" modname)))
(define (init-dynamic-module modname)
;; Register any linked modules which have been registered on the C level
(register-modules #f)
(or-map (lambda (modinfo)
(if (equal? (car modinfo) modname)
(begin
(warn-autoload-deprecation modname)
(set! registered-modules (delq! modinfo registered-modules))
(let ((mod (resolve-module modname #f)))
(save-module-excursion
(lambda ()
(set-current-module mod)
(set-module-public-interface! mod mod)
(dynamic-call (cadr modinfo) (caddr modinfo))
))
#t))
#f))
registered-modules))
(define (dynamic-maybe-call name dynobj)
(issue-deprecation-warning
"`dynamic-maybe-call' is deprecated. "
"Wrap `dynamic-call' in a `false-if-exception' yourself.")
(false-if-exception (dynamic-call name dynobj)))
(define (dynamic-maybe-link filename)
(issue-deprecation-warning
"`dynamic-maybe-link' is deprecated. "
"Wrap `dynamic-link' in a `false-if-exception' yourself.")
(false-if-exception (dynamic-link filename)))
(define (find-and-link-dynamic-module module-name)
(define (make-init-name mod-name)
(string-append "scm_init"
(list->string (map (lambda (c)
(if (or (char-alphabetic? c)
(char-numeric? c))
c
#\_))
(string->list mod-name)))
"_module"))
;; Put the subdirectory for this module in the car of SUBDIR-AND-LIBNAME,
;; and the `libname' (the name of the module prepended by `lib') in the cdr
;; field. For example, if MODULE-NAME is the list (inet tcp-ip udp), then
;; SUBDIR-AND-LIBNAME will be the pair ("inet/tcp-ip" . "libudp").
(let ((subdir-and-libname
(let loop ((dirs "")
(syms module-name))
(if (null? (cdr syms))
(cons dirs (string-append "lib" (symbol->string (car syms))))
(loop (string-append dirs (symbol->string (car syms)) "/")
(cdr syms)))))
(init (make-init-name (apply string-append
(map (lambda (s)
(string-append "_"
(symbol->string s)))
module-name)))))
(let ((subdir (car subdir-and-libname))
(libname (cdr subdir-and-libname)))
;; Now look in each dir in %LOAD-PATH for `subdir/libfoo.la'. If that
;; file exists, fetch the dlname from that file and attempt to link
;; against it. If `subdir/libfoo.la' does not exist, or does not seem
;; to name any shared library, look for `subdir/libfoo.so' instead and
;; link against that.
(let check-dirs ((dir-list %load-path))
(if (null? dir-list)
#f
(let* ((dir (in-vicinity (car dir-list) subdir))
(sharlib-full
(or (try-using-libtool-name dir libname)
(try-using-sharlib-name dir libname))))
(if (and sharlib-full (file-exists? sharlib-full))
(link-dynamic-module sharlib-full init)
(check-dirs (cdr dir-list)))))))))
(define (try-using-libtool-name libdir libname)
(let ((libtool-filename (in-vicinity libdir
(string-append libname ".la"))))
(and (file-exists? libtool-filename)
libtool-filename)))
(define (try-using-sharlib-name libdir libname)
(in-vicinity libdir (string-append libname ".so")))
(define (link-dynamic-module filename initname)
;; Register any linked modules which have been registered on the C level
(register-modules #f)
(let ((dynobj (dynamic-link filename)))
(dynamic-call initname dynobj)
(register-modules dynobj)))
(define (try-module-linked module-name)
(issue-deprecation-warning
"`try-module-linked' is deprecated."
"See the manual for how more on C extensions.")
(init-dynamic-module module-name))
(define (try-module-dynamic-link module-name)
(issue-deprecation-warning
"`try-module-dynamic-link' is deprecated."
"See the manual for how more on C extensions.")
(and (find-and-link-dynamic-module module-name)
(init-dynamic-module module-name)))
(define (list* . args)
(issue-deprecation-warning "'list*' is deprecated. Use 'cons*' instead.")
(apply cons* args))
(define (feature? sym)
(issue-deprecation-warning
"`feature?' is deprecated. Use `provided?' instead.")
(provided? sym))
(define-macro (eval-case . clauses)
(issue-deprecation-warning
"`eval-case' is deprecated. Use `eval-when' instead.")
;; Practically speaking, eval-case only had load-toplevel and else as
;; conditions.
(cond
((assoc-ref clauses '(load-toplevel))
=> (lambda (exps)
;; the *unspecified so that non-toplevel definitions will be
;; caught
`(begin *unspecified* . ,exps)))
((assoc-ref clauses 'else)
=> (lambda (exps)
`(begin *unspecified* . ,exps)))
(else
`(begin))))
;; The strange prototype system for uniform arrays has been
;; deprecated.
(read-hash-extend
#\y
(lambda (c port)
(issue-deprecation-warning
"The `#y' bytevector syntax is deprecated. Use `#s8' instead.")
(let ((x (read port)))
(cond
((list? x) (list->s8vector x))
(else (error "#y needs to be followed by a list" x))))))
(define (unmemoize-expr . args)
(issue-deprecation-warning
"`unmemoize-expr' is deprecated. Use `unmemoize-expression' instead.")
(apply unmemoize-expression args))
(define ($asinh z)
(issue-deprecation-warning
"`$asinh' is deprecated. Use `asinh' instead.")
(asinh z))
(define ($acosh z)
(issue-deprecation-warning
"`$acosh' is deprecated. Use `acosh' instead.")
(acosh z))
(define ($atanh z)
(issue-deprecation-warning
"`$atanh' is deprecated. Use `atanh' instead.")
(atanh z))
(define ($sqrt z)
(issue-deprecation-warning
"`$sqrt' is deprecated. Use `sqrt' instead.")
(sqrt z))
(define ($abs z)
(issue-deprecation-warning
"`$abs' is deprecated. Use `abs' instead.")
(abs z))
(define ($exp z)
(issue-deprecation-warning
"`$exp' is deprecated. Use `exp' instead.")
(exp z))
(define ($expt z1 z2)
(issue-deprecation-warning
"`$expt' is deprecated. Use `expt' instead.")
(expt z1 z2))
(define ($log z)
(issue-deprecation-warning
"`$log' is deprecated. Use `log' instead.")
(log z))
(define ($sin z)
(issue-deprecation-warning
"`$sin' is deprecated. Use `sin' instead.")
(sin z))
(define ($cos z)
(issue-deprecation-warning
"`$cos' is deprecated. Use `cos' instead.")
(cos z))
(define ($tan z)
(issue-deprecation-warning
"`$tan' is deprecated. Use `tan' instead.")
(tan z))
(define ($asin z)
(issue-deprecation-warning
"`$asin' is deprecated. Use `asin' instead.")
(asin z))
(define ($acos z)
(issue-deprecation-warning
"`$acos' is deprecated. Use `acos' instead.")
(acos z))
(define ($atan z)
(issue-deprecation-warning
"`$atan' is deprecated. Use `atan' instead.")
(atan z))
(define ($sinh z)
(issue-deprecation-warning
"`$sinh' is deprecated. Use `sinh' instead.")
(sinh z))
(define ($cosh z)
(issue-deprecation-warning
"`$cosh' is deprecated. Use `cosh' instead.")
(cosh z))
(define ($tanh z)
(issue-deprecation-warning
"`$tanh' is deprecated. Use `tanh' instead.")
(tanh z))
(define (closure? x)
(issue-deprecation-warning
"`closure?' is deprecated. Use `procedure?' instead.")
(procedure? x))
(define %nil #nil)
;;; @bind is used by the old elisp code as a dynamic scoping mechanism.
;;; Please let the Guile developers know if you are using this macro.
;;;
(define-syntax @bind
(lambda (x)
(define (bound-member id ids)
(cond ((null? ids) #f)
((bound-identifier=? id (car ids)) #t)
((bound-member (car ids) (cdr ids)))))
(issue-deprecation-warning
"`@bind' is deprecated. Use `with-fluids' instead.")
(syntax-case x ()
((_ () b0 b1 ...)
#'(let () b0 b1 ...))
((_ ((id val) ...) b0 b1 ...)
(and-map identifier? #'(id ...))
(if (let lp ((ids #'(id ...)))
(cond ((null? ids) #f)
((bound-member (car ids) (cdr ids)) #t)
(else (lp (cdr ids)))))
(syntax-violation '@bind "duplicate bound identifier" x)
(with-syntax (((old-v ...) (generate-temporaries #'(id ...)))
((v ...) (generate-temporaries #'(id ...))))
#'(let ((old-v id) ...
(v val) ...)
(dynamic-wind
(lambda ()
(set! id v) ...)
(lambda () b0 b1 ...)
(lambda ()
(set! id old-v) ...)))))))))
;; There are deprecated definitions for module-ref-submodule and
;; module-define-submodule! in boot-9.scm.
;; Define (%app) and (%app modules), and have (app) alias (%app). This
;; side-effects the-root-module, both to the submodules table and (through
;; module-define-submodule! above) the obarray.
;;
(let ((%app (make-module 31)))
(set-module-name! %app '(%app))
(module-define-submodule! the-root-module '%app %app)
(module-define-submodule! the-root-module 'app %app)
(module-define-submodule! %app 'modules (resolve-module '() #f)))
;; Allow code that poked %module-public-interface to keep on working.
;;
(set! module-public-interface
(let ((getter module-public-interface))
(lambda (mod)
(or (getter mod)
(cond
((and=> (module-local-variable mod '%module-public-interface)
variable-ref)
=> (lambda (iface)
(issue-deprecation-warning
"Setting a module's public interface via munging %module-public-interface is
deprecated. Use set-module-public-interface! instead.")
(set-module-public-interface! mod iface)
iface))
(else #f))))))
(set! set-module-public-interface!
(let ((setter set-module-public-interface!))
(lambda (mod iface)
(setter mod iface)
(module-define! mod '%module-public-interface iface))))
(define (bad-throw key . args)
(issue-deprecation-warning
"`bad-throw' in the default environment is deprecated.
Find it in the `(ice-9 scm-style-repl)' module instead.")
(apply (@ (ice-9 scm-style-repl) bad-throw) key args))
(define (error-catching-loop thunk)
(issue-deprecation-warning
"`error-catching-loop' in the default environment is deprecated.
Find it in the `(ice-9 scm-style-repl)' module instead.")
((@ (ice-9 scm-style-repl) error-catching-loop) thunk))
(define (error-catching-repl r e p)
(issue-deprecation-warning
"`error-catching-repl' in the default environment is deprecated.
Find it in the `(ice-9 scm-style-repl)' module instead.")
((@ (ice-9 scm-style-repl) error-catching-repl) r e p))
(define (scm-style-repl)
(issue-deprecation-warning
"`scm-style-repl' in the default environment is deprecated.
Find it in the `(ice-9 scm-style-repl)' module instead, or
better yet, use the repl from `(system repl repl)'.")
((@ (ice-9 scm-style-repl) scm-style-repl)))
;;; Apply-to-args had the following comment attached to it in boot-9, but it's
;;; wrong-headed: in the mentioned case, a point should either be a record or
;;; multiple values.
;;;
;;; apply-to-args is functionally redundant with apply and, worse,
;;; is less general than apply since it only takes two arguments.
;;;
;;; On the other hand, apply-to-args is a syntacticly convenient way to
;;; perform binding in many circumstances when the "let" family of
;;; of forms don't cut it. E.g.:
;;;
;;; (apply-to-args (return-3d-mouse-coords)
;;; (lambda (x y z)
;;; ...))
;;;
(define (apply-to-args args fn)
(issue-deprecation-warning
"`apply-to-args' is deprecated. Include a local copy in your program.")
(apply fn args))
(define (has-suffix? str suffix)
(issue-deprecation-warning
"`has-suffix?' is deprecated. Use `string-suffix?' instead (args reversed).")
(string-suffix? suffix str))
(define scheme-file-suffix
(lambda ()
(issue-deprecation-warning
"`scheme-file-suffix' is deprecated. Use `%load-extensions' instead.")
".scm"))
;;; {Command Line Options}
;;;
(define (get-option argv kw-opts kw-args return)
(issue-deprecation-warning
"`get-option' is deprecated. Use `(ice-9 getopt-long)' instead.")
(cond
((null? argv)
(return #f #f argv))
((or (not (eq? #\- (string-ref (car argv) 0)))
(eq? (string-length (car argv)) 1))
(return 'normal-arg (car argv) (cdr argv)))
((eq? #\- (string-ref (car argv) 1))
(let* ((kw-arg-pos (or (string-index (car argv) #\=)
(string-length (car argv))))
(kw (symbol->keyword (substring (car argv) 2 kw-arg-pos)))
(kw-opt? (member kw kw-opts))
(kw-arg? (member kw kw-args))
(arg (or (and (not (eq? kw-arg-pos (string-length (car argv))))
(substring (car argv)
(+ kw-arg-pos 1)
(string-length (car argv))))
(and kw-arg?
(begin (set! argv (cdr argv)) (car argv))))))
(if (or kw-opt? kw-arg?)
(return kw arg (cdr argv))
(return 'usage-error kw (cdr argv)))))
(else
(let* ((char (substring (car argv) 1 2))
(kw (symbol->keyword char)))
(cond
((member kw kw-opts)
(let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
(new-argv (if (= 0 (string-length rest-car))
(cdr argv)
(cons (string-append "-" rest-car) (cdr argv)))))
(return kw #f new-argv)))
((member kw kw-args)
(let* ((rest-car (substring (car argv) 2 (string-length (car argv))))
(arg (if (= 0 (string-length rest-car))
(cadr argv)
rest-car))
(new-argv (if (= 0 (string-length rest-car))
(cddr argv)
(cdr argv))))
(return kw arg new-argv)))
(else (return 'usage-error kw argv)))))))
(define (for-next-option proc argv kw-opts kw-args)
(issue-deprecation-warning
"`for-next-option' is deprecated. Use `(ice-9 getopt-long)' instead.")
(let loop ((argv argv))
(get-option argv kw-opts kw-args
(lambda (opt opt-arg argv)
(and opt (proc opt opt-arg argv loop))))))
(define (display-usage-report kw-desc)
(issue-deprecation-warning
"`display-usage-report' is deprecated. Use `(ice-9 getopt-long)' instead.")
(for-each
(lambda (kw)
(or (eq? (car kw) #t)
(eq? (car kw) 'else)
(let* ((opt-desc kw)
(help (cadr opt-desc))
(opts (car opt-desc))
(opts-proper (if (string? (car opts)) (cdr opts) opts))
(arg-name (if (string? (car opts))
(string-append "<" (car opts) ">")
""))
(left-part (string-append
(with-output-to-string
(lambda ()
(map (lambda (x) (display (keyword->symbol x)) (display " "))
opts-proper)))
arg-name))
(middle-part (if (and (< (string-length left-part) 30)
(< (string-length help) 40))
(make-string (- 30 (string-length left-part)) #\space)
"\n\t")))
(display left-part)
(display middle-part)
(display help)
(newline))))
kw-desc))
(define (transform-usage-lambda cases)
(issue-deprecation-warning
"`display-usage-report' is deprecated. Use `(ice-9 getopt-long)' instead.")
(let* ((raw-usage (delq! 'else (map car cases)))
(usage-sans-specials (map (lambda (x)
(or (and (not (list? x)) x)
(and (symbol? (car x)) #t)
(and (boolean? (car x)) #t)
x))
raw-usage))
(usage-desc (delq! #t usage-sans-specials))
(kw-desc (map car usage-desc))
(kw-opts (apply append (map (lambda (x) (and (not (string? (car x))) x)) kw-desc)))
(kw-args (apply append (map (lambda (x) (and (string? (car x)) (cdr x))) kw-desc)))
(transmogrified-cases (map (lambda (case)
(cons (let ((opts (car case)))
(if (or (boolean? opts) (eq? 'else opts))
opts
(cond
((symbol? (car opts)) opts)
((boolean? (car opts)) opts)
((string? (caar opts)) (cdar opts))
(else (car opts)))))
(cdr case)))
cases)))
`(let ((%display-usage (lambda () (display-usage-report ',usage-desc))))
(lambda (%argv)
(let %next-arg ((%argv %argv))
(get-option %argv
',kw-opts
',kw-args
(lambda (%opt %arg %new-argv)
(case %opt
,@ transmogrified-cases))))))))
;;; {collect}
;;;
;;; Similar to `begin' but returns a list of the results of all constituent
;;; forms instead of the result of the last form.
;;;
(define-syntax collect
(lambda (x)
(issue-deprecation-warning
"`collect' is deprecated. Define it yourself.")
(syntax-case x ()
((_) #''())
((_ x x* ...)
#'(let ((val x))
(cons val (collect x* ...)))))))
(define (assert-repl-silence v)
(issue-deprecation-warning
"`assert-repl-silence' has moved to `(ice-9 scm-style-repl)'.")
((@ (ice-9 scm-style-repl) assert-repl-silence) v))
(define (assert-repl-print-unspecified v)
(issue-deprecation-warning
"`assert-repl-print-unspecified' has moved to `(ice-9 scm-style-repl)'.")
((@ (ice-9 scm-style-repl) assert-repl-print-unspecified) v))
(define (assert-repl-verbosity v)
(issue-deprecation-warning
"`assert-repl-verbosity' has moved to `(ice-9 scm-style-repl)'.")
((@ (ice-9 scm-style-repl) assert-repl-verbosity) v))
(define (set-repl-prompt! v)
(issue-deprecation-warning
"`set-repl-prompt!' is deprecated. Use `repl-default-prompt-set!' from
the `(system repl common)' module.")
;; Avoid @, as when bootstrapping it will cause the (system repl common)
;; module to be loaded at expansion time, which eventually loads srfi-1, but
;; that fails due to an unbuilt supporting lib... grrrrrrrrr.
((module-ref (resolve-interface '(system repl common))
'repl-default-prompt-set!)
v))
(define (set-batch-mode?! arg)
(cond
(arg
(issue-deprecation-warning
"`set-batch-mode?!' is deprecated. Use `ensure-batch-mode!' instead.")
(ensure-batch-mode!))
(else
(issue-deprecation-warning
"`set-batch-mode?!' with an argument of `#f' is deprecated. Use the
`*repl-stack*' fluid instead.")
#t)))
(define (repl read evaler print)
(issue-deprecation-warning
"`repl' is deprecated. Define it yourself.")
(let loop ((source (read (current-input-port))))
(print (evaler source))
(loop (read (current-input-port)))))
(define (pre-unwind-handler-dispatch key . args)
(issue-deprecation-warning
"`pre-unwind-handler-dispatch' is deprecated. Use
`default-pre-unwind-handler' from `(ice-9 scm-style-repl)' directly.")
(apply (@ (ice-9 scm-style-repl) default-pre-unwind-handler) key args))
(define (default-pre-unwind-handler key . args)
(issue-deprecation-warning
"`default-pre-unwind-handler' is deprecated. Use it from
`(ice-9 scm-style-repl)' if you need it.")
(apply (@ (ice-9 scm-style-repl) default-pre-unwind-handler) key args))
(define (handle-system-error key . args)
(issue-deprecation-warning
"`handle-system-error' is deprecated. Use it from
`(ice-9 scm-style-repl)' if you need it.")
(apply (@ (ice-9 scm-style-repl) handle-system-error) key args))
(define-syntax stack-saved?
(make-variable-transformer
(lambda (x)
(issue-deprecation-warning
"`stack-saved?' is deprecated. Use it from
`(ice-9 save-stack)' if you need it.")
(syntax-case x (set!)
((set! id val)
(identifier? #'id)
#'(set! (@ (ice-9 save-stack) stack-saved?) val))
(id
(identifier? #'id)
#'(@ (ice-9 save-stack) stack-saved?))))))
(define-syntax the-last-stack
(lambda (x)
(issue-deprecation-warning
"`the-last-stack' is deprecated. Use it from `(ice-9 save-stack)'
if you need it.")
(syntax-case x ()
(id
(identifier? #'id)
#'(@ (ice-9 save-stack) the-last-stack)))))
(define (save-stack . args)
(issue-deprecation-warning
"`save-stack' is deprecated. Use it from `(ice-9 save-stack)' if you need
it.")
(apply (@ (ice-9 save-stack) save-stack) args))
(define (named-module-use! user usee)
(issue-deprecation-warning
"`named-module-use!' is deprecated. Define it yourself if you need it.")
(module-use! (resolve-module user) (resolve-interface usee)))
(define (top-repl)
(issue-deprecation-warning
"`top-repl' has moved to the `(ice-9 top-repl)' module.")
((module-ref (resolve-module '(ice-9 top-repl)) 'top-repl)))
(set! debug-enable
(let ((debug-enable debug-enable))
(lambda opts
(if (memq 'debug opts)
(begin
(issue-deprecation-warning
"`(debug-enable 'debug)' is obsolete and has no effect."
"Remove it from your code.")
(apply debug-enable (delq 'debug opts)))
(apply debug-enable opts)))))
(define (turn-on-debugging)
(issue-deprecation-warning
"`(turn-on-debugging)' is obsolete and usually has no effect."
"Debugging capabilities are present by default.")
(debug-enable 'backtrace)
(read-enable 'positions))
(define (read-hash-procedures-warning)
(issue-deprecation-warning
"`read-hash-procedures' is deprecated."
"Use the fluid `%read-hash-procedures' instead."))
(define-syntax read-hash-procedures
(identifier-syntax
(_
(begin (read-hash-procedures-warning)
(fluid-ref %read-hash-procedures)))
((set! _ expr)
(begin (read-hash-procedures-warning)
(fluid-set! %read-hash-procedures expr)))))
(define (process-define-module args)
(define (missing kw)
(error "missing argument to define-module keyword" kw))
(define (unrecognized arg)
(error "unrecognized define-module argument" arg))
(issue-deprecation-warning
"`process-define-module' is deprecated. Use `define-module*' instead.")
(let ((name (car args))
(filename #f)
(pure? #f)
(version #f)
(system? #f)
(duplicates '())
(transformer #f))
(let loop ((kws (cdr args))
(imports '())
(exports '())
(re-exports '())
(replacements '())
(autoloads '()))
(if (null? kws)
(define-module* name
#\filename filename #\pure pure? #\version version
#\duplicates duplicates #\transformer transformer
#\imports (reverse! imports)
#\exports exports
#\re-exports re-exports
#\replacements replacements
#\autoloads autoloads)
(case (car kws)
((#\use-module #\use-syntax)
(or (pair? (cdr kws))
(missing (car kws)))
(cond
((equal? (cadr kws) '(ice-9 syncase))
(issue-deprecation-warning
"(ice-9 syncase) is deprecated. Support for syntax-case is now in Guile core.")
(loop (cddr kws)
imports exports re-exports replacements autoloads))
(else
(let ((iface-spec (cadr kws)))
(if (eq? (car kws) #\use-syntax)
(set! transformer iface-spec))
(loop (cddr kws)
(cons iface-spec imports) exports re-exports
replacements autoloads)))))
((#\autoload)
(or (and (pair? (cdr kws)) (pair? (cddr kws)))
(missing (car kws)))
(let ((name (cadr kws))
(bindings (caddr kws)))
(loop (cdddr kws)
imports exports re-exports
replacements (cons* name bindings autoloads))))
((#\no-backtrace)
;; FIXME: deprecate?
(set! system? #t)
(loop (cdr kws)
imports exports re-exports replacements autoloads))
((#\pure)
(set! pure? #t)
(loop (cdr kws)
imports exports re-exports replacements autoloads))
((#\version)
(or (pair? (cdr kws))
(missing (car kws)))
(set! version (cadr kws))
(loop (cddr kws)
imports exports re-exports replacements autoloads))
((#\duplicates)
(if (not (pair? (cdr kws)))
(missing (car kws)))
(set! duplicates (cadr kws))
(loop (cddr kws)
imports exports re-exports replacements autoloads))
((#\export #\export-syntax)
(or (pair? (cdr kws))
(missing (car kws)))
(loop (cddr kws)
imports (append exports (cadr kws)) re-exports
replacements autoloads))
((#\re-export #\re-export-syntax)
(or (pair? (cdr kws))
(missing (car kws)))
(loop (cddr kws)
imports exports (append re-exports (cadr kws))
replacements autoloads))
((#\replace #\replace-syntax)
(or (pair? (cdr kws))
(missing (car kws)))
(loop (cddr kws)
imports exports re-exports
(append replacements (cadr kws)) autoloads))
((#\filename)
(or (pair? (cdr kws))
(missing (car kws)))
(set! filename (cadr kws))
(loop (cddr kws)
imports exports re-exports replacements autoloads))
(else
(unrecognized kws)))))))
(define-syntax fluid-let-syntax
(lambda (x)
(issue-deprecation-warning
"`fluid-let-syntax' is deprecated. Use syntax parameters instead.")
(syntax-case x ()
((_ ((k v) ...) body0 body ...)
#'(syntax-parameterize ((k v) ...)
body0 body ...)))))
(define (close-io-port port)
(issue-deprecation-warning
"`close-io-port' is deprecated. Use `close-port' instead.")
(close-port port))
(define (set-system-module! m s)
(issue-deprecation-warning
"`set-system-module!' is deprecated. There is no need to use it.")
(set-procedure-property! (module-eval-closure m) 'system-module s))
(set! module-eval-closure
(lambda (m)
(issue-deprecation-warning
"`module-eval-closure' is deprecated. Use module-variable or module-define! instead.")
(standard-eval-closure m)))
;; Legacy definition. We can't make it identifier-syntax yet though,
;; because compiled code might rely on it.
(define char-code-limit 256)
;;;; Copyright (C) 2000,2001, 2002, 2003, 2006, 2009, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; * This module exports:
;;
;; file-commentary -- a procedure that returns a file's "commentary"
;;
;; documentation-files -- a search-list of files using the Guile
;; Documentation Format Version 2.
;;
;; search-documentation-files -- a procedure that takes NAME (a symbol)
;; and searches `documentation-files' for
;; associated documentation. optional
;; arg FILES is a list of filenames to use
;; instead of `documentation-files'.
;;
;; object-documentation -- a procedure that returns its arg's docstring
;;
;; * Guile Documentation Format
;;
;; Here is the complete and authoritative documentation for the Guile
;; Documentation Format Version 2:
;;
;; HEADER
;; ^LPROC1
;; DOCUMENTATION1
;;
;; ^LPROC2
;; DOCUMENTATION2
;;
;; ^L...
;;
;; The HEADER is completely ignored. The "^L" are formfeeds. PROC1, PROC2
;; and so on are symbols that name the element documented. DOCUMENTATION1,
;; DOCUMENTATION2 and so on are the related documentation, w/o any further
;; formatting. Note that there are two newlines before the next formfeed;
;; these are discarded when the documentation is read in.
;;
;; (Version 1, corresponding to guile-1.4 and prior, is documented as being
;; not documented anywhere except by this embarrassingly circular comment.)
;;
;; * File Commentary
;;
;; A file's commentary is the body of text found between comments
;; ;;; Commentary:
;; and
;; ;;; Code:
;; both of which must be at the beginning of the line. In the result string,
;; semicolons at the beginning of each line are discarded.
;;
;; You can specify to `file-commentary' alternate begin and end strings, and
;; scrub procedure. Use #t to get default values. For example:
;;
;; (file-commentary "documentation.scm")
;; You should see this text!
;;
;; (file-commentary "documentation.scm" "^;;; Code:" "ends here$")
;; You should see the rest of this file.
;;
;; (file-commentary "documentation.scm" #t #t string-upcase)
;; You should see this text very loudly (note semicolons untouched).
;;; Code:
(define-module (ice-9 documentation)
\:use-module (ice-9 rdelim)
\:export (file-commentary
documentation-files search-documentation-files
object-documentation)
\:autoload (ice-9 regex) (match:suffix)
\:no-backtrace)
;;
;; commentary extraction
;;
(define (file-commentary filename . cust) ; (IN-LINE-RE AFTER-LINE-RE SCRUB)
;; These are constants but are not at the top level because the repl in
;; boot-9.scm loads session.scm which in turn loads this file, and we want
;; that to work even even when regexps are not available (ie. make-regexp
;; doesn't exist), as for instance is the case on mingw.
;;
(define default-in-line-re (make-regexp "^;;; Commentary:"))
(define default-after-line-re (make-regexp "^;;; Code:"))
(define default-scrub (let ((dirt (make-regexp "^;+")))
(lambda (line)
(let ((m (regexp-exec dirt line)))
(if m (match:suffix m) line)))))
;; fixme: might be cleaner to use optargs here...
(let ((in-line-re (if (> 1 (length cust))
default-in-line-re
(let ((v (car cust)))
(cond ((regexp? v) v)
((string? v) (make-regexp v))
(else default-in-line-re)))))
(after-line-re (if (> 2 (length cust))
default-after-line-re
(let ((v (cadr cust)))
(cond ((regexp? v) v)
((string? v) (make-regexp v))
(else default-after-line-re)))))
(scrub (if (> 3 (length cust))
default-scrub
(let ((v (caddr cust)))
(cond ((procedure? v) v)
(else default-scrub))))))
(call-with-input-file filename
(lambda (port)
(let loop ((line (read-delimited "\n" port))
(doc "")
(parse-state 'before))
(if (or (eof-object? line) (eq? 'after parse-state))
doc
(let ((new-state
(cond ((regexp-exec in-line-re line) 'in)
((regexp-exec after-line-re line) 'after)
(else parse-state))))
(if (eq? 'after new-state)
doc
(loop (read-delimited "\n" port)
(if (and (eq? 'in new-state) (eq? 'in parse-state))
(string-append doc (scrub line) "\n")
doc)
new-state)))))))))
;;
;; documentation-files is the list of places to look for documentation
;;
(define documentation-files
(map (lambda (vicinity)
(in-vicinity (vicinity) "guile-procedures.txt"))
(list %library-dir
%package-data-dir
%site-dir
(lambda () "."))))
(define entry-delimiter "\f")
(define (find-documentation-in-file name file)
(and (file-exists? file)
(call-with-input-file file
(lambda (port)
(let ((name (symbol->string name)))
(let ((len (string-length name)))
(read-delimited entry-delimiter port) ;skip to first entry
(let loop ((entry (read-delimited entry-delimiter port)))
(cond ((eof-object? entry) #f)
;; match?
((and ;; large enough?
(>= (string-length entry) len)
;; matching name?
(string=? (substring entry 0 len) name)
;; terminated?
(memq (string-ref entry len) '(#\newline)))
;; cut away name tag and extra surrounding newlines
(substring entry (+ len 2) (- (string-length entry) 2)))
(else (loop (read-delimited entry-delimiter port)))))))))))
(define (search-documentation-files name . files)
(or-map (lambda (file)
(find-documentation-in-file name file))
(cond ((null? files) documentation-files)
(else files))))
(define (object-documentation object)
"Return the docstring for OBJECT.
OBJECT can be a procedure, macro or any object that has its
`documentation' property set."
(or (and (procedure? object)
(procedure-documentation object))
(object-property object 'documentation)
(and (macro? object)
(object-documentation (macro-transformer object)))
(and (procedure? object)
(procedure-name object)
(let ((docstring (search-documentation-files
(procedure-name object))))
(if docstring
(set-procedure-property! object 'documentation docstring))
docstring))))
;;; documentation.scm ends here
;;; Evaluating code from users
;;; Copyright (C) 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (ice-9 eval-string)
#\use-module (system base compile)
#\use-module (system base language)
#\use-module (system vm program)
#\replace (eval-string))
(define (ensure-language x)
(if (language? x)
x
(lookup-language x)))
(define* (read-and-eval port #\key (lang (current-language)))
(parameterize ((current-language (ensure-language lang)))
(define (read)
((language-reader (current-language)) port (current-module)))
(define (eval exp)
((language-evaluator (current-language)) exp (current-module)))
(let ((exp (read)))
(if (eof-object? exp)
;; The behavior of read-and-compile and of the old
;; eval-string.
*unspecified*
(let lp ((exp exp))
(call-with-values
(lambda () (eval exp))
(lambda vals
(let ((next (read)))
(cond
((eof-object? next)
(apply values vals))
(else
(lp next)))))))))))
(define* (eval-string str #\key
(module (current-module))
(file #f)
(line #f)
(column #f)
(lang (current-language))
(compile? #f))
(define (maybe-with-module module thunk)
(if module
(save-module-excursion
(lambda ()
(set-current-module module)
(thunk)))
(thunk)))
(let ((lang (ensure-language lang)))
(call-with-input-string
str
(lambda (port)
(maybe-with-module
module
(lambda ()
(if module
(set-current-module module))
(if file
(set-port-filename! port file))
(if line
(set-port-line! port line))
(if column
(set-port-column! port line))
(if (or compile? (not (language-evaluator lang)))
((make-program (read-and-compile port #\from lang #\to 'objcode)))
(read-and-eval port #\lang lang))))))))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;; Copyright (C) 2009, 2010, 2012, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; Scheme eval, written in Scheme.
;;;
;;; Expressions are first expanded, by the syntax expander (i.e.
;;; psyntax), then memoized into internal forms. The evaluator itself
;;; only operates on the internal forms ("memoized expressions").
;;;
;;; Environments are represented as linked lists of the form (VAL ... .
;;; MOD). If MOD is #f, it means the environment was captured before
;;; modules were booted. If MOD is the literal value '(), we are
;;; evaluating at the top level, and so should track changes to the
;;; current module.
;;;
;;; Evaluate this in Emacs to make code indentation work right:
;;;
;;; (put 'memoized-expression-case 'scheme-indent-function 1)
;;;
;;; Code:
(eval-when (compile)
(define-syntax capture-env
(syntax-rules ()
((_ (exp ...))
(let ((env (exp ...)))
(capture-env env)))
((_ env)
(if (null? env)
(current-module)
(if (not env)
;; the and current-module checks that modules are booted,
;; and thus the-root-module is defined
(and (current-module) the-root-module)
env)))))
;; Fast case for procedures with fixed arities.
(define-syntax make-fixed-closure
(lambda (x)
(define *max-static-argument-count* 8)
(define (make-formals n)
(map (lambda (i)
(datum->syntax
x
(string->symbol
(string (integer->char (+ (char->integer #\a) i))))))
(iota n)))
(syntax-case x ()
((_ eval nreq body env) (not (identifier? #'env))
#'(let ((e env))
(make-fixed-closure eval nreq body e)))
((_ eval nreq body env)
#`(case nreq
#,@(map (lambda (nreq)
(let ((formals (make-formals nreq)))
#`((#,nreq)
(lambda (#,@formals)
(eval body
(cons* #,@(reverse formals) env))))))
(iota *max-static-argument-count*))
(else
#,(let ((formals (make-formals *max-static-argument-count*)))
#`(lambda (#,@formals . more)
(let lp ((new-env (cons* #,@(reverse formals) env))
(nreq (- nreq #,*max-static-argument-count*))
(args more))
(if (zero? nreq)
(eval body
(if (null? args)
new-env
(scm-error 'wrong-number-of-args
"eval" "Wrong number of arguments"
'() #f)))
(if (null? args)
(scm-error 'wrong-number-of-args
"eval" "Wrong number of arguments"
'() #f)
(lp (cons (car args) new-env)
(1- nreq)
(cdr args)))))))))))))
(define-syntax call
(lambda (x)
(define *max-static-call-count* 4)
(syntax-case x ()
((_ eval proc nargs args env) (identifier? #'env)
#`(case nargs
#,@(map (lambda (nargs)
#`((#,nargs)
(proc
#,@(map
(lambda (n)
(let lp ((n n) (args #'args))
(if (zero? n)
#`(eval (car #,args) env)
(lp (1- n) #`(cdr #,args)))))
(iota nargs)))))
(iota *max-static-call-count*))
(else
(apply proc
#,@(map
(lambda (n)
(let lp ((n n) (args #'args))
(if (zero? n)
#`(eval (car #,args) env)
(lp (1- n) #`(cdr #,args)))))
(iota *max-static-call-count*))
(let lp ((exps #,(let lp ((n *max-static-call-count*)
(args #'args))
(if (zero? n)
args
(lp (1- n) #`(cdr #,args)))))
(args '()))
(if (null? exps)
(reverse args)
(lp (cdr exps)
(cons (eval (car exps) env) args)))))))))))
;; This macro could be more straightforward if the compiler had better
;; copy propagation. As it is we do some copy propagation by hand.
(define-syntax mx-bind
(lambda (x)
(syntax-case x ()
((_ data () body)
#'body)
((_ data (a . b) body) (and (identifier? #'a) (identifier? #'b))
#'(let ((a (car data))
(b (cdr data)))
body))
((_ data (a . b) body) (identifier? #'a)
#'(let ((a (car data))
(xb (cdr data)))
(mx-bind xb b body)))
((_ data (a . b) body)
#'(let ((xa (car data))
(xb (cdr data)))
(mx-bind xa a (mx-bind xb b body))))
((_ data v body) (identifier? #'v)
#'(let ((v data))
body)))))
;; The resulting nested if statements will be an O(n) dispatch. Once
;; we compile `case' effectively, this situation will improve.
(define-syntax mx-match
(lambda (x)
(syntax-case x (quote)
((_ mx data tag)
#'(error "what" mx))
((_ mx data tag (('type pat) body) c* ...)
#`(if (eqv? tag #,(or (memoized-typecode (syntax->datum #'type))
(error "not a typecode" #'type)))
(mx-bind data pat body)
(mx-match mx data tag c* ...))))))
(define-syntax memoized-expression-case
(lambda (x)
(syntax-case x ()
((_ mx c ...)
#'(let ((tag (memoized-expression-typecode mx))
(data (memoized-expression-data mx)))
(mx-match mx data tag c ...)))))))
;;;
;;; On 18 Feb 2010, I did a profile of how often the various memoized expression
;;; types occur when getting to a prompt on a fresh build. Here are the numbers
;;; I got:
;;;
;;; lexical-ref: 32933054
;;; call: 20281547
;;; toplevel-ref: 13228724
;;; if: 9156156
;;; quote: 6610137
;;; let: 2619707
;;; lambda: 1010921
;;; begin: 948945
;;; lexical-set: 509862
;;; call-with-values: 139668
;;; apply: 49402
;;; module-ref: 14468
;;; define: 1259
;;; toplevel-set: 328
;;; dynwind: 162
;;; with-fluids: 0
;;; call/cc: 0
;;; module-set: 0
;;;
;;; So until we compile `case' into a computed goto, we'll order the clauses in
;;; `eval' in this order, to put the most frequent cases first.
;;;
(define primitive-eval
(let ()
;; We pre-generate procedures with fixed arities, up to some number of
;; arguments; see make-fixed-closure above.
;; A unique marker for unbound keywords.
(define unbound-arg (list 'unbound-arg))
;; Procedures with rest, optional, or keyword arguments, potentially with
;; multiple arities, as with case-lambda.
(define (make-general-closure env body nreq rest? nopt kw inits alt)
(define alt-proc
(and alt ; (body docstring nreq ...)
(let* ((body (car alt))
(spec (cddr alt))
(nreq (car spec))
(rest (if (null? (cdr spec)) #f (cadr spec)))
(tail (and (pair? (cdr spec)) (pair? (cddr spec)) (cddr spec)))
(nopt (if tail (car tail) 0))
(kw (and tail (cadr tail)))
(inits (if tail (caddr tail) '()))
(alt (and tail (cadddr tail))))
(make-general-closure env body nreq rest nopt kw inits alt))))
(define (set-procedure-arity! proc)
(let lp ((alt alt) (nreq nreq) (nopt nopt) (rest? rest?))
(if (not alt)
(begin
(set-procedure-property! proc 'arglist
(list nreq
nopt
(if kw (cdr kw) '())
(and kw (car kw))
(and rest? '_)))
(set-procedure-minimum-arity! proc nreq nopt rest?))
(let* ((spec (cddr alt))
(nreq* (car spec))
(rest?* (if (null? (cdr spec)) #f (cadr spec)))
(tail (and (pair? (cdr spec)) (pair? (cddr spec)) (cddr spec)))
(nopt* (if tail (car tail) 0))
(alt* (and tail (cadddr tail))))
(if (or (< nreq* nreq)
(and (= nreq* nreq)
(if rest?
(and rest?* (> nopt* nopt))
(or rest?* (> nopt* nopt)))))
(lp alt* nreq* nopt* rest?*)
(lp alt* nreq nopt rest?)))))
proc)
(set-procedure-arity!
(lambda %args
(let lp ((env env)
(nreq* nreq)
(args %args))
(if (> nreq* 0)
;; First, bind required arguments.
(if (null? args)
(if alt
(apply alt-proc %args)
(scm-error 'wrong-number-of-args
"eval" "Wrong number of arguments"
'() #f))
(lp (cons (car args) env)
(1- nreq*)
(cdr args)))
;; Move on to optional arguments.
(if (not kw)
;; Without keywords, bind optionals from arguments.
(let lp ((env env)
(nopt nopt)
(args args)
(inits inits))
(if (zero? nopt)
(if rest?
(eval body (cons args env))
(if (null? args)
(eval body env)
(if alt
(apply alt-proc %args)
(scm-error 'wrong-number-of-args
"eval" "Wrong number of arguments"
'() #f))))
(if (null? args)
(lp (cons (eval (car inits) env) env)
(1- nopt) args (cdr inits))
(lp (cons (car args) env)
(1- nopt) (cdr args) (cdr inits)))))
(let lp ((env env)
(nopt* nopt)
(args args)
(inits inits))
(cond
;; With keywords, we stop binding optionals at the
;; first keyword.
((> nopt* 0)
(if (or (null? args) (keyword? (car args)))
(lp (cons (eval (car inits) env) env)
(1- nopt*) args (cdr inits))
(lp (cons (car args) env)
(1- nopt*) (cdr args) (cdr inits))))
;; Finished with optionals.
((and alt (pair? args) (not (keyword? (car args)))
(not rest?))
;; Too many positional args, no #\rest arg,
;; and we have an alternate.
(apply alt-proc %args))
(else
(let* ((aok (car kw))
(kw (cdr kw))
(kw-base (+ nopt nreq (if rest? 1 0)))
(imax (let lp ((imax (1- kw-base)) (kw kw))
(if (null? kw)
imax
(lp (max (cdar kw) imax)
(cdr kw)))))
;; Fill in kwargs with "undefined" vals.
(env (let lp ((i kw-base)
;; Also, here we bind the rest
;; arg, if any.
(env (if rest?
(cons args env)
env)))
(if (<= i imax)
(lp (1+ i) (cons unbound-arg env))
env))))
;; Now scan args for keywords.
(let lp ((args args))
(cond
((pair? args)
(cond
((keyword? (car args))
(let ((k (car args))
(args (cdr args)))
(cond
((assq k kw)
=> (lambda (kw-pair)
;; Found a known keyword; set its value.
(if (pair? args)
(let ((v (car args))
(args (cdr args)))
(list-set! env
(- imax (cdr kw-pair))
v)
(lp args))
(scm-error 'keyword-argument-error
"eval"
"Keyword argument has no value"
'() (list k)))))
;; Otherwise unknown keyword.
(aok
(lp (if (pair? args) (cdr args) args)))
(else
(scm-error 'keyword-argument-error
"eval" "Unrecognized keyword"
'() (list k))))))
(rest?
;; Be lenient parsing rest args.
(lp (cdr args)))
(else
(scm-error 'keyword-argument-error
"eval" "Invalid keyword"
'() (list (car args))))))
(else
;; Finished parsing keywords. Fill in
;; uninitialized kwargs by evalling init
;; expressions in their appropriate
;; environment.
(let lp ((i (- imax kw-base))
(inits inits))
(if (pair? inits)
(let ((tail (list-tail env i)))
(if (eq? (car tail) unbound-arg)
(set-car! tail
(eval (car inits)
(cdr tail))))
(lp (1- i) (cdr inits)))
;; Finally, eval the body.
(eval body env)))))
)))))))))))
;; The "engine". EXP is a memoized expression.
(define (eval exp env)
(memoized-expression-case exp
(('lexical-ref n)
(list-ref env n))
(('call (f nargs . args))
(let ((proc (eval f env)))
(call eval proc nargs args env)))
(('toplevel-ref var-or-sym)
(variable-ref
(if (variable? var-or-sym)
var-or-sym
(memoize-variable-access! exp
(capture-env (if (pair? env)
(cdr (last-pair env))
env))))))
(('if (test consequent . alternate))
(if (eval test env)
(eval consequent env)
(eval alternate env)))
(('quote x)
x)
(('let (inits . body))
(let lp ((inits inits) (new-env (capture-env env)))
(if (null? inits)
(eval body new-env)
(lp (cdr inits)
(cons (eval (car inits) env) new-env)))))
(('lambda (body docstring nreq . tail))
(let ((proc
(if (null? tail)
(make-fixed-closure eval nreq body (capture-env env))
(if (null? (cdr tail))
(make-general-closure (capture-env env) body
nreq (car tail)
0 #f '() #f)
(apply make-general-closure (capture-env env)
body nreq tail)))))
(when docstring
(set-procedure-property! proc 'documentation docstring))
proc))
(('begin (first . rest))
(let lp ((first first) (rest rest))
(if (null? rest)
(eval first env)
(begin
(eval first env)
(lp (car rest) (cdr rest))))))
(('lexical-set! (n . x))
(let ((val (eval x env)))
(list-set! env n val)))
(('call-with-values (producer . consumer))
(call-with-values (eval producer env)
(eval consumer env)))
(('apply (f args))
(apply (eval f env) (eval args env)))
(('module-ref var-or-spec)
(variable-ref
(if (variable? var-or-spec)
var-or-spec
(memoize-variable-access! exp #f))))
(('define (name . x))
(let ((x (eval x env)))
(if (and (procedure? x) (not (procedure-property x 'name)))
(set-procedure-property! x 'name name))
(define! name x)
(if #f #f)))
(('toplevel-set! (var-or-sym . x))
(variable-set!
(if (variable? var-or-sym)
var-or-sym
(memoize-variable-access! exp
(capture-env (if (pair? env)
(cdr (last-pair env))
env))))
(eval x env)))
(('dynwind (in exp . out))
(dynamic-wind (eval in env)
(lambda () (eval exp env))
(eval out env)))
(('with-fluids (fluids vals . exp))
(let* ((fluids (map (lambda (x) (eval x env)) fluids))
(vals (map (lambda (x) (eval x env)) vals)))
(let lp ((fluids fluids) (vals vals))
(if (null? fluids)
(eval exp env)
(with-fluids (((car fluids) (car vals)))
(lp (cdr fluids) (cdr vals)))))))
(('prompt (tag exp . handler))
(@prompt (eval tag env)
(eval exp env)
(eval handler env)))
(('call/cc proc)
(call/cc (eval proc env)))
(('module-set! (x . var-or-spec))
(variable-set!
(if (variable? var-or-spec)
var-or-spec
(memoize-variable-access! exp #f))
(eval x env)))))
;; primitive-eval
(lambda (exp)
"Evaluate @var{exp} in the current module."
(eval
(memoize-expression
(if (macroexpanded? exp)
exp
((module-transformer (current-module)) exp)))
'()))))
;;;; Copyright (C) 1996, 1998, 1999, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; This module is documented in the Guile Reference Manual.
;; Briefly, these are exported:
;; procedures: expect-select, expect-regexec
;; variables: expect-port, expect-timeout, expect-timeout-proc,
;; expect-eof-proc, expect-char-proc,
;; expect-strings-compile-flags, expect-strings-exec-flags,
;; macros: expect, expect-strings
;;; Code:
(define-module (ice-9 expect)
\:use-module (ice-9 regex)
\:export-syntax (expect expect-strings)
\:export (expect-port expect-timeout expect-timeout-proc
expect-eof-proc expect-char-proc expect-strings-compile-flags
expect-strings-exec-flags expect-select expect-regexec))
;;; Expect: a macro for selecting actions based on what it reads from a port.
;;; The idea is from Don Libes' expect based on Tcl.
;;; This version by Gary Houston incorporating ideas from Aubrey Jaffer.
(define expect-port #f)
(define expect-timeout #f)
(define expect-timeout-proc #f)
(define expect-eof-proc #f)
(define expect-char-proc #f)
;;; expect: each test is a procedure which is applied to the accumulating
;;; string.
(defmacro expect clauses
(let ((s (gensym))
(c (gensym))
(port (gensym))
(timeout (gensym)))
`(let ((,s "")
(,port (or expect-port (current-input-port)))
;; when timeout occurs, in floating point seconds.
(,timeout (if expect-timeout
(let* ((secs-usecs (gettimeofday)))
(+ (car secs-usecs)
expect-timeout
(/ (cdr secs-usecs)
1000000))) ; one million.
#f)))
(let next-char ()
(if (and expect-timeout
(not (expect-select ,port ,timeout)))
(if expect-timeout-proc
(expect-timeout-proc ,s)
#f)
(let ((,c (read-char ,port)))
(if expect-char-proc
(expect-char-proc ,c))
(if (not (eof-object? ,c))
(set! ,s (string-append ,s (string ,c))))
(cond
;; this expands to clauses where the car invokes the
;; match proc and the cdr is the return value from expect
;; if the proc matched.
,@(let next-expr ((tests (map car clauses))
(exprs (map cdr clauses))
(body '()))
(cond
((null? tests)
(reverse body))
(else
(next-expr
(cdr tests)
(cdr exprs)
(cons
`((,(car tests) ,s (eof-object? ,c))
,@(cond ((null? (car exprs))
'())
((eq? (caar exprs) '=>)
(if (not (= (length (car exprs))
2))
(scm-error 'misc-error
"expect"
"bad recipient: ~S"
(list (car exprs))
#f)
`((apply ,(cadar exprs)
(,(car tests) ,s ,port)))))
(else
(car exprs))))
body)))))
;; if none of the clauses matched the current string.
(else (cond ((eof-object? ,c)
(if expect-eof-proc
(expect-eof-proc ,s)
#f))
(else
(next-char)))))))))))
(define expect-strings-compile-flags regexp/newline)
(define expect-strings-exec-flags regexp/noteol)
;;; the regexec front-end to expect:
;;; each test must evaluate to a regular expression.
(defmacro expect-strings clauses
`(let ,@(let next-test ((tests (map car clauses))
(exprs (map cdr clauses))
(defs '())
(body '()))
(cond ((null? tests)
(list (reverse defs) `(expect ,@(reverse body))))
(else
(let ((rxname (gensym)))
(next-test (cdr tests)
(cdr exprs)
(cons `(,rxname (make-regexp
,(car tests)
expect-strings-compile-flags))
defs)
(cons `((lambda (s eof?)
(expect-regexec ,rxname s eof?))
,@(car exprs))
body))))))))
;;; simplified select: returns #t if input is waiting or #f if timed out or
;;; select was interrupted by a signal.
;;; timeout is an absolute time in floating point seconds.
(define (expect-select port timeout)
(let* ((secs-usecs (gettimeofday))
(relative (- timeout
(car secs-usecs)
(/ (cdr secs-usecs)
1000000)))) ; one million.
(and (> relative 0)
(pair? (car (select (list port) '() '()
relative))))))
;;; match a string against a regexp, returning a list of strings (required
;;; by the => syntax) or #f. called once each time a character is added
;;; to s (eof? will be #f), and once when eof is reached (with eof? #t).
(define (expect-regexec rx s eof?)
;; if expect-strings-exec-flags contains regexp/noteol,
;; remove it for the eof test.
(let* ((flags (if (and eof?
(logand expect-strings-exec-flags regexp/noteol))
(logxor expect-strings-exec-flags regexp/noteol)
expect-strings-exec-flags))
(match (regexp-exec rx s 0 flags)))
(if match
(do ((i (- (match:count match) 1) (- i 1))
(result '() (cons (match:substring match i) result)))
((< i 0) result))
#f)))
;;; expect.scm ends here
;;;; "format.scm" Common LISP text output formatter for SLIB
;;; Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;
;;; This code was orignally in the public domain.
;;;
;;; Written 1992-1994 by Dirk Lutzebaeck (lutzeb@cs.tu-berlin.de).
;;;
;;; Authors of the version from SLIB (< 1.4) were Ken Dickey and Aubrey
;;; Jaffer.
;;;
;;; Assimilated into Guile May 1999.
;;;
;;; Please don't bother the original authors with bug reports, though;
;;; send them to bug-guile@gnu.org.
;;;
(define-module (ice-9 format)
#\autoload (ice-9 pretty-print) (pretty-print truncated-print)
#\autoload (ice-9 i18n) (%global-locale number->locale-string)
#\replace (format))
(define format:version "3.0")
(define (format destination format-string . format-args)
(if (not (string? format-string))
(error "format: expected a string for format string" format-string))
(let* ((port
(cond
((not destination)
;; Use a Unicode-capable output string port.
(with-fluids ((%default-port-encoding "UTF-8"))
(open-output-string)))
((boolean? destination) (current-output-port)) ; boolean but not false
((output-port? destination) destination)
((number? destination)
(issue-deprecation-warning
"Passing a number to format as the port is deprecated."
"Pass (current-error-port) instead.")
(current-error-port))
(else
(error "format: bad destination `~a'" destination))))
(output-col (or (port-column port) 0))
(flush-output? #f))
(define format:case-conversion #f)
(define format:pos 0) ; curr. format string parsing position
(define format:arg-pos 0) ; curr. format argument position
; this is global for error presentation
;; format string and char output routines on port
(define (format:out-str str)
(if format:case-conversion
(display (format:case-conversion str) port)
(display str port))
(set! output-col
(+ output-col (string-length str))))
(define (format:out-char ch)
(if format:case-conversion
(display (format:case-conversion (string ch))
port)
(write-char ch port))
(set! output-col
(if (char=? ch #\newline)
0
(+ output-col 1))))
;;(define (format:out-substr str i n) ; this allocates a new string
;; (display (substring str i n) port)
;; (set! output-col (+ output-col n)))
(define (format:out-substr str i n)
(do ((k i (+ k 1)))
((= k n))
(write-char (string-ref str k) port))
(set! output-col (+ output-col (- n i))))
;;(define (format:out-fill n ch) ; this allocates a new string
;; (format:out-str (make-string n ch)))
(define (format:out-fill n ch)
(do ((i 0 (+ i 1)))
((= i n))
(write-char ch port))
(set! output-col (+ output-col n)))
;; format's user error handler
(define (format:error . args) ; never returns!
(let ((port (current-error-port)))
(set! format:error format:intern-error)
(if (not (zero? format:arg-pos))
(set! format:arg-pos (- format:arg-pos 1)))
(format port
"~%FORMAT: error with call: (format ~a \"~a<===~a\" ~
~{~a ~}===>~{~a ~})~% "
destination
(substring format-string 0 format:pos)
(substring format-string format:pos
(string-length format-string))
(list-head format-args format:arg-pos)
(list-tail format-args format:arg-pos))
(apply format port args)
(newline port)
(set! format:error format:error-save)
(format:abort)))
(define (format:intern-error . args)
;;if something goes wrong in format:error
(display "FORMAT: INTERNAL ERROR IN FORMAT:ERROR!") (newline)
(display " destination: ") (write destination) (newline)
(display " format string: ") (write format-string) (newline)
(display " format args: ") (write format-args) (newline)
(display " error args: ") (write args) (newline)
(set! format:error format:error-save)
(format:abort))
(define format:error-save format:error)
(define format:parameter-characters
'(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\- #\+ #\v #\# #\'))
(define (format:format-work format-string arglist) ; does the formatting work
(letrec
((format-string-len (string-length format-string))
(arg-pos 0) ; argument position in arglist
(arg-len (length arglist)) ; number of arguments
(modifier #f) ; 'colon | 'at | 'colon-at | #f
(params '()) ; directive parameter list
(param-value-found #f) ; a directive
; parameter value
; found
(conditional-nest 0) ; conditional nesting level
(clause-pos 0) ; last cond. clause
; beginning char pos
(clause-default #f) ; conditional default
; clause string
(clauses '()) ; conditional clause
; string list
(conditional-type #f) ; reflects the
; contional modifiers
(conditional-arg #f) ; argument to apply the conditional
(iteration-nest 0) ; iteration nesting level
(iteration-pos 0) ; iteration string
; beginning char pos
(iteration-type #f) ; reflects the
; iteration modifiers
(max-iterations #f) ; maximum number of
; iterations
(recursive-pos-save format:pos)
(next-char ; gets the next char
; from format-string
(lambda ()
(let ((ch (peek-next-char)))
(set! format:pos (+ 1 format:pos))
ch)))
(peek-next-char
(lambda ()
(if (>= format:pos format-string-len)
(format:error "illegal format string")
(string-ref format-string format:pos))))
(one-positive-integer?
(lambda (params)
(cond
((null? params) #f)
((and (integer? (car params))
(>= (car params) 0)
(= (length params) 1)) #t)
(else
(format:error
"one positive integer parameter expected")))))
(next-arg
(lambda ()
(if (>= arg-pos arg-len)
(begin
(set! format:arg-pos (+ arg-len 1))
(format:error "missing argument(s)")))
(add-arg-pos 1)
(list-ref arglist (- arg-pos 1))))
(prev-arg
(lambda ()
(add-arg-pos -1)
(if (negative? arg-pos)
(format:error "missing backward argument(s)"))
(list-ref arglist arg-pos)))
(rest-args
(lambda ()
(let loop ((l arglist) (k arg-pos)) ; list-tail definition
(if (= k 0) l (loop (cdr l) (- k 1))))))
(add-arg-pos
(lambda (n)
(set! arg-pos (+ n arg-pos))
(set! format:arg-pos arg-pos)))
(anychar-dispatch ; dispatches the format-string
(lambda ()
(if (>= format:pos format-string-len)
arg-pos ; used for ~? continuance
(let ((char (next-char)))
(cond
((char=? char #\~)
(set! modifier #f)
(set! params '())
(set! param-value-found #f)
(tilde-dispatch))
(else
(if (and (zero? conditional-nest)
(zero? iteration-nest))
(format:out-char char))
(anychar-dispatch)))))))
(tilde-dispatch
(lambda ()
(cond
((>= format:pos format-string-len)
(format:out-str "~") ; tilde at end of
; string is just
; output
arg-pos) ; used for ~?
; continuance
((and (or (zero? conditional-nest)
(memv (peek-next-char) ; find conditional
; directives
(append '(#\[ #\] #\; #\: #\@ #\^)
format:parameter-characters)))
(or (zero? iteration-nest)
(memv (peek-next-char) ; find iteration
; directives
(append '(#\{ #\} #\: #\@ #\^)
format:parameter-characters))))
(case (char-upcase (next-char))
;; format directives
((#\A) ; Any -- for humans
(set! format:read-proof
(memq modifier '(colon colon-at)))
(format:out-obj-padded (memq modifier '(at colon-at))
(next-arg) #f params)
(anychar-dispatch))
((#\S) ; Slashified -- for parsers
(set! format:read-proof
(memq modifier '(colon colon-at)))
(format:out-obj-padded (memq modifier '(at colon-at))
(next-arg) #t params)
(anychar-dispatch))
((#\D) ; Decimal
(format:out-num-padded modifier (next-arg) params 10)
(anychar-dispatch))
((#\H) ; Localized number
(let* ((num (next-arg))
(locale (case modifier
((colon) (next-arg))
(else %global-locale)))
(argc (length params))
(width (format:par params argc 0 #f "width"))
(decimals (format:par params argc 1 #t "decimals"))
(padchar (integer->char
(format:par params argc 2 format:space-ch
"padchar")))
(str (number->locale-string num decimals
locale)))
(format:out-str (if (and width
(< (string-length str) width))
(string-pad str width padchar)
str)))
(anychar-dispatch))
((#\X) ; Hexadecimal
(format:out-num-padded modifier (next-arg) params 16)
(anychar-dispatch))
((#\O) ; Octal
(format:out-num-padded modifier (next-arg) params 8)
(anychar-dispatch))
((#\B) ; Binary
(format:out-num-padded modifier (next-arg) params 2)
(anychar-dispatch))
((#\R)
(if (null? params)
(format:out-obj-padded ; Roman, cardinal,
; ordinal numerals
#f
((case modifier
((at) format:num->roman)
((colon-at) format:num->old-roman)
((colon) format:num->ordinal)
(else format:num->cardinal))
(next-arg))
#f params)
(format:out-num-padded ; any Radix
modifier (next-arg) (cdr params) (car params)))
(anychar-dispatch))
((#\F) ; Fixed-format floating-point
(format:out-fixed modifier (next-arg) params)
(anychar-dispatch))
((#\E) ; Exponential floating-point
(format:out-expon modifier (next-arg) params)
(anychar-dispatch))
((#\G) ; General floating-point
(format:out-general modifier (next-arg) params)
(anychar-dispatch))
((#\$) ; Dollars floating-point
(format:out-dollar modifier (next-arg) params)
(anychar-dispatch))
((#\I) ; Complex numbers
(let ((z (next-arg)))
(if (not (complex? z))
(format:error "argument not a complex number"))
(format:out-fixed modifier (real-part z) params)
(format:out-fixed 'at (imag-part z) params)
(format:out-char #\i))
(anychar-dispatch))
((#\C) ; Character
(let ((ch (if (one-positive-integer? params)
(integer->char (car params))
(next-arg))))
(if (not (char? ch))
(format:error "~~c expects a character"))
(case modifier
((at)
(format:out-str (object->string ch)))
((colon)
(let ((c (char->integer ch)))
(if (< c 0)
(set! c (+ c 256))) ; compensate
; complement
; impl.
(cond
((< c #x20) ; assumes that control
; chars are < #x20
(format:out-char #\^)
(format:out-char
(integer->char (+ c #x40))))
((>= c #x7f)
(format:out-str "#\\")
(format:out-str
(number->string c 8)))
(else
(format:out-char ch)))))
(else (format:out-char ch))))
(anychar-dispatch))
((#\P) ; Plural
(if (memq modifier '(colon colon-at))
(prev-arg))
(let ((arg (next-arg)))
(if (not (number? arg))
(format:error "~~p expects a number argument"))
(if (= arg 1)
(if (memq modifier '(at colon-at))
(format:out-char #\y))
(if (memq modifier '(at colon-at))
(format:out-str "ies")
(format:out-char #\s))))
(anychar-dispatch))
((#\~) ; Tilde
(if (one-positive-integer? params)
(format:out-fill (car params) #\~)
(format:out-char #\~))
(anychar-dispatch))
((#\%) ; Newline
(if (one-positive-integer? params)
(format:out-fill (car params) #\newline)
(format:out-char #\newline))
(set! output-col 0)
(anychar-dispatch))
((#\&) ; Fresh line
(if (one-positive-integer? params)
(begin
(if (> (car params) 0)
(format:out-fill (- (car params)
(if (>
output-col
0) 0 1))
#\newline))
(set! output-col 0))
(if (> output-col 0)
(format:out-char #\newline)))
(anychar-dispatch))
((#\_) ; Space character
(if (one-positive-integer? params)
(format:out-fill (car params) #\space)
(format:out-char #\space))
(anychar-dispatch))
((#\/) ; Tabulator character
(if (one-positive-integer? params)
(format:out-fill (car params) #\tab)
(format:out-char #\tab))
(anychar-dispatch))
((#\|) ; Page seperator
(if (one-positive-integer? params)
(format:out-fill (car params) #\page)
(format:out-char #\page))
(set! output-col 0)
(anychar-dispatch))
((#\T) ; Tabulate
(format:tabulate modifier params)
(anychar-dispatch))
((#\Y) ; Structured print
(let ((width (if (one-positive-integer? params)
(car params)
79)))
(case modifier
((at)
(format:out-str
(call-with-output-string
(lambda (p)
(truncated-print (next-arg) p
#\width width)))))
((colon-at)
(format:out-str
(call-with-output-string
(lambda (p)
(truncated-print (next-arg) p
#\width
(max (- width
output-col)
1))))))
((colon)
(format:error "illegal modifier in ~~?"))
(else
(pretty-print (next-arg) port
#\width width)
(set! output-col 0))))
(anychar-dispatch))
((#\? #\K) ; Indirection (is "~K" in T-Scheme)
(cond
((memq modifier '(colon colon-at))
(format:error "illegal modifier in ~~?"))
((eq? modifier 'at)
(let* ((frmt (next-arg))
(args (rest-args)))
(add-arg-pos (format:format-work frmt args))))
(else
(let* ((frmt (next-arg))
(args (next-arg)))
(format:format-work frmt args))))
(anychar-dispatch))
((#\!) ; Flush output
(set! flush-output? #t)
(anychar-dispatch))
((#\newline) ; Continuation lines
(if (eq? modifier 'at)
(format:out-char #\newline))
(if (< format:pos format-string-len)
(do ((ch (peek-next-char) (peek-next-char)))
((or (not (char-whitespace? ch))
(= format:pos (- format-string-len 1))))
(if (eq? modifier 'colon)
(format:out-char (next-char))
(next-char))))
(anychar-dispatch))
((#\*) ; Argument jumping
(case modifier
((colon) ; jump backwards
(if (one-positive-integer? params)
(do ((i 0 (+ i 1)))
((= i (car params)))
(prev-arg))
(prev-arg)))
((at) ; jump absolute
(set! arg-pos (if (one-positive-integer? params)
(car params) 0)))
((colon-at)
(format:error "illegal modifier `:@' in ~~* directive"))
(else ; jump forward
(if (one-positive-integer? params)
(do ((i 0 (+ i 1)))
((= i (car params)))
(next-arg))
(next-arg))))
(anychar-dispatch))
((#\() ; Case conversion begin
(set! format:case-conversion
(case modifier
((at) string-capitalize-first)
((colon) string-capitalize)
((colon-at) string-upcase)
(else string-downcase)))
(anychar-dispatch))
((#\)) ; Case conversion end
(if (not format:case-conversion)
(format:error "missing ~~("))
(set! format:case-conversion #f)
(anychar-dispatch))
((#\[) ; Conditional begin
(set! conditional-nest (+ conditional-nest 1))
(cond
((= conditional-nest 1)
(set! clause-pos format:pos)
(set! clause-default #f)
(set! clauses '())
(set! conditional-type
(case modifier
((at) 'if-then)
((colon) 'if-else-then)
((colon-at) (format:error "illegal modifier in ~~["))
(else 'num-case)))
(set! conditional-arg
(if (one-positive-integer? params)
(car params)
(next-arg)))))
(anychar-dispatch))
((#\;) ; Conditional separator
(if (zero? conditional-nest)
(format:error "~~; not in ~~[~~] conditional"))
(if (not (null? params))
(format:error "no parameter allowed in ~~;"))
(if (= conditional-nest 1)
(let ((clause-str
(cond
((eq? modifier 'colon)
(set! clause-default #t)
(substring format-string clause-pos
(- format:pos 3)))
((memq modifier '(at colon-at))
(format:error "illegal modifier in ~~;"))
(else
(substring format-string clause-pos
(- format:pos 2))))))
(set! clauses (append clauses (list clause-str)))
(set! clause-pos format:pos)))
(anychar-dispatch))
((#\]) ; Conditional end
(if (zero? conditional-nest) (format:error "missing ~~["))
(set! conditional-nest (- conditional-nest 1))
(if modifier
(format:error "no modifier allowed in ~~]"))
(if (not (null? params))
(format:error "no parameter allowed in ~~]"))
(cond
((zero? conditional-nest)
(let ((clause-str (substring format-string clause-pos
(- format:pos 2))))
(if clause-default
(set! clause-default clause-str)
(set! clauses (append clauses (list clause-str)))))
(case conditional-type
((if-then)
(if conditional-arg
(format:format-work (car clauses)
(list conditional-arg))))
((if-else-then)
(add-arg-pos
(format:format-work (if conditional-arg
(cadr clauses)
(car clauses))
(rest-args))))
((num-case)
(if (or (not (integer? conditional-arg))
(< conditional-arg 0))
(format:error "argument not a positive integer"))
(if (not (and (>= conditional-arg (length clauses))
(not clause-default)))
(add-arg-pos
(format:format-work
(if (>= conditional-arg (length clauses))
clause-default
(list-ref clauses conditional-arg))
(rest-args))))))))
(anychar-dispatch))
((#\{) ; Iteration begin
(set! iteration-nest (+ iteration-nest 1))
(cond
((= iteration-nest 1)
(set! iteration-pos format:pos)
(set! iteration-type
(case modifier
((at) 'rest-args)
((colon) 'sublists)
((colon-at) 'rest-sublists)
(else 'list)))
(set! max-iterations (if (one-positive-integer? params)
(car params) #f))))
(anychar-dispatch))
((#\}) ; Iteration end
(if (zero? iteration-nest) (format:error "missing ~~{"))
(set! iteration-nest (- iteration-nest 1))
(case modifier
((colon)
(if (not max-iterations) (set! max-iterations 1)))
((colon-at at) (format:error "illegal modifier")))
(if (not (null? params))
(format:error "no parameters allowed in ~~}"))
(if (zero? iteration-nest)
(let ((iteration-str
(substring format-string iteration-pos
(- format:pos (if modifier 3 2)))))
(if (string=? iteration-str "")
(set! iteration-str (next-arg)))
(case iteration-type
((list)
(let ((args (next-arg))
(args-len 0))
(if (not (list? args))
(format:error "expected a list argument"))
(set! args-len (length args))
(do ((arg-pos 0 (+ arg-pos
(format:format-work
iteration-str
(list-tail args arg-pos))))
(i 0 (+ i 1)))
((or (>= arg-pos args-len)
(and max-iterations
(>= i max-iterations)))))))
((sublists)
(let ((args (next-arg))
(args-len 0))
(if (not (list? args))
(format:error "expected a list argument"))
(set! args-len (length args))
(do ((arg-pos 0 (+ arg-pos 1)))
((or (>= arg-pos args-len)
(and max-iterations
(>= arg-pos max-iterations))))
(let ((sublist (list-ref args arg-pos)))
(if (not (list? sublist))
(format:error
"expected a list of lists argument"))
(format:format-work iteration-str sublist)))))
((rest-args)
(let* ((args (rest-args))
(args-len (length args))
(usedup-args
(do ((arg-pos 0 (+ arg-pos
(format:format-work
iteration-str
(list-tail
args arg-pos))))
(i 0 (+ i 1)))
((or (>= arg-pos args-len)
(and max-iterations
(>= i max-iterations)))
arg-pos))))
(add-arg-pos usedup-args)))
((rest-sublists)
(let* ((args (rest-args))
(args-len (length args))
(usedup-args
(do ((arg-pos 0 (+ arg-pos 1)))
((or (>= arg-pos args-len)
(and max-iterations
(>= arg-pos max-iterations)))
arg-pos)
(let ((sublist (list-ref args arg-pos)))
(if (not (list? sublist))
(format:error "expected list arguments"))
(format:format-work iteration-str sublist)))))
(add-arg-pos usedup-args)))
(else (format:error "internal error in ~~}")))))
(anychar-dispatch))
((#\^) ; Up and out
(let* ((continue
(cond
((not (null? params))
(not
(case (length params)
((1) (zero? (car params)))
((2) (= (list-ref params 0) (list-ref params 1)))
((3) (<= (list-ref params 0)
(list-ref params 1)
(list-ref params 2)))
(else (format:error "too much parameters")))))
(format:case-conversion ; if conversion stop conversion
(set! format:case-conversion string-copy) #t)
((= iteration-nest 1) #t)
((= conditional-nest 1) #t)
((>= arg-pos arg-len)
(set! format:pos format-string-len) #f)
(else #t))))
(if continue
(anychar-dispatch))))
;; format directive modifiers and parameters
((#\@) ; `@' modifier
(if (memq modifier '(at colon-at))
(format:error "double `@' modifier"))
(set! modifier (if (eq? modifier 'colon) 'colon-at 'at))
(tilde-dispatch))
((#\:) ; `:' modifier
(if (memq modifier '(colon colon-at))
(format:error "double `:' modifier"))
(set! modifier (if (eq? modifier 'at) 'colon-at 'colon))
(tilde-dispatch))
((#\') ; Character parameter
(if modifier (format:error "misplaced modifier"))
(set! params (append params (list (char->integer (next-char)))))
(set! param-value-found #t)
(tilde-dispatch))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\- #\+) ; num. paramtr
(if modifier (format:error "misplaced modifier"))
(let ((num-str-beg (- format:pos 1))
(num-str-end format:pos))
(do ((ch (peek-next-char) (peek-next-char)))
((not (char-numeric? ch)))
(next-char)
(set! num-str-end (+ 1 num-str-end)))
(set! params
(append params
(list (string->number
(substring format-string
num-str-beg
num-str-end))))))
(set! param-value-found #t)
(tilde-dispatch))
((#\V) ; Variable parameter from next argum.
(if modifier (format:error "misplaced modifier"))
(set! params (append params (list (next-arg))))
(set! param-value-found #t)
(tilde-dispatch))
((#\#) ; Parameter is number of remaining args
(if param-value-found (format:error "misplaced '#'"))
(if modifier (format:error "misplaced modifier"))
(set! params (append params (list (length (rest-args)))))
(set! param-value-found #t)
(tilde-dispatch))
((#\,) ; Parameter separators
(if modifier (format:error "misplaced modifier"))
(if (not param-value-found)
(set! params (append params '(#f)))) ; append empty paramtr
(set! param-value-found #f)
(tilde-dispatch))
((#\Q) ; Inquiry messages
(if (eq? modifier 'colon)
(format:out-str format:version)
(let ((nl (string #\newline)))
(format:out-str
(string-append
"SLIB Common LISP format version " format:version nl
" (C) copyright 1992-1994 by Dirk Lutzebaeck" nl
" please send bug reports to `lutzeb@cs.tu-berlin.de'"
nl))))
(anychar-dispatch))
(else ; Unknown tilde directive
(format:error "unknown control character `~c'"
(string-ref format-string (- format:pos 1))))))
(else (anychar-dispatch)))))) ; in case of conditional
(set! format:pos 0)
(set! format:arg-pos 0)
(anychar-dispatch) ; start the formatting
(set! format:pos recursive-pos-save)
arg-pos)) ; return the position in the arg. list
;; when format:read-proof is true, format:obj->str will wrap
;; result strings starting with "#<" in an extra pair of double
;; quotes.
(define format:read-proof #f)
;; format:obj->str returns a R4RS representation as a string of
;; an arbitrary scheme object.
(define (format:obj->str obj slashify)
(let ((res (if slashify
(object->string obj)
(call-with-output-string (lambda (p) (display obj p))))))
(if (and format:read-proof (string-prefix? "#<" res))
(object->string res)
res)))
(define format:space-ch (char->integer #\space))
(define format:zero-ch (char->integer #\0))
(define (format:par pars length index default name)
(if (> length index)
(let ((par (list-ref pars index)))
(if par
(if name
(if (< par 0)
(format:error
"~s parameter must be a positive integer" name)
par)
par)
default))
default))
(define (format:out-obj-padded pad-left obj slashify pars)
(if (null? pars)
(format:out-str (format:obj->str obj slashify))
(let ((l (length pars)))
(let ((mincol (format:par pars l 0 0 "mincol"))
(colinc (format:par pars l 1 1 "colinc"))
(minpad (format:par pars l 2 0 "minpad"))
(padchar (integer->char
(format:par pars l 3 format:space-ch #f)))
(objstr (format:obj->str obj slashify)))
(if (not pad-left)
(format:out-str objstr))
(do ((objstr-len (string-length objstr))
(i minpad (+ i colinc)))
((>= (+ objstr-len i) mincol)
(format:out-fill i padchar)))
(if pad-left
(format:out-str objstr))))))
(define (format:out-num-padded modifier number pars radix)
(if (not (integer? number)) (format:error "argument not an integer"))
(let ((numstr (number->string number radix)))
(if (and (null? pars) (not modifier))
(format:out-str numstr)
(let ((l (length pars))
(numstr-len (string-length numstr)))
(let ((mincol (format:par pars l 0 #f "mincol"))
(padchar (integer->char
(format:par pars l 1 format:space-ch #f)))
(commachar (integer->char
(format:par pars l 2 (char->integer #\,) #f)))
(commawidth (format:par pars l 3 3 "commawidth")))
(if mincol
(let ((numlen numstr-len)) ; calc. the output len of number
(if (and (memq modifier '(at colon-at)) (>= number 0))
(set! numlen (+ numlen 1)))
(if (memq modifier '(colon colon-at))
(set! numlen (+ (quotient (- numstr-len
(if (< number 0) 2 1))
commawidth)
numlen)))
(if (> mincol numlen)
(format:out-fill (- mincol numlen) padchar))))
(if (and (memq modifier '(at colon-at))
(>= number 0))
(format:out-char #\+))
(if (memq modifier '(colon colon-at)) ; insert comma character
(let ((start (remainder numstr-len commawidth))
(ns (if (< number 0) 1 0)))
(format:out-substr numstr 0 start)
(do ((i start (+ i commawidth)))
((>= i numstr-len))
(if (> i ns)
(format:out-char commachar))
(format:out-substr numstr i (+ i commawidth))))
(format:out-str numstr)))))))
(define (format:tabulate modifier pars)
(let ((l (length pars)))
(let ((colnum (format:par pars l 0 1 "colnum"))
(colinc (format:par pars l 1 1 "colinc"))
(padch (integer->char (format:par pars l 2 format:space-ch #f))))
(case modifier
((colon colon-at)
(format:error "unsupported modifier for ~~t"))
((at) ; relative tabulation
(format:out-fill
(if (= colinc 0)
colnum ; colnum = colrel
(do ((c 0 (+ c colinc))
(col (+ output-col colnum)))
((>= c col)
(- c output-col))))
padch))
(else ; absolute tabulation
(format:out-fill
(cond
((< output-col colnum)
(- colnum output-col))
((= colinc 0)
0)
(else
(do ((c colnum (+ c colinc)))
((>= c output-col)
(- c output-col)))))
padch))))))
;; roman numerals (from dorai@cs.rice.edu).
(define format:roman-alist
'((1000 #\M) (500 #\D) (100 #\C) (50 #\L)
(10 #\X) (5 #\V) (1 #\I)))
(define format:roman-boundary-values
'(100 100 10 10 1 1 #f))
(define (format:num->old-roman n)
(if (and (integer? n) (>= n 1))
(let loop ((n n)
(romans format:roman-alist)
(s '()))
(if (null? romans) (list->string (reverse s))
(let ((roman-val (caar romans))
(roman-dgt (cadar romans)))
(do ((q (quotient n roman-val) (- q 1))
(s s (cons roman-dgt s)))
((= q 0)
(loop (remainder n roman-val)
(cdr romans) s))))))
(format:error "only positive integers can be romanized")))
(define (format:num->roman n)
(if (and (integer? n) (> n 0))
(let loop ((n n)
(romans format:roman-alist)
(boundaries format:roman-boundary-values)
(s '()))
(if (null? romans)
(list->string (reverse s))
(let ((roman-val (caar romans))
(roman-dgt (cadar romans))
(bdry (car boundaries)))
(let loop2 ((q (quotient n roman-val))
(r (remainder n roman-val))
(s s))
(if (= q 0)
(if (and bdry (>= r (- roman-val bdry)))
(loop (remainder r bdry) (cdr romans)
(cdr boundaries)
(cons roman-dgt
(append
(cdr (assv bdry romans))
s)))
(loop r (cdr romans) (cdr boundaries) s))
(loop2 (- q 1) r (cons roman-dgt s)))))))
(format:error "only positive integers can be romanized")))
;; cardinals & ordinals (from dorai@cs.rice.edu)
(define format:cardinal-ones-list
'(#f "one" "two" "three" "four" "five"
"six" "seven" "eight" "nine" "ten" "eleven" "twelve" "thirteen"
"fourteen" "fifteen" "sixteen" "seventeen" "eighteen"
"nineteen"))
(define format:cardinal-tens-list
'(#f #f "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty"
"ninety"))
(define (format:num->cardinal999 n)
;; this procedure is inspired by the Bruno Haible's CLisp
;; function format-small-cardinal, which converts numbers
;; in the range 1 to 999, and is used for converting each
;; thousand-block in a larger number
(let* ((hundreds (quotient n 100))
(tens+ones (remainder n 100))
(tens (quotient tens+ones 10))
(ones (remainder tens+ones 10)))
(append
(if (> hundreds 0)
(append
(string->list
(list-ref format:cardinal-ones-list hundreds))
(string->list" hundred")
(if (> tens+ones 0) '(#\space) '()))
'())
(if (< tens+ones 20)
(if (> tens+ones 0)
(string->list
(list-ref format:cardinal-ones-list tens+ones))
'())
(append
(string->list
(list-ref format:cardinal-tens-list tens))
(if (> ones 0)
(cons #\-
(string->list
(list-ref format:cardinal-ones-list ones)))
'()))))))
(define format:cardinal-thousand-block-list
'("" " thousand" " million" " billion" " trillion" " quadrillion"
" quintillion" " sextillion" " septillion" " octillion" " nonillion"
" decillion" " undecillion" " duodecillion" " tredecillion"
" quattuordecillion" " quindecillion" " sexdecillion" " septendecillion"
" octodecillion" " novemdecillion" " vigintillion"))
(define (format:num->cardinal n)
(cond ((not (integer? n))
(format:error
"only integers can be converted to English cardinals"))
((= n 0) "zero")
((< n 0) (string-append "minus " (format:num->cardinal (- n))))
(else
(let ((power3-word-limit
(length format:cardinal-thousand-block-list)))
(let loop ((n n)
(power3 0)
(s '()))
(if (= n 0)
(list->string s)
(let ((n-before-block (quotient n 1000))
(n-after-block (remainder n 1000)))
(loop n-before-block
(+ power3 1)
(if (> n-after-block 0)
(append
(if (> n-before-block 0)
(string->list ", ") '())
(format:num->cardinal999 n-after-block)
(if (< power3 power3-word-limit)
(string->list
(list-ref
format:cardinal-thousand-block-list
power3))
(append
(string->list " times ten to the ")
(string->list
(format:num->ordinal
(* power3 3)))
(string->list " power")))
s)
s)))))))))
(define format:ordinal-ones-list
'(#f "first" "second" "third" "fourth" "fifth"
"sixth" "seventh" "eighth" "ninth" "tenth" "eleventh" "twelfth"
"thirteenth" "fourteenth" "fifteenth" "sixteenth" "seventeenth"
"eighteenth" "nineteenth"))
(define format:ordinal-tens-list
'(#f #f "twentieth" "thirtieth" "fortieth" "fiftieth" "sixtieth"
"seventieth" "eightieth" "ninetieth"))
(define (format:num->ordinal n)
(cond ((not (integer? n))
(format:error
"only integers can be converted to English ordinals"))
((= n 0) "zeroth")
((< n 0) (string-append "minus " (format:num->ordinal (- n))))
(else
(let ((hundreds (quotient n 100))
(tens+ones (remainder n 100)))
(string-append
(if (> hundreds 0)
(string-append
(format:num->cardinal (* hundreds 100))
(if (= tens+ones 0) "th" " "))
"")
(if (= tens+ones 0) ""
(if (< tens+ones 20)
(list-ref format:ordinal-ones-list tens+ones)
(let ((tens (quotient tens+ones 10))
(ones (remainder tens+ones 10)))
(if (= ones 0)
(list-ref format:ordinal-tens-list tens)
(string-append
(list-ref format:cardinal-tens-list tens)
"-"
(list-ref format:ordinal-ones-list ones))))
)))))))
;; format inf and nan.
(define (format:out-inf-nan number width digits edigits overch padch)
;; inf and nan are always printed exactly as "+inf.0", "-inf.0" or
;; "+nan.0", suitably justified in their field. We insist on
;; printing this exact form so that the numbers can be read back in.
(let* ((str (number->string number))
(len (string-length str))
(dot (string-index str #\.))
(digits (+ (or digits 0)
(if edigits (+ edigits 2) 0))))
(if (and width overch (< width len))
(format:out-fill width (integer->char overch))
(let* ((leftpad (if width
(max (- width (max len (+ dot 1 digits))) 0)
0))
(rightpad (if width
(max (- width leftpad len) 0)
0))
(padch (integer->char (or padch format:space-ch))))
(format:out-fill leftpad padch)
(format:out-str str)
(format:out-fill rightpad padch)))))
;; format fixed flonums (~F)
(define (format:out-fixed modifier number pars)
(if (not (or (number? number) (string? number)))
(format:error "argument is not a number or a number string"))
(let ((l (length pars)))
(let ((width (format:par pars l 0 #f "width"))
(digits (format:par pars l 1 #f "digits"))
(scale (format:par pars l 2 0 #f))
(overch (format:par pars l 3 #f #f))
(padch (format:par pars l 4 format:space-ch #f)))
(cond
((and (number? number)
(or (inf? number) (nan? number)))
(format:out-inf-nan number width digits #f overch padch))
(digits
(format:parse-float number #t scale)
(if (<= (- format:fn-len format:fn-dot) digits)
(format:fn-zfill #f (- digits (- format:fn-len format:fn-dot)))
(format:fn-round digits))
(if width
(let ((numlen (+ format:fn-len 1)))
(if (or (not format:fn-pos?) (eq? modifier 'at))
(set! numlen (+ numlen 1)))
(if (and (= format:fn-dot 0) (> width (+ digits 1)))
(set! numlen (+ numlen 1)))
(if (< numlen width)
(format:out-fill (- width numlen) (integer->char padch)))
(if (and overch (> numlen width))
(format:out-fill width (integer->char overch))
(format:fn-out modifier (> width (+ digits 1)))))
(format:fn-out modifier #t)))
(else
(format:parse-float number #t scale)
(format:fn-strip)
(if width
(let ((numlen (+ format:fn-len 1)))
(if (or (not format:fn-pos?) (eq? modifier 'at))
(set! numlen (+ numlen 1)))
(if (= format:fn-dot 0)
(set! numlen (+ numlen 1)))
(if (< numlen width)
(format:out-fill (- width numlen) (integer->char padch)))
(if (> numlen width) ; adjust precision if possible
(let ((dot-index (- numlen
(- format:fn-len format:fn-dot))))
(if (> dot-index width)
(if overch ; numstr too big for required width
(format:out-fill width (integer->char overch))
(format:fn-out modifier #t))
(begin
(format:fn-round (- width dot-index))
(format:fn-out modifier #t))))
(format:fn-out modifier #t)))
(format:fn-out modifier #t)))))))
;; format exponential flonums (~E)
(define (format:out-expon modifier number pars)
(if (not (or (number? number) (string? number)))
(format:error "argument is not a number"))
(let ((l (length pars)))
(let ((width (format:par pars l 0 #f "width"))
(digits (format:par pars l 1 #f "digits"))
(edigits (format:par pars l 2 #f "exponent digits"))
(scale (format:par pars l 3 1 #f))
(overch (format:par pars l 4 #f #f))
(padch (format:par pars l 5 format:space-ch #f))
(expch (format:par pars l 6 #f #f)))
(cond
((and (number? number)
(or (inf? number) (nan? number)))
(format:out-inf-nan number width digits edigits overch padch))
(digits ; fixed precision
(let ((digits (if (> scale 0)
(if (< scale (+ digits 2))
(+ (- digits scale) 1)
0)
digits)))
(format:parse-float number #f scale)
(if (<= (- format:fn-len format:fn-dot) digits)
(format:fn-zfill #f (- digits (- format:fn-len format:fn-dot)))
(format:fn-round digits))
(if width
(if (and edigits overch (> format:en-len edigits))
(format:out-fill width (integer->char overch))
(let ((numlen (+ format:fn-len 3))) ; .E+
(if (or (not format:fn-pos?) (eq? modifier 'at))
(set! numlen (+ numlen 1)))
(if (and (= format:fn-dot 0) (> width (+ digits 1)))
(set! numlen (+ numlen 1)))
(set! numlen
(+ numlen
(if (and edigits (>= edigits format:en-len))
edigits
format:en-len)))
(if (< numlen width)
(format:out-fill (- width numlen)
(integer->char padch)))
(if (and overch (> numlen width))
(format:out-fill width (integer->char overch))
(begin
(format:fn-out modifier (> width (- numlen 1)))
(format:en-out edigits expch)))))
(begin
(format:fn-out modifier #t)
(format:en-out edigits expch)))))
(else
(format:parse-float number #f scale)
(format:fn-strip)
(if width
(if (and edigits overch (> format:en-len edigits))
(format:out-fill width (integer->char overch))
(let ((numlen (+ format:fn-len 3))) ; .E+
(if (or (not format:fn-pos?) (eq? modifier 'at))
(set! numlen (+ numlen 1)))
(if (= format:fn-dot 0)
(set! numlen (+ numlen 1)))
(set! numlen
(+ numlen
(if (and edigits (>= edigits format:en-len))
edigits
format:en-len)))
(if (< numlen width)
(format:out-fill (- width numlen)
(integer->char padch)))
(if (> numlen width) ; adjust precision if possible
(let ((f (- format:fn-len format:fn-dot))) ; fract len
(if (> (- numlen f) width)
(if overch ; numstr too big for required width
(format:out-fill width
(integer->char overch))
(begin
(format:fn-out modifier #t)
(format:en-out edigits expch)))
(begin
(format:fn-round (+ (- f numlen) width))
(format:fn-out modifier #t)
(format:en-out edigits expch))))
(begin
(format:fn-out modifier #t)
(format:en-out edigits expch)))))
(begin
(format:fn-out modifier #t)
(format:en-out edigits expch))))))))
;; format general flonums (~G)
(define (format:out-general modifier number pars)
(if (not (or (number? number) (string? number)))
(format:error "argument is not a number or a number string"))
(let ((l (length pars)))
(let ((width (if (> l 0) (list-ref pars 0) #f))
(digits (if (> l 1) (list-ref pars 1) #f))
(edigits (if (> l 2) (list-ref pars 2) #f))
(overch (if (> l 4) (list-ref pars 4) #f))
(padch (if (> l 5) (list-ref pars 5) #f)))
(cond
((and (number? number)
(or (inf? number) (nan? number)))
;; FIXME: this isn't right.
(format:out-inf-nan number width digits edigits overch padch))
(else
(format:parse-float number #t 0)
(format:fn-strip)
(let* ((ee (if edigits (+ edigits 2) 4)) ; for the following algorithm
(ww (if width (- width ee) #f)) ; see Steele's CL book p.395
(n (if (= format:fn-dot 0) ; number less than (abs 1.0) ?
(- (format:fn-zlead))
format:fn-dot))
(d (if digits
digits
(max format:fn-len (min n 7)))) ; q = format:fn-len
(dd (- d n)))
(if (<= 0 dd d)
(begin
(format:out-fixed modifier number (list ww dd #f overch padch))
(format:out-fill ee #\space)) ;~@T not implemented yet
(format:out-expon modifier number pars))))))))
;; format dollar flonums (~$)
(define (format:out-dollar modifier number pars)
(if (not (or (number? number) (string? number)))
(format:error "argument is not a number or a number string"))
(let ((l (length pars)))
(let ((digits (format:par pars l 0 2 "digits"))
(mindig (format:par pars l 1 1 "mindig"))
(width (format:par pars l 2 0 "width"))
(padch (format:par pars l 3 format:space-ch #f)))
(cond
((and (number? number)
(or (inf? number) (nan? number)))
(format:out-inf-nan number width digits #f #f padch))
(else
(format:parse-float number #t 0)
(if (<= (- format:fn-len format:fn-dot) digits)
(format:fn-zfill #f (- digits (- format:fn-len format:fn-dot)))
(format:fn-round digits))
(let ((numlen (+ format:fn-len 1)))
(if (or (not format:fn-pos?) (memq modifier '(at colon-at)))
(set! numlen (+ numlen 1)))
(if (and mindig (> mindig format:fn-dot))
(set! numlen (+ numlen (- mindig format:fn-dot))))
(if (and (= format:fn-dot 0) (not mindig))
(set! numlen (+ numlen 1)))
(if (< numlen width)
(case modifier
((colon)
(if (not format:fn-pos?)
(format:out-char #\-))
(format:out-fill (- width numlen) (integer->char padch)))
((at)
(format:out-fill (- width numlen) (integer->char padch))
(format:out-char (if format:fn-pos? #\+ #\-)))
((colon-at)
(format:out-char (if format:fn-pos? #\+ #\-))
(format:out-fill (- width numlen) (integer->char padch)))
(else
(format:out-fill (- width numlen) (integer->char padch))
(if (not format:fn-pos?)
(format:out-char #\-))))
(if format:fn-pos?
(if (memq modifier '(at colon-at)) (format:out-char #\+))
(format:out-char #\-))))
(if (and mindig (> mindig format:fn-dot))
(format:out-fill (- mindig format:fn-dot) #\0))
(if (and (= format:fn-dot 0) (not mindig))
(format:out-char #\0))
(format:out-substr format:fn-str 0 format:fn-dot)
(format:out-char #\.)
(format:out-substr format:fn-str format:fn-dot format:fn-len))))))
; the flonum buffers
(define format:fn-max 400) ; max. number of number digits
(define format:fn-str (make-string format:fn-max)) ; number buffer
(define format:fn-len 0) ; digit length of number
(define format:fn-dot #f) ; dot position of number
(define format:fn-pos? #t) ; number positive?
(define format:en-max 10) ; max. number of exponent digits
(define format:en-str (make-string format:en-max)) ; exponent buffer
(define format:en-len 0) ; digit length of exponent
(define format:en-pos? #t) ; exponent positive?
(define (format:parse-float num fixed? scale)
(let ((num-str (if (string? num)
num
(number->string (exact->inexact num)))))
(set! format:fn-pos? #t)
(set! format:fn-len 0)
(set! format:fn-dot #f)
(set! format:en-pos? #t)
(set! format:en-len 0)
(do ((i 0 (+ i 1))
(left-zeros 0)
(mantissa? #t)
(all-zeros? #t)
(num-len (string-length num-str))
(c #f)) ; current exam. character in num-str
((= i num-len)
(if (not format:fn-dot)
(set! format:fn-dot format:fn-len))
(if all-zeros?
(begin
(set! left-zeros 0)
(set! format:fn-dot 0)
(set! format:fn-len 1)))
;; now format the parsed values according to format's need
(if fixed?
(begin ; fixed format m.nnn or .nnn
(if (and (> left-zeros 0) (> format:fn-dot 0))
(if (> format:fn-dot left-zeros)
(begin ; norm 0{0}nn.mm to nn.mm
(format:fn-shiftleft left-zeros)
(set! format:fn-dot (- format:fn-dot left-zeros))
(set! left-zeros 0))
(begin ; normalize 0{0}.nnn to .nnn
(format:fn-shiftleft format:fn-dot)
(set! left-zeros (- left-zeros format:fn-dot))
(set! format:fn-dot 0))))
(if (or (not (= scale 0)) (> format:en-len 0))
(let ((shift (+ scale (format:en-int))))
(cond
(all-zeros? #t)
((> (+ format:fn-dot shift) format:fn-len)
(format:fn-zfill
#f (- shift (- format:fn-len format:fn-dot)))
(set! format:fn-dot format:fn-len))
((< (+ format:fn-dot shift) 0)
(format:fn-zfill #t (- (- shift) format:fn-dot))
(set! format:fn-dot 0))
(else
(if (> left-zeros 0)
(if (<= left-zeros shift) ; shift always > 0 here
(format:fn-shiftleft shift) ; shift out 0s
(begin
(format:fn-shiftleft left-zeros)
(set! format:fn-dot (- shift left-zeros))))
(set! format:fn-dot (+ format:fn-dot shift))))))))
(let ((negexp ; expon format m.nnnEee
(if (> left-zeros 0)
(- left-zeros format:fn-dot -1)
(if (= format:fn-dot 0) 1 0))))
(if (> left-zeros 0)
(begin ; normalize 0{0}.nnn to n.nn
(format:fn-shiftleft left-zeros)
(set! format:fn-dot 1))
(if (= format:fn-dot 0)
(set! format:fn-dot 1)))
(format:en-set (- (+ (- format:fn-dot scale) (format:en-int))
negexp))
(cond
(all-zeros?
(format:en-set 0)
(set! format:fn-dot 1))
((< scale 0) ; leading zero
(format:fn-zfill #t (- scale))
(set! format:fn-dot 0))
((> scale format:fn-dot)
(format:fn-zfill #f (- scale format:fn-dot))
(set! format:fn-dot scale))
(else
(set! format:fn-dot scale)))))
#t)
;; do body
(set! c (string-ref num-str i)) ; parse the output of number->string
(cond ; which can be any valid number
((char-numeric? c) ; representation of R4RS except
(if mantissa? ; complex numbers
(begin
(if (char=? c #\0)
(if all-zeros?
(set! left-zeros (+ left-zeros 1)))
(begin
(set! all-zeros? #f)))
(string-set! format:fn-str format:fn-len c)
(set! format:fn-len (+ format:fn-len 1)))
(begin
(string-set! format:en-str format:en-len c)
(set! format:en-len (+ format:en-len 1)))))
((or (char=? c #\-) (char=? c #\+))
(if mantissa?
(set! format:fn-pos? (char=? c #\+))
(set! format:en-pos? (char=? c #\+))))
((char=? c #\.)
(set! format:fn-dot format:fn-len))
((char=? c #\e)
(set! mantissa? #f))
((char=? c #\E)
(set! mantissa? #f))
((char-whitespace? c) #t)
((char=? c #\d) #t) ; decimal radix prefix
((char=? c #\#) #t)
(else
(format:error "illegal character `~c' in number->string" c))))))
(define (format:en-int) ; convert exponent string to integer
(if (= format:en-len 0)
0
(do ((i 0 (+ i 1))
(n 0))
((= i format:en-len)
(if format:en-pos?
n
(- n)))
(set! n (+ (* n 10) (- (char->integer (string-ref format:en-str i))
format:zero-ch))))))
(define (format:en-set en) ; set exponent string number
(set! format:en-len 0)
(set! format:en-pos? (>= en 0))
(let ((en-str (number->string en)))
(do ((i 0 (+ i 1))
(en-len (string-length en-str))
(c #f))
((= i en-len))
(set! c (string-ref en-str i))
(if (char-numeric? c)
(begin
(string-set! format:en-str format:en-len c)
(set! format:en-len (+ format:en-len 1)))))))
(define (format:fn-zfill left? n) ; fill current number string with 0s
(if (> (+ n format:fn-len) format:fn-max) ; from the left or right
(format:error "number is too long to format (enlarge format:fn-max)"))
(set! format:fn-len (+ format:fn-len n))
(if left?
(do ((i format:fn-len (- i 1))) ; fill n 0s to left
((< i 0))
(string-set! format:fn-str i
(if (< i n)
#\0
(string-ref format:fn-str (- i n)))))
(do ((i (- format:fn-len n) (+ i 1))) ; fill n 0s to the right
((= i format:fn-len))
(string-set! format:fn-str i #\0))))
(define (format:fn-shiftleft n) ; shift left current number n positions
(if (> n format:fn-len)
(format:error "internal error in format:fn-shiftleft (~d,~d)"
n format:fn-len))
(do ((i n (+ i 1)))
((= i format:fn-len)
(set! format:fn-len (- format:fn-len n)))
(string-set! format:fn-str (- i n) (string-ref format:fn-str i))))
(define (format:fn-round digits) ; round format:fn-str
(set! digits (+ digits format:fn-dot))
(do ((i digits (- i 1)) ; "099",2 -> "10"
(c 5)) ; "023",2 -> "02"
((or (= c 0) (< i 0)) ; "999",2 -> "100"
(if (= c 1) ; "005",2 -> "01"
(begin ; carry overflow
(set! format:fn-len digits)
(format:fn-zfill #t 1) ; add a 1 before fn-str
(string-set! format:fn-str 0 #\1)
(set! format:fn-dot (+ format:fn-dot 1)))
(set! format:fn-len digits)))
(set! c (+ (- (char->integer (string-ref format:fn-str i))
format:zero-ch) c))
(string-set! format:fn-str i (integer->char
(if (< c 10)
(+ c format:zero-ch)
(+ (- c 10) format:zero-ch))))
(set! c (if (< c 10) 0 1))))
(define (format:fn-out modifier add-leading-zero?)
(if format:fn-pos?
(if (eq? modifier 'at)
(format:out-char #\+))
(format:out-char #\-))
(if (= format:fn-dot 0)
(if add-leading-zero?
(format:out-char #\0))
(format:out-substr format:fn-str 0 format:fn-dot))
(format:out-char #\.)
(format:out-substr format:fn-str format:fn-dot format:fn-len))
(define (format:en-out edigits expch)
(format:out-char (if expch (integer->char expch) #\E))
(format:out-char (if format:en-pos? #\+ #\-))
(if edigits
(if (< format:en-len edigits)
(format:out-fill (- edigits format:en-len) #\0)))
(format:out-substr format:en-str 0 format:en-len))
(define (format:fn-strip) ; strip trailing zeros but one
(string-set! format:fn-str format:fn-len #\0)
(do ((i format:fn-len (- i 1)))
((or (not (char=? (string-ref format:fn-str i) #\0))
(<= i format:fn-dot))
(set! format:fn-len (+ i 1)))))
(define (format:fn-zlead) ; count leading zeros
(do ((i 0 (+ i 1)))
((or (= i format:fn-len)
(not (char=? (string-ref format:fn-str i) #\0)))
(if (= i format:fn-len) ; found a real zero
0
i))))
;;; some global functions not found in SLIB
(define (string-capitalize-first str) ; "hello" -> "Hello"
(let ((cap-str (string-copy str)) ; "hELLO" -> "Hello"
(non-first-alpha #f) ; "*hello" -> "*Hello"
(str-len (string-length str))) ; "hello you" -> "Hello you"
(do ((i 0 (+ i 1)))
((= i str-len) cap-str)
(let ((c (string-ref str i)))
(if (char-alphabetic? c)
(if non-first-alpha
(string-set! cap-str i (char-downcase c))
(begin
(set! non-first-alpha #t)
(string-set! cap-str i (char-upcase c)))))))))
;; Aborts the program when a formatting error occures. This is a null
;; argument closure to jump to the interpreters toplevel continuation.
(define (format:abort) (error "error in format"))
(let ((arg-pos (format:format-work format-string format-args))
(arg-len (length format-args)))
(cond
((> arg-pos arg-len)
(set! format:arg-pos (+ arg-len 1))
(display format:arg-pos)
(format:error "~a missing argument~:p" (- arg-pos arg-len)))
(else
(if flush-output?
(force-output port))
(if destination
#t
(let ((str (get-output-string port)))
(close-port port)
str)))))))
(begin-deprecated
(set! format
(let ((format format))
(case-lambda
((destination format-string . args)
(if (string? destination)
(begin
(issue-deprecation-warning
"Omitting the destination on a call to format is deprecated."
"Pass #f as the destination, before the format string.")
(apply format #f destination format-string args))
(apply format destination format-string args)))
((deprecated-format-string-only)
(issue-deprecation-warning
"Omitting the destination port on a call to format is deprecated."
"Pass #f as the destination port, before the format string.")
(format #f deprecated-format-string-only))))))
;; Thanks to Shuji Narazaki
(module-set! the-root-module 'format format)
;;;; ftw.scm --- file system tree walk
;;;; Copyright (C) 2002, 2003, 2006, 2011, 2012, 2014, 2016 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Two procedures are provided: `ftw' and `nftw'.
;; NOTE: The following description was adapted from the GNU libc info page, w/
;; significant modifications for a more "Schemey" interface. Most noticible
;; are the inlining of `struct FTW *' parameters `base' and `level' and the
;; omission of `descriptors' parameters.
;; * Types
;;
;; The X/Open specification defines two procedures to process whole
;; hierarchies of directories and the contained files. Both procedures
;; of this `ftw' family take as one of the arguments a callback procedure
;; which must be of these types.
;;
;; - Data Type: __ftw_proc_t
;; (lambda (filename statinfo flag) ...) => status
;;
;; Type for callback procedures given to the `ftw' procedure. The
;; first parameter is a filename, the second parameter is the
;; vector value as returned by calling `stat' on FILENAME.
;;
;; The last parameter is a symbol giving more information about
;; FILENAM. It can have one of the following values:
;;
;; `regular'
;; The current item is a normal file or files which do not fit
;; into one of the following categories. This means
;; especially special files, sockets etc.
;;
;; `directory'
;; The current item is a directory.
;;
;; `invalid-stat'
;; The `stat' call to fill the object pointed to by the second
;; parameter failed and so the information is invalid.
;;
;; `directory-not-readable'
;; The item is a directory which cannot be read.
;;
;; `symlink'
;; The item is a symbolic link. Since symbolic links are
;; normally followed seeing this value in a `ftw' callback
;; procedure means the referenced file does not exist. The
;; situation for `nftw' is different.
;;
;; - Data Type: __nftw_proc_t
;; (lambda (filename statinfo flag base level) ...) => status
;;
;; The first three arguments have the same as for the
;; `__ftw_proc_t' type. A difference is that for the third
;; argument some additional values are defined to allow finer
;; differentiation:
;;
;; `directory-processed'
;; The current item is a directory and all subdirectories have
;; already been visited and reported. This flag is returned
;; instead of `directory' if the `depth' flag is given to
;; `nftw' (see below).
;;
;; `stale-symlink'
;; The current item is a stale symbolic link. The file it
;; points to does not exist.
;;
;; The last two parameters are described below. They contain
;; information to help interpret FILENAME and give some information
;; about current state of the traversal of the directory hierarchy.
;;
;; `base'
;; The value specifies which part of the filename argument
;; given in the first parameter to the callback procedure is
;; the name of the file. The rest of the string is the path
;; to locate the file. This information is especially
;; important if the `chdir' flag for `nftw' was set since then
;; the current directory is the one the current item is found
;; in.
;;
;; `level'
;; While processing the directory the procedures tracks how
;; many directories have been examined to find the current
;; item. This nesting level is 0 for the item given starting
;; item (file or directory) and is incremented by one for each
;; entered directory.
;;
;; * Procedure: (ftw filename proc . options)
;; Do a file system tree walk starting at FILENAME using PROC.
;;
;; The `ftw' procedure calls the callback procedure given in the
;; parameter PROC for every item which is found in the directory
;; specified by FILENAME and all directories below. The procedure
;; follows symbolic links if necessary but does not process an item
;; twice. If FILENAME names no directory this item is the only
;; object reported by calling the callback procedure.
;;
;; The filename given to the callback procedure is constructed by
;; taking the FILENAME parameter and appending the names of all
;; passed directories and then the local file name. So the
;; callback procedure can use this parameter to access the file.
;; Before the callback procedure is called `ftw' calls `stat' for
;; this file and passes the information up to the callback
;; procedure. If this `stat' call was not successful the failure is
;; indicated by setting the flag argument of the callback procedure
;; to `invalid-stat'. Otherwise the flag is set according to the
;; description given in the description of `__ftw_proc_t' above.
;;
;; The callback procedure is expected to return non-#f to indicate
;; that no error occurred and the processing should be continued.
;; If an error occurred in the callback procedure or the call to
;; `ftw' shall return immediately the callback procedure can return
;; #f. This is the only correct way to stop the procedure. The
;; program must not use `throw' or similar techniques to continue
;; the program in another place. [Can we relax this? --ttn]
;;
;; The return value of the `ftw' procedure is #t if all callback
;; procedure calls returned #t and all actions performed by the
;; `ftw' succeeded. If some procedure call failed (other than
;; calling `stat' on an item) the procedure returns #f. If a
;; callback procedure returns a value other than #t this value is
;; returned as the return value of `ftw'.
;;
;; * Procedure: (nftw filename proc . control-flags)
;; Do a new-style file system tree walk starting at FILENAME using PROC.
;; Various optional CONTROL-FLAGS alter the default behavior.
;;
;; The `nftw' procedures works like the `ftw' procedures. It calls
;; the callback procedure PROC for all items it finds in the
;; directory FILENAME and below.
;;
;; The differences are that for one the callback procedure is of a
;; different type. It takes also `base' and `level' parameters as
;; described above.
;;
;; The second difference is that `nftw' takes additional optional
;; arguments which are zero or more of the following symbols:
;;
;; physical'
;; While traversing the directory symbolic links are not
;; followed. I.e., if this flag is given symbolic links are
;; reported using the `symlink' value for the type parameter
;; to the callback procedure. Please note that if this flag is
;; used the appearance of `symlink' in a callback procedure
;; does not mean the referenced file does not exist. To
;; indicate this the extra value `stale-symlink' exists.
;;
;; mount'
;; The callback procedure is only called for items which are on
;; the same mounted file system as the directory given as the
;; FILENAME parameter to `nftw'.
;;
;; chdir'
;; If this flag is given the current working directory is
;; changed to the directory containing the reported object
;; before the callback procedure is called.
;;
;; depth'
;; If this option is given the procedure visits first all files
;; and subdirectories before the callback procedure is called
;; for the directory itself (depth-first processing). This
;; also means the type flag given to the callback procedure is
;; `directory-processed' and not `directory'.
;;
;; The return value is computed in the same way as for `ftw'.
;; `nftw' returns #t if no failure occurred in `nftw' and all
;; callback procedure call return values are also #t. For internal
;; errors such as memory problems the error `ftw-error' is thrown.
;; If the return value of a callback invocation is not #t this
;; very same value is returned.
;;; Code:
(define-module (ice-9 ftw)
#\use-module (ice-9 match)
#\use-module (ice-9 vlist)
#\use-module (srfi srfi-1)
#\autoload (ice-9 i18n) (string-locale<?)
#\export (ftw nftw
file-system-fold
file-system-tree
scandir))
(define (directory-files dir)
(let ((dir-stream (opendir dir)))
(let loop ((new (readdir dir-stream))
(acc '()))
(if (eof-object? new)
(begin
(closedir dir-stream)
acc)
(loop (readdir dir-stream)
(if (or (string=? "." new) ;;; ignore
(string=? ".." new)) ;;; ignore
acc
(cons new acc)))))))
(define (pathify . nodes)
(let loop ((nodes nodes)
(result ""))
(if (null? nodes)
(or (and (string=? "" result) "")
(substring result 1 (string-length result)))
(loop (cdr nodes) (string-append result "/" (car nodes))))))
(define (abs? filename)
(char=? #\/ (string-ref filename 0)))
;; `visited?-proc' returns a test procedure VISITED? which when called as
;; (VISITED? stat-obj) returns #f the first time a distinct file is seen,
;; then #t on any subsequent sighting of it.
;;
;; stat:dev and stat:ino together uniquely identify a file (see "Attribute
;; Meanings" in the glibc manual). Often there'll be just one dev, and
;; usually there's just a handful mounted, so the strategy here is a small
;; hash table indexed by dev, containing hash tables indexed by ino.
;;
;; It'd be possible to make a pair (dev . ino) and use that as the key to a
;; single hash table. It'd use an extra pair for every file visited, but
;; might be a little faster if it meant less scheme code.
;;
(define (visited?-proc size)
(let ((dev-hash (make-hash-table 7)))
(lambda (s)
(and s
(let ((ino-hash (hashv-ref dev-hash (stat:dev s)))
(ino (stat:ino s)))
(or ino-hash
(begin
(set! ino-hash (make-hash-table size))
(hashv-set! dev-hash (stat:dev s) ino-hash)))
(or (hashv-ref ino-hash ino)
(begin
(hashv-set! ino-hash ino #t)
#f)))))))
(define (stat-dir-readable?-proc uid gid)
(let ((uid (getuid))
(gid (getgid)))
(lambda (s)
(let* ((perms (stat:perms s))
(perms-bit-set? (lambda (mask)
(not (= 0 (logand mask perms))))))
(or (zero? uid)
(and (= uid (stat:uid s))
(perms-bit-set? #o400))
(and (= gid (stat:gid s))
(perms-bit-set? #o040))
(perms-bit-set? #o004))))))
(define (stat&flag-proc dir-readable? . control-flags)
(let* ((directory-flag (if (memq 'depth control-flags)
'directory-processed
'directory))
(stale-symlink-flag (if (memq 'nftw-style control-flags)
'stale-symlink
'symlink))
(physical? (memq 'physical control-flags))
(easy-flag (lambda (s)
(let ((type (stat:type s)))
(if (eq? 'directory type)
(if (dir-readable? s)
directory-flag
'directory-not-readable)
'regular)))))
(lambda (name)
(let ((s (false-if-exception (lstat name))))
(cond ((not s)
(values s 'invalid-stat))
((eq? 'symlink (stat:type s))
(let ((s-follow (false-if-exception (stat name))))
(cond ((not s-follow)
(values s stale-symlink-flag))
((and s-follow physical?)
(values s 'symlink))
((and s-follow (not physical?))
(values s-follow (easy-flag s-follow))))))
(else (values s (easy-flag s))))))))
(define (clean name)
(let ((last-char-index (1- (string-length name))))
(if (char=? #\/ (string-ref name last-char-index))
(substring name 0 last-char-index)
name)))
(define (ftw filename proc . options)
(let* ((visited? (visited?-proc (cond ((memq 'hash-size options) => cadr)
(else 211))))
(stat&flag (stat&flag-proc
(stat-dir-readable?-proc (getuid) (getgid)))))
(letrec ((go (lambda (fullname)
(call-with-values (lambda () (stat&flag fullname))
(lambda (s flag)
(or (visited? s)
(let ((ret (proc fullname s flag))) ; callback
(or (eq? #t ret)
(throw 'ftw-early-exit ret))
(and (eq? 'directory flag)
(for-each
(lambda (child)
(go (pathify fullname child)))
(directory-files fullname)))
#t)))))))
(catch 'ftw-early-exit
(lambda () (go (clean filename)))
(lambda (key val) val)))))
(define (nftw filename proc . control-flags)
(let* ((od (getcwd)) ; orig dir
(odev (let ((s (false-if-exception (lstat filename))))
(if s (stat:dev s) -1)))
(same-dev? (if (memq 'mount control-flags)
(lambda (s) (= (stat:dev s) odev))
(lambda (s) #t)))
(base-sub (lambda (name base) (substring name 0 base)))
(maybe-cd (if (memq 'chdir control-flags)
(if (abs? filename)
(lambda (fullname base)
(or (= 0 base)
(chdir (base-sub fullname base))))
(lambda (fullname base)
(chdir
(pathify od (base-sub fullname base)))))
(lambda (fullname base) #t)))
(maybe-cd-back (if (memq 'chdir control-flags)
(lambda () (chdir od))
(lambda () #t)))
(depth-first? (memq 'depth control-flags))
(visited? (visited?-proc
(cond ((memq 'hash-size control-flags) => cadr)
(else 211))))
(has-kids? (if depth-first?
(lambda (flag) (eq? flag 'directory-processed))
(lambda (flag) (eq? flag 'directory))))
(stat&flag (apply stat&flag-proc
(stat-dir-readable?-proc (getuid) (getgid))
(cons 'nftw-style control-flags))))
(letrec ((go (lambda (fullname base level)
(call-with-values (lambda () (stat&flag fullname))
(lambda (s flag)
(letrec ((self (lambda ()
(maybe-cd fullname base)
;; the callback
(let ((ret (proc fullname s flag
base level)))
(maybe-cd-back)
(or (eq? #t ret)
(throw 'nftw-early-exit ret)))))
(kids (lambda ()
(and (has-kids? flag)
(for-each
(lambda (child)
(go (pathify fullname child)
(1+ (string-length
fullname))
(1+ level)))
(directory-files fullname))))))
(or (visited? s)
(not (same-dev? s))
(if depth-first?
(begin (kids) (self))
(begin (self) (kids)))))))
#t)))
(let ((ret (catch 'nftw-early-exit
(lambda () (go (clean filename) 0 0))
(lambda (key val) val))))
(chdir od)
ret))))
;;;
;;; `file-system-fold' & co.
;;;
(define-syntax-rule (errno-if-exception expr)
(catch 'system-error
(lambda ()
expr)
(lambda args
(system-error-errno args))))
(define* (file-system-fold enter? leaf down up skip error init file-name
#\optional (stat lstat))
"Traverse the directory at FILE-NAME, recursively. Enter
sub-directories only when (ENTER? PATH STAT RESULT) returns true. When
a sub-directory is entered, call (DOWN PATH STAT RESULT), where PATH is
the path of the sub-directory and STAT the result of (stat PATH); when
it is left, call (UP PATH STAT RESULT). For each file in a directory,
call (LEAF PATH STAT RESULT). When ENTER? returns false, call (SKIP
PATH STAT RESULT). When an `opendir' or STAT call raises an exception,
call (ERROR PATH STAT ERRNO RESULT), with ERRNO being the operating
system error number that was raised.
Return the result of these successive applications.
When FILE-NAME names a flat file, (LEAF PATH STAT INIT) is returned.
The optional STAT parameter defaults to `lstat'."
(define (mark v s)
(vhash-cons (cons (stat:dev s) (stat:ino s)) #t v))
(define (visited? v s)
(vhash-assoc (cons (stat:dev s) (stat:ino s)) v))
(let loop ((name file-name)
(path "")
(dir-stat (errno-if-exception (stat file-name)))
(result init)
(visited vlist-null))
(define full-name
(if (string=? path "")
name
(string-append path "/" name)))
(cond
((integer? dir-stat)
;; FILE-NAME is not readable.
(error full-name #f dir-stat result))
((visited? visited dir-stat)
(values result visited))
((eq? 'directory (stat:type dir-stat)) ; true except perhaps the 1st time
(if (enter? full-name dir-stat result)
(let ((dir (errno-if-exception (opendir full-name)))
(visited (mark visited dir-stat)))
(cond
((directory-stream? dir)
(let liip ((entry (readdir dir))
(result (down full-name dir-stat result))
(subdirs '()))
(cond ((eof-object? entry)
(begin
(closedir dir)
(let ((r+v
(fold (lambda (subdir result+visited)
(call-with-values
(lambda ()
(loop (car subdir)
full-name
(cdr subdir)
(car result+visited)
(cdr result+visited)))
cons))
(cons result visited)
subdirs)))
(values (up full-name dir-stat (car r+v))
(cdr r+v)))))
((or (string=? entry ".")
(string=? entry ".."))
(liip (readdir dir)
result
subdirs))
(else
(let* ((child (string-append full-name "/" entry))
(st (errno-if-exception (stat child))))
(if (integer? st) ; CHILD is a dangling symlink?
(liip (readdir dir)
(error child #f st result)
subdirs)
(if (eq? (stat:type st) 'directory)
(liip (readdir dir)
result
(alist-cons entry st subdirs))
(liip (readdir dir)
(leaf child st result)
subdirs))))))))
(else
;; Directory FULL-NAME not readable, but it is stat'able.
(values (error full-name dir-stat dir result)
visited))))
(values (skip full-name dir-stat result)
(mark visited dir-stat))))
(else
;; Caller passed a FILE-NAME that names a flat file, not a directory.
(leaf full-name dir-stat result)))))
(define* (file-system-tree file-name
#\optional (enter? (lambda (n s) #t))
(stat lstat))
"Return a tree of the form (FILE-NAME STAT CHILDREN ...) where STAT is
the result of (STAT FILE-NAME) and CHILDREN are similar structures for
each file contained in FILE-NAME when it designates a directory. The
optional ENTER? predicate is invoked as (ENTER? NAME STAT) and should
return true to allow recursion into directory NAME; the default value is
a procedure that always returns #t. When a directory does not match
ENTER?, it nonetheless appears in the resulting tree, only with zero
children. The optional STAT parameter defaults to `lstat'. Return #f
when FILE-NAME is not readable."
(define (enter?* name stat result)
(enter? name stat))
(define (leaf name stat result)
(match result
(((siblings ...) rest ...)
(cons (alist-cons (basename name) (cons stat '()) siblings)
rest))))
(define (down name stat result)
(cons '() result))
(define (up name stat result)
(match result
(((children ...) (siblings ...) rest ...)
(cons (alist-cons (basename name) (cons stat children)
siblings)
rest))))
(define skip ; keep an entry for skipped directories
leaf)
(define (error name stat errno result)
(if (string=? name file-name)
result
(leaf name stat result)))
(match (file-system-fold enter?* leaf down up skip error '(())
file-name stat)
(((tree)) tree)
((()) #f))) ; FILE-NAME is unreadable
(define* (scandir name #\optional (select? (const #t))
(entry<? string-locale<?))
"Return the list of the names of files contained in directory NAME
that match predicate SELECT? (by default, all files.) The returned list
of file names is sorted according to ENTRY<?, which defaults to
`string-locale<?'. Return #f when NAME is unreadable or is not a
directory."
;; This procedure is implemented in terms of 'readdir' instead of
;; 'file-system-fold' to avoid the extra 'stat' call that the latter
;; makes for each entry.
(define (opendir* directory)
(catch 'system-error
(lambda ()
(opendir directory))
(const #f)))
(and=> (opendir* name)
(lambda (stream)
(let loop ((entry (readdir stream))
(files '()))
(if (eof-object? entry)
(begin
(closedir stream)
(sort files entry<?))
(loop (readdir stream)
(if (select? entry)
(cons entry files)
files)))))))
;;; ftw.scm ends here
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 futures)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (srfi srfi-11)
#\use-module (ice-9 q)
#\use-module (ice-9 match)
#\use-module (ice-9 control)
#\export (future make-future future? touch))
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;;
;;; Commentary:
;;;
;;; This module provides an implementation of futures, a mechanism for
;;; fine-grain parallelism. Futures were first described by Henry Baker
;;; in ``The Incremental Garbage Collection of Processes'', 1977, and
;;; then implemented in MultiLisp (an implicit variant thereof, i.e.,
;;; without `touch'.)
;;;
;;; This modules uses a fixed thread pool, normally one per CPU core.
;;; Futures are off-loaded to these threads, when they are idle.
;;;
;;; Code:
;;;
;;; Futures.
;;;
(define-record-type <future>
(%make-future thunk state mutex completion)
future?
(thunk future-thunk set-future-thunk!)
(state future-state set-future-state!) ; done | started | queued
(result future-result set-future-result!)
(mutex future-mutex)
(completion future-completion)) ; completion cond. var.
(set-record-type-printer!
<future>
(lambda (future port)
(simple-format port "#<future ~a ~a ~s>"
(number->string (object-address future) 16)
(future-state future)
(future-thunk future))))
(define (make-future thunk)
"Return a new future for THUNK. Execution may start at any point
concurrently, or it can start at the time when the returned future is
touched."
(create-workers!)
(let ((future (%make-future thunk 'queued
(make-mutex) (make-condition-variable))))
(register-future! future)
future))
;;;
;;; Future queues.
;;;
;; Global queue of pending futures.
;; TODO: Use per-worker queues to reduce contention.
(define %futures (make-q))
;; Lock for %FUTURES and %FUTURES-WAITING.
(define %futures-mutex (make-mutex))
(define %futures-available (make-condition-variable))
;; A mapping of nested futures to futures waiting for them to complete.
(define %futures-waiting '())
;; Nesting level of futures. Incremented each time a future is touched
;; from within a future.
(define %nesting-level (make-parameter 0))
;; Maximum nesting level. The point is to avoid stack overflows when
;; nested futures are executed on the same stack. See
;; <http://bugs.gnu.org/13188>.
(define %max-nesting-level 200)
(define-syntax-rule (with-mutex m e0 e1 ...)
;; Copied from (ice-9 threads) to avoid circular dependency.
(let ((x m))
(dynamic-wind
(lambda () (lock-mutex x))
(lambda () (begin e0 e1 ...))
(lambda () (unlock-mutex x)))))
(define %future-prompt
;; The prompt futures abort to when they want to wait for another
;; future.
(make-prompt-tag))
(define (register-future! future)
;; Register FUTURE as being processable.
(lock-mutex %futures-mutex)
(enq! %futures future)
(signal-condition-variable %futures-available)
(unlock-mutex %futures-mutex))
(define (process-future! future)
"Process FUTURE. When FUTURE completes, return #t and update its
result; otherwise, when FUTURE touches a nested future that has not
completed yet, then suspend it and return #f. Suspending a future
consists in capturing its continuation, marking it as `queued', and
adding it to the waiter queue."
(let/ec return
(let* ((suspend
(lambda (cont future-to-wait)
;; FUTURE wishes to wait for the completion of FUTURE-TO-WAIT.
;; At this point, FUTURE is unlocked and in `started' state,
;; and FUTURE-TO-WAIT is unlocked.
(with-mutex %futures-mutex
(with-mutex (future-mutex future)
(set-future-thunk! future cont)
(set-future-state! future 'queued))
(with-mutex (future-mutex future-to-wait)
;; If FUTURE-TO-WAIT completed in the meantime, then
;; reschedule FUTURE directly; otherwise, add it to the
;; waiter queue.
(if (eq? 'done (future-state future-to-wait))
(begin
(enq! %futures future)
(signal-condition-variable %futures-available))
(set! %futures-waiting
(alist-cons future-to-wait future
%futures-waiting))))
(return #f))))
(thunk (lambda ()
(call-with-prompt %future-prompt
(lambda ()
(parameterize ((%nesting-level
(1+ (%nesting-level))))
((future-thunk future))))
suspend))))
(set-future-result! future
(catch #t
(lambda ()
(call-with-values thunk
(lambda results
(lambda ()
(apply values results)))))
(lambda args
(lambda ()
(apply throw args)))))
#t)))
(define (process-one-future)
"Attempt to pick one future from the queue and process it."
;; %FUTURES-MUTEX must be locked on entry, and is locked on exit.
(or (q-empty? %futures)
(let ((future (deq! %futures)))
(lock-mutex (future-mutex future))
(case (future-state future)
((done started)
;; Nothing to do.
(unlock-mutex (future-mutex future)))
(else
;; Do the actual work.
;; We want to release %FUTURES-MUTEX so that other workers can
;; progress. However, to avoid deadlocks, we have to unlock
;; FUTURE as well, to preserve lock ordering.
(unlock-mutex (future-mutex future))
(unlock-mutex %futures-mutex)
(lock-mutex (future-mutex future))
(if (eq? (future-state future) 'queued) ; lost the race?
(begin ; no, so let's process it
(set-future-state! future 'started)
(unlock-mutex (future-mutex future))
(let ((done? (process-future! future)))
(when done?
(with-mutex %futures-mutex
(with-mutex (future-mutex future)
(set-future-state! future 'done)
(notify-completion future))))))
(unlock-mutex (future-mutex future))) ; yes
(lock-mutex %futures-mutex))))))
(define (process-futures)
"Continuously process futures from the queue."
(lock-mutex %futures-mutex)
(let loop ()
(when (q-empty? %futures)
(wait-condition-variable %futures-available
%futures-mutex))
(process-one-future)
(loop)))
(define (notify-completion future)
"Notify futures and callers waiting that FUTURE completed."
;; FUTURE and %FUTURES-MUTEX are locked.
(broadcast-condition-variable (future-completion future))
(let-values (((waiting remaining)
(partition (match-lambda ; TODO: optimize
((waitee . _)
(eq? waitee future)))
%futures-waiting)))
(set! %futures-waiting remaining)
(for-each (match-lambda
((_ . waiter)
(enq! %futures waiter)))
waiting)))
(define (touch future)
"Return the result of FUTURE, computing it if not already done."
(define (work)
;; Do some work while waiting for FUTURE to complete.
(lock-mutex %futures-mutex)
(if (q-empty? %futures)
(begin
(unlock-mutex %futures-mutex)
(with-mutex (future-mutex future)
(unless (eq? 'done (future-state future))
(wait-condition-variable (future-completion future)
(future-mutex future)))))
(begin
(process-one-future)
(unlock-mutex %futures-mutex))))
(let loop ()
(lock-mutex (future-mutex future))
(case (future-state future)
((done)
(unlock-mutex (future-mutex future)))
((started)
(unlock-mutex (future-mutex future))
(if (> (%nesting-level) 0)
(abort-to-prompt %future-prompt future)
(begin
(work)
(loop))))
(else ; queued
(unlock-mutex (future-mutex future))
(if (> (%nesting-level) %max-nesting-level)
(abort-to-prompt %future-prompt future)
(work))
(loop))))
((future-result future)))
;;;
;;; Workers.
;;;
(define %worker-count
(if (provided? 'threads)
(- (current-processor-count) 1)
0))
;; A dock of workers that stay here forever.
;; TODO
;; 1. Allow the pool to be shrunk, as in libgomp (though that we'd
;; need semaphores, which aren't yet in libguile!).
;; 2. Provide a `worker-count' fluid.
(define %workers '())
(define (%create-workers!)
(with-mutex
%futures-mutex
;; Setting 'create-workers!' to a no-op is an optimization, but it is
;; still possible for '%create-workers!' to be called more than once
;; from different threads. Therefore, to avoid creating %workers more
;; than once (and thus creating too many threads), we check to make
;; sure %workers is empty within the critical section.
(when (null? %workers)
(set! %workers
(unfold (lambda (i) (>= i %worker-count))
(lambda (i) (call-with-new-thread process-futures))
1+
0))
(set! create-workers! (lambda () #t)))))
(define create-workers!
(lambda () (%create-workers!)))
;;;
;;; Syntax.
;;;
(define-syntax-rule (future body)
"Return a new future for BODY."
(make-future (lambda () body)))
;;; Local Variables:
;;; eval: (put 'with-mutex 'scheme-indent-function 1)
;;; End:
;;; gap-buffer.scm --- String buffer that supports point
;;; Copyright (C) 2002, 2003, 2006 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; A gap buffer is a structure that models a string but allows relatively
;; efficient insertion of text somewhere in the middle. The insertion
;; location is called `point' with minimum value 1, and a maximum value of the
;; length of the string (which is not fixed).
;;
;; Specifically, we allocate a continuous buffer of characters that is
;; composed of the BEFORE, the GAP and the AFTER (reading L->R), like so:
;;
;; +--- POINT
;; v
;; +--------------------+--------------------+--------------------+
;; | BEFORE | GAP | AFTER |
;; +--------------------+--------------------+--------------------+
;;
;; <----- bef-sz ----->|<----- gap-sz ----->|<----- aft-sz ----->
;;
;; <-------------------| usr-sz |------------------->
;;
;; <-------------------------- all-sz -------------------------->
;;
;; This diagram also shows how the different sizes are computed, and the
;; location of POINT. Note that the user-visible buffer size `usr-sz' does
;; NOT include the GAP, while the allocation `all-sz' DOES.
;;
;; The consequence of this arrangement is that "moving point" is simply a
;; matter of kicking characters across the GAP, while insertion can be viewed
;; as filling up the gap, increasing `bef-sz' and decreasing `gap-sz'. When
;; `gap-sz' falls below some threshold, we reallocate with a larger `all-sz'.
;;
;; In the implementation, we actually keep track of the AFTER start offset
;; `aft-ofs' since it is used more often than `gap-sz'. In fact, most of the
;; variables in the diagram are for conceptualization only.
;;
;; A gap buffer port is a soft port (see Guile manual) that wraps a gap
;; buffer. Character and string writes, as well as character reads, are
;; supported. Flushing and closing are not supported.
;;
;; These procedures are exported:
;; (gb? OBJ)
;; (make-gap-buffer . INIT)
;; (gb-point GB)
;; (gb-point-min GB)
;; (gb-point-max GB)
;; (gb-insert-string! GB STRING)
;; (gb-insert-char! GB CHAR)
;; (gb-delete-char! GB COUNT)
;; (gb-goto-char GB LOCATION)
;; (gb->string GB)
;; (gb-filter! GB STRING-PROC)
;; (gb->lines GB)
;; (gb-filter-lines! GB LINES-PROC)
;; (make-gap-buffer-port GB)
;;
;; INIT is an optional port or a string. COUNT and LOCATION are integers.
;; STRING-PROC is a procedure that takes and returns a string. LINES-PROC is
;; a procedure that takes and returns a list of strings, each representing a
;; line of text (newlines are stripped and added back automatically).
;;
;; (The term and concept of "gap buffer" are borrowed from Emacs. We will
;; gladly return them when libemacs.so is available. ;-)
;;
;; Notes:
;; - overrun errors are suppressed silently
;;; Code:
(define-module (ice-9 gap-buffer)
\:autoload (srfi srfi-13) (string-join)
\:export (gb?
make-gap-buffer
gb-point
gb-point-min
gb-point-max
gb-insert-string!
gb-insert-char!
gb-delete-char!
gb-erase!
gb-goto-char
gb->string
gb-filter!
gb->lines
gb-filter-lines!
make-gap-buffer-port))
(define gap-buffer
(make-record-type 'gap-buffer
'(s ; the buffer, a string
all-sz ; total allocation
gap-ofs ; GAP starts, aka (1- point)
aft-ofs ; AFTER starts
)))
(define gb? (record-predicate gap-buffer))
(define s\: (record-accessor gap-buffer 's))
(define all-sz\: (record-accessor gap-buffer 'all-sz))
(define gap-ofs\: (record-accessor gap-buffer 'gap-ofs))
(define aft-ofs\: (record-accessor gap-buffer 'aft-ofs))
(define s! (record-modifier gap-buffer 's))
(define all-sz! (record-modifier gap-buffer 'all-sz))
(define gap-ofs! (record-modifier gap-buffer 'gap-ofs))
(define aft-ofs! (record-modifier gap-buffer 'aft-ofs))
;; todo: expose
(define default-initial-allocation 128)
(define default-chunk-size 128)
(define default-realloc-threshold 32)
(define (round-up n)
(* default-chunk-size (+ 1 (quotient n default-chunk-size))))
(define new (record-constructor gap-buffer '()))
(define (realloc gb inc)
(let* ((old-s (s\: gb))
(all-sz (all-sz\: gb))
(new-sz (+ all-sz inc))
(gap-ofs (gap-ofs\: gb))
(aft-ofs (aft-ofs\: gb))
(new-s (make-string new-sz))
(new-aft-ofs (+ aft-ofs inc)))
(substring-move! old-s 0 gap-ofs new-s 0)
(substring-move! old-s aft-ofs all-sz new-s new-aft-ofs)
(s! gb new-s)
(all-sz! gb new-sz)
(aft-ofs! gb new-aft-ofs)))
(define (make-gap-buffer . init) ; port/string
(let ((gb (new)))
(cond ((null? init)
(s! gb (make-string default-initial-allocation))
(all-sz! gb default-initial-allocation)
(gap-ofs! gb 0)
(aft-ofs! gb default-initial-allocation))
(else (let ((jam! (lambda (string len)
(let ((alloc (round-up len)))
(s! gb (make-string alloc))
(all-sz! gb alloc)
(substring-move! string 0 len (s\: gb) 0)
(gap-ofs! gb len)
(aft-ofs! gb alloc))))
(v (car init)))
(cond ((port? v)
(let ((next (lambda () (read-char v))))
(let loop ((c (next)) (acc '()) (len 0))
(if (eof-object? c)
(jam! (list->string (reverse acc)) len)
(loop (next) (cons c acc) (1+ len))))))
((string? v)
(jam! v (string-length v)))
(else (error "bad init type"))))))
gb))
(define (gb-point gb)
(1+ (gap-ofs\: gb)))
(define (gb-point-min gb) 1) ; no narrowing (for now)
(define (gb-point-max gb)
(1+ (- (all-sz\: gb) (- (aft-ofs\: gb) (gap-ofs\: gb)))))
(define (insert-prep gb len)
(let* ((gap-ofs (gap-ofs\: gb))
(aft-ofs (aft-ofs\: gb))
(slack (- (- aft-ofs gap-ofs) len)))
(and (< slack default-realloc-threshold)
(realloc gb (round-up (- slack))))
gap-ofs))
(define (gb-insert-string! gb string)
(let* ((len (string-length string))
(gap-ofs (insert-prep gb len)))
(substring-move! string 0 len (s\: gb) gap-ofs)
(gap-ofs! gb (+ gap-ofs len))))
(define (gb-insert-char! gb char)
(let ((gap-ofs (insert-prep gb 1)))
(string-set! (s\: gb) gap-ofs char)
(gap-ofs! gb (+ gap-ofs 1))))
(define (gb-delete-char! gb count)
(cond ((< count 0) ; backwards
(gap-ofs! gb (max 0 (+ (gap-ofs\: gb) count))))
((> count 0) ; forwards
(aft-ofs! gb (min (all-sz\: gb) (+ (aft-ofs\: gb) count))))
((= count 0) ; do nothing
#t)))
(define (gb-erase! gb)
(gap-ofs! gb 0)
(aft-ofs! gb (all-sz\: gb)))
(define (point++n! gb n s gap-ofs aft-ofs) ; n>0; warning: reckless
(substring-move! s aft-ofs (+ aft-ofs n) s gap-ofs)
(gap-ofs! gb (+ gap-ofs n))
(aft-ofs! gb (+ aft-ofs n)))
(define (point+-n! gb n s gap-ofs aft-ofs) ; n<0; warning: reckless
(substring-move! s (+ gap-ofs n) gap-ofs s (+ aft-ofs n))
(gap-ofs! gb (+ gap-ofs n))
(aft-ofs! gb (+ aft-ofs n)))
(define (gb-goto-char gb new-point)
(let ((pmax (gb-point-max gb)))
(or (and (< new-point 1) (gb-goto-char gb 1))
(and (> new-point pmax) (gb-goto-char gb pmax))
(let ((delta (- new-point (gb-point gb))))
(or (= delta 0)
((if (< delta 0)
point+-n!
point++n!)
gb delta (s\: gb) (gap-ofs\: gb) (aft-ofs\: gb))))))
new-point)
(define (gb->string gb)
(let ((s (s\: gb)))
(string-append (substring s 0 (gap-ofs\: gb))
(substring s (aft-ofs\: gb)))))
(define (gb-filter! gb string-proc)
(let ((new (string-proc (gb->string gb))))
(gb-erase! gb)
(gb-insert-string! gb new)))
(define (gb->lines gb)
(let ((str (gb->string gb)))
(let loop ((start 0) (acc '()))
(cond ((string-index str #\newline start)
=> (lambda (w)
(loop (1+ w) (cons (substring str start w) acc))))
(else (reverse (cons (substring str start) acc)))))))
(define (gb-filter-lines! gb lines-proc)
(let ((new-lines (lines-proc (gb->lines gb))))
(gb-erase! gb)
(gb-insert-string! gb (string-join new-lines #\newline))))
(define (make-gap-buffer-port gb)
(or (gb? gb)
(error "not a gap-buffer:" gb))
(make-soft-port
(vector
(lambda (c) (gb-insert-char! gb c))
(lambda (s) (gb-insert-string! gb s))
#f
(lambda () (let ((gap-ofs (gap-ofs\: gb))
(aft-ofs (aft-ofs\: gb)))
(if (= aft-ofs (all-sz\: gb))
#f
(let* ((s (s\: gb))
(c (string-ref s aft-ofs)))
(string-set! s gap-ofs c)
(gap-ofs! gb (1+ gap-ofs))
(aft-ofs! gb (1+ aft-ofs))
c))))
#f)
"rw"))
;;; gap-buffer.scm ends here
;;; Copyright (C) 1998, 2001, 2006, 2009, 2011 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Russ McManus (rewritten by Thien-Thi Nguyen)
;;; Commentary:
;;; This module implements some complex command line option parsing, in
;;; the spirit of the GNU C library function `getopt_long'. Both long
;;; and short options are supported.
;;;
;;; The theory is that people should be able to constrain the set of
;;; options they want to process using a grammar, rather than some arbitrary
;;; structure. The grammar makes the option descriptions easy to read.
;;;
;;; `getopt-long' is a procedure for parsing command-line arguments in a
;;; manner consistent with other GNU programs. `option-ref' is a procedure
;;; that facilitates processing of the `getopt-long' return value.
;;; (getopt-long ARGS GRAMMAR)
;;; Parse the arguments ARGS according to the argument list grammar GRAMMAR.
;;;
;;; ARGS should be a list of strings. Its first element should be the
;;; name of the program; subsequent elements should be the arguments
;;; that were passed to the program on the command line. The
;;; `program-arguments' procedure returns a list of this form.
;;;
;;; GRAMMAR is a list of the form:
;;; ((OPTION (PROPERTY VALUE) ...) ...)
;;;
;;; Each OPTION should be a symbol. `getopt-long' will accept a
;;; command-line option named `--OPTION'.
;;; Each option can have the following (PROPERTY VALUE) pairs:
;;;
;;; (single-char CHAR) --- Accept `-CHAR' as a single-character
;;; equivalent to `--OPTION'. This is how to specify traditional
;;; Unix-style flags.
;;; (required? BOOL) --- If BOOL is true, the option is required.
;;; getopt-long will raise an error if it is not found in ARGS.
;;; (value BOOL) --- If BOOL is #t, the option accepts a value; if
;;; it is #f, it does not; and if it is the symbol
;;; `optional', the option may appear in ARGS with or
;;; without a value.
;;; (predicate FUNC) --- If the option accepts a value (i.e. you
;;; specified `(value #t)' for this option), then getopt
;;; will apply FUNC to the value, and throw an exception
;;; if it returns #f. FUNC should be a procedure which
;;; accepts a string and returns a boolean value; you may
;;; need to use quasiquotes to get it into GRAMMAR.
;;;
;;; The (PROPERTY VALUE) pairs may occur in any order, but each
;;; property may occur only once. By default, options do not have
;;; single-character equivalents, are not required, and do not take
;;; values.
;;;
;;; In ARGS, single-character options may be combined, in the usual
;;; Unix fashion: ("-x" "-y") is equivalent to ("-xy"). If an option
;;; accepts values, then it must be the last option in the
;;; combination; the value is the next argument. So, for example, using
;;; the following grammar:
;;; ((apples (single-char #\a))
;;; (blimps (single-char #\b) (value #t))
;;; (catalexis (single-char #\c) (value #t)))
;;; the following argument lists would be acceptable:
;;; ("-a" "-b" "bang" "-c" "couth") ("bang" and "couth" are the values
;;; for "blimps" and "catalexis")
;;; ("-ab" "bang" "-c" "couth") (same)
;;; ("-ac" "couth" "-b" "bang") (same)
;;; ("-abc" "couth" "bang") (an error, since `-b' is not the
;;; last option in its combination)
;;;
;;; If an option's value is optional, then `getopt-long' decides
;;; whether it has a value by looking at what follows it in ARGS. If
;;; the next element is does not appear to be an option itself, then
;;; that element is the option's value.
;;;
;;; The value of a long option can appear as the next element in ARGS,
;;; or it can follow the option name, separated by an `=' character.
;;; Thus, using the same grammar as above, the following argument lists
;;; are equivalent:
;;; ("--apples" "Braeburn" "--blimps" "Goodyear")
;;; ("--apples=Braeburn" "--blimps" "Goodyear")
;;; ("--blimps" "Goodyear" "--apples=Braeburn")
;;;
;;; If the option "--" appears in ARGS, argument parsing stops there;
;;; subsequent arguments are returned as ordinary arguments, even if
;;; they resemble options. So, in the argument list:
;;; ("--apples" "Granny Smith" "--" "--blimp" "Goodyear")
;;; `getopt-long' will recognize the `apples' option as having the
;;; value "Granny Smith", but it will not recognize the `blimp'
;;; option; it will return the strings "--blimp" and "Goodyear" as
;;; ordinary argument strings.
;;;
;;; The `getopt-long' function returns the parsed argument list as an
;;; assocation list, mapping option names --- the symbols from GRAMMAR
;;; --- onto their values, or #t if the option does not accept a value.
;;; Unused options do not appear in the alist.
;;;
;;; All arguments that are not the value of any option are returned
;;; as a list, associated with the empty list.
;;;
;;; `getopt-long' throws an exception if:
;;; - it finds an unrecognized property in GRAMMAR
;;; - the value of the `single-char' property is not a character
;;; - it finds an unrecognized option in ARGS
;;; - a required option is omitted
;;; - an option that requires an argument doesn't get one
;;; - an option that doesn't accept an argument does get one (this can
;;; only happen using the long option `--opt=value' syntax)
;;; - an option predicate fails
;;;
;;; So, for example:
;;;
;;; (define grammar
;;; `((lockfile-dir (required? #t)
;;; (value #t)
;;; (single-char #\k)
;;; (predicate ,file-is-directory?))
;;; (verbose (required? #f)
;;; (single-char #\v)
;;; (value #f))
;;; (x-includes (single-char #\x))
;;; (rnet-server (single-char #\y)
;;; (predicate ,string?))))
;;;
;;; (getopt-long '("my-prog" "-vk" "/tmp" "foo1" "--x-includes=/usr/include"
;;; "--rnet-server=lamprod" "--" "-fred" "foo2" "foo3")
;;; grammar)
;;; => ((() "foo1" "-fred" "foo2" "foo3")
;;; (rnet-server . "lamprod")
;;; (x-includes . "/usr/include")
;;; (lockfile-dir . "/tmp")
;;; (verbose . #t))
;;; (option-ref OPTIONS KEY DEFAULT)
;;; Return value in alist OPTIONS using KEY, a symbol; or DEFAULT if not
;;; found. The value is either a string or `#t'.
;;;
;;; For example, using the `getopt-long' return value from above:
;;;
;;; (option-ref (getopt-long ...) 'x-includes 42) => "/usr/include"
;;; (option-ref (getopt-long ...) 'not-a-key! 31) => 31
;;; Code:
(define-module (ice-9 getopt-long)
#\use-module ((ice-9 common-list) #\select (remove-if-not))
#\use-module (srfi srfi-9)
#\use-module (ice-9 match)
#\use-module (ice-9 regex)
#\use-module (ice-9 optargs)
#\export (getopt-long option-ref))
(define %program-name (make-fluid "guile"))
(define (program-name)
(fluid-ref %program-name))
(define (fatal-error fmt . args)
(format (current-error-port) "~a: " (program-name))
(apply format (current-error-port) fmt args)
(newline (current-error-port))
(exit 1))
(define-record-type option-spec
(%make-option-spec name required? option-spec->single-char predicate value-policy)
option-spec?
(name
option-spec->name set-option-spec-name!)
(required?
option-spec->required? set-option-spec-required?!)
(option-spec->single-char
option-spec->single-char set-option-spec-single-char!)
(predicate
option-spec->predicate set-option-spec-predicate!)
(value-policy
option-spec->value-policy set-option-spec-value-policy!))
(define (make-option-spec name)
(%make-option-spec name #f #f #f #f))
(define (parse-option-spec desc)
(let ((spec (make-option-spec (symbol->string (car desc)))))
(for-each (match-lambda
(('required? val)
(set-option-spec-required?! spec val))
(('value val)
(set-option-spec-value-policy! spec val))
(('single-char val)
(or (char? val)
(error "`single-char' value must be a char!"))
(set-option-spec-single-char! spec val))
(('predicate pred)
(set-option-spec-predicate!
spec (lambda (name val)
(or (not val)
(pred val)
(fatal-error "option predicate failed: --~a"
name)))))
((prop val)
(error "invalid getopt-long option property:" prop)))
(cdr desc))
spec))
(define (split-arg-list argument-list)
;; Scan ARGUMENT-LIST for "--" and return (BEFORE-LS . AFTER-LS).
;; Discard the "--". If no "--" is found, AFTER-LS is empty.
(let loop ((yes '()) (no argument-list))
(cond ((null? no) (cons (reverse yes) no))
((string=? "--" (car no)) (cons (reverse yes) (cdr no)))
(else (loop (cons (car no) yes) (cdr no))))))
(define short-opt-rx (make-regexp "^-([a-zA-Z]+)(.*)"))
(define long-opt-no-value-rx (make-regexp "^--([^=]+)$"))
(define long-opt-with-value-rx (make-regexp "^--([^=]+)=(.*)"))
(define (looks-like-an-option string)
(or (regexp-exec short-opt-rx string)
(regexp-exec long-opt-with-value-rx string)
(regexp-exec long-opt-no-value-rx string)))
(define (process-options specs argument-ls stop-at-first-non-option)
;; Use SPECS to scan ARGUMENT-LS; return (FOUND . ETC).
;; FOUND is an unordered list of option specs for found options, while ETC
;; is an order-maintained list of elements in ARGUMENT-LS that are neither
;; options nor their values.
(let ((idx (map (lambda (spec)
(cons (option-spec->name spec) spec))
specs))
(sc-idx (map (lambda (spec)
(cons (make-string 1 (option-spec->single-char spec))
spec))
(remove-if-not option-spec->single-char specs))))
(let loop ((unclumped 0) (argument-ls argument-ls) (found '()) (etc '()))
(define (eat! spec ls)
(cond
((eq? 'optional (option-spec->value-policy spec))
(if (or (null? ls)
(looks-like-an-option (car ls)))
(loop (- unclumped 1) ls (acons spec #t found) etc)
(loop (- unclumped 2) (cdr ls) (acons spec (car ls) found) etc)))
((eq? #t (option-spec->value-policy spec))
(if (or (null? ls)
(looks-like-an-option (car ls)))
(fatal-error "option must be specified with argument: --~a"
(option-spec->name spec))
(loop (- unclumped 2) (cdr ls) (acons spec (car ls) found) etc)))
(else
(loop (- unclumped 1) ls (acons spec #t found) etc))))
(match argument-ls
(()
(cons found (reverse etc)))
((opt . rest)
(cond
((regexp-exec short-opt-rx opt)
=> (lambda (match)
(if (> unclumped 0)
;; Next option is known not to be clumped.
(let* ((c (match:substring match 1))
(spec (or (assoc-ref sc-idx c)
(fatal-error "no such option: -~a" c))))
(eat! spec rest))
;; Expand a clumped group of short options.
(let* ((extra (match:substring match 2))
(unclumped-opts
(append (map (lambda (c)
(string-append "-" (make-string 1 c)))
(string->list
(match:substring match 1)))
(if (string=? "" extra) '() (list extra)))))
(loop (length unclumped-opts)
(append unclumped-opts rest)
found
etc)))))
((regexp-exec long-opt-no-value-rx opt)
=> (lambda (match)
(let* ((opt (match:substring match 1))
(spec (or (assoc-ref idx opt)
(fatal-error "no such option: --~a" opt))))
(eat! spec rest))))
((regexp-exec long-opt-with-value-rx opt)
=> (lambda (match)
(let* ((opt (match:substring match 1))
(spec (or (assoc-ref idx opt)
(fatal-error "no such option: --~a" opt))))
(if (option-spec->value-policy spec)
(eat! spec (cons (match:substring match 2) rest))
(fatal-error "option does not support argument: --~a"
opt)))))
((and stop-at-first-non-option
(<= unclumped 0))
(cons found (append (reverse etc) argument-ls)))
(else
(loop (- unclumped 1) rest found (cons opt etc)))))))))
(define* (getopt-long program-arguments option-desc-list
#\key stop-at-first-non-option)
"Process options, handling both long and short options, similar to
the glibc function 'getopt_long'. PROGRAM-ARGUMENTS should be a value
similar to what (program-arguments) returns. OPTION-DESC-LIST is a
list of option descriptions. Each option description must satisfy the
following grammar:
<option-spec> :: (<name> . <attribute-ls>)
<attribute-ls> :: (<attribute> . <attribute-ls>)
| ()
<attribute> :: <required-attribute>
| <arg-required-attribute>
| <single-char-attribute>
| <predicate-attribute>
| <value-attribute>
<required-attribute> :: (required? <boolean>)
<single-char-attribute> :: (single-char <char>)
<value-attribute> :: (value #t)
(value #f)
(value optional)
<predicate-attribute> :: (predicate <1-ary-function>)
The procedure returns an alist of option names and values. Each
option name is a symbol. The option value will be '#t' if no value
was specified. There is a special item in the returned alist with a
key of the empty list, (): the list of arguments that are not options
or option values.
By default, options are not required, and option values are not
required. By default, single character equivalents are not supported;
if you want to allow the user to use single character options, you need
to add a `single-char' clause to the option description."
(with-fluids ((%program-name (car program-arguments)))
(let* ((specifications (map parse-option-spec option-desc-list))
(pair (split-arg-list (cdr program-arguments)))
(split-ls (car pair))
(non-split-ls (cdr pair))
(found/etc (process-options specifications split-ls
stop-at-first-non-option))
(found (car found/etc))
(rest-ls (append (cdr found/etc) non-split-ls)))
(for-each (lambda (spec)
(let ((name (option-spec->name spec))
(val (assq-ref found spec)))
(and (option-spec->required? spec)
(or val
(fatal-error "option must be specified: --~a"
name)))
(let ((pred (option-spec->predicate spec)))
(and pred (pred name val)))))
specifications)
(for-each (lambda (spec+val)
(set-car! spec+val
(string->symbol (option-spec->name (car spec+val)))))
found)
(cons (cons '() rest-ls) found))))
(define (option-ref options key default)
"Return value in alist OPTIONS using KEY, a symbol; or DEFAULT if not found.
The value is either a string or `#t'."
(or (assq-ref options key) default))
;;; getopt-long.scm ends here
;;;; hash-table.scm --- Additional hash table procedures
;;;; Copyright (C) 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 hash-table)
#\export (alist->hash-table
alist->hashq-table
alist->hashv-table
alist->hashx-table))
(define-syntax-rule (define-alist-converter name hash-set-proc)
(define (name alist)
"Convert ALIST into a hash table."
(let ((table (make-hash-table)))
(for-each (lambda (pair)
(hash-set-proc table (car pair) (cdr pair)))
(reverse alist))
table)))
(define-alist-converter alist->hash-table hash-set!)
(define-alist-converter alist->hashq-table hashq-set!)
(define-alist-converter alist->hashv-table hashv-set!)
(define (alist->hashx-table hash assoc alist)
"Convert ALIST into a hash table with custom HASH and ASSOC
procedures."
(let ((table (make-hash-table)))
(for-each (lambda (pair)
(hashx-set! hash assoc table (car pair) (cdr pair)))
(reverse alist))
table))
;;; installed-scm-file
;;;; Copyright (C) 1995, 1996, 1998, 2001, 2003, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 hcons)
\:export (hashq-cons-hash hashq-cons-assoc hashq-cons-get-handle
hashq-cons-create-handle! hashq-cons-ref hashq-cons-set! hashq-cons
hashq-conser make-gc-buffer))
;;; {Eq? hash-consing}
;;;
;;; A hash conser maintains a private universe of pairs s.t. if
;;; two cons calls pass eq? arguments, the pairs returned are eq?.
;;;
;;; A hash conser does not contribute life to the pairs it returns.
;;;
(define (hashq-cons-hash pair n)
(modulo (logxor (hashq (car pair) 4194303)
(hashq (cdr pair) 4194303))
n))
(define (hashq-cons-assoc key l)
(and (not (null? l))
(or (and (pair? l) ; If not a pair, use its cdr?
(pair? (car l))
(pair? (caar l))
(eq? (car key) (caaar l))
(eq? (cdr key) (cdaar l))
(car l))
(hashq-cons-assoc key (cdr l)))))
(define (hashq-cons-get-handle table key)
(hashx-get-handle hashq-cons-hash hashq-cons-assoc table key))
(define (hashq-cons-create-handle! table key init)
(hashx-create-handle! hashq-cons-hash hashq-cons-assoc table key init))
(define (hashq-cons-ref table key)
(hashx-ref hashq-cons-hash hashq-cons-assoc table key #f))
(define (hashq-cons-set! table key val)
(hashx-set! hashq-cons-hash hashq-cons-assoc table key val))
(define (hashq-cons table a d)
(car (hashq-cons-create-handle! table (cons a d) #f)))
(define (hashq-conser hash-tab-or-size)
(let ((table (if (vector? hash-tab-or-size)
hash-tab-or-size
(make-doubly-weak-hash-table hash-tab-or-size))))
(lambda (a d) (hashq-cons table a d))))
(define (make-gc-buffer n)
(let ((ring (make-list n #f)))
(append! ring ring)
(lambda (next)
(set-car! ring next)
(set! ring (cdr ring))
next)))
;;;; Copyright (C) 2000, 2001, 2004, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; A simple value history support
(define-module (ice-9 history)
#\export (value-history-enabled? enable-value-history! disable-value-history!
clear-value-history!))
(define-module* '(value-history))
(define *value-history-enabled?* #f)
(define (value-history-enabled?)
*value-history-enabled?*)
(define (use-value-history x)
(module-use! (current-module)
(resolve-interface '(value-history))))
(define save-value-history
(let ((count 0)
(history (resolve-module '(value-history))))
(lambda (v)
(if (not (unspecified? v))
(let* ((c (1+ count))
(s (string->symbol (simple-format #f "$~A" c))))
(simple-format #t "~A = " s)
(module-define! history s v)
(module-export! history (list s))
(set! count c))))))
(define (enable-value-history!)
(if (not (value-history-enabled?))
(begin
(add-hook! before-eval-hook use-value-history)
(add-hook! before-print-hook save-value-history)
(set! *value-history-enabled?* #t))))
(define (disable-value-history!)
(if (value-history-enabled?)
(begin
(remove-hook! before-eval-hook use-value-history)
(remove-hook! before-print-hook save-value-history)
(set! *value-history-enabled?* #f))))
(define (clear-value-history!)
(let ((history (resolve-module '(value-history))))
(hash-clear! (module-obarray history))
(hash-clear! (module-obarray (module-public-interface history)))))
(enable-value-history!)
;;;; i18n.scm --- internationalization support -*- coding: utf-8 -*-
;;;; Copyright (C) 2006, 2007, 2009, 2010, 2012,
;;;; 2017 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;;;
;;; This module provides a number of routines that support
;;; internationalization (e.g., locale-dependent text collation, character
;;; mapping, etc.). It also defines `locale' objects, representing locale
;;; settings, that may be passed around to most of these procedures.
;;;
;;; Code:
(define-module (ice-9 i18n)
\:use-module (ice-9 optargs)
\:export (;; `locale' type
make-locale locale?
%global-locale
;; text collation
string-locale<? string-locale>?
string-locale-ci<? string-locale-ci>? string-locale-ci=?
char-locale<? char-locale>?
char-locale-ci<? char-locale-ci>? char-locale-ci=?
;; character mapping
char-locale-downcase char-locale-upcase char-locale-titlecase
string-locale-downcase string-locale-upcase string-locale-titlecase
;; reading numbers
locale-string->integer locale-string->inexact
;; charset/encoding
locale-encoding
;; days and months
locale-day-short locale-day locale-month-short locale-month
;; date and time
locale-am-string locale-pm-string
locale-date+time-format locale-date-format locale-time-format
locale-time+am/pm-format
locale-era locale-era-year
locale-era-date-format locale-era-date+time-format
locale-era-time-format
;; monetary
locale-currency-symbol
locale-monetary-decimal-point locale-monetary-thousands-separator
locale-monetary-grouping locale-monetary-fractional-digits
locale-currency-symbol-precedes-positive?
locale-currency-symbol-precedes-negative?
locale-positive-separated-by-space?
locale-negative-separated-by-space?
locale-monetary-positive-sign locale-monetary-negative-sign
locale-positive-sign-position locale-negative-sign-position
monetary-amount->locale-string
;; number formatting
locale-digit-grouping locale-decimal-point
locale-thousands-separator
number->locale-string
;; miscellaneous
locale-yes-regexp locale-no-regexp))
(eval-when (expand load eval)
(load-extension (string-append "libguile-" (effective-version))
"scm_init_i18n"))
;;;
;;; Charset/encoding.
;;;
(define (locale-encoding . locale)
(apply nl-langinfo CODESET locale))
;;;
;;; Months and days.
;;;
;; Helper macro: Define a procedure named NAME that maps its argument to
;; NL-ITEMS. Gnulib guarantees that these items are available.
(define-macro (define-vector-langinfo-mapping name nl-items)
(let* ((item-count (length nl-items))
(defines `(define %nl-items (vector #f ,@nl-items)))
(make-body (lambda (result)
`(if (and (integer? item) (exact? item))
(if (and (>= item 1) (<= item ,item-count))
,result
(throw 'out-of-range "out of range" item))
(throw 'wrong-type-arg "wrong argument type" item)))))
`(define (,name item . locale)
,defines
,(make-body '(apply nl-langinfo (vector-ref %nl-items item) locale)))))
(define-vector-langinfo-mapping locale-day-short
(ABDAY_1 ABDAY_2 ABDAY_3 ABDAY_4 ABDAY_5 ABDAY_6 ABDAY_7))
(define-vector-langinfo-mapping locale-day
(DAY_1 DAY_2 DAY_3 DAY_4 DAY_5 DAY_6 DAY_7))
(define-vector-langinfo-mapping locale-month-short
(ABMON_1 ABMON_2 ABMON_3 ABMON_4 ABMON_5 ABMON_6
ABMON_7 ABMON_8 ABMON_9 ABMON_10 ABMON_11 ABMON_12))
(define-vector-langinfo-mapping locale-month
(MON_1 MON_2 MON_3 MON_4 MON_5 MON_6 MON_7 MON_8 MON_9 MON_10 MON_11 MON_12))
;;;
;;; Date and time.
;;;
;; Define a procedure NAME that gets langinfo item ITEM. Gnulib's
;; `nl_langinfo' does not guarantee that all these items are supported
;; (for instance, `GROUPING' is lacking on Darwin and Gnulib provides no
;; replacement), so use DEFAULT as the default value when ITEM is not
;; available.
(define-macro (define-simple-langinfo-mapping name item default)
(let ((body (if (defined? item)
`(apply nl-langinfo ,item locale)
default)))
`(define (,name . locale)
,body)))
(define-simple-langinfo-mapping locale-am-string
AM_STR "AM")
(define-simple-langinfo-mapping locale-pm-string
PM_STR "PM")
(define-simple-langinfo-mapping locale-date+time-format
D_T_FMT "%a %b %e %H:%M:%S %Y")
(define-simple-langinfo-mapping locale-date-format
D_FMT "%m/%d/%y")
(define-simple-langinfo-mapping locale-time-format
T_FMT "%H:%M:%S")
(define-simple-langinfo-mapping locale-time+am/pm-format
T_FMT_AMPM "%I:%M:%S %p")
(define-simple-langinfo-mapping locale-era
ERA "")
(define-simple-langinfo-mapping locale-era-year
ERA_YEAR "")
(define-simple-langinfo-mapping locale-era-date+time-format
ERA_D_T_FMT "")
(define-simple-langinfo-mapping locale-era-date-format
ERA_D_FMT "")
(define-simple-langinfo-mapping locale-era-time-format
ERA_T_FMT "")
;;;
;;; Monetary information.
;;;
;; Define a procedure NAME that gets item LOCAL-ITEM or INTL-ITEM,
;; depending on whether the caller asked for the international version
;; or not. Since Gnulib's `nl_langinfo' module doesn't guarantee that
;; all these items are available, use DEFAULT/LOCAL and DEFAULT/INTL as
;; default values when the system does not support them.
(define-macro (define-monetary-langinfo-mapping name local-item intl-item
default/local default/intl)
(let ((body
(let ((intl (if (defined? intl-item)
`(apply nl-langinfo ,intl-item locale)
default/intl))
(local (if (defined? local-item)
`(apply nl-langinfo ,local-item locale)
default/local)))
`(if intl? ,intl ,local))))
`(define (,name intl? . locale)
,body)))
;; FIXME: How can we use ALT_DIGITS?
(define-monetary-langinfo-mapping locale-currency-symbol
CRNCYSTR INT_CURR_SYMBOL
"-" "")
(define-monetary-langinfo-mapping locale-monetary-fractional-digits
FRAC_DIGITS INT_FRAC_DIGITS
2 2)
(define-simple-langinfo-mapping locale-monetary-positive-sign
POSITIVE_SIGN "+")
(define-simple-langinfo-mapping locale-monetary-negative-sign
NEGATIVE_SIGN "-")
(define-simple-langinfo-mapping locale-monetary-decimal-point
MON_DECIMAL_POINT "")
(define-simple-langinfo-mapping locale-monetary-thousands-separator
MON_THOUSANDS_SEP "")
(define-simple-langinfo-mapping locale-monetary-digit-grouping
MON_GROUPING '())
(define-monetary-langinfo-mapping locale-currency-symbol-precedes-positive?
P_CS_PRECEDES INT_P_CS_PRECEDES
#t #t)
(define-monetary-langinfo-mapping locale-currency-symbol-precedes-negative?
N_CS_PRECEDES INT_N_CS_PRECEDES
#t #t)
(define-monetary-langinfo-mapping locale-positive-separated-by-space?
;; Whether a space should be inserted between a positive amount and the
;; currency symbol.
P_SEP_BY_SPACE INT_P_SEP_BY_SPACE
#t #t)
(define-monetary-langinfo-mapping locale-negative-separated-by-space?
;; Whether a space should be inserted between a negative amount and the
;; currency symbol.
N_SEP_BY_SPACE INT_N_SEP_BY_SPACE
#t #t)
(define-monetary-langinfo-mapping locale-positive-sign-position
;; Position of the positive sign wrt. currency symbol and quantity in a
;; monetary amount.
P_SIGN_POSN INT_P_SIGN_POSN
'unspecified 'unspecified)
(define-monetary-langinfo-mapping locale-negative-sign-position
;; Position of the negative sign wrt. currency symbol and quantity in a
;; monetary amount.
N_SIGN_POSN INT_N_SIGN_POSN
'unspecified 'unspecified)
(define (integer->string number)
"Return a string representing NUMBER, an integer, written in base 10."
(define (digit->char digit)
(integer->char (+ digit (char->integer #\0))))
(if (zero? number)
"0"
(let loop ((number number)
(digits '()))
(if (zero? number)
(list->string digits)
(loop (quotient number 10)
(cons (digit->char (modulo number 10))
digits))))))
(define (number-decimal-string number digit-count)
"Return a string representing the decimal part of NUMBER. When
DIGIT-COUNT is an integer, return exactly DIGIT-COUNT digits; when
DIGIT-COUNT is #t, return as many decimals as necessary, up to an
arbitrary limit."
(define max-decimals
5)
;; XXX: This is brute-force and could be improved by following one of
;; the "Printing Floating-Point Numbers Quickly and Accurately"
;; papers.
(if (integer? digit-count)
(let ((number (* (expt 10 digit-count)
(- number (floor number)))))
(string-pad (integer->string (round (inexact->exact number)))
digit-count
#\0))
(let loop ((decimals 0))
(let ((number\' (* number (expt 10 decimals))))
(if (or (= number\' (floor number\'))
(>= decimals max-decimals))
(let* ((fraction (- number\'
(* (floor number)
(expt 10 decimals))))
(str (integer->string
(round (inexact->exact fraction)))))
(if (zero? fraction)
""
str))
(loop (+ decimals 1)))))))
(define (%number-integer-part int grouping separator)
;; Process INT (a string denoting a number's integer part) and return a new
;; string with digit grouping and separators according to GROUPING (a list,
;; potentially circular) and SEPARATOR (a string).
;; Process INT from right to left.
(let loop ((int int)
(grouping grouping)
(result '()))
(cond ((string=? int "") (apply string-append result))
((null? grouping) (apply string-append int result))
(else
(let* ((len (string-length int))
(cut (min (car grouping) len)))
(loop (substring int 0 (- len cut))
(cdr grouping)
(let ((sub (substring int (- len cut) len)))
(if (> len cut)
(cons* separator sub result)
(cons sub result)))))))))
(define (add-monetary-sign+currency amount figure intl? locale)
;; Add a sign and currency symbol around FIGURE. FIGURE should be a
;; formatted unsigned amount (a string) representing AMOUNT.
(let* ((positive? (> amount 0))
(sign
(cond ((> amount 0) (locale-monetary-positive-sign locale))
((< amount 0) (locale-monetary-negative-sign locale))
(else "")))
(currency (locale-currency-symbol intl? locale))
(currency-precedes?
(if positive?
locale-currency-symbol-precedes-positive?
locale-currency-symbol-precedes-negative?))
(separated?
(if positive?
locale-positive-separated-by-space?
locale-negative-separated-by-space?))
(sign-position
(if positive?
locale-positive-sign-position
locale-negative-sign-position))
(currency-space
(if (separated? intl? locale) " " ""))
(append-currency
(lambda (amt)
(if (currency-precedes? intl? locale)
(string-append currency currency-space amt)
(string-append amt currency-space currency)))))
(case (sign-position intl? locale)
((parenthesize)
(string-append "(" (append-currency figure) ")"))
((sign-before)
(string-append sign (append-currency figure)))
((sign-after unspecified)
;; following glibc's recommendation for `unspecified'.
(if (currency-precedes? intl? locale)
(string-append currency currency-space sign figure)
(string-append figure currency-space currency sign)))
((sign-before-currency-symbol)
(if (currency-precedes? intl? locale)
(string-append sign currency currency-space figure)
(string-append figure currency-space sign currency))) ;; unlikely
((sign-after-currency-symbol)
(if (currency-precedes? intl? locale)
(string-append currency sign currency-space figure)
(string-append figure currency-space currency sign)))
(else
(error "unsupported sign position" (sign-position intl? locale))))))
(define* (monetary-amount->locale-string amount intl?
#\optional (locale %global-locale))
"Convert @var{amount} (an inexact) into a string according to the cultural
conventions of either @var{locale} (a locale object) or the current locale.
If @var{intl?} is true, then the international monetary format for the given
locale is used."
(let* ((fraction-digits
(or (locale-monetary-fractional-digits intl? locale) 2))
(decimal-part
(lambda (dec)
(if (or (string=? dec "") (eq? 0 fraction-digits))
""
(string-append (locale-monetary-decimal-point locale)
(if (< fraction-digits (string-length dec))
(substring dec 0 fraction-digits)
dec)))))
(int (integer->string (inexact->exact
(floor (abs amount)))))
(dec (decimal-part
(number-decimal-string (abs amount)
fraction-digits)))
(grouping (locale-monetary-digit-grouping locale))
(separator (locale-monetary-thousands-separator locale)))
(add-monetary-sign+currency amount
(string-append
(%number-integer-part int grouping
separator)
dec)
intl? locale)))
;;;
;;; Number formatting.
;;;
(define-simple-langinfo-mapping locale-digit-grouping
GROUPING '())
(define-simple-langinfo-mapping locale-decimal-point
RADIXCHAR ".")
(define-simple-langinfo-mapping locale-thousands-separator
THOUSEP "")
(define* (number->locale-string number
#\optional (fraction-digits #t)
(locale %global-locale))
"Convert @var{number} (an inexact) into a string according to the cultural
conventions of either @var{locale} (a locale object) or the current locale.
By default, print as many fractional digits as necessary, up to an upper bound.
Optionally, @var{fraction-digits} may be bound to an integer specifying the
number of fractional digits to be displayed."
(let* ((sign
(cond ((> number 0) "")
((< number 0) "-")
(else "")))
(decimal-part
(lambda (dec)
(if (or (string=? dec "") (eq? 0 fraction-digits))
""
(string-append (locale-decimal-point locale)
(if (and (integer? fraction-digits)
(< fraction-digits
(string-length dec)))
(substring dec 0 fraction-digits)
dec))))))
(let* ((int (integer->string (inexact->exact
(floor (abs number)))))
(dec (decimal-part
(number-decimal-string (abs number)
fraction-digits)))
(grouping (locale-digit-grouping locale))
(separator (locale-thousands-separator locale)))
(string-append sign
(%number-integer-part int grouping separator)
dec))))
;;;
;;; Miscellaneous.
;;;
(define-simple-langinfo-mapping locale-yes-regexp
YESEXPR "^[yY]")
(define-simple-langinfo-mapping locale-no-regexp
NOEXPR "^[nN]")
;; `YESSTR' and `NOSTR' are considered deprecated so we don't provide them.
;;; i18n.scm ends here
;;; Encoding and decoding byte representations of strings
;; Copyright (C) 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (ice-9 iconv)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\use-module ((ice-9 rdelim) #\select (read-string))
#\export (string->bytevector
bytevector->string
call-with-encoded-output-string))
;; Like call-with-output-string, but actually closes the port.
(define (call-with-output-string* proc)
(let ((port (open-output-string)))
(proc port)
(let ((str (get-output-string port)))
(close-port port)
str)))
(define (call-with-output-bytevector* proc)
(call-with-values (lambda () (open-bytevector-output-port))
(lambda (port get-bytevector)
(proc port)
(let ((bv (get-bytevector)))
(close-port port)
bv))))
(define* (call-with-encoded-output-string encoding proc
#\optional
(conversion-strategy 'error))
"Call PROC on a fresh port. Encode the resulting string as a
bytevector according to ENCODING, and return the bytevector."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
;; I don't know why, but this appears to be faster; at least for
;; serving examples/debug-sxml.scm (1464 reqs/s versus 850
;; reqs/s).
(string->utf8 (call-with-output-string* proc))
(call-with-output-bytevector*
(lambda (port)
(set-port-encoding! port encoding)
(if conversion-strategy
(set-port-conversion-strategy! port conversion-strategy))
(proc port)))))
;; TODO: Provide C implementations that call scm_from_stringn and
;; friends?
(define* (string->bytevector str encoding
#\optional (conversion-strategy 'error))
"Encode STRING according to ENCODING, which should be a string naming
a character encoding, like \"utf-8\"."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
(string->utf8 str)
(call-with-encoded-output-string
encoding
(lambda (port)
(display str port))
conversion-strategy)))
(define* (bytevector->string bv encoding
#\optional (conversion-strategy 'error))
"Decode the string represented by BV. The bytes in the bytevector
will be interpreted according to ENCODING, which should be a string
naming a character encoding, like \"utf-8\"."
(if (and (string-ci=? encoding "utf-8")
(eq? conversion-strategy 'error))
(utf8->string bv)
(let ((p (open-bytevector-input-port bv)))
(set-port-encoding! p encoding)
(if conversion-strategy
(set-port-conversion-strategy! p conversion-strategy))
(let ((res (read-string p)))
(close-port p)
(if (eof-object? res)
""
res)))))
;;; installed-scm-file
;;;; Copyright (C) 1996, 1998, 2001, 2003, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 lineio)
\:use-module (ice-9 rdelim)
\:export (unread-string read-string lineio-port?
make-line-buffering-input-port))
;;; {Line Buffering Input Ports}
;;;
;;; [This is a work-around to get past certain deficiencies in the capabilities
;;; of ports. Eventually, ports should be fixed and this module nuked.]
;;;
;;; A line buffering input port supports:
;;;
;;; read-string which returns the next line of input
;;; unread-string which pushes a line back onto the stream
;;;
;;; The implementation of unread-string is kind of limited; it doesn't
;;; interact properly with unread-char, or any of the other port
;;; reading functions. Only read-string will get you back the things that
;;; unread-string accepts.
;;;
;;; Normally a "line" is all characters up to and including a newline.
;;; If lines are put back using unread-string, they can be broken arbitrarily
;;; -- that is, read-string returns strings passed to unread-string (or
;;; shared substrings of them).
;;;
;; read-string port
;; unread-string port str
;; Read (or buffer) a line from PORT.
;;
;; Not all ports support these functions -- only those with
;; 'unread-string and 'read-string properties, bound to hooks
;; implementing these functions.
;;
(define (unread-string str line-buffering-input-port)
((object-property line-buffering-input-port 'unread-string) str))
;;
(define (read-string line-buffering-input-port)
((object-property line-buffering-input-port 'read-string)))
(define (lineio-port? port)
(not (not (object-property port 'read-string))))
;; make-line-buffering-input-port port
;; Return a wrapper for PORT. The wrapper handles read-string/unread-string.
;;
;; The port returned by this function reads newline terminated lines from PORT.
;; It buffers these characters internally, and parsels them out via calls
;; to read-char, read-string, and unread-string.
;;
(define (make-line-buffering-input-port underlying-port)
(let* (;; buffers - a list of strings put back by unread-string or cached
;; using read-line.
;;
(buffers '())
;; getc - return the next character from a buffer or from the underlying
;; port.
;;
(getc (lambda ()
(if (not buffers)
(read-char underlying-port)
(let ((c (string-ref (car buffers) 0)))
(if (= 1 (string-length (car buffers)))
(set! buffers (cdr buffers))
(set-car! buffers (substring (car buffers) 1)))
c))))
(propogate-close (lambda () (close-port underlying-port)))
(self (make-soft-port (vector #f #f #f getc propogate-close) "r"))
(unread-string (lambda (str)
(and (< 0 (string-length str))
(set! buffers (cons str buffers)))))
(read-string (lambda ()
(cond
((not (null? buffers))
(let ((answer (car buffers)))
(set! buffers (cdr buffers))
answer))
(else
(read-line underlying-port 'concat)))))) ;handle-newline->concat
(set-object-property! self 'unread-string unread-string)
(set-object-property! self 'read-string read-string)
self))
;;;; List functions not provided in R5RS or srfi-1
;;; Copyright (C) 2003, 2006 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 list)
\:export (rassoc rassv rassq))
(define (generic-rassoc key alist =)
(let loop ((ls alist))
(and (not (null? ls))
(if (= key (cdar ls))
(car ls)
(loop (cdr ls))))))
(define (rassoc key alist . =)
(generic-rassoc key alist (if (null? =) equal? (car =))))
(define (rassv key alist)
(generic-rassoc key alist eqv?))
(define (rassq key alist)
(generic-rassoc key alist eq?))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2012, 2013 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 local-eval)
#\use-module (ice-9 format)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (system base compile)
#\use-module (system syntax)
#\export (the-environment local-eval local-compile))
(define-record-type lexical-environment-type
(make-lexical-environment scope wrapper boxes patterns)
lexical-environment?
(scope lexenv-scope)
(wrapper lexenv-wrapper)
(boxes lexenv-boxes)
(patterns lexenv-patterns))
(set-record-type-printer!
lexical-environment-type
(lambda (e port)
(format port "#<lexical-environment ~S (~S bindings)>"
(syntax-module (lexenv-scope e))
(+ (length (lexenv-boxes e)) (length (lexenv-patterns e))))))
(define-syntax syntax-object-of
(lambda (form)
(syntax-case form ()
((_ x) #`(quote #,(datum->syntax #'x #'x))))))
(define-syntax-rule (make-box v)
(case-lambda
(() v)
((x) (set! v x))))
(define (make-transformer-from-box id trans)
(set-procedure-property! trans 'identifier-syntax-box id)
trans)
(define-syntax-rule (identifier-syntax-from-box box)
(make-transformer-from-box
(syntax-object-of box)
(identifier-syntax (id (box))
((set! id x) (box x)))))
(define (unsupported-binding name)
(make-variable-transformer
(lambda (x)
(syntax-violation
'local-eval
"unsupported binding captured by (the-environment)"
x))))
(define (within-nested-ellipses id lvl)
(let loop ((s id) (n lvl))
(if (zero? n)
s
(loop #`(#,s (... ...)) (- n 1)))))
;; Analyze the set of bound identifiers IDS. Return four values:
;;
;; capture: A list of forms that will be emitted in the expansion of
;; `the-environment' to capture lexical variables.
;;
;; formals: Corresponding formal parameters for use in the lambda that
;; re-introduces those variables. These are temporary identifiers, and
;; as such if we have a nested `the-environment', there is no need to
;; capture them. (See the notes on nested `the-environment' and
;; proxies, below.)
;;
;; wrappers: A list of procedures of type SYNTAX -> SYNTAX, used to wrap
;; the expression to be evaluated in forms that re-introduce the
;; variable. The forms will be nested so that the variable shadowing
;; semantics of the original form are maintained.
;;
;; patterns: A terrible hack. The issue is that for pattern variables,
;; we can't emit lexically nested with-syntax forms, like:
;;
;; (with-syntax ((foo 1)) (the-environment))
;; => (with-syntax ((foo 1))
;; ... #'(with-syntax ((foo ...)) ... exp) ...)
;;
;; The reason is that the outer "foo" substitutes into the inner "foo",
;; yielding something like:
;;
;; (with-syntax ((foo 1))
;; ... (with-syntax ((1 ...)) ...)
;;
;; Which ain't what we want. So we hide the information needed to
;; re-make the inner pattern binding form in the lexical environment
;; object, and then introduce those identifiers via another with-syntax.
;;
;;
;; There are four different kinds of lexical bindings: normal lexicals,
;; macros, displaced lexicals, and pattern variables. See the
;; documentation of syntax-local-binding for more info on these.
;;
;; We capture normal lexicals via `make-box', which creates a
;; case-lambda that can reference or set a variable. These get
;; re-introduced with an identifier-syntax.
;;
;; We can't capture macros currently. However we do recognize our own
;; macros that are actually proxying lexicals, so that nested
;; `the-environment' forms are possible. In that case we drill down to
;; the identifier for the already-existing box, and just capture that
;; box.
;;
;; And that's it: we skip displaced lexicals, and the pattern variables
;; are discussed above.
;;
(define (analyze-identifiers ids)
(define (mktmp)
(datum->syntax #'here (gensym "t ")))
(let lp ((ids ids) (capture '()) (formals '()) (wrappers '()) (patterns '()))
(cond
((null? ids)
(values capture formals wrappers patterns))
(else
(let ((id (car ids)) (ids (cdr ids)))
(call-with-values (lambda () (syntax-local-binding id))
(lambda (type val)
(case type
((lexical)
(if (or-map (lambda (x) (bound-identifier=? x id)) formals)
(lp ids capture formals wrappers patterns)
(let ((t (mktmp)))
(lp ids
(cons #`(make-box #,id) capture)
(cons t formals)
(cons (lambda (x)
#`(let-syntax ((#,id (identifier-syntax-from-box #,t)))
#,x))
wrappers)
patterns))))
((displaced-lexical)
(lp ids capture formals wrappers patterns))
((macro)
(let ((b (procedure-property val 'identifier-syntax-box)))
(if b
(lp ids (cons b capture) (cons b formals)
(cons (lambda (x)
#`(let-syntax ((#,id (identifier-syntax-from-box #,b)))
#,x))
wrappers)
patterns)
(lp ids capture formals
(cons (lambda (x)
#`(let-syntax ((#,id (unsupported-binding '#,id)))
#,x))
wrappers)
patterns))))
((pattern-variable)
(let ((t (datum->syntax id (gensym "p ")))
(nested (within-nested-ellipses id (cdr val))))
(lp ids capture formals
(cons (lambda (x)
#`(with-syntax ((#,t '#,nested))
#,x))
wrappers)
;; This dance is to hide these pattern variables
;; from the expander.
(cons (list (datum->syntax #'here (syntax->datum id))
(cdr val)
t)
patterns))))
((ellipsis)
(lp ids capture formals
(cons (lambda (x)
#`(with-ellipsis #,val #,x))
wrappers)
patterns))
(else
(error "what" type val))))))))))
(define-syntax the-environment
(lambda (x)
(syntax-case x ()
((the-environment)
#'(the-environment the-environment))
((the-environment scope)
(call-with-values (lambda ()
(analyze-identifiers
(syntax-locally-bound-identifiers #'scope)))
(lambda (capture formals wrappers patterns)
(define (wrap-expression x)
(let lp ((x x) (wrappers wrappers))
(if (null? wrappers)
x
(lp ((car wrappers) x) (cdr wrappers)))))
(with-syntax (((f ...) formals)
((c ...) capture)
(((pname plvl pformal) ...) patterns)
(wrapped (wrap-expression #'(begin #f exp))))
#'(make-lexical-environment
#'scope
(lambda (exp pformal ...)
(with-syntax ((exp exp)
(pformal pformal)
...)
#'(lambda (f ...)
wrapped)))
(list c ...)
(list (list 'pname plvl #'pformal) ...)))))))))
(define (env-module e)
(cond
((lexical-environment? e) (resolve-module (syntax-module (lexenv-scope e))))
((module? e) e)
(else (error "invalid lexical environment" e))))
(define (env-boxes e)
(cond
((lexical-environment? e) (lexenv-boxes e))
((module? e) '())
(else (error "invalid lexical environment" e))))
(define (local-wrap x e)
(cond
((lexical-environment? e)
(apply (lexenv-wrapper e)
(datum->syntax (lexenv-scope e) x)
(map (lambda (l)
(let ((name (car l))
(lvl (cadr l))
(scope (caddr l)))
(within-nested-ellipses (datum->syntax scope name) lvl)))
(lexenv-patterns e))))
((module? e) #`(lambda () #f #,x))
(else (error "invalid lexical environment" e))))
(define (local-eval x e)
"Evaluate the expression @var{x} within the lexical environment @var{e}."
(apply (eval (local-wrap x e) (env-module e))
(env-boxes e)))
(define* (local-compile x e #\key (opts '()))
"Compile and evaluate the expression @var{x} within the lexical
environment @var{e}."
(apply (compile (local-wrap x e) #\env (env-module e)
#\from 'scheme #\opts opts)
(env-boxes e)))
;;;; ls.scm --- functions for browsing modules
;;;;
;;;; Copyright (C) 1995, 1996, 1997, 1999, 2001, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 ls)
\:use-module (ice-9 common-list)
\:export (local-definitions-in definitions-in ls lls
recursive-local-define))
;;;;
;;; local-definitions-in root name
;;; Returns a list of names defined locally in the named
;;; subdirectory of root.
;;; definitions-in root name
;;; Returns a list of all names defined in the named
;;; subdirectory of root. The list includes alll locally
;;; defined names as well as all names inherited from a
;;; member of a use-list.
;;;
;;; A convenient interface for examining the nature of things:
;;;
;;; ls . various-names
;;;
;;; With no arguments, return a list of definitions in
;;; `(current-module)'.
;;;
;;; With just one argument, interpret that argument as the
;;; name of a subdirectory of the current module and
;;; return a list of names defined there.
;;;
;;; With more than one argument, still compute
;;; subdirectory lists, but return a list:
;;; ((<subdir-name> . <names-defined-there>)
;;; (<subdir-name> . <names-defined-there>)
;;; ...)
;;;
;;; lls . various-names
;;;
;;; Analogous to `ls', but with local definitions only.
(define (local-definitions-in root names)
(let ((m (nested-ref-module root names)))
(if m
(module-map (lambda (k v) k) m)
(nested-ref root names))))
(define (definitions-in root names)
(let ((m (nested-ref-module root names)))
(if m
(reduce union
(cons (local-definitions-in m '())
(map (lambda (m2) (definitions-in m2 '()))
(module-uses m))))
(nested-ref root names))))
(define (ls . various-refs)
(if (pair? various-refs)
(if (cdr various-refs)
(map (lambda (ref)
(cons ref (definitions-in (current-module) ref)))
various-refs)
(definitions-in (current-module) (car various-refs)))
(definitions-in (current-module) '())))
(define (lls . various-refs)
(if (pair? various-refs)
(if (cdr various-refs)
(map (lambda (ref)
(cons ref (local-definitions-in (current-module) ref)))
various-refs)
(local-definitions-in (current-module) (car various-refs)))
(local-definitions-in (current-module) '())))
(define (recursive-local-define name value)
(let ((parent (reverse! (cdr (reverse name)))))
(module-define! (make-modules-in (current-module) parent)
name value)))
;;; ls.scm ends here
;;; installed-scm-file
;;;; Copyright (C) 1996, 2001, 2006, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 mapping)
\:use-module (ice-9 poe)
\:export (mapping-hooks-type make-mapping-hooks mapping-hooks?
mapping-hooks-get-handle mapping-hooks-create-handle
mapping-hooks-remove mapping-type make-mapping mapping?
mapping-hooks mapping-data set-mapping-hooks! set-mapping-data!
mapping-get-handle mapping-create-handle! mapping-remove!
mapping-ref mapping-set! hash-table-mapping-hooks
make-hash-table-mapping hash-table-mapping))
(issue-deprecation-warning
"(ice-9 mapping) is deprecated. Use srfi-69 or rnrs hash tables instead.")
(define mapping-hooks-type (make-record-type 'mapping-hooks '(get-handle
create-handle
remove)))
(define make-mapping-hooks (perfect-funcq 17 (record-constructor mapping-hooks-type)))
(define mapping-hooks? (record-predicate mapping-hooks-type))
(define mapping-hooks-get-handle (record-accessor mapping-hooks-type 'get-handle))
(define mapping-hooks-create-handle (record-accessor mapping-hooks-type 'create-handle))
(define mapping-hooks-remove (record-accessor mapping-hooks-type 'remove))
(define mapping-type (make-record-type 'mapping '(hooks data)))
(define make-mapping (record-constructor mapping-type))
(define mapping? (record-predicate mapping-type))
(define mapping-hooks (record-accessor mapping-type 'hooks))
(define mapping-data (record-accessor mapping-type 'data))
(define set-mapping-hooks! (record-modifier mapping-type 'hooks))
(define set-mapping-data! (record-modifier mapping-type 'data))
(define (mapping-get-handle map key)
((mapping-hooks-get-handle (mapping-hooks map)) map key))
(define (mapping-create-handle! map key init)
((mapping-hooks-create-handle (mapping-hooks map)) map key init))
(define (mapping-remove! map key)
((mapping-hooks-remove (mapping-hooks map)) map key))
(define* (mapping-ref map key #\optional dflt)
(cond
((mapping-get-handle map key) => cdr)
(else dflt)))
(define (mapping-set! map key val)
(set-cdr! (mapping-create-handle! map key #f) val))
(define hash-table-mapping-hooks
(let ((wrap (lambda (proc) (lambda (1st . rest) (apply proc (mapping-data 1st) rest)))))
(perfect-funcq 17
(lambda (hash-proc assoc-proc)
(let ((procs (list hash-proc assoc-proc)))
(cond
((equal? procs `(,hashq ,assq))
(make-mapping-hooks (wrap hashq-get-handle)
(wrap hashq-create-handle!)
(wrap hashq-remove!)))
((equal? procs `(,hashv ,assv))
(make-mapping-hooks (wrap hashv-get-handle)
(wrap hashv-create-handle!)
(wrap hashv-remove!)))
((equal? procs `(,hash ,assoc))
(make-mapping-hooks (wrap hash-get-handle)
(wrap hash-create-handle!)
(wrap hash-remove!)))
(else
(make-mapping-hooks (wrap
(lambda (table key)
(hashx-get-handle hash-proc assoc-proc table key)))
(wrap
(lambda (table key init)
(hashx-create-handle! hash-proc assoc-proc table key init)))
(wrap
(lambda (table key)
(hashx-remove! hash-proc assoc-proc table key)))))))))))
(define (make-hash-table-mapping table hash-proc assoc-proc)
(make-mapping (hash-table-mapping-hooks hash-proc assoc-proc) table))
(define* (hash-table-mapping #\optional (size 71) #\key
(hash-proc hash)
(assoc-proc
(or (assq-ref `((,hashq . ,assq)
(,hashv . ,assv)
(,hash . ,assoc))
hash-proc)
(error 'hash-table-mapping
"Hash-procedure specified with no known assoc function."
hash-proc)))
(table-constructor
(lambda (len) (make-vector len '()))))
(make-hash-table-mapping (table-constructor size)
hash-proc
assoc-proc))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 match)
#\export (match
match-lambda
match-lambda*
match-let
match-let*
match-letrec))
(define (error _ . args)
;; Error procedure for run-time "no matching pattern" errors.
(apply throw 'match-error "match" args))
;; Support for record matching.
(define-syntax slot-ref
(syntax-rules ()
((_ rtd rec n)
(struct-ref rec n))))
(define-syntax slot-set!
(syntax-rules ()
((_ rtd rec n value)
(struct-set! rec n value))))
(define-syntax is-a?
(syntax-rules ()
((_ rec rtd)
(and (struct? rec)
(eq? (struct-vtable rec) rtd)))))
;; Compared to Andrew K. Wright's `match', this one lacks `match-define',
;; `match:error-control', `match:set-error-control', `match:error',
;; `match:set-error', and all structure-related procedures. Also,
;; `match' doesn't support clauses of the form `(pat => exp)'.
;; Unmodified public domain code by Alex Shinn retrieved from
;; the Chibi-Scheme repository, commit 1206:acd808700e91.
;;
;; Note: Make sure to update `match.test.upstream' when updating this
;; file.
(include-from-path "ice-9/match.upstream.scm")
;;;; match.scm -- portable hygienic pattern matcher -*- coding: utf-8 -*-
;;
;; This code is written by Alex Shinn and placed in the
;; Public Domain. All warranties are disclaimed.
;;> @example-import[(srfi 9)]
;;> This is a full superset of the popular @hyperlink[
;;> "http://www.cs.indiana.edu/scheme-repository/code.match.html"]{match}
;;> package by Andrew Wright, written in fully portable @scheme{syntax-rules}
;;> and thus preserving hygiene.
;;> The most notable extensions are the ability to use @emph{non-linear}
;;> patterns - patterns in which the same identifier occurs multiple
;;> times, tail patterns after ellipsis, and the experimental tree patterns.
;;> @subsubsection{Patterns}
;;> Patterns are written to look like the printed representation of
;;> the objects they match. The basic usage is
;;> @scheme{(match expr (pat body ...) ...)}
;;> where the result of @var{expr} is matched against each pattern in
;;> turn, and the corresponding body is evaluated for the first to
;;> succeed. Thus, a list of three elements matches a list of three
;;> elements.
;;> @example{(let ((ls (list 1 2 3))) (match ls ((1 2 3) #t)))}
;;> If no patterns match an error is signalled.
;;> Identifiers will match anything, and make the corresponding
;;> binding available in the body.
;;> @example{(match (list 1 2 3) ((a b c) b))}
;;> If the same identifier occurs multiple times, the first instance
;;> will match anything, but subsequent instances must match a value
;;> which is @scheme{equal?} to the first.
;;> @example{(match (list 1 2 1) ((a a b) 1) ((a b a) 2))}
;;> The special identifier @scheme{_} matches anything, no matter how
;;> many times it is used, and does not bind the result in the body.
;;> @example{(match (list 1 2 1) ((_ _ b) 1) ((a b a) 2))}
;;> To match a literal identifier (or list or any other literal), use
;;> @scheme{quote}.
;;> @example{(match 'a ('b 1) ('a 2))}
;;> Analogous to its normal usage in scheme, @scheme{quasiquote} can
;;> be used to quote a mostly literally matching object with selected
;;> parts unquoted.
;;> @example|{(match (list 1 2 3) (`(1 ,b ,c) (list b c)))}|
;;> Often you want to match any number of a repeated pattern. Inside
;;> a list pattern you can append @scheme{...} after an element to
;;> match zero or more of that pattern (like a regexp Kleene star).
;;> @example{(match (list 1 2) ((1 2 3 ...) #t))}
;;> @example{(match (list 1 2 3) ((1 2 3 ...) #t))}
;;> @example{(match (list 1 2 3 3 3) ((1 2 3 ...) #t))}
;;> Pattern variables matched inside the repeated pattern are bound to
;;> a list of each matching instance in the body.
;;> @example{(match (list 1 2) ((a b c ...) c))}
;;> @example{(match (list 1 2 3) ((a b c ...) c))}
;;> @example{(match (list 1 2 3 4 5) ((a b c ...) c))}
;;> More than one @scheme{...} may not be used in the same list, since
;;> this would require exponential backtracking in the general case.
;;> However, @scheme{...} need not be the final element in the list,
;;> and may be succeeded by a fixed number of patterns.
;;> @example{(match (list 1 2 3 4) ((a b c ... d e) c))}
;;> @example{(match (list 1 2 3 4 5) ((a b c ... d e) c))}
;;> @example{(match (list 1 2 3 4 5 6 7) ((a b c ... d e) c))}
;;> @scheme{___} is provided as an alias for @scheme{...} when it is
;;> inconvenient to use the ellipsis (as in a syntax-rules template).
;;> The @scheme{..1} syntax is exactly like the @scheme{...} except
;;> that it matches one or more repetitions (like a regexp "+").
;;> @example{(match (list 1 2) ((a b c ..1) c))}
;;> @example{(match (list 1 2 3) ((a b c ..1) c))}
;;> The boolean operators @scheme{and}, @scheme{or} and @scheme{not}
;;> can be used to group and negate patterns analogously to their
;;> Scheme counterparts.
;;> The @scheme{and} operator ensures that all subpatterns match.
;;> This operator is often used with the idiom @scheme{(and x pat)} to
;;> bind @var{x} to the entire value that matches @var{pat}
;;> (c.f. "as-patterns" in ML or Haskell). Another common use is in
;;> conjunction with @scheme{not} patterns to match a general case
;;> with certain exceptions.
;;> @example{(match 1 ((and) #t))}
;;> @example{(match 1 ((and x) x))}
;;> @example{(match 1 ((and x 1) x))}
;;> The @scheme{or} operator ensures that at least one subpattern
;;> matches. If the same identifier occurs in different subpatterns,
;;> it is matched independently. All identifiers from all subpatterns
;;> are bound if the @scheme{or} operator matches, but the binding is
;;> only defined for identifiers from the subpattern which matched.
;;> @example{(match 1 ((or) #t) (else #f))}
;;> @example{(match 1 ((or x) x))}
;;> @example{(match 1 ((or x 2) x))}
;;> The @scheme{not} operator succeeds if the given pattern doesn't
;;> match. None of the identifiers used are available in the body.
;;> @example{(match 1 ((not 2) #t))}
;;> The more general operator @scheme{?} can be used to provide a
;;> predicate. The usage is @scheme{(? predicate pat ...)} where
;;> @var{predicate} is a Scheme expression evaluating to a predicate
;;> called on the value to match, and any optional patterns after the
;;> predicate are then matched as in an @scheme{and} pattern.
;;> @example{(match 1 ((? odd? x) x))}
;;> The field operator @scheme{=} is used to extract an arbitrary
;;> field and match against it. It is useful for more complex or
;;> conditional destructuring that can't be more directly expressed in
;;> the pattern syntax. The usage is @scheme{(= field pat)}, where
;;> @var{field} can be any expression, and should result in a
;;> procedure of one argument, which is applied to the value to match
;;> to generate a new value to match against @var{pat}.
;;> Thus the pattern @scheme{(and (= car x) (= cdr y))} is equivalent
;;> to @scheme{(x . y)}, except it will result in an immediate error
;;> if the value isn't a pair.
;;> @example{(match '(1 . 2) ((= car x) x))}
;;> @example{(match 4 ((= sqrt x) x))}
;;> The record operator @scheme{$} is used as a concise way to match
;;> records defined by SRFI-9 (or SRFI-99). The usage is
;;> @scheme{($ rtd field ...)}, where @var{rtd} should be the record
;;> type descriptor specified as the first argument to
;;> @scheme{define-record-type}, and each @var{field} is a subpattern
;;> matched against the fields of the record in order. Not all fields
;;> must be present.
;;> @example{
;;> (let ()
;;> (define-record-type employee
;;> (make-employee name title)
;;> employee?
;;> (name get-name)
;;> (title get-title))
;;> (match (make-employee "Bob" "Doctor")
;;> (($ employee n t) (list t n))))
;;> }
;;> The @scheme{set!} and @scheme{get!} operators are used to bind an
;;> identifier to the setter and getter of a field, respectively. The
;;> setter is a procedure of one argument, which mutates the field to
;;> that argument. The getter is a procedure of no arguments which
;;> returns the current value of the field.
;;> @example{(let ((x (cons 1 2))) (match x ((1 . (set! s)) (s 3) x)))}
;;> @example{(match '(1 . 2) ((1 . (get! g)) (g)))}
;;> The new operator @scheme{***} can be used to search a tree for
;;> subpatterns. A pattern of the form @scheme{(x *** y)} represents
;;> the subpattern @var{y} located somewhere in a tree where the path
;;> from the current object to @var{y} can be seen as a list of the
;;> form @scheme{(x ...)}. @var{y} can immediately match the current
;;> object in which case the path is the empty list. In a sense it's
;;> a 2-dimensional version of the @scheme{...} pattern.
;;> As a common case the pattern @scheme{(_ *** y)} can be used to
;;> search for @var{y} anywhere in a tree, regardless of the path
;;> used.
;;> @example{(match '(a (a (a b))) ((x *** 'b) x))}
;;> @example{(match '(a (b) (c (d e) (f g))) ((x *** 'g) x))}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Notes
;; The implementation is a simple generative pattern matcher - each
;; pattern is expanded into the required tests, calling a failure
;; continuation if the tests fail. This makes the logic easy to
;; follow and extend, but produces sub-optimal code in cases where you
;; have many similar clauses due to repeating the same tests.
;; Nonetheless a smart compiler should be able to remove the redundant
;; tests. For MATCH-LET and DESTRUCTURING-BIND type uses there is no
;; performance hit.
;; The original version was written on 2006/11/29 and described in the
;; following Usenet post:
;; http://groups.google.com/group/comp.lang.scheme/msg/0941234de7112ffd
;; and is still available at
;; http://synthcode.com/scheme/match-simple.scm
;; It's just 80 lines for the core MATCH, and an extra 40 lines for
;; MATCH-LET, MATCH-LAMBDA and other syntactic sugar.
;;
;; A variant of this file which uses COND-EXPAND in a few places for
;; performance can be found at
;; http://synthcode.com/scheme/match-cond-expand.scm
;;
;; 2012/05/23 - fixing combinatorial explosion of code in certain or patterns
;; 2011/09/25 - fixing bug when directly matching an identifier repeated in
;; the pattern (thanks to Stefan Israelsson Tampe)
;; 2011/01/27 - fixing bug when matching tail patterns against improper lists
;; 2010/09/26 - adding `..1' patterns (thanks to Ludovic Courtès)
;; 2010/09/07 - fixing identifier extraction in some `...' and `***' patterns
;; 2009/11/25 - adding `***' tree search patterns
;; 2008/03/20 - fixing bug where (a ...) matched non-lists
;; 2008/03/15 - removing redundant check in vector patterns
;; 2008/03/06 - you can use `...' portably now (thanks to Taylor Campbell)
;; 2007/09/04 - fixing quasiquote patterns
;; 2007/07/21 - allowing ellipse patterns in non-final list positions
;; 2007/04/10 - fixing potential hygiene issue in match-check-ellipse
;; (thanks to Taylor Campbell)
;; 2007/04/08 - clean up, commenting
;; 2006/12/24 - bugfixes
;; 2006/12/01 - non-linear patterns, shared variables in OR, get!/set!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; force compile-time syntax errors with useful messages
(define-syntax match-syntax-error
(syntax-rules ()
((_) (match-syntax-error "invalid match-syntax-error usage"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;> @subsubsection{Syntax}
;;> @subsubsubsection{@rawcode{(match expr (pattern . body) ...)@br{}
;;> (match expr (pattern (=> failure) . body) ...)}}
;;> The result of @var{expr} is matched against each @var{pattern} in
;;> turn, according to the pattern rules described in the previous
;;> section, until the the first @var{pattern} matches. When a match is
;;> found, the corresponding @var{body}s are evaluated in order,
;;> and the result of the last expression is returned as the result
;;> of the entire @scheme{match}. If a @var{failure} is provided,
;;> then it is bound to a procedure of no arguments which continues,
;;> processing at the next @var{pattern}. If no @var{pattern} matches,
;;> an error is signalled.
;; The basic interface. MATCH just performs some basic syntax
;; validation, binds the match expression to a temporary variable `v',
;; and passes it on to MATCH-NEXT. It's a constant throughout the
;; code below that the binding `v' is a direct variable reference, not
;; an expression.
(define-syntax match
(syntax-rules ()
((match)
(match-syntax-error "missing match expression"))
((match atom)
(match-syntax-error "no match clauses"))
((match (app ...) (pat . body) ...)
(let ((v (app ...)))
(match-next v ((app ...) (set! (app ...))) (pat . body) ...)))
((match #(vec ...) (pat . body) ...)
(let ((v #(vec ...)))
(match-next v (v (set! v)) (pat . body) ...)))
((match atom (pat . body) ...)
(let ((v atom))
(match-next v (atom (set! atom)) (pat . body) ...)))
))
;; MATCH-NEXT passes each clause to MATCH-ONE in turn with its failure
;; thunk, which is expanded by recursing MATCH-NEXT on the remaining
;; clauses. `g+s' is a list of two elements, the get! and set!
;; expressions respectively.
(define-syntax match-next
(syntax-rules (=>)
;; no more clauses, the match failed
((match-next v g+s)
;; Here we wrap error within a double set of parentheses, so that
;; the call to 'error' won't be in tail position. This allows the
;; backtrace to show the source location of the failing match form.
((error 'match "no matching pattern" v)))
;; named failure continuation
((match-next v g+s (pat (=> failure) . body) . rest)
(let ((failure (lambda () (match-next v g+s . rest))))
;; match-one analyzes the pattern for us
(match-one v pat g+s (match-drop-ids (begin . body)) (failure) ())))
;; anonymous failure continuation, give it a dummy name
((match-next v g+s (pat . body) . rest)
(match-next v g+s (pat (=> failure) . body) . rest))))
;; MATCH-ONE first checks for ellipse patterns, otherwise passes on to
;; MATCH-TWO.
(define-syntax match-one
(syntax-rules ()
;; If it's a list of two or more values, check to see if the
;; second one is an ellipse and handle accordingly, otherwise go
;; to MATCH-TWO.
((match-one v (p q . r) g+s sk fk i)
(match-check-ellipse
q
(match-extract-vars p (match-gen-ellipses v p r g+s sk fk i) i ())
(match-two v (p q . r) g+s sk fk i)))
;; Go directly to MATCH-TWO.
((match-one . x)
(match-two . x))))
;; This is the guts of the pattern matcher. We are passed a lot of
;; information in the form:
;;
;; (match-two var pattern getter setter success-k fail-k (ids ...))
;;
;; usually abbreviated
;;
;; (match-two v p g+s sk fk i)
;;
;; where VAR is the symbol name of the current variable we are
;; matching, PATTERN is the current pattern, getter and setter are the
;; corresponding accessors (e.g. CAR and SET-CAR! of the pair holding
;; VAR), SUCCESS-K is the success continuation, FAIL-K is the failure
;; continuation (which is just a thunk call and is thus safe to expand
;; multiple times) and IDS are the list of identifiers bound in the
;; pattern so far.
(define-syntax match-two
(syntax-rules (_ ___ \.\.1 *** quote quasiquote ? $ = and or not set! get!)
((match-two v () g+s (sk ...) fk i)
(if (null? v) (sk ... i) fk))
((match-two v (quote p) g+s (sk ...) fk i)
(if (equal? v 'p) (sk ... i) fk))
((match-two v (quasiquote p) . x)
(match-quasiquote v p . x))
((match-two v (and) g+s (sk ...) fk i) (sk ... i))
((match-two v (and p q ...) g+s sk fk i)
(match-one v p g+s (match-one v (and q ...) g+s sk fk) fk i))
((match-two v (or) g+s sk fk i) fk)
((match-two v (or p) . x)
(match-one v p . x))
((match-two v (or p ...) g+s sk fk i)
(match-extract-vars (or p ...) (match-gen-or v (p ...) g+s sk fk i) i ()))
((match-two v (not p) g+s (sk ...) fk i)
(match-one v p g+s (match-drop-ids fk) (sk ... i) i))
((match-two v (get! getter) (g s) (sk ...) fk i)
(let ((getter (lambda () g))) (sk ... i)))
((match-two v (set! setter) (g (s ...)) (sk ...) fk i)
(let ((setter (lambda (x) (s ... x)))) (sk ... i)))
((match-two v (? pred . p) g+s sk fk i)
(if (pred v) (match-one v (and . p) g+s sk fk i) fk))
((match-two v (= proc p) . x)
(let ((w (proc v))) (match-one w p . x)))
((match-two v (p ___ . r) g+s sk fk i)
(match-extract-vars p (match-gen-ellipses v p r g+s sk fk i) i ()))
((match-two v (p) g+s sk fk i)
(if (and (pair? v) (null? (cdr v)))
(let ((w (car v)))
(match-one w p ((car v) (set-car! v)) sk fk i))
fk))
((match-two v (p *** q) g+s sk fk i)
(match-extract-vars p (match-gen-search v p q g+s sk fk i) i ()))
((match-two v (p *** . q) g+s sk fk i)
(match-syntax-error "invalid use of ***" (p *** . q)))
((match-two v (p \.\.1) g+s sk fk i)
(if (pair? v)
(match-one v (p ___) g+s sk fk i)
fk))
((match-two v ($ rec p ...) g+s sk fk i)
(if (is-a? v rec)
(match-record-refs v rec 0 (p ...) g+s sk fk i)
fk))
((match-two v (p . q) g+s sk fk i)
(if (pair? v)
(let ((w (car v)) (x (cdr v)))
(match-one w p ((car v) (set-car! v))
(match-one x q ((cdr v) (set-cdr! v)) sk fk)
fk
i))
fk))
((match-two v #(p ...) g+s . x)
(match-vector v 0 () (p ...) . x))
((match-two v _ g+s (sk ...) fk i) (sk ... i))
;; Not a pair or vector or special literal, test to see if it's a
;; new symbol, in which case we just bind it, or if it's an
;; already bound symbol or some other literal, in which case we
;; compare it with EQUAL?.
((match-two v x g+s (sk ...) fk (id ...))
(let-syntax
((new-sym?
(syntax-rules (id ...)
((new-sym? x sk2 fk2) sk2)
((new-sym? y sk2 fk2) fk2))))
(new-sym? random-sym-to-match
(let ((x v)) (sk ... (id ... x)))
(if (equal? v x) (sk ... (id ...)) fk))))
))
;; QUASIQUOTE patterns
(define-syntax match-quasiquote
(syntax-rules (unquote unquote-splicing quasiquote)
((_ v (unquote p) g+s sk fk i)
(match-one v p g+s sk fk i))
((_ v ((unquote-splicing p) . rest) g+s sk fk i)
(if (pair? v)
(match-one v
(p . tmp)
(match-quasiquote tmp rest g+s sk fk)
fk
i)
fk))
((_ v (quasiquote p) g+s sk fk i . depth)
(match-quasiquote v p g+s sk fk i #f . depth))
((_ v (unquote p) g+s sk fk i x . depth)
(match-quasiquote v p g+s sk fk i . depth))
((_ v (unquote-splicing p) g+s sk fk i x . depth)
(match-quasiquote v p g+s sk fk i . depth))
((_ v (p . q) g+s sk fk i . depth)
(if (pair? v)
(let ((w (car v)) (x (cdr v)))
(match-quasiquote
w p g+s
(match-quasiquote-step x q g+s sk fk depth)
fk i . depth))
fk))
((_ v #(elt ...) g+s sk fk i . depth)
(if (vector? v)
(let ((ls (vector->list v)))
(match-quasiquote ls (elt ...) g+s sk fk i . depth))
fk))
((_ v x g+s sk fk i . depth)
(match-one v 'x g+s sk fk i))))
(define-syntax match-quasiquote-step
(syntax-rules ()
((match-quasiquote-step x q g+s sk fk depth i)
(match-quasiquote x q g+s sk fk i . depth))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utilities
;; Takes two values and just expands into the first.
(define-syntax match-drop-ids
(syntax-rules ()
((_ expr ids ...) expr)))
(define-syntax match-tuck-ids
(syntax-rules ()
((_ (letish args (expr ...)) ids ...)
(letish args (expr ... ids ...)))))
(define-syntax match-drop-first-arg
(syntax-rules ()
((_ arg expr) expr)))
;; To expand an OR group we try each clause in succession, passing the
;; first that succeeds to the success continuation. On failure for
;; any clause, we just try the next clause, finally resorting to the
;; failure continuation fk if all clauses fail. The only trick is
;; that we want to unify the identifiers, so that the success
;; continuation can refer to a variable from any of the OR clauses.
(define-syntax match-gen-or
(syntax-rules ()
((_ v p g+s (sk ...) fk (i ...) ((id id-ls) ...))
(let ((sk2 (lambda (id ...) (sk ... (i ... id ...)))))
(match-gen-or-step v p g+s (match-drop-ids (sk2 id ...)) fk (i ...))))))
(define-syntax match-gen-or-step
(syntax-rules ()
((_ v () g+s sk fk . x)
;; no OR clauses, call the failure continuation
fk)
((_ v (p) . x)
;; last (or only) OR clause, just expand normally
(match-one v p . x))
((_ v (p . q) g+s sk fk i)
;; match one and try the remaining on failure
(let ((fk2 (lambda () (match-gen-or-step v q g+s sk fk i))))
(match-one v p g+s sk (fk2) i)))
))
;; We match a pattern (p ...) by matching the pattern p in a loop on
;; each element of the variable, accumulating the bound ids into lists.
;; Look at the body of the simple case - it's just a named let loop,
;; matching each element in turn to the same pattern. The only trick
;; is that we want to keep track of the lists of each extracted id, so
;; when the loop recurses we cons the ids onto their respective list
;; variables, and on success we bind the ids (what the user input and
;; expects to see in the success body) to the reversed accumulated
;; list IDs.
(define-syntax match-gen-ellipses
(syntax-rules ()
((_ v p () g+s (sk ...) fk i ((id id-ls) ...))
(match-check-identifier p
;; simplest case equivalent to (p ...), just bind the list
(let ((p v))
(if (list? p)
(sk ... i)
fk))
;; simple case, match all elements of the list
(let loop ((ls v) (id-ls '()) ...)
(cond
((null? ls)
(let ((id (reverse id-ls)) ...) (sk ... i)))
((pair? ls)
(let ((w (car ls)))
(match-one w p ((car ls) (set-car! ls))
(match-drop-ids (loop (cdr ls) (cons id id-ls) ...))
fk i)))
(else
fk)))))
((_ v p r g+s (sk ...) fk i ((id id-ls) ...))
;; general case, trailing patterns to match, keep track of the
;; remaining list length so we don't need any backtracking
(match-verify-no-ellipses
r
(let* ((tail-len (length 'r))
(ls v)
(len (and (list? ls) (length ls))))
(if (or (not len) (< len tail-len))
fk
(let loop ((ls ls) (n len) (id-ls '()) ...)
(cond
((= n tail-len)
(let ((id (reverse id-ls)) ...)
(match-one ls r (#f #f) (sk ...) fk i)))
((pair? ls)
(let ((w (car ls)))
(match-one w p ((car ls) (set-car! ls))
(match-drop-ids
(loop (cdr ls) (- n 1) (cons id id-ls) ...))
fk
i)))
(else
fk)))))))))
;; This is just a safety check. Although unlike syntax-rules we allow
;; trailing patterns after an ellipses, we explicitly disable multiple
;; ellipses at the same level. This is because in the general case
;; such patterns are exponential in the number of ellipses, and we
;; don't want to make it easy to construct very expensive operations
;; with simple looking patterns. For example, it would be O(n^2) for
;; patterns like (a ... b ...) because we must consider every trailing
;; element for every possible break for the leading "a ...".
(define-syntax match-verify-no-ellipses
(syntax-rules ()
((_ (x . y) sk)
(match-check-ellipse
x
(match-syntax-error
"multiple ellipse patterns not allowed at same level")
(match-verify-no-ellipses y sk)))
((_ () sk)
sk)
((_ x sk)
(match-syntax-error "dotted tail not allowed after ellipse" x))))
;; To implement the tree search, we use two recursive procedures. TRY
;; attempts to match Y once, and on success it calls the normal SK on
;; the accumulated list ids as in MATCH-GEN-ELLIPSES. On failure, we
;; call NEXT which first checks if the current value is a list
;; beginning with X, then calls TRY on each remaining element of the
;; list. Since TRY will recursively call NEXT again on failure, this
;; effects a full depth-first search.
;;
;; The failure continuation throughout is a jump to the next step in
;; the tree search, initialized with the original failure continuation
;; FK.
(define-syntax match-gen-search
(syntax-rules ()
((match-gen-search v p q g+s sk fk i ((id id-ls) ...))
(letrec ((try (lambda (w fail id-ls ...)
(match-one w q g+s
(match-tuck-ids
(let ((id (reverse id-ls)) ...)
sk))
(next w fail id-ls ...) i)))
(next (lambda (w fail id-ls ...)
(if (not (pair? w))
(fail)
(let ((u (car w)))
(match-one
u p ((car w) (set-car! w))
(match-drop-ids
;; accumulate the head variables from
;; the p pattern, and loop over the tail
(let ((id-ls (cons id id-ls)) ...)
(let lp ((ls (cdr w)))
(if (pair? ls)
(try (car ls)
(lambda () (lp (cdr ls)))
id-ls ...)
(fail)))))
(fail) i))))))
;; the initial id-ls binding here is a dummy to get the right
;; number of '()s
(let ((id-ls '()) ...)
(try v (lambda () fk) id-ls ...))))))
;; Vector patterns are just more of the same, with the slight
;; exception that we pass around the current vector index being
;; matched.
(define-syntax match-vector
(syntax-rules (___)
((_ v n pats (p q) . x)
(match-check-ellipse q
(match-gen-vector-ellipses v n pats p . x)
(match-vector-two v n pats (p q) . x)))
((_ v n pats (p ___) sk fk i)
(match-gen-vector-ellipses v n pats p sk fk i))
((_ . x)
(match-vector-two . x))))
;; Check the exact vector length, then check each element in turn.
(define-syntax match-vector-two
(syntax-rules ()
((_ v n ((pat index) ...) () sk fk i)
(if (vector? v)
(let ((len (vector-length v)))
(if (= len n)
(match-vector-step v ((pat index) ...) sk fk i)
fk))
fk))
((_ v n (pats ...) (p . q) . x)
(match-vector v (+ n 1) (pats ... (p n)) q . x))))
(define-syntax match-vector-step
(syntax-rules ()
((_ v () (sk ...) fk i) (sk ... i))
((_ v ((pat index) . rest) sk fk i)
(let ((w (vector-ref v index)))
(match-one w pat ((vector-ref v index) (vector-set! v index))
(match-vector-step v rest sk fk)
fk i)))))
;; With a vector ellipse pattern we first check to see if the vector
;; length is at least the required length.
(define-syntax match-gen-vector-ellipses
(syntax-rules ()
((_ v n ((pat index) ...) p sk fk i)
(if (vector? v)
(let ((len (vector-length v)))
(if (>= len n)
(match-vector-step v ((pat index) ...)
(match-vector-tail v p n len sk fk)
fk i)
fk))
fk))))
(define-syntax match-vector-tail
(syntax-rules ()
((_ v p n len sk fk i)
(match-extract-vars p (match-vector-tail-two v p n len sk fk i) i ()))))
(define-syntax match-vector-tail-two
(syntax-rules ()
((_ v p n len (sk ...) fk i ((id id-ls) ...))
(let loop ((j n) (id-ls '()) ...)
(if (>= j len)
(let ((id (reverse id-ls)) ...) (sk ... i))
(let ((w (vector-ref v j)))
(match-one w p ((vector-ref v j) (vetor-set! v j))
(match-drop-ids (loop (+ j 1) (cons id id-ls) ...))
fk i)))))))
(define-syntax match-record-refs
(syntax-rules ()
((_ v rec n (p . q) g+s sk fk i)
(let ((w (slot-ref rec v n)))
(match-one w p ((slot-ref rec v n) (slot-set! rec v n))
(match-record-refs v rec (+ n 1) q g+s sk fk) fk i)))
((_ v rec n () g+s (sk ...) fk i)
(sk ... i))))
;; Extract all identifiers in a pattern. A little more complicated
;; than just looking for symbols, we need to ignore special keywords
;; and non-pattern forms (such as the predicate expression in ?
;; patterns), and also ignore previously bound identifiers.
;;
;; Calls the continuation with all new vars as a list of the form
;; ((orig-var tmp-name) ...), where tmp-name can be used to uniquely
;; pair with the original variable (e.g. it's used in the ellipse
;; generation for list variables).
;;
;; (match-extract-vars pattern continuation (ids ...) (new-vars ...))
(define-syntax match-extract-vars
(syntax-rules (_ ___ \.\.1 *** ? $ = quote quasiquote and or not get! set!)
((match-extract-vars (? pred . p) . x)
(match-extract-vars p . x))
((match-extract-vars ($ rec . p) . x)
(match-extract-vars p . x))
((match-extract-vars (= proc p) . x)
(match-extract-vars p . x))
((match-extract-vars (quote x) (k ...) i v)
(k ... v))
((match-extract-vars (quasiquote x) k i v)
(match-extract-quasiquote-vars x k i v (#t)))
((match-extract-vars (and . p) . x)
(match-extract-vars p . x))
((match-extract-vars (or . p) . x)
(match-extract-vars p . x))
((match-extract-vars (not . p) . x)
(match-extract-vars p . x))
;; A non-keyword pair, expand the CAR with a continuation to
;; expand the CDR.
((match-extract-vars (p q . r) k i v)
(match-check-ellipse
q
(match-extract-vars (p . r) k i v)
(match-extract-vars p (match-extract-vars-step (q . r) k i v) i ())))
((match-extract-vars (p . q) k i v)
(match-extract-vars p (match-extract-vars-step q k i v) i ()))
((match-extract-vars #(p ...) . x)
(match-extract-vars (p ...) . x))
((match-extract-vars _ (k ...) i v) (k ... v))
((match-extract-vars ___ (k ...) i v) (k ... v))
((match-extract-vars *** (k ...) i v) (k ... v))
((match-extract-vars \.\.1 (k ...) i v) (k ... v))
;; This is the main part, the only place where we might add a new
;; var if it's an unbound symbol.
((match-extract-vars p (k ...) (i ...) v)
(let-syntax
((new-sym?
(syntax-rules (i ...)
((new-sym? p sk fk) sk)
((new-sym? any sk fk) fk))))
(new-sym? random-sym-to-match
(k ... ((p p-ls) . v))
(k ... v))))
))
;; Stepper used in the above so it can expand the CAR and CDR
;; separately.
(define-syntax match-extract-vars-step
(syntax-rules ()
((_ p k i v ((v2 v2-ls) ...))
(match-extract-vars p k (v2 ... . i) ((v2 v2-ls) ... . v)))
))
(define-syntax match-extract-quasiquote-vars
(syntax-rules (quasiquote unquote unquote-splicing)
((match-extract-quasiquote-vars (quasiquote x) k i v d)
(match-extract-quasiquote-vars x k i v (#t . d)))
((match-extract-quasiquote-vars (unquote-splicing x) k i v d)
(match-extract-quasiquote-vars (unquote x) k i v d))
((match-extract-quasiquote-vars (unquote x) k i v (#t))
(match-extract-vars x k i v))
((match-extract-quasiquote-vars (unquote x) k i v (#t . d))
(match-extract-quasiquote-vars x k i v d))
((match-extract-quasiquote-vars (x . y) k i v (#t . d))
(match-extract-quasiquote-vars
x
(match-extract-quasiquote-vars-step y k i v d) i ()))
((match-extract-quasiquote-vars #(x ...) k i v (#t . d))
(match-extract-quasiquote-vars (x ...) k i v d))
((match-extract-quasiquote-vars x (k ...) i v (#t . d))
(k ... v))
))
(define-syntax match-extract-quasiquote-vars-step
(syntax-rules ()
((_ x k i v d ((v2 v2-ls) ...))
(match-extract-quasiquote-vars x k (v2 ... . i) ((v2 v2-ls) ... . v) d))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Gimme some sugar baby.
;;> Shortcut for @scheme{lambda} + @scheme{match}. Creates a
;;> procedure of one argument, and matches that argument against each
;;> clause.
(define-syntax match-lambda
(syntax-rules ()
((_ (pattern . body) ...) (lambda (expr) (match expr (pattern . body) ...)))))
;;> Similar to @scheme{match-lambda}. Creates a procedure of any
;;> number of arguments, and matches the argument list against each
;;> clause.
(define-syntax match-lambda*
(syntax-rules ()
((_ (pattern . body) ...) (lambda expr (match expr (pattern . body) ...)))))
;;> Matches each var to the corresponding expression, and evaluates
;;> the body with all match variables in scope. Raises an error if
;;> any of the expressions fail to match. Syntax analogous to named
;;> let can also be used for recursive functions which match on their
;;> arguments as in @scheme{match-lambda*}.
(define-syntax match-let
(syntax-rules ()
((_ ((var value) ...) . body)
(match-let/helper let () () ((var value) ...) . body))
((_ loop ((var init) ...) . body)
(match-named-let loop ((var init) ...) . body))))
;;> Similar to @scheme{match-let}, but analogously to @scheme{letrec}
;;> matches and binds the variables with all match variables in scope.
(define-syntax match-letrec
(syntax-rules ()
((_ ((var value) ...) . body)
(match-let/helper letrec () () ((var value) ...) . body))))
(define-syntax match-let/helper
(syntax-rules ()
((_ let ((var expr) ...) () () . body)
(let ((var expr) ...) . body))
((_ let ((var expr) ...) ((pat tmp) ...) () . body)
(let ((var expr) ...)
(match-let* ((pat tmp) ...)
. body)))
((_ let (v ...) (p ...) (((a . b) expr) . rest) . body)
(match-let/helper
let (v ... (tmp expr)) (p ... ((a . b) tmp)) rest . body))
((_ let (v ...) (p ...) ((#(a ...) expr) . rest) . body)
(match-let/helper
let (v ... (tmp expr)) (p ... (#(a ...) tmp)) rest . body))
((_ let (v ...) (p ...) ((a expr) . rest) . body)
(match-let/helper let (v ... (a expr)) (p ...) rest . body))))
(define-syntax match-named-let
(syntax-rules ()
((_ loop ((pat expr var) ...) () . body)
(let loop ((var expr) ...)
(match-let ((pat var) ...)
. body)))
((_ loop (v ...) ((pat expr) . rest) . body)
(match-named-let loop (v ... (pat expr tmp)) rest . body))))
;;> @subsubsubsection{@rawcode{(match-let* ((var value) ...) body ...)}}
;;> Similar to @scheme{match-let}, but analogously to @scheme{let*}
;;> matches and binds the variables in sequence, with preceding match
;;> variables in scope.
(define-syntax match-let*
(syntax-rules ()
((_ () . body)
(begin . body))
((_ ((pat expr) . rest) . body)
(match expr (pat (match-let* rest . body))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Otherwise COND-EXPANDed bits.
;; This *should* work, but doesn't :(
;; (define-syntax match-check-ellipse
;; (syntax-rules (...)
;; ((_ ... sk fk) sk)
;; ((_ x sk fk) fk)))
;; This is a little more complicated, and introduces a new let-syntax,
;; but should work portably in any R[56]RS Scheme. Taylor Campbell
;; originally came up with the idea.
(define-syntax match-check-ellipse
(syntax-rules ()
;; these two aren't necessary but provide fast-case failures
((match-check-ellipse (a . b) success-k failure-k) failure-k)
((match-check-ellipse #(a ...) success-k failure-k) failure-k)
;; matching an atom
((match-check-ellipse id success-k failure-k)
(let-syntax ((ellipse? (syntax-rules ()
;; iff `id' is `...' here then this will
;; match a list of any length
((ellipse? (foo id) sk fk) sk)
((ellipse? other sk fk) fk))))
;; this list of three elements will only many the (foo id) list
;; above if `id' is `...'
(ellipse? (a b c) success-k failure-k)))))
;; This is portable but can be more efficient with non-portable
;; extensions. This trick was originally discovered by Oleg Kiselyov.
(define-syntax match-check-identifier
(syntax-rules ()
;; fast-case failures, lists and vectors are not identifiers
((_ (x . y) success-k failure-k) failure-k)
((_ #(x ...) success-k failure-k) failure-k)
;; x is an atom
((_ x success-k failure-k)
(let-syntax
((sym?
(syntax-rules ()
;; if the symbol `abracadabra' matches x, then x is a
;; symbol
((sym? x sk fk) sk)
;; otherwise x is a non-symbol datum
((sym? y sk fk) fk))))
(sym? abracadabra success-k failure-k)))))
;;; installed-scm-file
;;;; Copyright (C) 1999, 2005, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
(define (gethostbyaddr addr) (gethost addr))
(define (gethostbyname name) (gethost name))
(define (getnetbyaddr addr) (getnet addr))
(define (getnetbyname name) (getnet name))
(define (getprotobyname name) (getproto name))
(define (getprotobynumber addr) (getproto addr))
(define (getservbyname name proto) (getserv name proto))
(define (getservbyport port proto) (getserv port proto))
(define (sethostent . stayopen)
(if (pair? stayopen)
(sethost (car stayopen))
(sethost #f)))
(define (setnetent . stayopen)
(if (pair? stayopen)
(setnet (car stayopen))
(setnet #f)))
(define (setprotoent . stayopen)
(if (pair? stayopen)
(setproto (car stayopen))
(setproto #f)))
(define (setservent . stayopen)
(if (pair? stayopen)
(setserv (car stayopen))
(setserv #f)))
(define (gethostent) (gethost))
(define (getnetent) (getnet))
(define (getprotoent) (getproto))
(define (getservent) (getserv))
(define (endhostent) (sethost))
(define (endnetent) (setnet))
(define (endprotoent) (setproto))
(define (endservent) (setserv))
(define (hostent:name obj) (vector-ref obj 0))
(define (hostent:aliases obj) (vector-ref obj 1))
(define (hostent:addrtype obj) (vector-ref obj 2))
(define (hostent:length obj) (vector-ref obj 3))
(define (hostent:addr-list obj) (vector-ref obj 4))
(define (netent:name obj) (vector-ref obj 0))
(define (netent:aliases obj) (vector-ref obj 1))
(define (netent:addrtype obj) (vector-ref obj 2))
(define (netent:net obj) (vector-ref obj 3))
(define (protoent:name obj) (vector-ref obj 0))
(define (protoent:aliases obj) (vector-ref obj 1))
(define (protoent:proto obj) (vector-ref obj 2))
(define (servent:name obj) (vector-ref obj 0))
(define (servent:aliases obj) (vector-ref obj 1))
(define (servent:port obj) (vector-ref obj 2))
(define (servent:proto obj) (vector-ref obj 3))
(define (sockaddr:fam obj) (vector-ref obj 0))
(define (sockaddr:path obj) (vector-ref obj 1))
(define (sockaddr:addr obj) (vector-ref obj 1))
(define (sockaddr:port obj) (vector-ref obj 2))
(define (sockaddr:flowinfo obj) (vector-ref obj 3))
(define (sockaddr:scopeid obj) (vector-ref obj 4))
(define (addrinfo:flags obj) (vector-ref obj 0))
(define (addrinfo:fam obj) (vector-ref obj 1))
(define (addrinfo:socktype obj) (vector-ref obj 2))
(define (addrinfo:protocol obj) (vector-ref obj 3))
(define (addrinfo:addr obj) (vector-ref obj 4))
(define (addrinfo:canonname obj) (vector-ref obj 5))
;;;; Copyright (C) 2000, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; The null environment - only syntactic bindings
(define-module (ice-9 null)
\:re-export-syntax (define quote lambda if set!
cond case and or
let let* letrec
begin do
delay
quasiquote
define-syntax
let-syntax letrec-syntax))
;;;; Occam-like channels
;;; Copyright (C) 2003, 2006 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 occam-channel)
#\use-module (oop goops)
#\use-module (ice-9 threads)
#\export-syntax (alt
;; macro use:
oc:lock oc:unlock oc:consequence
oc:immediate-dispatch oc:late-dispatch oc:first-channel
oc:set-handshake-channel oc:unset-handshake-channel)
#\export (make-channel
?
!
make-timer
;; macro use:
handshake-channel mutex
sender-waiting?
immediate-receive late-receive
)
)
(define no-data '(no-data))
(define receiver-waiting '(receiver-waiting))
(define-class <channel> ())
(define-class <data-channel> (<channel>)
(handshake-channel #\accessor handshake-channel)
(data #\accessor data #\init-value no-data)
(cv #\accessor cv #\init-form (make-condition-variable))
(mutex #\accessor mutex #\init-form (make-mutex)))
(define-method (initialize (ch <data-channel>) initargs)
(next-method)
(set! (handshake-channel ch) ch))
(define-method (make-channel)
(make <data-channel>))
(define-method (sender-waiting? (ch <data-channel>))
(not (eq? (data ch) no-data)))
(define-method (receiver-waiting? (ch <data-channel>))
(eq? (data ch) receiver-waiting))
(define-method (immediate-receive (ch <data-channel>))
(signal-condition-variable (cv ch))
(let ((res (data ch)))
(set! (data ch) no-data)
res))
(define-method (late-receive (ch <data-channel>))
(let ((res (data ch)))
(set! (data ch) no-data)
res))
(define-method (? (ch <data-channel>))
(lock-mutex (mutex ch))
(let ((res (cond ((receiver-waiting? ch)
(unlock-mutex (mutex ch))
(scm-error 'misc-error '?
"another process is already receiving on ~A"
(list ch) #f))
((sender-waiting? ch)
(immediate-receive ch))
(else
(set! (data ch) receiver-waiting)
(wait-condition-variable (cv ch) (mutex ch))
(late-receive ch)))))
(unlock-mutex (mutex ch))
res))
(define-method (! (ch <data-channel>))
(! ch *unspecified*))
(define-method (! (ch <data-channel>) (x <top>))
(lock-mutex (mutex (handshake-channel ch)))
(cond ((receiver-waiting? ch)
(set! (data ch) x)
(signal-condition-variable (cv (handshake-channel ch))))
((sender-waiting? ch)
(unlock-mutex (mutex (handshake-channel ch)))
(scm-error 'misc-error '! "another process is already sending on ~A"
(list ch) #f))
(else
(set! (data ch) x)
(wait-condition-variable (cv ch) (mutex ch))))
(unlock-mutex (mutex (handshake-channel ch))))
;;; Add protocols?
(define-class <port-channel> (<channel>)
(port #\accessor port #\init-keyword #\port))
(define-method (make-channel (port <port>))
(make <port-channel> #\port port))
(define-method (? (ch <port-channel>))
(read (port ch)))
(define-method (! (ch <port-channel>))
(write (port ch)))
(define-class <timer-channel> (<channel>))
(define the-timer (make <timer-channel>))
(define timer-cv (make-condition-variable))
(define timer-mutex (make-mutex))
(define (make-timer)
the-timer)
(define (timeofday->us t)
(+ (* 1000000 (car t)) (cdr t)))
(define (us->timeofday n)
(cons (quotient n 1000000)
(remainder n 1000000)))
(define-method (? (ch <timer-channel>))
(timeofday->us (gettimeofday)))
(define-method (? (ch <timer-channel>) (t <integer>))
(lock-mutex timer-mutex)
(wait-condition-variable timer-cv timer-mutex (us->timeofday t))
(unlock-mutex timer-mutex))
;;; (alt CLAUSE ...)
;;;
;;; CLAUSE ::= ((? CH) FORM ...)
;;; | (EXP (? CH) FORM ...)
;;; | (EXP FORM ...)
;;;
;;; where FORM ... can be => (lambda (x) ...)
;;;
;;; *fixme* Currently only handles <data-channel>:s
;;;
(define-syntax oc:lock
(syntax-rules (?)
((_ ((? ch) form ...)) (lock-mutex (mutex ch)))
((_ (exp (? ch) form ...)) (lock-mutex (mutex ch)))
((_ (exp form ...)) #f)))
(define-syntax oc:unlock
(syntax-rules (?)
((_ ((? ch) form ...)) (unlock-mutex (mutex ch)))
((_ (exp (? ch) form ...)) (unlock-mutex (mutex ch)))
((_ (exp form ...)) #f)))
(define-syntax oc:consequence
(syntax-rules (=>)
((_ data) data)
((_ data => (lambda (x) e1 e2 ...))
(let ((x data)) e1 e2 ...))
((_ data e1 e2 ...)
(begin data e1 e2 ...))))
(define-syntax oc:immediate-dispatch
(syntax-rules (?)
((_ ((? ch) e1 ...))
((sender-waiting? ch)
(oc:consequence (immediate-receive ch) e1 ...)))
((_ (exp (? ch) e1 ...))
((and exp (sender-waiting? ch))
(oc:consequence (immediate-receive ch) e1 ...)))
((_ (exp e1 ...))
(exp e1 ...))))
(define-syntax oc:late-dispatch
(syntax-rules (?)
((_ ((? ch) e1 ...))
((sender-waiting? ch)
(oc:consequence (late-receive ch) e1 ...)))
((_ (exp (? ch) e1 ...))
((and exp (sender-waiting? ch))
(oc:consequence (late-receive ch) e1 ...)))
((_ (exp e1 ...))
(#f))))
(define-syntax oc:first-channel
(syntax-rules (?)
((_ ((? ch) e1 ...) c2 ...)
ch)
((_ (exp (? ch) e1 ...) c2 ...)
ch)
((_ c1 c2 ...)
(first-channel c2 ...))))
(define-syntax oc:set-handshake-channel
(syntax-rules (?)
((_ ((? ch) e1 ...) handshake)
(set! (handshake-channel ch) handshake))
((_ (exp (? ch) e1 ...) handshake)
(and exp (set! (handshake-channel ch) handshake)))
((_ (exp e1 ...) handshake)
#f)))
(define-syntax oc:unset-handshake-channel
(syntax-rules (?)
((_ ((? ch) e1 ...))
(set! (handshake-channel ch) ch))
((_ (exp (? ch) e1 ...))
(and exp (set! (handshake-channel ch) ch)))
((_ (exp e1 ...))
#f)))
(define-syntax alt
(lambda (x)
(define (else-clause? x)
(syntax-case x (else)
((_) #f)
((_ (else e1 e2 ...)) #t)
((_ c1 c2 ...) (else-clause? (syntax (_ c2 ...))))))
(syntax-case x (else)
((_ c1 c2 ...)
(else-clause? x)
(syntax (begin
(oc:lock c1)
(oc:lock c2) ...
(let ((res (cond (oc:immediate-dispatch c1)
(oc:immediate-dispatch c2) ...)))
(oc:unlock c1)
(oc:unlock c2) ...
res))))
((_ c1 c2 ...)
(syntax (begin
(oc:lock c1)
(oc:lock c2) ...
(let ((res (cond (oc:immediate-dispatch c1)
(oc:immediate-dispatch c2) ...
(else (let ((ch (oc:first-channel c1 c2 ...)))
(oc:set-handshake-channel c1 ch)
(oc:set-handshake-channel c2 ch) ...
(wait-condition-variable (cv ch)
(mutex ch))
(oc:unset-handshake-channel c1)
(oc:unset-handshake-channel c2) ...
(cond (oc:late-dispatch c1)
(oc:late-dispatch c2) ...))))))
(oc:unlock c1)
(oc:unlock c2) ...
res)))))))
;;;; optargs.scm -- support for optional arguments
;;;;
;;;; Copyright (C) 1997, 1998, 1999, 2001, 2002, 2004, 2006, 2009, 2010, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; Contributed by Maciej Stachowiak <mstachow@alum.mit.edu>
;;; Commentary:
;;; {Optional Arguments}
;;;
;;; The C interface for creating Guile procedures has a very handy
;;; "optional argument" feature. This module attempts to provide
;;; similar functionality for procedures defined in Scheme with
;;; a convenient and attractive syntax.
;;;
;;; exported macros are:
;;; let-optional
;;; let-optional*
;;; let-keywords
;;; let-keywords*
;;; lambda*
;;; define*
;;; define*-public
;;; defmacro*
;;; defmacro*-public
;;;
;;;
;;; Summary of the lambda* extended parameter list syntax (brackets
;;; are used to indicate grouping only):
;;;
;;; ext-param-list ::= [identifier]* [#\optional [ext-var-decl]+]?
;;; [#\key [ext-var-decl]+ [#\allow-other-keys]?]?
;;; [[#\rest identifier]|[. identifier]]?
;;;
;;; ext-var-decl ::= identifier | ( identifier expression )
;;;
;;; The characters `*', `+' and `?' are not to be taken literally; they
;;; mean respectively, zero or more occurences, one or more occurences,
;;; and one or zero occurences.
;;;
;;; Code:
(define-module (ice-9 optargs)
#\use-module (system base pmatch)
#\re-export (lambda* define*)
#\export (let-optional
let-optional*
let-keywords
let-keywords*
define*-public
defmacro*
defmacro*-public))
;; let-optional rest-arg (binding ...) . body
;; let-optional* rest-arg (binding ...) . body
;; macros used to bind optional arguments
;;
;; These two macros give you an optional argument interface that is
;; very "Schemey" and introduces no fancy syntax. They are compatible
;; with the scsh macros of the same name, but are slightly
;; extended. Each of binding may be of one of the forms <var> or
;; (<var> <default-value>). rest-arg should be the rest-argument of
;; the procedures these are used from. The items in rest-arg are
;; sequentially bound to the variable namess are given. When rest-arg
;; runs out, the remaining vars are bound either to the default values
;; or to `#f' if no default value was specified. rest-arg remains
;; bound to whatever may have been left of rest-arg.
;;
(define (vars&inits bindings)
(let lp ((bindings bindings) (vars '()) (inits '()))
(syntax-case bindings ()
(()
(values (reverse vars) (reverse inits)))
(((v init) . rest) (identifier? #'v)
(lp #'rest (cons #'v vars) (cons #'init inits)))
((v . rest) (identifier? #'v)
(lp #'rest (cons #'v vars) (cons #'#f inits))))))
(define-syntax let-optional
(lambda (x)
(syntax-case x ()
((_ rest-arg (binding ...) b0 b1 ...) (identifier? #'rest-arg)
(call-with-values (lambda () (vars&inits #'(binding ...)))
(lambda (vars inits)
(with-syntax ((n (length vars))
(n+1 (1+ (length vars)))
(vars (append vars (list #'rest-arg)))
((t ...) (generate-temporaries vars))
((i ...) inits))
#'(let ((t (lambda vars i))
...)
(apply (lambda vars b0 b1 ...)
(or (parse-lambda-case '(0 n n n+1 #f '())
(list t ...)
rest-arg)
(error "sth" rest-arg)))))))))))
(define-syntax let-optional*
(lambda (x)
(syntax-case x ()
((_ rest-arg (binding ...) b0 b1 ...) (identifier? #'rest-arg)
(call-with-values (lambda () (vars&inits #'(binding ...)))
(lambda (vars inits)
(with-syntax ((n (length vars))
(n+1 (1+ (length vars)))
(vars (append vars (list #'rest-arg)))
((i ...) inits))
#'(apply (lambda vars b0 b1 ...)
(or (parse-lambda-case '(0 n n n+1 #f '())
(list (lambda vars i) ...)
rest-arg)
(error "sth" rest-arg))))))))))
;; let-keywords rest-arg allow-other-keys? (binding ...) . body
;; let-keywords* rest-arg allow-other-keys? (binding ...) . body
;; macros used to bind keyword arguments
;;
;; These macros pick out keyword arguments from rest-arg, but do not
;; modify it. This is consistent at least with Common Lisp, which
;; duplicates keyword args in the rest arg. More explanation of what
;; keyword arguments in a lambda list look like can be found below in
;; the documentation for lambda*. Bindings can have the same form as
;; for let-optional. If allow-other-keys? is false, an error will be
;; thrown if anything that looks like a keyword argument but does not
;; match a known keyword parameter will result in an error.
;;
(define-syntax let-keywords
(lambda (x)
(syntax-case x ()
((_ rest-arg aok (binding ...) b0 b1 ...) (identifier? #'rest-arg)
(call-with-values (lambda () (vars&inits #'(binding ...)))
(lambda (vars inits)
(with-syntax ((n (length vars))
(vars vars)
(ivars (generate-temporaries vars))
((kw ...) (map symbol->keyword
(map syntax->datum vars)))
((idx ...) (iota (length vars)))
((t ...) (generate-temporaries vars))
((i ...) inits))
#'(let ((t (lambda ivars i))
...)
(apply (lambda vars b0 b1 ...)
(or (parse-lambda-case '(0 0 #f n aok ((kw . idx) ...))
(list t ...)
rest-arg)
(error "sth" rest-arg))))))))
((_ rest-arg aok (binding ...) b0 b1 ...)
#'(let ((r rest-arg))
(let-keywords r aok (binding ...) b0 b1 ...))))))
(define-syntax let-keywords*
(lambda (x)
(syntax-case x ()
((_ rest-arg aok (binding ...) b0 b1 ...) (identifier? #'rest-arg)
(call-with-values (lambda () (vars&inits #'(binding ...)))
(lambda (vars inits)
(with-syntax ((n (length vars))
(vars vars)
((kw ...) (map symbol->keyword
(map syntax->datum vars)))
((idx ...) (iota (length vars)))
((i ...) inits))
#'(apply (lambda vars b0 b1 ...)
(or (parse-lambda-case '(0 0 #f n aok ((kw . idx) ...))
(list (lambda vars i) ...)
rest-arg)
(error "sth" rest-arg)))))))
((_ rest-arg aok (binding ...) b0 b1 ...)
#'(let ((r rest-arg))
(let-keywords* r aok (binding ...) b0 b1 ...))))))
;; lambda* args . body
;; lambda extended for optional and keyword arguments
;;
;; lambda* creates a procedure that takes optional arguments. These
;; are specified by putting them inside brackets at the end of the
;; paramater list, but before any dotted rest argument. For example,
;; (lambda* (a b #\optional c d . e) '())
;; creates a procedure with fixed arguments a and b, optional arguments c
;; and d, and rest argument e. If the optional arguments are omitted
;; in a call, the variables for them are bound to `#f'.
;;
;; lambda* can also take keyword arguments. For example, a procedure
;; defined like this:
;; (lambda* (#\key xyzzy larch) '())
;; can be called with any of the argument lists (#\xyzzy 11)
;; (#\larch 13) (#\larch 42 #\xyzzy 19) (). Whichever arguments
;; are given as keywords are bound to values.
;;
;; Optional and keyword arguments can also be given default values
;; which they take on when they are not present in a call, by giving a
;; two-item list in place of an optional argument, for example in:
;; (lambda* (foo #\optional (bar 42) #\key (baz 73)) (list foo bar baz))
;; foo is a fixed argument, bar is an optional argument with default
;; value 42, and baz is a keyword argument with default value 73.
;; Default value expressions are not evaluated unless they are needed
;; and until the procedure is called.
;;
;; lambda* now supports two more special parameter list keywords.
;;
;; lambda*-defined procedures now throw an error by default if a
;; keyword other than one of those specified is found in the actual
;; passed arguments. However, specifying #\allow-other-keys
;; immediately after the keyword argument declarations restores the
;; previous behavior of ignoring unknown keywords. lambda* also now
;; guarantees that if the same keyword is passed more than once, the
;; last one passed is the one that takes effect. For example,
;; ((lambda* (#\key (heads 0) (tails 0)) (display (list heads tails)))
;; #\heads 37 #\tails 42 #\heads 99)
;; would result in (99 47) being displayed.
;;
;; #\rest is also now provided as a synonym for the dotted syntax rest
;; argument. The argument lists (a . b) and (a #\rest b) are equivalent in
;; all respects to lambda*. This is provided for more similarity to DSSSL,
;; MIT-Scheme and Kawa among others, as well as for refugees from other
;; Lisp dialects.
;; define* args . body
;; define*-public args . body
;; define and define-public extended for optional and keyword arguments
;;
;; define* and define*-public support optional arguments with
;; a similar syntax to lambda*. Some examples:
;; (define* (x y #\optional a (z 3) #\key w . u) (display (list y z u)))
;; defines a procedure x with a fixed argument y, an optional agument
;; a, another optional argument z with default value 3, a keyword argument w,
;; and a rest argument u.
;;
;; Of course, define*[-public] also supports #\rest and #\allow-other-keys
;; in the same way as lambda*.
(define-syntax define*-public
(lambda (x)
(syntax-case x ()
((_ (id . args) b0 b1 ...)
#'(define-public id (lambda* args b0 b1 ...)))
((_ id val) (identifier? #'id)
#'(define-public id val)))))
;; defmacro* name args . body
;; defmacro*-public args . body
;; defmacro and defmacro-public extended for optional and keyword arguments
;;
;; These are just like defmacro and defmacro-public except that they
;; take lambda*-style extended paramter lists, where #\optional,
;; #\key, #\allow-other-keys and #\rest are allowed with the usual
;; semantics. Here is an example of a macro with an optional argument:
;; (defmacro* transmogrify (a #\optional b)
(define-syntax defmacro*
(lambda (x)
(syntax-case x ()
((_ id args doc b0 b1 ...) (string? (syntax->datum #'doc))
#'(define-macro id doc (lambda* args b0 b1 ...)))
((_ id args b0 b1 ...)
#'(define-macro id #f (lambda* args b0 b1 ...))))))
(define-syntax-rule (defmacro*-public id args b0 b1 ...)
(begin
(defmacro* id args b0 b1 ...)
(export-syntax id)))
;;; Support for optional & keyword args with the interpreter.
(define *uninitialized* (list 'uninitialized))
(define (parse-lambda-case spec inits args)
(pmatch spec
((,nreq ,nopt ,rest-idx ,nargs ,allow-other-keys? ,kw-indices)
(define (req args prev tail n)
(cond
((zero? n)
(if prev (set-cdr! prev '()))
(let ((slots-tail (make-list (- nargs nreq) *uninitialized*)))
(opt (if prev (append! args slots-tail) slots-tail)
slots-tail tail nopt inits)))
((null? tail)
#f) ;; fail
(else
(req args tail (cdr tail) (1- n)))))
(define (opt slots slots-tail args-tail n inits)
(cond
((zero? n)
(rest-or-key slots slots-tail args-tail inits rest-idx))
((null? args-tail)
(set-car! slots-tail (apply (car inits) slots))
(opt slots (cdr slots-tail) '() (1- n) (cdr inits)))
(else
(set-car! slots-tail (car args-tail))
(opt slots (cdr slots-tail) (cdr args-tail) (1- n) (cdr inits)))))
(define (rest-or-key slots slots-tail args-tail inits rest-idx)
(cond
(rest-idx
;; it has to be this way, vars are allocated in this order
(set-car! slots-tail args-tail)
(if (pair? kw-indices)
(permissive-keys slots (cdr slots-tail) args-tail inits)
(rest-or-key slots (cdr slots-tail) '() inits #f)))
((pair? kw-indices)
;; fail early here, because once we're in keyword land we throw
;; errors instead of failing
(and (or (null? args-tail) rest-idx (keyword? (car args-tail)))
(key slots slots-tail args-tail inits)))
((pair? args-tail)
#f) ;; fail
(else
slots)))
(define (permissive-keys slots slots-tail args-tail inits)
(cond
((null? args-tail)
(if (null? inits)
slots
(begin
(if (eq? (car slots-tail) *uninitialized*)
(set-car! slots-tail (apply (car inits) slots)))
(permissive-keys slots (cdr slots-tail) '() (cdr inits)))))
((not (keyword? (car args-tail)))
(permissive-keys slots slots-tail (cdr args-tail) inits))
((and (keyword? (car args-tail))
(pair? (cdr args-tail))
(assq-ref kw-indices (car args-tail)))
=> (lambda (i)
(list-set! slots i (cadr args-tail))
(permissive-keys slots slots-tail (cddr args-tail) inits)))
((and (keyword? (car args-tail))
(pair? (cdr args-tail))
allow-other-keys?)
(permissive-keys slots slots-tail (cddr args-tail) inits))
(else (scm-error 'keyword-argument-error #f "Unrecognized keyword"
'() args-tail))))
(define (key slots slots-tail args-tail inits)
(cond
((null? args-tail)
(if (null? inits)
slots
(begin
(if (eq? (car slots-tail) *uninitialized*)
(set-car! slots-tail (apply (car inits) slots)))
(key slots (cdr slots-tail) '() (cdr inits)))))
((not (keyword? (car args-tail)))
(if rest-idx
;; no error checking, everything goes to the rest..
(key slots slots-tail '() inits)
(scm-error 'keyword-argument-error #f "Invalid keyword"
'() args-tail)))
((and (keyword? (car args-tail))
(pair? (cdr args-tail))
(assq-ref kw-indices (car args-tail)))
=> (lambda (i)
(list-set! slots i (cadr args-tail))
(key slots slots-tail (cddr args-tail) inits)))
((and (keyword? (car args-tail))
(pair? (cdr args-tail))
allow-other-keys?)
(key slots slots-tail (cddr args-tail) inits))
(else (scm-error 'keyword-argument-error #f "Unrecognized keyword"
'() args-tail))))
(let ((args (list-copy args)))
(req args #f args nreq)))
(else (error "unexpected spec" spec))))
;;; installed-scm-file
;;;; Copyright (C) 1996, 2001, 2006, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 poe)
\:use-module (ice-9 hcons)
\:export (pure-funcq perfect-funcq))
;;; {Pure Functions}
;;;
;;; A pure function (of some sort) is characterized by two equality
;;; relations: one on argument lists and one on return values.
;;; A pure function is one that when applied to equal arguments lists
;;; yields equal results.
;;;
;;; If the equality relationship on return values can be eq?, it may make
;;; sense to cache values returned by the function. Choosing the right
;;; equality relation on arguments is tricky.
;;;
;;; {pure-funcq}
;;;
;;; The simplest case of pure functions are those in which results
;;; are only certainly eq? if all of the arguments are. These functions
;;; are called "pure-funcq", for obvious reasons.
;;;
(define funcq-memo (make-weak-key-hash-table 523)) ; !!! randomly selected values
(define funcq-buffer (make-gc-buffer 256))
(define (funcq-hash arg-list n)
(let ((it (let loop ((x 0)
(arg-list arg-list))
(if (null? arg-list)
(modulo x n)
(loop (logior x (hashq (car arg-list) 4194303))
(cdr arg-list))))))
it))
;; return true if lists X and Y are the same length and each element is `eq?'
(define (eq?-list x y)
(if (null? x)
(null? y)
(and (not (null? y))
(eq? (car x) (car y))
(eq?-list (cdr x) (cdr y)))))
(define (funcq-assoc arg-list alist)
(if (null? alist)
#f
(if (eq?-list arg-list (caar alist))
(car alist)
(funcq-assoc arg-list (cdr alist)))))
(define not-found (list 'not-found))
(define (pure-funcq base-func)
(lambda args
(let* ((key (cons base-func args))
(cached (hashx-ref funcq-hash funcq-assoc funcq-memo key not-found)))
(if (not (eq? cached not-found))
(begin
(funcq-buffer key)
cached)
(let ((val (apply base-func args)))
(funcq-buffer key)
(hashx-set! funcq-hash funcq-assoc funcq-memo key val)
val)))))
;;; {Perfect funq}
;;;
;;; A pure funq may sometimes forget its past but a perfect
;;; funcq never does.
;;;
(define (perfect-funcq size base-func)
(define funcq-memo (make-hash-table size))
(lambda args
(let* ((key (cons base-func args))
(cached (hashx-ref funcq-hash funcq-assoc funcq-memo key not-found)))
(if (not (eq? cached not-found))
(begin
(funcq-buffer key)
cached)
(let ((val (apply base-func args)))
(funcq-buffer key)
(hashx-set! funcq-hash funcq-assoc funcq-memo key val)
val)))))
;; poll
;;;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 poll)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (rnrs bytevectors)
#\export (make-empty-poll-set
poll-set?
poll-set-nfds
poll-set-find-port
poll-set-port
poll-set-events
set-poll-set-events!
poll-set-revents
set-poll-set-revents!
poll-set-add!
poll-set-remove!
poll))
(eval-when (expand load eval)
(load-extension (string-append "libguile-" (effective-version))
"scm_init_poll"))
(if (not (= %sizeof-struct-pollfd 8))
(error "Unexpected struct pollfd size" %sizeof-struct-pollfd))
(if (defined? 'POLLIN)
(export POLLIN))
(if (defined? 'POLLPRI)
(export POLLPRI))
(if (defined? 'POLLOUT)
(export POLLOUT))
(if (defined? 'POLLRDHUP)
(export POLLRDHUP))
(if (defined? 'POLLERR)
(export POLLERR))
(if (defined? 'POLLHUP)
(export POLLHUP))
(if (defined? 'POLLNVAL)
(export POLLNVAL))
(define-record-type <poll-set>
(make-poll-set pollfds nfds ports)
poll-set?
(pollfds pset-pollfds set-pset-pollfds!)
(nfds poll-set-nfds set-pset-nfds!)
(ports pset-ports set-pset-ports!)
)
(define-syntax-rule (pollfd-offset n)
(* n 8))
(define* (make-empty-poll-set #\optional (pre-allocated 4))
(make-poll-set (make-bytevector (pollfd-offset pre-allocated) 0)
0
(make-vector pre-allocated #f)))
(define (pset-size set)
(vector-length (pset-ports set)))
(define (ensure-pset-size! set size)
(let ((prev (pset-size set)))
(if (< prev size)
(let lp ((new prev))
(if (< new size)
(lp (* new 2))
(let ((old-pollfds (pset-pollfds set))
(nfds (poll-set-nfds set))
(old-ports (pset-ports set))
(new-pollfds (make-bytevector (pollfd-offset new) 0))
(new-ports (make-vector new #f)))
(bytevector-copy! old-pollfds 0 new-pollfds 0
(pollfd-offset nfds))
(vector-move-left! old-ports 0 nfds new-ports 0)
(set-pset-pollfds! set new-pollfds)
(set-pset-ports! set new-ports)))))))
(define (poll-set-find-port set port)
(let lp ((i 0))
(if (< i (poll-set-nfds set))
(if (equal? (vector-ref (pset-ports set) i) port)
i
(lp (1+ i)))
#f)))
(define (poll-set-port set idx)
(if (< idx (poll-set-nfds set))
(vector-ref (pset-ports set) idx)
(error "poll set index out of bounds" set idx)))
(define (poll-set-events set idx)
(if (< idx (poll-set-nfds set))
(bytevector-u16-native-ref (pset-pollfds set) (+ (pollfd-offset idx) 4))
(error "poll set index out of bounds" set idx)))
(define (set-poll-set-events! set idx events)
(if (< idx (poll-set-nfds set))
(bytevector-u16-native-set! (pset-pollfds set) (+ (pollfd-offset idx) 4)
events)
(error "poll set index out of bounds" set idx)))
(define (poll-set-revents set idx)
(if (< idx (poll-set-nfds set))
(bytevector-u16-native-ref (pset-pollfds set) (+ (pollfd-offset idx) 6))
(error "poll set index out of bounds" set idx)))
(define (set-poll-set-revents! set idx revents)
(if (< idx (poll-set-nfds set))
(bytevector-u16-native-set! (pset-pollfds set) (+ (pollfd-offset idx) 6)
revents)
(error "poll set index out of bounds" set idx)))
(define (poll-set-add! set fd-or-port events)
(let* ((idx (poll-set-nfds set))
(off (pollfd-offset idx))
(fd (if (integer? fd-or-port)
fd-or-port
(port->fdes fd-or-port))))
(if (port? fd-or-port)
;; As we store the port in the fdset, there is no need to
;; increment the revealed count to prevent the fd from being
;; closed by a gc'd port.
(release-port-handle fd-or-port))
(ensure-pset-size! set (1+ idx))
(bytevector-s32-native-set! (pset-pollfds set) off fd)
(bytevector-u16-native-set! (pset-pollfds set) (+ off 4) events)
(bytevector-u16-native-set! (pset-pollfds set) (+ off 6) 0) ; revents
(vector-set! (pset-ports set) idx fd-or-port)
(set-pset-nfds! set (1+ idx))))
(define (poll-set-remove! set idx)
(if (not (< idx (poll-set-nfds set)))
(error "poll set index out of bounds" set idx))
(let ((nfds (poll-set-nfds set))
(off (pollfd-offset idx))
(port (vector-ref (pset-ports set) idx)))
(vector-move-left! (pset-ports set) (1+ idx) nfds
(pset-ports set) idx)
(vector-set! (pset-ports set) (1- nfds) #f)
(bytevector-copy! (pset-pollfds set) (pollfd-offset (1+ idx))
(pset-pollfds set) off
(- (pollfd-offset nfds) (pollfd-offset (1+ idx))))
;; zero the struct pollfd all at once
(bytevector-u64-native-set! (pset-pollfds set) (pollfd-offset (1- nfds)) 0)
(set-pset-nfds! set (1- nfds))
port))
(define* (poll poll-set #\optional (timeout -1))
(primitive-poll (pset-pollfds poll-set)
(poll-set-nfds poll-set)
(pset-ports poll-set)
timeout))
;; popen emulation, for non-stdio based ports.
;;;; Copyright (C) 1998, 1999, 2000, 2001, 2003, 2006, 2010, 2011, 2012,
;;;; 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 popen)
\:use-module (ice-9 threads)
\:use-module (srfi srfi-9)
\:export (port/pid-table open-pipe* open-pipe close-pipe open-input-pipe
open-output-pipe open-input-output-pipe))
(eval-when (expand load eval)
(load-extension (string-append "libguile-" (effective-version))
"scm_init_popen"))
(define-record-type <pipe-info>
(make-pipe-info pid)
pipe-info?
(pid pipe-info-pid set-pipe-info-pid!))
(define (make-rw-port read-port write-port)
(make-soft-port
(vector
(lambda (c) (write-char c write-port))
(lambda (s) (display s write-port))
(lambda () (force-output write-port))
(lambda () (read-char read-port))
(lambda () (close-port read-port) (close-port write-port)))
"r+"))
;; a guardian to ensure the cleanup is done correctly when
;; an open pipe is gc'd or a close-port is used.
(define pipe-guardian (make-guardian))
;; a weak hash-table to store the process ids.
;; XXX use of this table is deprecated. It is no longer used here, and
;; is populated for backward compatibility only (since it is exported).
(define port/pid-table (make-weak-key-hash-table 31))
(define port/pid-table-mutex (make-mutex))
(define (open-pipe* mode command . args)
"Executes the program @var{command} with optional arguments
@var{args} (all strings) in a subprocess.
A port to the process (based on pipes) is created and returned.
@var{mode} specifies whether an input, an output or an input-output
port to the process is created: it should be the value of
@code{OPEN_READ}, @code{OPEN_WRITE} or @code{OPEN_BOTH}."
(call-with-values (lambda ()
(apply open-process mode command args))
(lambda (read-port write-port pid)
(let ((port (or (and read-port write-port
(make-rw-port read-port write-port))
read-port
write-port
(%make-void-port mode)))
(pipe-info (make-pipe-info pid)))
;; Guard the pipe-info instead of the port, so that we can still
;; call 'waitpid' even if 'close-port' is called (which clears
;; the port entry).
(pipe-guardian pipe-info)
(%set-port-property! port 'popen-pipe-info pipe-info)
;; XXX populate port/pid-table for backward compatibility.
(with-mutex port/pid-table-mutex
(hashq-set! port/pid-table port pid))
port))))
(define (open-pipe command mode)
"Executes the shell command @var{command} (a string) in a subprocess.
A port to the process (based on pipes) is created and returned.
@var{mode} specifies whether an input, an output or an input-output
port to the process is created: it should be the value of
@code{OPEN_READ}, @code{OPEN_WRITE} or @code{OPEN_BOTH}."
(open-pipe* mode "/bin/sh" "-c" command))
(define (fetch-pipe-info port)
(%port-property port 'popen-pipe-info))
(define (close-process port pid)
(close-port port)
(cdr (waitpid pid)))
(define (close-pipe p)
"Closes the pipe created by @code{open-pipe}, then waits for the process
to terminate and returns its status value, @xref{Processes, waitpid}, for
information on how to interpret this value."
(let ((pipe-info (fetch-pipe-info p)))
(unless pipe-info
(error "close-pipe: port not created by (ice-9 popen)"))
(let ((pid (pipe-info-pid pipe-info)))
(unless pid
(error "close-pipe: pid has already been cleared"))
;; clear the pid to avoid repeated calls to 'waitpid'.
(set-pipe-info-pid! pipe-info #f)
(close-process p pid))))
(define (reap-pipes)
(let loop ()
(let ((pipe-info (pipe-guardian)))
(when pipe-info
(let ((pid (pipe-info-pid pipe-info)))
;; maybe 'close-pipe' was already called.
(when pid
;; clean up without reporting errors. also avoids blocking
;; the process: if the child isn't ready to be collected,
;; puts it back into the guardian's live list so it can be
;; tried again the next time the cleanup runs.
(catch 'system-error
(lambda ()
(let ((pid/status (waitpid pid WNOHANG)))
(if (zero? (car pid/status))
(pipe-guardian pipe-info) ; not ready for collection
(set-pipe-info-pid! pipe-info #f))))
(lambda args #f))))
(loop)))))
(add-hook! after-gc-hook reap-pipes)
(define (open-input-pipe command)
"Equivalent to @code{open-pipe} with mode @code{OPEN_READ}"
(open-pipe command OPEN_READ))
(define (open-output-pipe command)
"Equivalent to @code{open-pipe} with mode @code{OPEN_WRITE}"
(open-pipe command OPEN_WRITE))
(define (open-input-output-pipe command)
"Equivalent to @code{open-pipe} with mode @code{OPEN_BOTH}"
(open-pipe command OPEN_BOTH))
;;; installed-scm-file
;;;; Copyright (C) 1999, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
(define (stat:dev f) (vector-ref f 0))
(define (stat:ino f) (vector-ref f 1))
(define (stat:mode f) (vector-ref f 2))
(define (stat:nlink f) (vector-ref f 3))
(define (stat:uid f) (vector-ref f 4))
(define (stat:gid f) (vector-ref f 5))
(define (stat:rdev f) (vector-ref f 6))
(define (stat:size f) (vector-ref f 7))
(define (stat:atime f) (vector-ref f 8))
(define (stat:mtime f) (vector-ref f 9))
(define (stat:ctime f) (vector-ref f 10))
(define (stat:blksize f) (vector-ref f 11))
(define (stat:blocks f) (vector-ref f 12))
(define (stat:atimensec f) (vector-ref f 15))
(define (stat:mtimensec f) (vector-ref f 16))
(define (stat:ctimensec f) (vector-ref f 17))
;; derived from stat mode.
(define (stat:type f) (vector-ref f 13))
(define (stat:perms f) (vector-ref f 14))
(define (passwd:name obj) (vector-ref obj 0))
(define (passwd:passwd obj) (vector-ref obj 1))
(define (passwd:uid obj) (vector-ref obj 2))
(define (passwd:gid obj) (vector-ref obj 3))
(define (passwd:gecos obj) (vector-ref obj 4))
(define (passwd:dir obj) (vector-ref obj 5))
(define (passwd:shell obj) (vector-ref obj 6))
(define (group:name obj) (vector-ref obj 0))
(define (group:passwd obj) (vector-ref obj 1))
(define (group:gid obj) (vector-ref obj 2))
(define (group:mem obj) (vector-ref obj 3))
(define (utsname:sysname obj) (vector-ref obj 0))
(define (utsname:nodename obj) (vector-ref obj 1))
(define (utsname:release obj) (vector-ref obj 2))
(define (utsname:version obj) (vector-ref obj 3))
(define (utsname:machine obj) (vector-ref obj 4))
(define (getpwent) (getpw))
(define (setpwent) (setpw #t))
(define (endpwent) (setpw))
(define (getpwnam name) (getpw name))
(define (getpwuid uid) (getpw uid))
(define (getgrent) (getgr))
(define (setgrent) (setgr #t))
(define (endgrent) (setgr))
(define (getgrnam name) (getgr name))
(define (getgrgid id) (getgr id))
;;;; -*- coding: utf-8; mode: scheme -*-
;;;;
;;;; Copyright (C) 2001, 2004, 2006, 2009, 2010,
;;;; 2012, 2014 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 pretty-print)
#\use-module (ice-9 match)
#\use-module (srfi srfi-1)
#\use-module (rnrs bytevectors)
#\export (pretty-print
truncated-print))
;; From SLIB.
;;"genwrite.scm" generic write used by pretty-print and truncated-print.
;; Copyright (c) 1991, Marc Feeley
;; Author: Marc Feeley (feeley@iro.umontreal.ca)
;; Distribution restrictions: none
(define genwrite:newline-str (make-string 1 #\newline))
(define (generic-write
obj display? width max-expr-width per-line-prefix output)
(define (read-macro? l)
(define (length1? l) (and (pair? l) (null? (cdr l))))
(let ((head (car l)) (tail (cdr l)))
(case head
((quote quasiquote unquote unquote-splicing) (length1? tail))
(else #f))))
(define (read-macro-body l)
(cadr l))
(define (read-macro-prefix l)
(let ((head (car l)))
(case head
((quote) "'")
((quasiquote) "`")
((unquote) ",")
((unquote-splicing) ",@"))))
(define (out str col)
(and col (output str) (+ col (string-length str))))
(define (wr obj col)
(let loop ((obj obj)
(col col))
(match obj
(((or 'quote 'quasiquote 'unquote 'unquote-splicing) body)
(wr body (out (read-macro-prefix obj) col)))
((head . (rest ...))
;; A proper list: do our own list printing so as to catch read
;; macros that appear in the middle of the list.
(let ((col (loop head (out "(" col))))
(out ")"
(fold (lambda (i col)
(loop i (out " " col)))
col rest))))
(_
(out (object->string obj (if display? display write)) col)))))
(define (pp obj col)
(define (spaces n col)
(if (> n 0)
(if (> n 7)
(spaces (- n 8) (out " " col))
(out (substring " " 0 n) col))
col))
(define (indent to col)
(and col
(if (< to col)
(and (out genwrite:newline-str col)
(out per-line-prefix 0)
(spaces to 0))
(spaces (- to col) col))))
(define (pr obj col extra pp-pair)
(if (or (pair? obj) (vector? obj)) ; may have to split on multiple lines
(let ((result '())
(left (min (+ (- (- width col) extra) 1) max-expr-width)))
(generic-write obj display? #f max-expr-width ""
(lambda (str)
(set! result (cons str result))
(set! left (- left (string-length str)))
(> left 0)))
(if (> left 0) ; all can be printed on one line
(out (reverse-string-append result) col)
(if (pair? obj)
(pp-pair obj col extra)
(pp-list (vector->list obj) (out "#" col) extra pp-expr))))
(wr obj col)))
(define (pp-expr expr col extra)
(if (read-macro? expr)
(pr (read-macro-body expr)
(out (read-macro-prefix expr) col)
extra
pp-expr)
(let ((head (car expr)))
(if (symbol? head)
(let ((proc (style head)))
(if proc
(proc expr col extra)
(if (> (string-length (symbol->string head))
max-call-head-width)
(pp-general expr col extra #f #f #f pp-expr)
(pp-call expr col extra pp-expr))))
(pp-list expr col extra pp-expr)))))
; (head item1
; item2
; item3)
(define (pp-call expr col extra pp-item)
(let ((col* (wr (car expr) (out "(" col))))
(and col
(pp-down (cdr expr) col* (+ col* 1) extra pp-item))))
; (item1
; item2
; item3)
(define (pp-list l col extra pp-item)
(let ((col (out "(" col)))
(pp-down l col col extra pp-item)))
(define (pp-down l col1 col2 extra pp-item)
(let loop ((l l) (col col1))
(and col
(cond ((pair? l)
(let ((rest (cdr l)))
(let ((extra (if (null? rest) (+ extra 1) 0)))
(loop rest
(pr (car l) (indent col2 col) extra pp-item)))))
((null? l)
(out ")" col))
(else
(out ")"
(pr l
(indent col2 (out "." (indent col2 col)))
(+ extra 1)
pp-item)))))))
(define (pp-general expr col extra named? pp-1 pp-2 pp-3)
(define (tail1 rest col1 col2 col3)
(if (and pp-1 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail2 rest col1 (pr val1 (indent col3 col2) extra pp-1) col3))
(tail2 rest col1 col2 col3)))
(define (tail2 rest col1 col2 col3)
(if (and pp-2 (pair? rest))
(let* ((val1 (car rest))
(rest (cdr rest))
(extra (if (null? rest) (+ extra 1) 0)))
(tail3 rest col1 (pr val1 (indent col3 col2) extra pp-2)))
(tail3 rest col1 col2)))
(define (tail3 rest col1 col2)
(pp-down rest col2 col1 extra pp-3))
(let* ((head (car expr))
(rest (cdr expr))
(col* (wr head (out "(" col))))
(if (and named? (pair? rest))
(let* ((name (car rest))
(rest (cdr rest))
(col** (wr name (out " " col*))))
(tail1 rest (+ col indent-general) col** (+ col** 1)))
(tail1 rest (+ col indent-general) col* (+ col* 1)))))
(define (pp-expr-list l col extra)
(pp-list l col extra pp-expr))
(define (pp-LAMBDA expr col extra)
(pp-general expr col extra #f pp-expr-list #f pp-expr))
(define (pp-IF expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr))
(define (pp-COND expr col extra)
(pp-call expr col extra pp-expr-list))
(define (pp-CASE expr col extra)
(pp-general expr col extra #f pp-expr #f pp-expr-list))
(define (pp-AND expr col extra)
(pp-call expr col extra pp-expr))
(define (pp-LET expr col extra)
(let* ((rest (cdr expr))
(named? (and (pair? rest) (symbol? (car rest)))))
(pp-general expr col extra named? pp-expr-list #f pp-expr)))
(define (pp-BEGIN expr col extra)
(pp-general expr col extra #f #f #f pp-expr))
(define (pp-DO expr col extra)
(pp-general expr col extra #f pp-expr-list pp-expr-list pp-expr))
(define (pp-SYNTAX-CASE expr col extra)
(pp-general expr col extra #t pp-expr-list #f pp-expr))
; define formatting style (change these to suit your style)
(define indent-general 2)
(define max-call-head-width 5)
(define (style head)
(case head
((lambda lambda* let* letrec define define* define-public
define-syntax let-syntax letrec-syntax with-syntax)
pp-LAMBDA)
((if set!) pp-IF)
((cond) pp-COND)
((case) pp-CASE)
((and or) pp-AND)
((let) pp-LET)
((begin) pp-BEGIN)
((do) pp-DO)
((syntax-rules) pp-LAMBDA)
((syntax-case) pp-SYNTAX-CASE)
(else #f)))
(pr obj col 0 pp-expr))
(out per-line-prefix 0)
(if width
(out genwrite:newline-str (pp obj 0))
(wr obj 0))
;; Return `unspecified'
(if #f #f))
; (reverse-string-append l) = (apply string-append (reverse l))
(define (reverse-string-append l)
(define (rev-string-append l i)
(if (pair? l)
(let* ((str (car l))
(len (string-length str))
(result (rev-string-append (cdr l) (+ i len))))
(let loop ((j 0) (k (- (- (string-length result) i) len)))
(if (< j len)
(begin
(string-set! result k (string-ref str j))
(loop (+ j 1) (+ k 1)))
result)))
(make-string i)))
(rev-string-append l 0))
(define* (pretty-print obj #\optional port*
#\key
(port (or port* (current-output-port)))
(width 79)
(max-expr-width 50)
(display? #f)
(per-line-prefix ""))
"Pretty-print OBJ on PORT, which is a keyword argument defaulting to
the current output port. Formatting can be controlled by a number of
keyword arguments: Each line in the output is preceded by the string
PER-LINE-PREFIX, which is empty by default. The output lines will be
at most WIDTH characters wide; the default is 79. If DISPLAY? is
true, display rather than write representation will be used.
Instead of with a keyword argument, you can also specify the output
port directly after OBJ, like (pretty-print OBJ PORT)."
(generic-write obj display?
(- width (string-length per-line-prefix))
max-expr-width
per-line-prefix
(lambda (s) (display s port) #t)))
;; `truncated-print' was written in 2009 by Andy Wingo, and is not from
;; genwrite.scm.
(define* (truncated-print x #\optional port*
#\key
(port (or port* (current-output-port)))
(width 79)
(display? #f)
(breadth-first? #f))
"Print @var{x}, truncating the output, if necessary, to make it fit
into @var{width} characters. By default, @var{x} will be printed using
@code{write}, though that behavior can be overriden via the
@var{display?} keyword argument.
The default behaviour is to print depth-first, meaning that the entire
remaining width will be available to each sub-expression of @var{x} --
e.g., if @var{x} is a vector, each member of @var{x}. One can attempt to
\"ration\" the available width, trying to allocate it equally to each
sub-expression, via the @var{breadth-first?} keyword argument."
;; Make sure string ports are created with the right encoding.
(with-fluids ((%default-port-encoding (port-encoding port)))
(define ellipsis
;; Choose between `HORIZONTAL ELLIPSIS' (U+2026) and three dots, depending
;; on the encoding of PORT.
(let ((e "…"))
(catch 'encoding-error
(lambda ()
(with-fluids ((%default-port-conversion-strategy 'error))
(with-output-to-string
(lambda ()
(display e)))))
(lambda (key . args)
"..."))))
(let ((ellipsis-width (string-length ellipsis)))
(define (print-sequence x width len ref next)
(let lp ((x x)
(width width)
(i 0))
(if (> i 0)
(display #\space))
(cond
((= i len)) ; catches 0-length case
((and (= i (1- len)) (or (zero? i) (> width 1)))
(print (ref x i) (if (zero? i) width (1- width))))
((<= width (+ 1 ellipsis-width))
(display ellipsis))
(else
(let ((str
(with-fluids ((%default-port-encoding (port-encoding port)))
(with-output-to-string
(lambda ()
(print (ref x i)
(if breadth-first?
(max 1
(1- (floor (/ width (- len i)))))
(- width (+ 1 ellipsis-width)))))))))
(display str)
(lp (next x) (- width 1 (string-length str)) (1+ i)))))))
(define (print-tree x width)
;; width is >= the width of # . #, which is 5
(let lp ((x x)
(width width))
(cond
((or (not (pair? x)) (<= width 4))
(display ". ")
(print x (- width 2)))
(else
;; width >= 5
(let ((str (with-output-to-string
(lambda ()
(print (car x)
(if breadth-first?
(floor (/ (- width 3) 2))
(- width 4)))))))
(display str)
(display " ")
(lp (cdr x) (- width 1 (string-length str))))))))
(define (truncate-string str width)
;; width is < (string-length str)
(let lp ((fixes '(("#<" . ">")
("#(" . ")")
("(" . ")")
("\"" . "\""))))
(cond
((null? fixes)
"#")
((and (string-prefix? (caar fixes) str)
(string-suffix? (cdar fixes) str)
(>= (string-length str)
width
(+ (string-length (caar fixes))
(string-length (cdar fixes))
ellipsis-width)))
(format #f "~a~a~a~a"
(caar fixes)
(substring str (string-length (caar fixes))
(- width (string-length (cdar fixes))
ellipsis-width))
ellipsis
(cdar fixes)))
(else
(lp (cdr fixes))))))
(define (print x width)
(cond
((<= width 0)
(error "expected a positive width" width))
((list? x)
(cond
((>= width (+ 2 ellipsis-width))
(display "(")
(print-sequence x (- width 2) (length x)
(lambda (x i) (car x)) cdr)
(display ")"))
(else
(display "#"))))
((vector? x)
(cond
((>= width (+ 3 ellipsis-width))
(display "#(")
(print-sequence x (- width 3) (vector-length x)
vector-ref identity)
(display ")"))
(else
(display "#"))))
((bytevector? x)
(cond
((>= width 9)
(format #t "#~a(" (array-type x))
(print-sequence x (- width 6) (array-length x)
array-ref identity)
(display ")"))
(else
(display "#"))))
((pair? x)
(cond
((>= width (+ 4 ellipsis-width))
(display "(")
(print-tree x (- width 2))
(display ")"))
(else
(display "#"))))
(else
(let* ((str (with-output-to-string
(lambda () (if display? (display x) (write x)))))
(len (string-length str)))
(display (if (<= (string-length str) width)
str
(truncate-string str width)))))))
(with-output-to-port port
(lambda ()
(print x width))))))
(eval-when (compile) (set-current-module (resolve-module (quote (guile)))))
(if #f #f)
(letrec*
((make-void
(lambda (src) (make-struct (vector-ref %expanded-vtables 0) 0 src)))
(make-const
(lambda (src exp)
(make-struct (vector-ref %expanded-vtables 1) 0 src exp)))
(make-primitive-ref
(lambda (src name)
(make-struct (vector-ref %expanded-vtables 2) 0 src name)))
(make-lexical-ref
(lambda (src name gensym)
(make-struct (vector-ref %expanded-vtables 3) 0 src name gensym)))
(make-lexical-set
(lambda (src name gensym exp)
(make-struct (vector-ref %expanded-vtables 4) 0 src name gensym exp)))
(make-module-ref
(lambda (src mod name public?)
(make-struct (vector-ref %expanded-vtables 5) 0 src mod name public?)))
(make-module-set
(lambda (src mod name public? exp)
(make-struct
(vector-ref %expanded-vtables 6)
0
src
mod
name
public?
exp)))
(make-toplevel-ref
(lambda (src name)
(make-struct (vector-ref %expanded-vtables 7) 0 src name)))
(make-toplevel-set
(lambda (src name exp)
(make-struct (vector-ref %expanded-vtables 8) 0 src name exp)))
(make-toplevel-define
(lambda (src name exp)
(make-struct (vector-ref %expanded-vtables 9) 0 src name exp)))
(make-conditional
(lambda (src test consequent alternate)
(make-struct
(vector-ref %expanded-vtables 10)
0
src
test
consequent
alternate)))
(make-application
(lambda (src proc args)
(make-struct (vector-ref %expanded-vtables 11) 0 src proc args)))
(make-sequence
(lambda (src exps)
(make-struct (vector-ref %expanded-vtables 12) 0 src exps)))
(make-lambda
(lambda (src meta body)
(make-struct (vector-ref %expanded-vtables 13) 0 src meta body)))
(make-lambda-case
(lambda (src req opt rest kw inits gensyms body alternate)
(make-struct
(vector-ref %expanded-vtables 14)
0
src
req
opt
rest
kw
inits
gensyms
body
alternate)))
(make-let
(lambda (src names gensyms vals body)
(make-struct
(vector-ref %expanded-vtables 15)
0
src
names
gensyms
vals
body)))
(make-letrec
(lambda (src in-order? names gensyms vals body)
(make-struct
(vector-ref %expanded-vtables 16)
0
src
in-order?
names
gensyms
vals
body)))
(make-dynlet
(lambda (src fluids vals body)
(make-struct
(vector-ref %expanded-vtables 17)
0
src
fluids
vals
body)))
(lambda?
(lambda (x)
(and (struct? x)
(eq? (struct-vtable x) (vector-ref %expanded-vtables 13)))))
(lambda-meta (lambda (x) (struct-ref x 1)))
(set-lambda-meta! (lambda (x v) (struct-set! x 1 v)))
(top-level-eval-hook (lambda (x mod) (primitive-eval x)))
(local-eval-hook (lambda (x mod) (primitive-eval x)))
(session-id
(let ((v (module-variable (current-module) 'syntax-session-id)))
(lambda () ((variable-ref v)))))
(put-global-definition-hook
(lambda (symbol type val)
(module-define!
(current-module)
symbol
(make-syntax-transformer symbol type val))))
(get-global-definition-hook
(lambda (symbol module)
(if (and (not module) (current-module))
(warn "module system is booted, we should have a module" symbol))
(let ((v (module-variable
(if module (resolve-module (cdr module)) (current-module))
symbol)))
(and v
(variable-bound? v)
(let ((val (variable-ref v)))
(and (macro? val)
(macro-type val)
(cons (macro-type val) (macro-binding val))))))))
(decorate-source
(lambda (e s)
(if (and s (supports-source-properties? e))
(set-source-properties! e s))
e))
(maybe-name-value!
(lambda (name val)
(if (lambda? val)
(let ((meta (lambda-meta val)))
(if (not (assq 'name meta))
(set-lambda-meta! val (acons 'name name meta)))))))
(build-void (lambda (source) (make-void source)))
(build-application
(lambda (source fun-exp arg-exps)
(make-application source fun-exp arg-exps)))
(build-conditional
(lambda (source test-exp then-exp else-exp)
(make-conditional source test-exp then-exp else-exp)))
(build-dynlet
(lambda (source fluids vals body)
(make-dynlet source fluids vals body)))
(build-lexical-reference
(lambda (type source name var) (make-lexical-ref source name var)))
(build-lexical-assignment
(lambda (source name var exp)
(maybe-name-value! name exp)
(make-lexical-set source name var exp)))
(analyze-variable
(lambda (mod var modref-cont bare-cont)
(if (not mod)
(bare-cont var)
(let ((kind (car mod)) (mod (cdr mod)))
(let ((key kind))
(cond ((memv key '(public)) (modref-cont mod var #t))
((memv key '(private))
(if (not (equal? mod (module-name (current-module))))
(modref-cont mod var #f)
(bare-cont var)))
((memv key '(bare)) (bare-cont var))
((memv key '(hygiene))
(if (and (not (equal? mod (module-name (current-module))))
(module-variable (resolve-module mod) var))
(modref-cont mod var #f)
(bare-cont var)))
(else (syntax-violation #f "bad module kind" var mod))))))))
(build-global-reference
(lambda (source var mod)
(analyze-variable
mod
var
(lambda (mod var public?) (make-module-ref source mod var public?))
(lambda (var) (make-toplevel-ref source var)))))
(build-global-assignment
(lambda (source var exp mod)
(maybe-name-value! var exp)
(analyze-variable
mod
var
(lambda (mod var public?)
(make-module-set source mod var public? exp))
(lambda (var) (make-toplevel-set source var exp)))))
(build-global-definition
(lambda (source var exp)
(maybe-name-value! var exp)
(make-toplevel-define source var exp)))
(build-simple-lambda
(lambda (src req rest vars meta exp)
(make-lambda
src
meta
(make-lambda-case src req #f rest #f '() vars exp #f))))
(build-case-lambda
(lambda (src meta body) (make-lambda src meta body)))
(build-lambda-case
(lambda (src req opt rest kw inits vars body else-case)
(make-lambda-case src req opt rest kw inits vars body else-case)))
(build-primref
(lambda (src name)
(if (equal? (module-name (current-module)) '(guile))
(make-toplevel-ref src name)
(make-module-ref src '(guile) name #f))))
(build-data (lambda (src exp) (make-const src exp)))
(build-sequence
(lambda (src exps)
(if (null? (cdr exps)) (car exps) (make-sequence src exps))))
(build-let
(lambda (src ids vars val-exps body-exp)
(for-each maybe-name-value! ids val-exps)
(if (null? vars) body-exp (make-let src ids vars val-exps body-exp))))
(build-named-let
(lambda (src ids vars val-exps body-exp)
(let ((f (car vars)) (f-name (car ids)) (vars (cdr vars)) (ids (cdr ids)))
(let ((proc (build-simple-lambda src ids #f vars '() body-exp)))
(maybe-name-value! f-name proc)
(for-each maybe-name-value! ids val-exps)
(make-letrec
src
#f
(list f-name)
(list f)
(list proc)
(build-application
src
(build-lexical-reference 'fun src f-name f)
val-exps))))))
(build-letrec
(lambda (src in-order? ids vars val-exps body-exp)
(if (null? vars)
body-exp
(begin
(for-each maybe-name-value! ids val-exps)
(make-letrec src in-order? ids vars val-exps body-exp)))))
(make-syntax-object
(lambda (expression wrap module)
(vector 'syntax-object expression wrap module)))
(syntax-object?
(lambda (x)
(and (vector? x)
(= (vector-length x) 4)
(eq? (vector-ref x 0) 'syntax-object))))
(syntax-object-expression (lambda (x) (vector-ref x 1)))
(syntax-object-wrap (lambda (x) (vector-ref x 2)))
(syntax-object-module (lambda (x) (vector-ref x 3)))
(set-syntax-object-expression!
(lambda (x update) (vector-set! x 1 update)))
(set-syntax-object-wrap!
(lambda (x update) (vector-set! x 2 update)))
(set-syntax-object-module!
(lambda (x update) (vector-set! x 3 update)))
(source-annotation
(lambda (x)
(let ((props (source-properties
(if (syntax-object? x) (syntax-object-expression x) x))))
(and (pair? props) props))))
(extend-env
(lambda (labels bindings r)
(if (null? labels)
r
(extend-env
(cdr labels)
(cdr bindings)
(cons (cons (car labels) (car bindings)) r)))))
(extend-var-env
(lambda (labels vars r)
(if (null? labels)
r
(extend-var-env
(cdr labels)
(cdr vars)
(cons (cons (car labels) (cons 'lexical (car vars))) r)))))
(macros-only-env
(lambda (r)
(if (null? r)
'()
(let ((a (car r)))
(if (memq (cadr a) '(macro ellipsis))
(cons a (macros-only-env (cdr r)))
(macros-only-env (cdr r)))))))
(lookup
(lambda (x r mod)
(let ((t (assq x r)))
(cond (t (cdr t))
((symbol? x) (or (get-global-definition-hook x mod) '(global)))
(else '(displaced-lexical))))))
(global-extend
(lambda (type sym val) (put-global-definition-hook sym type val)))
(nonsymbol-id?
(lambda (x)
(and (syntax-object? x) (symbol? (syntax-object-expression x)))))
(id? (lambda (x)
(if (symbol? x)
#t
(and (syntax-object? x) (symbol? (syntax-object-expression x))))))
(id-sym-name&marks
(lambda (x w)
(if (syntax-object? x)
(values
(syntax-object-expression x)
(join-marks (car w) (car (syntax-object-wrap x))))
(values x (car w)))))
(gen-label (lambda () (symbol->string (module-gensym "l"))))
(gen-labels
(lambda (ls)
(if (null? ls) '() (cons (gen-label) (gen-labels (cdr ls))))))
(make-ribcage
(lambda (symnames marks labels)
(vector 'ribcage symnames marks labels)))
(ribcage?
(lambda (x)
(and (vector? x)
(= (vector-length x) 4)
(eq? (vector-ref x 0) 'ribcage))))
(ribcage-symnames (lambda (x) (vector-ref x 1)))
(ribcage-marks (lambda (x) (vector-ref x 2)))
(ribcage-labels (lambda (x) (vector-ref x 3)))
(set-ribcage-symnames! (lambda (x update) (vector-set! x 1 update)))
(set-ribcage-marks! (lambda (x update) (vector-set! x 2 update)))
(set-ribcage-labels! (lambda (x update) (vector-set! x 3 update)))
(anti-mark
(lambda (w) (cons (cons #f (car w)) (cons 'shift (cdr w)))))
(extend-ribcage!
(lambda (ribcage id label)
(set-ribcage-symnames!
ribcage
(cons (syntax-object-expression id) (ribcage-symnames ribcage)))
(set-ribcage-marks!
ribcage
(cons (car (syntax-object-wrap id)) (ribcage-marks ribcage)))
(set-ribcage-labels! ribcage (cons label (ribcage-labels ribcage)))))
(make-binding-wrap
(lambda (ids labels w)
(if (null? ids)
w
(cons (car w)
(cons (let* ((labelvec (list->vector labels)) (n (vector-length labelvec)))
(let ((symnamevec (make-vector n)) (marksvec (make-vector n)))
(let f ((ids ids) (i 0))
(if (not (null? ids))
(call-with-values
(lambda () (id-sym-name&marks (car ids) w))
(lambda (symname marks)
(vector-set! symnamevec i symname)
(vector-set! marksvec i marks)
(f (cdr ids) (+ i 1))))))
(make-ribcage symnamevec marksvec labelvec)))
(cdr w))))))
(smart-append (lambda (m1 m2) (if (null? m2) m1 (append m1 m2))))
(join-wraps
(lambda (w1 w2)
(let ((m1 (car w1)) (s1 (cdr w1)))
(if (null? m1)
(if (null? s1) w2 (cons (car w2) (smart-append s1 (cdr w2))))
(cons (smart-append m1 (car w2)) (smart-append s1 (cdr w2)))))))
(join-marks (lambda (m1 m2) (smart-append m1 m2)))
(same-marks?
(lambda (x y)
(or (eq? x y)
(and (not (null? x))
(not (null? y))
(eq? (car x) (car y))
(same-marks? (cdr x) (cdr y))))))
(id-var-name
(lambda (id w)
(letrec*
((search
(lambda (sym subst marks)
(if (null? subst)
(values #f marks)
(let ((fst (car subst)))
(if (eq? fst 'shift)
(search sym (cdr subst) (cdr marks))
(let ((symnames (ribcage-symnames fst)))
(if (vector? symnames)
(search-vector-rib sym subst marks symnames fst)
(search-list-rib sym subst marks symnames fst))))))))
(search-list-rib
(lambda (sym subst marks symnames ribcage)
(let f ((symnames symnames) (i 0))
(cond ((null? symnames) (search sym (cdr subst) marks))
((and (eq? (car symnames) sym)
(same-marks? marks (list-ref (ribcage-marks ribcage) i)))
(values (list-ref (ribcage-labels ribcage) i) marks))
(else (f (cdr symnames) (+ i 1)))))))
(search-vector-rib
(lambda (sym subst marks symnames ribcage)
(let ((n (vector-length symnames)))
(let f ((i 0))
(cond ((= i n) (search sym (cdr subst) marks))
((and (eq? (vector-ref symnames i) sym)
(same-marks? marks (vector-ref (ribcage-marks ribcage) i)))
(values (vector-ref (ribcage-labels ribcage) i) marks))
(else (f (+ i 1)))))))))
(cond ((symbol? id) (or (search id (cdr w) (car w)) id))
((syntax-object? id)
(let ((id (syntax-object-expression id)) (w1 (syntax-object-wrap id)))
(let ((marks (join-marks (car w) (car w1))))
(call-with-values
(lambda () (search id (cdr w) marks))
(lambda (new-id marks) (or new-id (search id (cdr w1) marks) id))))))
(else (syntax-violation 'id-var-name "invalid id" id))))))
(locally-bound-identifiers
(lambda (w mod)
(letrec*
((scan (lambda (subst results)
(if (null? subst)
results
(let ((fst (car subst)))
(if (eq? fst 'shift)
(scan (cdr subst) results)
(let ((symnames (ribcage-symnames fst)) (marks (ribcage-marks fst)))
(if (vector? symnames)
(scan-vector-rib subst symnames marks results)
(scan-list-rib subst symnames marks results))))))))
(scan-list-rib
(lambda (subst symnames marks results)
(let f ((symnames symnames) (marks marks) (results results))
(if (null? symnames)
(scan (cdr subst) results)
(f (cdr symnames)
(cdr marks)
(cons (wrap (car symnames) (anti-mark (cons (car marks) subst)) mod)
results))))))
(scan-vector-rib
(lambda (subst symnames marks results)
(let ((n (vector-length symnames)))
(let f ((i 0) (results results))
(if (= i n)
(scan (cdr subst) results)
(f (+ i 1)
(cons (wrap (vector-ref symnames i)
(anti-mark (cons (vector-ref marks i) subst))
mod)
results))))))))
(scan (cdr w) '()))))
(resolve-identifier
(lambda (id w r mod)
(letrec*
((resolve-global
(lambda (var mod)
(let ((b (or (get-global-definition-hook var mod) '(global))))
(if (eq? (car b) 'global)
(values 'global var mod)
(values (car b) (cdr b) mod)))))
(resolve-lexical
(lambda (label mod)
(let ((b (or (assq-ref r label) '(displaced-lexical))))
(values (car b) (cdr b) mod)))))
(let ((n (id-var-name id w)))
(cond ((symbol? n)
(resolve-global
n
(if (syntax-object? id) (syntax-object-module id) mod)))
((string? n)
(resolve-lexical
n
(if (syntax-object? id) (syntax-object-module id) mod)))
(else (error "unexpected id-var-name" id w n)))))))
(transformer-environment
(make-fluid
(lambda (k)
(error "called outside the dynamic extent of a syntax transformer"))))
(with-transformer-environment
(lambda (k) ((fluid-ref transformer-environment) k)))
(free-id=?
(lambda (i j)
(and (eq? (let ((x i)) (if (syntax-object? x) (syntax-object-expression x) x))
(let ((x j)) (if (syntax-object? x) (syntax-object-expression x) x)))
(eq? (id-var-name i '(())) (id-var-name j '(()))))))
(bound-id=?
(lambda (i j)
(if (and (syntax-object? i) (syntax-object? j))
(and (eq? (syntax-object-expression i) (syntax-object-expression j))
(same-marks?
(car (syntax-object-wrap i))
(car (syntax-object-wrap j))))
(eq? i j))))
(valid-bound-ids?
(lambda (ids)
(and (let all-ids? ((ids ids))
(or (null? ids) (and (id? (car ids)) (all-ids? (cdr ids)))))
(distinct-bound-ids? ids))))
(distinct-bound-ids?
(lambda (ids)
(let distinct? ((ids ids))
(or (null? ids)
(and (not (bound-id-member? (car ids) (cdr ids)))
(distinct? (cdr ids)))))))
(bound-id-member?
(lambda (x list)
(and (not (null? list))
(or (bound-id=? x (car list)) (bound-id-member? x (cdr list))))))
(wrap (lambda (x w defmod)
(cond ((and (null? (car w)) (null? (cdr w))) x)
((syntax-object? x)
(make-syntax-object
(syntax-object-expression x)
(join-wraps w (syntax-object-wrap x))
(syntax-object-module x)))
((null? x) x)
(else (make-syntax-object x w defmod)))))
(source-wrap
(lambda (x w s defmod) (wrap (decorate-source x s) w defmod)))
(expand-sequence
(lambda (body r w s mod)
(build-sequence
s
(let dobody ((body body) (r r) (w w) (mod mod))
(if (null? body)
'()
(let ((first (expand (car body) r w mod)))
(cons first (dobody (cdr body) r w mod))))))))
(expand-top-sequence
(lambda (body r w s m esew mod)
(letrec*
((scan (lambda (body r w s m esew mod exps)
(if (null? body)
exps
(call-with-values
(lambda ()
(call-with-values
(lambda ()
(let ((e (car body)))
(syntax-type e r w (or (source-annotation e) s) #f mod #f)))
(lambda (type value form e w s mod)
(let ((key type))
(cond ((memv key '(begin-form))
(let* ((tmp e) (tmp-1 ($sc-dispatch tmp '(_))))
(if tmp-1
(apply (lambda () exps) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ any . each-any))))
(if tmp-1
(apply (lambda (e1 e2) (scan (cons e1 e2) r w s m esew mod exps))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))
((memv key '(local-syntax-form))
(expand-local-syntax
value
e
r
w
s
mod
(lambda (body r w s mod) (scan body r w s m esew mod exps))))
((memv key '(eval-when-form))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ each-any any . each-any))))
(if tmp
(apply (lambda (x e1 e2)
(let ((when-list (parse-when-list e x)) (body (cons e1 e2)))
(cond ((eq? m 'e)
(if (memq 'eval when-list)
(scan body
r
w
s
(if (memq 'expand when-list) 'c&e 'e)
'(eval)
mod
exps)
(begin
(if (memq 'expand when-list)
(top-level-eval-hook
(expand-top-sequence body r w s 'e '(eval) mod)
mod))
(values exps))))
((memq 'load when-list)
(cond ((or (memq 'compile when-list)
(memq 'expand when-list)
(and (eq? m 'c&e) (memq 'eval when-list)))
(scan body r w s 'c&e '(compile load) mod exps))
((memq m '(c c&e))
(scan body r w s 'c '(load) mod exps))
(else (values exps))))
((or (memq 'compile when-list)
(memq 'expand when-list)
(and (eq? m 'c&e) (memq 'eval when-list)))
(top-level-eval-hook
(expand-top-sequence body r w s 'e '(eval) mod)
mod)
(values exps))
(else (values exps)))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
((memv key '(define-syntax-form define-syntax-parameter-form))
(let ((n (id-var-name value w)) (r (macros-only-env r)))
(let ((key m))
(cond ((memv key '(c))
(cond ((memq 'compile esew)
(let ((e (expand-install-global n (expand e r w mod))))
(top-level-eval-hook e mod)
(if (memq 'load esew) (values (cons e exps)) (values exps))))
((memq 'load esew)
(values
(cons (expand-install-global n (expand e r w mod)) exps)))
(else (values exps))))
((memv key '(c&e))
(let ((e (expand-install-global n (expand e r w mod))))
(top-level-eval-hook e mod)
(values (cons e exps))))
(else
(if (memq 'eval esew)
(top-level-eval-hook
(expand-install-global n (expand e r w mod))
mod))
(values exps))))))
((memv key '(define-form))
(let* ((n (id-var-name value w)) (type (car (lookup n r mod))) (key type))
(cond ((memv key '(global core macro module-ref))
(if (and (memq m '(c c&e))
(not (module-local-variable (current-module) n))
(current-module))
(let ((old (module-variable (current-module) n)))
(if (and (variable? old)
(variable-bound? old)
(not (macro? (variable-ref old))))
(module-define! (current-module) n (variable-ref old))
(module-add! (current-module) n (make-undefined-variable)))))
(values
(cons (if (eq? m 'c&e)
(let ((x (build-global-definition s n (expand e r w mod))))
(top-level-eval-hook x mod)
x)
(lambda () (build-global-definition s n (expand e r w mod))))
exps)))
((memv key '(displaced-lexical))
(syntax-violation
#f
"identifier out of context"
(source-wrap form w s mod)
(wrap value w mod)))
(else
(syntax-violation
#f
"cannot define keyword at top level"
(source-wrap form w s mod)
(wrap value w mod))))))
(else
(values
(cons (if (eq? m 'c&e)
(let ((x (expand-expr type value form e r w s mod)))
(top-level-eval-hook x mod)
x)
(lambda () (expand-expr type value form e r w s mod)))
exps))))))))
(lambda (exps) (scan (cdr body) r w s m esew mod exps)))))))
(call-with-values
(lambda () (scan body r w s m esew mod '()))
(lambda (exps)
(if (null? exps)
(build-void s)
(build-sequence
s
(let lp ((in exps) (out '()))
(if (null? in)
out
(let ((e (car in)))
(lp (cdr in) (cons (if (procedure? e) (e) e) out))))))))))))
(expand-install-global
(lambda (name e)
(build-global-definition
#f
name
(build-application
#f
(build-primref #f 'make-syntax-transformer)
(list (build-data #f name) (build-data #f 'macro) e)))))
(parse-when-list
(lambda (e when-list)
(let ((result (strip when-list '(()))))
(let lp ((l result))
(cond ((null? l) result)
((memq (car l) '(compile load eval expand)) (lp (cdr l)))
(else (syntax-violation 'eval-when "invalid situation" e (car l))))))))
(syntax-type
(lambda (e r w s rib mod for-car?)
(cond ((symbol? e)
(let* ((n (id-var-name e w))
(b (lookup n r mod))
(type (car b))
(key type))
(cond ((memv key '(lexical)) (values type (cdr b) e e w s mod))
((memv key '(global)) (values type n e e w s mod))
((memv key '(macro))
(if for-car?
(values type (cdr b) e e w s mod)
(syntax-type
(expand-macro (cdr b) e r w s rib mod)
r
'(())
s
rib
mod
#f)))
(else (values type (cdr b) e e w s mod)))))
((pair? e)
(let ((first (car e)))
(call-with-values
(lambda () (syntax-type first r w s rib mod #t))
(lambda (ftype fval fform fe fw fs fmod)
(let ((key ftype))
(cond ((memv key '(lexical)) (values 'lexical-call fval e e w s mod))
((memv key '(global))
(values 'global-call (make-syntax-object fval w fmod) e e w s mod))
((memv key '(macro))
(syntax-type
(expand-macro fval e r w s rib mod)
r
'(())
s
rib
mod
for-car?))
((memv key '(module-ref))
(call-with-values
(lambda () (fval e r w))
(lambda (e r w s mod) (syntax-type e r w s rib mod for-car?))))
((memv key '(core)) (values 'core-form fval e e w s mod))
((memv key '(local-syntax))
(values 'local-syntax-form fval e e w s mod))
((memv key '(begin)) (values 'begin-form #f e e w s mod))
((memv key '(eval-when)) (values 'eval-when-form #f e e w s mod))
((memv key '(define))
(let* ((tmp e) (tmp-1 ($sc-dispatch tmp '(_ any any))))
(if (and tmp-1 (apply (lambda (name val) (id? name)) tmp-1))
(apply (lambda (name val) (values 'define-form name e val w s mod))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ (any . any) any . each-any))))
(if (and tmp-1
(apply (lambda (name args e1 e2)
(and (id? name) (valid-bound-ids? (lambda-var-list args))))
tmp-1))
(apply (lambda (name args e1 e2)
(values
'define-form
(wrap name w mod)
(wrap e w mod)
(decorate-source
(cons '#(syntax-object lambda ((top)) (hygiene guile))
(wrap (cons args (cons e1 e2)) w mod))
s)
'(())
s
mod))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ any))))
(if (and tmp-1 (apply (lambda (name) (id? name)) tmp-1))
(apply (lambda (name)
(values
'define-form
(wrap name w mod)
(wrap e w mod)
'(#(syntax-object if ((top)) (hygiene guile)) #f #f)
'(())
s
mod))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))))
((memv key '(define-syntax))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ any any))))
(if (and tmp (apply (lambda (name val) (id? name)) tmp))
(apply (lambda (name val) (values 'define-syntax-form name e val w s mod))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
((memv key '(define-syntax-parameter))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ any any))))
(if (and tmp (apply (lambda (name val) (id? name)) tmp))
(apply (lambda (name val)
(values 'define-syntax-parameter-form name e val w s mod))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
(else (values 'call #f e e w s mod))))))))
((syntax-object? e)
(syntax-type
(syntax-object-expression e)
r
(join-wraps w (syntax-object-wrap e))
(or (source-annotation e) s)
rib
(or (syntax-object-module e) mod)
for-car?))
((self-evaluating? e) (values 'constant #f e e w s mod))
(else (values 'other #f e e w s mod)))))
(expand
(lambda (e r w mod)
(call-with-values
(lambda () (syntax-type e r w (source-annotation e) #f mod #f))
(lambda (type value form e w s mod)
(expand-expr type value form e r w s mod)))))
(expand-expr
(lambda (type value form e r w s mod)
(let ((key type))
(cond ((memv key '(lexical)) (build-lexical-reference 'value s e value))
((memv key '(core core-form)) (value e r w s mod))
((memv key '(module-ref))
(call-with-values
(lambda () (value e r w))
(lambda (e r w s mod) (expand e r w mod))))
((memv key '(lexical-call))
(expand-application
(let ((id (car e)))
(build-lexical-reference
'fun
(source-annotation id)
(if (syntax-object? id) (syntax->datum id) id)
value))
e
r
w
s
mod))
((memv key '(global-call))
(expand-application
(build-global-reference
(source-annotation (car e))
(if (syntax-object? value) (syntax-object-expression value) value)
(if (syntax-object? value) (syntax-object-module value) mod))
e
r
w
s
mod))
((memv key '(constant))
(build-data s (strip (source-wrap e w s mod) '(()))))
((memv key '(global)) (build-global-reference s value mod))
((memv key '(call))
(expand-application (expand (car e) r w mod) e r w s mod))
((memv key '(begin-form))
(let* ((tmp e) (tmp-1 ($sc-dispatch tmp '(_ any . each-any))))
(if tmp-1
(apply (lambda (e1 e2) (expand-sequence (cons e1 e2) r w s mod))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_))))
(if tmp-1
(apply (lambda ()
(if (include-deprecated-features)
(begin
(issue-deprecation-warning
"Sequences of zero expressions are deprecated. Use *unspecified*.")
(expand-void))
(syntax-violation
#f
"sequence of zero expressions"
(source-wrap e w s mod))))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))
((memv key '(local-syntax-form))
(expand-local-syntax value e r w s mod expand-sequence))
((memv key '(eval-when-form))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ each-any any . each-any))))
(if tmp
(apply (lambda (x e1 e2)
(let ((when-list (parse-when-list e x)))
(if (memq 'eval when-list)
(expand-sequence (cons e1 e2) r w s mod)
(expand-void))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
((memv key
'(define-form define-syntax-form define-syntax-parameter-form))
(syntax-violation
#f
"definition in expression context, where definitions are not allowed,"
(source-wrap form w s mod)))
((memv key '(syntax))
(syntax-violation
#f
"reference to pattern variable outside syntax form"
(source-wrap e w s mod)))
((memv key '(displaced-lexical))
(syntax-violation
#f
"reference to identifier outside its scope"
(source-wrap e w s mod)))
(else
(syntax-violation #f "unexpected syntax" (source-wrap e w s mod)))))))
(expand-application
(lambda (x e r w s mod)
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(any . each-any))))
(if tmp
(apply (lambda (e0 e1)
(build-application s x (map (lambda (e) (expand e r w mod)) e1)))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
(expand-macro
(lambda (p e r w s rib mod)
(letrec*
((rebuild-macro-output
(lambda (x m)
(cond ((pair? x)
(decorate-source
(cons (rebuild-macro-output (car x) m)
(rebuild-macro-output (cdr x) m))
s))
((syntax-object? x)
(let ((w (syntax-object-wrap x)))
(let ((ms (car w)) (ss (cdr w)))
(if (and (pair? ms) (eq? (car ms) #f))
(make-syntax-object
(syntax-object-expression x)
(cons (cdr ms) (if rib (cons rib (cdr ss)) (cdr ss)))
(syntax-object-module x))
(make-syntax-object
(decorate-source (syntax-object-expression x) s)
(cons (cons m ms)
(if rib (cons rib (cons 'shift ss)) (cons 'shift ss)))
(syntax-object-module x))))))
((vector? x)
(let* ((n (vector-length x)) (v (decorate-source (make-vector n) s)))
(let loop ((i 0))
(if (= i n)
(begin (if #f #f) v)
(begin
(vector-set! v i (rebuild-macro-output (vector-ref x i) m))
(loop (+ i 1)))))))
((symbol? x)
(syntax-violation
#f
"encountered raw symbol in macro output"
(source-wrap e w (cdr w) mod)
x))
(else (decorate-source x s))))))
(with-fluids
((transformer-environment (lambda (k) (k e r w s rib mod))))
(rebuild-macro-output
(p (source-wrap e (anti-mark w) s mod))
(module-gensym "m"))))))
(expand-body
(lambda (body outer-form r w mod)
(let* ((r (cons '("placeholder" placeholder) r))
(ribcage (make-ribcage '() '() '()))
(w (cons (car w) (cons ribcage (cdr w)))))
(let parse ((body (map (lambda (x) (cons r (wrap x w mod))) body))
(ids '())
(labels '())
(var-ids '())
(vars '())
(vals '())
(bindings '()))
(if (null? body)
(syntax-violation #f "no expressions in body" outer-form)
(let ((e (cdar body)) (er (caar body)))
(call-with-values
(lambda ()
(syntax-type e er '(()) (source-annotation e) ribcage mod #f))
(lambda (type value form e w s mod)
(let ((key type))
(cond ((memv key '(define-form))
(let ((id (wrap value w mod)) (label (gen-label)))
(let ((var (gen-var id)))
(extend-ribcage! ribcage id label)
(parse (cdr body)
(cons id ids)
(cons label labels)
(cons id var-ids)
(cons var vars)
(cons (cons er (wrap e w mod)) vals)
(cons (cons 'lexical var) bindings)))))
((memv key '(define-syntax-form define-syntax-parameter-form))
(let ((id (wrap value w mod))
(label (gen-label))
(trans-r (macros-only-env er)))
(extend-ribcage! ribcage id label)
(set-cdr!
r
(extend-env
(list label)
(list (cons 'macro (eval-local-transformer (expand e trans-r w mod) mod)))
(cdr r)))
(parse (cdr body) (cons id ids) labels var-ids vars vals bindings)))
((memv key '(begin-form))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ . each-any))))
(if tmp
(apply (lambda (e1)
(parse (let f ((forms e1))
(if (null? forms)
(cdr body)
(cons (cons er (wrap (car forms) w mod)) (f (cdr forms)))))
ids
labels
var-ids
vars
vals
bindings))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
((memv key '(local-syntax-form))
(expand-local-syntax
value
e
er
w
s
mod
(lambda (forms er w s mod)
(parse (let f ((forms forms))
(if (null? forms)
(cdr body)
(cons (cons er (wrap (car forms) w mod)) (f (cdr forms)))))
ids
labels
var-ids
vars
vals
bindings))))
((null? ids)
(build-sequence
#f
(map (lambda (x) (expand (cdr x) (car x) '(()) mod))
(cons (cons er (source-wrap e w s mod)) (cdr body)))))
(else
(if (not (valid-bound-ids? ids))
(syntax-violation
#f
"invalid or duplicate identifier in definition"
outer-form))
(set-cdr! r (extend-env labels bindings (cdr r)))
(build-letrec
#f
#t
(reverse (map syntax->datum var-ids))
(reverse vars)
(map (lambda (x) (expand (cdr x) (car x) '(()) mod)) (reverse vals))
(build-sequence
#f
(map (lambda (x) (expand (cdr x) (car x) '(()) mod))
(cons (cons er (source-wrap e w s mod)) (cdr body))))))))))))))))
(expand-local-syntax
(lambda (rec? e r w s mod k)
(let* ((tmp e)
(tmp ($sc-dispatch tmp '(_ #(each (any any)) any . each-any))))
(if tmp
(apply (lambda (id val e1 e2)
(let ((ids id))
(if (not (valid-bound-ids? ids))
(syntax-violation #f "duplicate bound keyword" e)
(let* ((labels (gen-labels ids)) (new-w (make-binding-wrap ids labels w)))
(k (cons e1 e2)
(extend-env
labels
(let ((w (if rec? new-w w)) (trans-r (macros-only-env r)))
(map (lambda (x)
(cons 'macro (eval-local-transformer (expand x trans-r w mod) mod)))
val))
r)
new-w
s
mod)))))
tmp)
(syntax-violation
#f
"bad local syntax definition"
(source-wrap e w s mod))))))
(eval-local-transformer
(lambda (expanded mod)
(let ((p (local-eval-hook expanded mod)))
(if (procedure? p)
p
(syntax-violation #f "nonprocedure transformer" p)))))
(expand-void (lambda () (build-void #f)))
(ellipsis?
(lambda (e r mod)
(and (nonsymbol-id? e)
(let* ((id (make-syntax-object
'#{ $sc-ellipsis }
(syntax-object-wrap e)
(syntax-object-module e)))
(n (id-var-name id '(())))
(b (lookup n r mod)))
(if (eq? (car b) 'ellipsis)
(bound-id=? e (cdr b))
(free-id=? e '#(syntax-object ... ((top)) (hygiene guile))))))))
(lambda-formals
(lambda (orig-args)
(letrec*
((req (lambda (args rreq)
(let* ((tmp args) (tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (check (reverse rreq) #f)) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1 (apply (lambda (a b) (id? a)) tmp-1))
(apply (lambda (a b) (req b (cons a rreq))) tmp-1)
(let ((tmp-1 (list tmp)))
(if (and tmp-1 (apply (lambda (r) (id? r)) tmp-1))
(apply (lambda (r) (check (reverse rreq) r)) tmp-1)
(let ((else tmp))
(syntax-violation 'lambda "invalid argument list" orig-args args))))))))))
(check (lambda (req rest)
(if (distinct-bound-ids? (if rest (cons rest req) req))
(values req #f rest #f)
(syntax-violation
'lambda
"duplicate identifier in argument list"
orig-args)))))
(req orig-args '()))))
(expand-simple-lambda
(lambda (e r w s mod req rest meta body)
(let* ((ids (if rest (append req (list rest)) req))
(vars (map gen-var ids))
(labels (gen-labels ids)))
(build-simple-lambda
s
(map syntax->datum req)
(and rest (syntax->datum rest))
vars
meta
(expand-body
body
(source-wrap e w s mod)
(extend-var-env labels vars r)
(make-binding-wrap ids labels w)
mod)))))
(lambda*-formals
(lambda (orig-args)
(letrec*
((req (lambda (args rreq)
(let* ((tmp args) (tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (check (reverse rreq) '() #f '())) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1 (apply (lambda (a b) (id? a)) tmp-1))
(apply (lambda (a b) (req b (cons a rreq))) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\optional)) tmp-1))
(apply (lambda (a b) (opt b (reverse rreq) '())) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\key)) tmp-1))
(apply (lambda (a b) (key b (reverse rreq) '() '())) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\rest)) tmp-1))
(apply (lambda (a b) (rest b (reverse rreq) '() '())) tmp-1)
(let ((tmp-1 (list tmp)))
(if (and tmp-1 (apply (lambda (r) (id? r)) tmp-1))
(apply (lambda (r) (rest r (reverse rreq) '() '())) tmp-1)
(let ((else tmp))
(syntax-violation
'lambda*
"invalid argument list"
orig-args
args))))))))))))))))
(opt (lambda (args req ropt)
(let* ((tmp args) (tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (check req (reverse ropt) #f '())) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1 (apply (lambda (a b) (id? a)) tmp-1))
(apply (lambda (a b) (opt b req (cons (cons a '(#f)) ropt))) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '((any any) . any))))
(if (and tmp-1 (apply (lambda (a init b) (id? a)) tmp-1))
(apply (lambda (a init b) (opt b req (cons (list a init) ropt)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\key)) tmp-1))
(apply (lambda (a b) (key b req (reverse ropt) '())) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\rest)) tmp-1))
(apply (lambda (a b) (rest b req (reverse ropt) '())) tmp-1)
(let ((tmp-1 (list tmp)))
(if (and tmp-1 (apply (lambda (r) (id? r)) tmp-1))
(apply (lambda (r) (rest r req (reverse ropt) '())) tmp-1)
(let ((else tmp))
(syntax-violation
'lambda*
"invalid optional argument list"
orig-args
args))))))))))))))))
(key (lambda (args req opt rkey)
(let* ((tmp args) (tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (check req opt #f (cons #f (reverse rkey)))) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1 (apply (lambda (a b) (id? a)) tmp-1))
(apply (lambda (a b)
(let* ((tmp (symbol->keyword (syntax->datum a))) (k tmp))
(key b req opt (cons (cons k (cons a '(#f))) rkey))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '((any any) . any))))
(if (and tmp-1 (apply (lambda (a init b) (id? a)) tmp-1))
(apply (lambda (a init b)
(let* ((tmp (symbol->keyword (syntax->datum a))) (k tmp))
(key b req opt (cons (list k a init) rkey))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '((any any any) . any))))
(if (and tmp-1
(apply (lambda (a init k b) (and (id? a) (keyword? (syntax->datum k))))
tmp-1))
(apply (lambda (a init k b) (key b req opt (cons (list k a init) rkey)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any))))
(if (and tmp-1
(apply (lambda (aok) (eq? (syntax->datum aok) #\allow-other-keys))
tmp-1))
(apply (lambda (aok) (check req opt #f (cons #t (reverse rkey))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any any))))
(if (and tmp-1
(apply (lambda (aok a b)
(and (eq? (syntax->datum aok) #\allow-other-keys)
(eq? (syntax->datum a) #\rest)))
tmp-1))
(apply (lambda (aok a b) (rest b req opt (cons #t (reverse rkey))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if (and tmp-1
(apply (lambda (aok r)
(and (eq? (syntax->datum aok) #\allow-other-keys) (id? r)))
tmp-1))
(apply (lambda (aok r) (rest r req opt (cons #t (reverse rkey))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any))))
(if (and tmp-1
(apply (lambda (a b) (eq? (syntax->datum a) #\rest)) tmp-1))
(apply (lambda (a b) (rest b req opt (cons #f (reverse rkey))))
tmp-1)
(let ((tmp-1 (list tmp)))
(if (and tmp-1 (apply (lambda (r) (id? r)) tmp-1))
(apply (lambda (r) (rest r req opt (cons #f (reverse rkey))))
tmp-1)
(let ((else tmp))
(syntax-violation
'lambda*
"invalid keyword argument list"
orig-args
args))))))))))))))))))))))
(rest (lambda (args req opt kw)
(let* ((tmp-1 args) (tmp (list tmp-1)))
(if (and tmp (apply (lambda (r) (id? r)) tmp))
(apply (lambda (r) (check req opt r kw)) tmp)
(let ((else tmp-1))
(syntax-violation 'lambda* "invalid rest argument" orig-args args))))))
(check (lambda (req opt rest kw)
(if (distinct-bound-ids?
(append
req
(map car opt)
(if rest (list rest) '())
(if (pair? kw) (map cadr (cdr kw)) '())))
(values req opt rest kw)
(syntax-violation
'lambda*
"duplicate identifier in argument list"
orig-args)))))
(req orig-args '()))))
(expand-lambda-case
(lambda (e r w s mod get-formals clauses)
(letrec*
((parse-req
(lambda (req opt rest kw body)
(let ((vars (map gen-var req)) (labels (gen-labels req)))
(let ((r* (extend-var-env labels vars r))
(w* (make-binding-wrap req labels w)))
(parse-opt
(map syntax->datum req)
opt
rest
kw
body
(reverse vars)
r*
w*
'()
'())))))
(parse-opt
(lambda (req opt rest kw body vars r* w* out inits)
(cond ((pair? opt)
(let* ((tmp-1 (car opt)) (tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (id i)
(let* ((v (gen-var id))
(l (gen-labels (list v)))
(r** (extend-var-env l (list v) r*))
(w** (make-binding-wrap (list id) l w*)))
(parse-opt
req
(cdr opt)
rest
kw
body
(cons v vars)
r**
w**
(cons (syntax->datum id) out)
(cons (expand i r* w* mod) inits))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))
(rest
(let* ((v (gen-var rest))
(l (gen-labels (list v)))
(r* (extend-var-env l (list v) r*))
(w* (make-binding-wrap (list rest) l w*)))
(parse-kw
req
(and (pair? out) (reverse out))
(syntax->datum rest)
(if (pair? kw) (cdr kw) kw)
body
(cons v vars)
r*
w*
(and (pair? kw) (car kw))
'()
inits)))
(else
(parse-kw
req
(and (pair? out) (reverse out))
#f
(if (pair? kw) (cdr kw) kw)
body
vars
r*
w*
(and (pair? kw) (car kw))
'()
inits)))))
(parse-kw
(lambda (req opt rest kw body vars r* w* aok out inits)
(if (pair? kw)
(let* ((tmp-1 (car kw)) (tmp ($sc-dispatch tmp-1 '(any any any))))
(if tmp
(apply (lambda (k id i)
(let* ((v (gen-var id))
(l (gen-labels (list v)))
(r** (extend-var-env l (list v) r*))
(w** (make-binding-wrap (list id) l w*)))
(parse-kw
req
opt
rest
(cdr kw)
body
(cons v vars)
r**
w**
aok
(cons (list (syntax->datum k) (syntax->datum id) v) out)
(cons (expand i r* w* mod) inits))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))
(parse-body
req
opt
rest
(and (or aok (pair? out)) (cons aok (reverse out)))
body
(reverse vars)
r*
w*
(reverse inits)
'()))))
(parse-body
(lambda (req opt rest kw body vars r* w* inits meta)
(let* ((tmp body) (tmp-1 ($sc-dispatch tmp '(any any . each-any))))
(if (and tmp-1
(apply (lambda (docstring e1 e2) (string? (syntax->datum docstring)))
tmp-1))
(apply (lambda (docstring e1 e2)
(parse-body
req
opt
rest
kw
(cons e1 e2)
vars
r*
w*
inits
(append meta (list (cons 'documentation (syntax->datum docstring))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(vector #(each (any . any))) any . each-any))))
(if tmp-1
(apply (lambda (k v e1 e2)
(parse-body
req
opt
rest
kw
(cons e1 e2)
vars
r*
w*
inits
(append meta (syntax->datum (map cons k v)))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . each-any))))
(if tmp-1
(apply (lambda (e1 e2)
(values
meta
req
opt
rest
kw
inits
vars
(expand-body (cons e1 e2) (source-wrap e w s mod) r* w* mod)))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))))))
(let* ((tmp clauses) (tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (values '() #f)) tmp-1)
(let ((tmp-1 ($sc-dispatch
tmp
'((any any . each-any) . #(each (any any . each-any))))))
(if tmp-1
(apply (lambda (args e1 e2 args* e1* e2*)
(call-with-values
(lambda () (get-formals args))
(lambda (req opt rest kw)
(call-with-values
(lambda () (parse-req req opt rest kw (cons e1 e2)))
(lambda (meta req opt rest kw inits vars body)
(call-with-values
(lambda ()
(expand-lambda-case
e
r
w
s
mod
get-formals
(map (lambda (tmp-bde397a-a85 tmp-bde397a-a84 tmp-bde397a-a83)
(cons tmp-bde397a-a83 (cons tmp-bde397a-a84 tmp-bde397a-a85)))
e2*
e1*
args*)))
(lambda (meta* else*)
(values
(append meta meta*)
(build-lambda-case s req opt rest kw inits vars body else*)))))))))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))))
(strip (lambda (x w)
(if (memq 'top (car w))
x
(let f ((x x))
(cond ((syntax-object? x)
(strip (syntax-object-expression x) (syntax-object-wrap x)))
((pair? x)
(let ((a (f (car x))) (d (f (cdr x))))
(if (and (eq? a (car x)) (eq? d (cdr x))) x (cons a d))))
((vector? x)
(let* ((old (vector->list x)) (new (map f old)))
(let lp ((l1 old) (l2 new))
(cond ((null? l1) x)
((eq? (car l1) (car l2)) (lp (cdr l1) (cdr l2)))
(else (list->vector new))))))
(else x))))))
(gen-var
(lambda (id)
(let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
(module-gensym (symbol->string id)))))
(lambda-var-list
(lambda (vars)
(let lvl ((vars vars) (ls '()) (w '(())))
(cond ((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
((id? vars) (cons (wrap vars w #f) ls))
((null? vars) ls)
((syntax-object? vars)
(lvl (syntax-object-expression vars)
ls
(join-wraps w (syntax-object-wrap vars))))
(else (cons vars ls)))))))
(global-extend 'local-syntax 'letrec-syntax #t)
(global-extend 'local-syntax 'let-syntax #f)
(global-extend
'core
'syntax-parameterize
(lambda (e r w s mod)
(let* ((tmp e)
(tmp ($sc-dispatch tmp '(_ #(each (any any)) any . each-any))))
(if (and tmp (apply (lambda (var val e1 e2) (valid-bound-ids? var)) tmp))
(apply (lambda (var val e1 e2)
(let ((names (map (lambda (x) (id-var-name x w)) var)))
(for-each
(lambda (id n)
(let ((key (car (lookup n r mod))))
(if (memv key '(displaced-lexical))
(syntax-violation
'syntax-parameterize
"identifier out of context"
e
(source-wrap id w s mod)))))
var
names)
(expand-body
(cons e1 e2)
(source-wrap e w s mod)
(extend-env
names
(let ((trans-r (macros-only-env r)))
(map (lambda (x)
(cons 'macro (eval-local-transformer (expand x trans-r w mod) mod)))
val))
r)
w
mod)))
tmp)
(syntax-violation
'syntax-parameterize
"bad syntax"
(source-wrap e w s mod))))))
(global-extend
'core
'quote
(lambda (e r w s mod)
(let* ((tmp e) (tmp ($sc-dispatch tmp '(_ any))))
(if tmp
(apply (lambda (e) (build-data s (strip e w))) tmp)
(syntax-violation 'quote "bad syntax" (source-wrap e w s mod))))))
(global-extend
'core
'syntax
(letrec*
((gen-syntax
(lambda (src e r maps ellipsis? mod)
(if (id? e)
(let* ((label (id-var-name e '(()))) (b (lookup label r mod)))
(cond ((eq? (car b) 'syntax)
(call-with-values
(lambda ()
(let ((var.lev (cdr b)))
(gen-ref src (car var.lev) (cdr var.lev) maps)))
(lambda (var maps) (values (list 'ref var) maps))))
((ellipsis? e r mod)
(syntax-violation 'syntax "misplaced ellipsis" src))
(else (values (list 'quote e) maps))))
(let* ((tmp e) (tmp-1 ($sc-dispatch tmp '(any any))))
(if (and tmp-1 (apply (lambda (dots e) (ellipsis? dots r mod)) tmp-1))
(apply (lambda (dots e) (gen-syntax src e r maps (lambda (e r mod) #f) mod))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any . any))))
(if (and tmp-1 (apply (lambda (x dots y) (ellipsis? dots r mod)) tmp-1))
(apply (lambda (x dots y)
(let f ((y y)
(k (lambda (maps)
(call-with-values
(lambda () (gen-syntax src x r (cons '() maps) ellipsis? mod))
(lambda (x maps)
(if (null? (car maps))
(syntax-violation 'syntax "extra ellipsis" src)
(values (gen-map x (car maps)) (cdr maps))))))))
(let* ((tmp y) (tmp ($sc-dispatch tmp '(any . any))))
(if (and tmp (apply (lambda (dots y) (ellipsis? dots r mod)) tmp))
(apply (lambda (dots y)
(f y
(lambda (maps)
(call-with-values
(lambda () (k (cons '() maps)))
(lambda (x maps)
(if (null? (car maps))
(syntax-violation 'syntax "extra ellipsis" src)
(values (gen-mappend x (car maps)) (cdr maps))))))))
tmp)
(call-with-values
(lambda () (gen-syntax src y r maps ellipsis? mod))
(lambda (y maps)
(call-with-values
(lambda () (k maps))
(lambda (x maps) (values (gen-append x y) maps)))))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if tmp-1
(apply (lambda (x y)
(call-with-values
(lambda () (gen-syntax src x r maps ellipsis? mod))
(lambda (x maps)
(call-with-values
(lambda () (gen-syntax src y r maps ellipsis? mod))
(lambda (y maps) (values (gen-cons x y) maps))))))
tmp-1)
(let ((tmp ($sc-dispatch tmp '#(vector (any . each-any)))))
(if tmp
(apply (lambda (e1 e2)
(call-with-values
(lambda () (gen-syntax src (cons e1 e2) r maps ellipsis? mod))
(lambda (e maps) (values (gen-vector e) maps))))
tmp)
(values (list 'quote e) maps))))))))))))
(gen-ref
(lambda (src var level maps)
(cond ((= level 0) (values var maps))
((null? maps) (syntax-violation 'syntax "missing ellipsis" src))
(else
(call-with-values
(lambda () (gen-ref src var (- level 1) (cdr maps)))
(lambda (outer-var outer-maps)
(let ((b (assq outer-var (car maps))))
(if b
(values (cdr b) maps)
(let ((inner-var (gen-var 'tmp)))
(values
inner-var
(cons (cons (cons outer-var inner-var) (car maps)) outer-maps)))))))))))
(gen-mappend
(lambda (e map-env)
(list 'apply '(primitive append) (gen-map e map-env))))
(gen-map
(lambda (e map-env)
(let ((formals (map cdr map-env))
(actuals (map (lambda (x) (list 'ref (car x))) map-env)))
(cond ((eq? (car e) 'ref) (car actuals))
((and-map
(lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
(cdr e))
(cons 'map
(cons (list 'primitive (car e))
(map (let ((r (map cons formals actuals)))
(lambda (x) (cdr (assq (cadr x) r))))
(cdr e)))))
(else (cons 'map (cons (list 'lambda formals e) actuals)))))))
(gen-cons
(lambda (x y)
(let ((key (car y)))
(cond ((memv key '(quote))
(cond ((eq? (car x) 'quote) (list 'quote (cons (cadr x) (cadr y))))
((eq? (cadr y) '()) (list 'list x))
(else (list 'cons x y))))
((memv key '(list)) (cons 'list (cons x (cdr y))))
(else (list 'cons x y))))))
(gen-append (lambda (x y) (if (equal? y ''()) x (list 'append x y))))
(gen-vector
(lambda (x)
(cond ((eq? (car x) 'list) (cons 'vector (cdr x)))
((eq? (car x) 'quote) (list 'quote (list->vector (cadr x))))
(else (list 'list->vector x)))))
(regen (lambda (x)
(let ((key (car x)))
(cond ((memv key '(ref))
(build-lexical-reference 'value #f (cadr x) (cadr x)))
((memv key '(primitive)) (build-primref #f (cadr x)))
((memv key '(quote)) (build-data #f (cadr x)))
((memv key '(lambda))
(if (list? (cadr x))
(build-simple-lambda #f (cadr x) #f (cadr x) '() (regen (caddr x)))
(error "how did we get here" x)))
(else
(build-application #f (build-primref #f (car x)) (map regen (cdr x)))))))))
(lambda (e r w s mod)
(let* ((e (source-wrap e w s mod))
(tmp e)
(tmp ($sc-dispatch tmp '(_ any))))
(if tmp
(apply (lambda (x)
(call-with-values
(lambda () (gen-syntax e x r '() ellipsis? mod))
(lambda (e maps) (regen e))))
tmp)
(syntax-violation 'syntax "bad `syntax' form" e))))))
(global-extend
'core
'lambda
(lambda (e r w s mod)
(let* ((tmp e) (tmp ($sc-dispatch tmp '(_ any any . each-any))))
(if tmp
(apply (lambda (args e1 e2)
(call-with-values
(lambda () (lambda-formals args))
(lambda (req opt rest kw)
(let lp ((body (cons e1 e2)) (meta '()))
(let* ((tmp-1 body) (tmp ($sc-dispatch tmp-1 '(any any . each-any))))
(if (and tmp
(apply (lambda (docstring e1 e2) (string? (syntax->datum docstring)))
tmp))
(apply (lambda (docstring e1 e2)
(lp (cons e1 e2)
(append meta (list (cons 'documentation (syntax->datum docstring))))))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(#(vector #(each (any . any))) any . each-any))))
(if tmp
(apply (lambda (k v e1 e2)
(lp (cons e1 e2) (append meta (syntax->datum (map cons k v)))))
tmp)
(expand-simple-lambda e r w s mod req rest meta body)))))))))
tmp)
(syntax-violation 'lambda "bad lambda" e)))))
(global-extend
'core
'lambda*
(lambda (e r w s mod)
(let* ((tmp e) (tmp ($sc-dispatch tmp '(_ any any . each-any))))
(if tmp
(apply (lambda (args e1 e2)
(call-with-values
(lambda ()
(expand-lambda-case
e
r
w
s
mod
lambda*-formals
(list (cons args (cons e1 e2)))))
(lambda (meta lcase) (build-case-lambda s meta lcase))))
tmp)
(syntax-violation 'lambda "bad lambda*" e)))))
(global-extend
'core
'case-lambda
(lambda (e r w s mod)
(letrec*
((build-it
(lambda (meta clauses)
(call-with-values
(lambda () (expand-lambda-case e r w s mod lambda-formals clauses))
(lambda (meta* lcase)
(build-case-lambda s (append meta meta*) lcase))))))
(let* ((tmp-1 e)
(tmp ($sc-dispatch tmp-1 '(_ . #(each (any any . each-any))))))
(if tmp
(apply (lambda (args e1 e2)
(build-it
'()
(map (lambda (tmp-bde397a-c50 tmp-bde397a-c4f tmp-bde397a-c4e)
(cons tmp-bde397a-c4e (cons tmp-bde397a-c4f tmp-bde397a-c50)))
e2
e1
args)))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ any . #(each (any any . each-any))))))
(if (and tmp
(apply (lambda (docstring args e1 e2) (string? (syntax->datum docstring)))
tmp))
(apply (lambda (docstring args e1 e2)
(build-it
(list (cons 'documentation (syntax->datum docstring)))
(map (lambda (tmp-bde397a-c66 tmp-bde397a-c65 tmp-bde397a-c64)
(cons tmp-bde397a-c64 (cons tmp-bde397a-c65 tmp-bde397a-c66)))
e2
e1
args)))
tmp)
(syntax-violation 'case-lambda "bad case-lambda" e))))))))
(global-extend
'core
'case-lambda*
(lambda (e r w s mod)
(letrec*
((build-it
(lambda (meta clauses)
(call-with-values
(lambda () (expand-lambda-case e r w s mod lambda*-formals clauses))
(lambda (meta* lcase)
(build-case-lambda s (append meta meta*) lcase))))))
(let* ((tmp-1 e)
(tmp ($sc-dispatch tmp-1 '(_ . #(each (any any . each-any))))))
(if tmp
(apply (lambda (args e1 e2)
(build-it
'()
(map (lambda (tmp-bde397a-c86 tmp-bde397a-c85 tmp-bde397a-c84)
(cons tmp-bde397a-c84 (cons tmp-bde397a-c85 tmp-bde397a-c86)))
e2
e1
args)))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ any . #(each (any any . each-any))))))
(if (and tmp
(apply (lambda (docstring args e1 e2) (string? (syntax->datum docstring)))
tmp))
(apply (lambda (docstring args e1 e2)
(build-it
(list (cons 'documentation (syntax->datum docstring)))
(map (lambda (tmp-bde397a-c9c tmp-bde397a-c9b tmp-bde397a-c9a)
(cons tmp-bde397a-c9a (cons tmp-bde397a-c9b tmp-bde397a-c9c)))
e2
e1
args)))
tmp)
(syntax-violation 'case-lambda "bad case-lambda*" e))))))))
(global-extend
'core
'with-ellipsis
(lambda (e r w s mod)
(let* ((tmp e) (tmp ($sc-dispatch tmp '(_ any any . each-any))))
(if (and tmp (apply (lambda (dots e1 e2) (id? dots)) tmp))
(apply (lambda (dots e1 e2)
(let ((id (if (symbol? dots)
'#{ $sc-ellipsis }
(make-syntax-object
'#{ $sc-ellipsis }
(syntax-object-wrap dots)
(syntax-object-module dots)))))
(let ((ids (list id))
(labels (list (gen-label)))
(bindings (list (cons 'ellipsis (source-wrap dots w s mod)))))
(let ((nw (make-binding-wrap ids labels w))
(nr (extend-env labels bindings r)))
(expand-body (cons e1 e2) (source-wrap e nw s mod) nr nw mod)))))
tmp)
(syntax-violation
'with-ellipsis
"bad syntax"
(source-wrap e w s mod))))))
(global-extend
'core
'let
(letrec*
((expand-let
(lambda (e r w s mod constructor ids vals exps)
(if (not (valid-bound-ids? ids))
(syntax-violation 'let "duplicate bound variable" e)
(let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
(let ((nw (make-binding-wrap ids labels w))
(nr (extend-var-env labels new-vars r)))
(constructor
s
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) vals)
(expand-body exps (source-wrap e nw s mod) nr nw mod))))))))
(lambda (e r w s mod)
(let* ((tmp-1 e)
(tmp ($sc-dispatch tmp-1 '(_ #(each (any any)) any . each-any))))
(if (and tmp (apply (lambda (id val e1 e2) (and-map id? id)) tmp))
(apply (lambda (id val e1 e2)
(expand-let e r w s mod build-let id val (cons e1 e2)))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ any #(each (any any)) any . each-any))))
(if (and tmp
(apply (lambda (f id val e1 e2) (and (id? f) (and-map id? id))) tmp))
(apply (lambda (f id val e1 e2)
(expand-let e r w s mod build-named-let (cons f id) val (cons e1 e2)))
tmp)
(syntax-violation 'let "bad let" (source-wrap e w s mod)))))))))
(global-extend
'core
'letrec
(lambda (e r w s mod)
(let* ((tmp e)
(tmp ($sc-dispatch tmp '(_ #(each (any any)) any . each-any))))
(if (and tmp (apply (lambda (id val e1 e2) (and-map id? id)) tmp))
(apply (lambda (id val e1 e2)
(let ((ids id))
(if (not (valid-bound-ids? ids))
(syntax-violation 'letrec "duplicate bound variable" e)
(let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
(let ((w (make-binding-wrap ids labels w))
(r (extend-var-env labels new-vars r)))
(build-letrec
s
#f
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) val)
(expand-body (cons e1 e2) (source-wrap e w s mod) r w mod)))))))
tmp)
(syntax-violation 'letrec "bad letrec" (source-wrap e w s mod))))))
(global-extend
'core
'letrec*
(lambda (e r w s mod)
(let* ((tmp e)
(tmp ($sc-dispatch tmp '(_ #(each (any any)) any . each-any))))
(if (and tmp (apply (lambda (id val e1 e2) (and-map id? id)) tmp))
(apply (lambda (id val e1 e2)
(let ((ids id))
(if (not (valid-bound-ids? ids))
(syntax-violation 'letrec* "duplicate bound variable" e)
(let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
(let ((w (make-binding-wrap ids labels w))
(r (extend-var-env labels new-vars r)))
(build-letrec
s
#t
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) val)
(expand-body (cons e1 e2) (source-wrap e w s mod) r w mod)))))))
tmp)
(syntax-violation 'letrec* "bad letrec*" (source-wrap e w s mod))))))
(global-extend
'core
'set!
(lambda (e r w s mod)
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ any any))))
(if (and tmp (apply (lambda (id val) (id? id)) tmp))
(apply (lambda (id val)
(let ((n (id-var-name id w))
(id-mod (if (syntax-object? id) (syntax-object-module id) mod)))
(let* ((b (lookup n r id-mod)) (key (car b)))
(cond ((memv key '(lexical))
(build-lexical-assignment
s
(syntax->datum id)
(cdr b)
(expand val r w mod)))
((memv key '(global))
(build-global-assignment s n (expand val r w mod) id-mod))
((memv key '(macro))
(let ((p (cdr b)))
(if (procedure-property p 'variable-transformer)
(expand (expand-macro p e r w s #f mod) r '(()) mod)
(syntax-violation
'set!
"not a variable transformer"
(wrap e w mod)
(wrap id w id-mod)))))
((memv key '(displaced-lexical))
(syntax-violation 'set! "identifier out of context" (wrap id w mod)))
(else (syntax-violation 'set! "bad set!" (source-wrap e w s mod)))))))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ (any . each-any) any))))
(if tmp
(apply (lambda (head tail val)
(call-with-values
(lambda () (syntax-type head r '(()) #f #f mod #t))
(lambda (type value formform ee ww ss modmod)
(let ((key type))
(if (memv key '(module-ref))
(let ((val (expand val r w mod)))
(call-with-values
(lambda () (value (cons head tail) r w))
(lambda (e r w s* mod)
(let* ((tmp-1 e) (tmp (list tmp-1)))
(if (and tmp (apply (lambda (e) (id? e)) tmp))
(apply (lambda (e) (build-global-assignment s (syntax->datum e) val mod))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))
(build-application
s
(expand
(list '#(syntax-object setter ((top)) (hygiene guile)) head)
r
w
mod)
(map (lambda (e) (expand e r w mod)) (append tail (list val)))))))))
tmp)
(syntax-violation 'set! "bad set!" (source-wrap e w s mod))))))))
(global-extend
'module-ref
'@
(lambda (e r w)
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ each-any any))))
(if (and tmp
(apply (lambda (mod id) (and (and-map id? mod) (id? id))) tmp))
(apply (lambda (mod id)
(values
(syntax->datum id)
r
'((top))
#f
(syntax->datum
(cons '#(syntax-object public ((top)) (hygiene guile)) mod))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
(global-extend
'module-ref
'@@
(lambda (e r w)
(letrec*
((remodulate
(lambda (x mod)
(cond ((pair? x) (cons (remodulate (car x) mod) (remodulate (cdr x) mod)))
((syntax-object? x)
(make-syntax-object
(remodulate (syntax-object-expression x) mod)
(syntax-object-wrap x)
mod))
((vector? x)
(let* ((n (vector-length x)) (v (make-vector n)))
(let loop ((i 0))
(if (= i n)
(begin (if #f #f) v)
(begin
(vector-set! v i (remodulate (vector-ref x i) mod))
(loop (+ i 1)))))))
(else x)))))
(let* ((tmp-1 e) (tmp ($sc-dispatch tmp-1 '(_ each-any any))))
(if (and tmp
(apply (lambda (mod id) (and (and-map id? mod) (id? id))) tmp))
(apply (lambda (mod id)
(values
(syntax->datum id)
r
'((top))
#f
(syntax->datum
(cons '#(syntax-object private ((top)) (hygiene guile)) mod))))
tmp)
(let ((tmp ($sc-dispatch
tmp-1
'(_ #(free-id #(syntax-object @@ ((top)) (hygiene guile)))
each-any
any))))
(if (and tmp (apply (lambda (mod exp) (and-map id? mod)) tmp))
(apply (lambda (mod exp)
(let ((mod (syntax->datum
(cons '#(syntax-object private ((top)) (hygiene guile)) mod))))
(values (remodulate exp mod) r w (source-annotation exp) mod)))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))))
(global-extend
'core
'if
(lambda (e r w s mod)
(let* ((tmp e) (tmp-1 ($sc-dispatch tmp '(_ any any))))
(if tmp-1
(apply (lambda (test then)
(build-conditional
s
(expand test r w mod)
(expand then r w mod)
(build-void #f)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ any any any))))
(if tmp-1
(apply (lambda (test then else)
(build-conditional
s
(expand test r w mod)
(expand then r w mod)
(expand else r w mod)))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp)))))))
(global-extend
'core
'with-fluids
(lambda (e r w s mod)
(let* ((tmp-1 e)
(tmp ($sc-dispatch tmp-1 '(_ #(each (any any)) any . each-any))))
(if tmp
(apply (lambda (fluid val b b*)
(build-dynlet
s
(map (lambda (x) (expand x r w mod)) fluid)
(map (lambda (x) (expand x r w mod)) val)
(expand-body (cons b b*) (source-wrap e w s mod) r w mod)))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
(global-extend 'begin 'begin '())
(global-extend 'define 'define '())
(global-extend 'define-syntax 'define-syntax '())
(global-extend 'define-syntax-parameter 'define-syntax-parameter '())
(global-extend 'eval-when 'eval-when '())
(global-extend
'core
'syntax-case
(letrec*
((convert-pattern
(lambda (pattern keys ellipsis?)
(letrec*
((cvt* (lambda (p* n ids)
(let* ((tmp p*) (tmp ($sc-dispatch tmp '(any . any))))
(if tmp
(apply (lambda (x y)
(call-with-values
(lambda () (cvt* y n ids))
(lambda (y ids)
(call-with-values
(lambda () (cvt x n ids))
(lambda (x ids) (values (cons x y) ids))))))
tmp)
(cvt p* n ids)))))
(v-reverse
(lambda (x)
(let loop ((r '()) (x x))
(if (not (pair? x)) (values r x) (loop (cons (car x) r) (cdr x))))))
(cvt (lambda (p n ids)
(if (id? p)
(cond ((bound-id-member? p keys) (values (vector 'free-id p) ids))
((free-id=? p '#(syntax-object _ ((top)) (hygiene guile)))
(values '_ ids))
(else (values 'any (cons (cons p n) ids))))
(let* ((tmp p) (tmp-1 ($sc-dispatch tmp '(any any))))
(if (and tmp-1 (apply (lambda (x dots) (ellipsis? dots)) tmp-1))
(apply (lambda (x dots)
(call-with-values
(lambda () (cvt x (+ n 1) ids))
(lambda (p ids)
(values (if (eq? p 'any) 'each-any (vector 'each p)) ids))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any any . any))))
(if (and tmp-1 (apply (lambda (x dots ys) (ellipsis? dots)) tmp-1))
(apply (lambda (x dots ys)
(call-with-values
(lambda () (cvt* ys n ids))
(lambda (ys ids)
(call-with-values
(lambda () (cvt x (+ n 1) ids))
(lambda (x ids)
(call-with-values
(lambda () (v-reverse ys))
(lambda (ys e) (values (vector 'each+ x ys e) ids))))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if tmp-1
(apply (lambda (x y)
(call-with-values
(lambda () (cvt y n ids))
(lambda (y ids)
(call-with-values
(lambda () (cvt x n ids))
(lambda (x ids) (values (cons x y) ids))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () (values '() ids)) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '#(vector each-any))))
(if tmp-1
(apply (lambda (x)
(call-with-values
(lambda () (cvt x n ids))
(lambda (p ids) (values (vector 'vector p) ids))))
tmp-1)
(let ((x tmp)) (values (vector 'atom (strip p '(()))) ids))))))))))))))))
(cvt pattern 0 '()))))
(build-dispatch-call
(lambda (pvars exp y r mod)
(let ((ids (map car pvars)) (levels (map cdr pvars)))
(let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
(build-application
#f
(build-primref #f 'apply)
(list (build-simple-lambda
#f
(map syntax->datum ids)
#f
new-vars
'()
(expand
exp
(extend-env
labels
(map (lambda (var level) (cons 'syntax (cons var level)))
new-vars
(map cdr pvars))
r)
(make-binding-wrap ids labels '(()))
mod))
y))))))
(gen-clause
(lambda (x keys clauses r pat fender exp mod)
(call-with-values
(lambda ()
(convert-pattern pat keys (lambda (e) (ellipsis? e r mod))))
(lambda (p pvars)
(cond ((not (and-map (lambda (x) (not (ellipsis? (car x) r mod))) pvars))
(syntax-violation 'syntax-case "misplaced ellipsis" pat))
((not (distinct-bound-ids? (map car pvars)))
(syntax-violation 'syntax-case "duplicate pattern variable" pat))
(else
(let ((y (gen-var 'tmp)))
(build-application
#f
(build-simple-lambda
#f
(list 'tmp)
#f
(list y)
'()
(let ((y (build-lexical-reference 'value #f 'tmp y)))
(build-conditional
#f
(let* ((tmp fender) (tmp ($sc-dispatch tmp '#(atom #t))))
(if tmp
(apply (lambda () y) tmp)
(build-conditional
#f
y
(build-dispatch-call pvars fender y r mod)
(build-data #f #f))))
(build-dispatch-call pvars exp y r mod)
(gen-syntax-case x keys clauses r mod))))
(list (if (eq? p 'any)
(build-application #f (build-primref #f 'list) (list x))
(build-application
#f
(build-primref #f '$sc-dispatch)
(list x (build-data #f p)))))))))))))
(gen-syntax-case
(lambda (x keys clauses r mod)
(if (null? clauses)
(build-application
#f
(build-primref #f 'syntax-violation)
(list (build-data #f #f)
(build-data #f "source expression failed to match any pattern")
x))
(let* ((tmp-1 (car clauses)) (tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (pat exp)
(if (and (id? pat)
(and-map
(lambda (x) (not (free-id=? pat x)))
(cons '#(syntax-object ... ((top)) (hygiene guile)) keys)))
(if (free-id=? pat '#(syntax-object _ ((top)) (hygiene guile)))
(expand exp r '(()) mod)
(let ((labels (list (gen-label))) (var (gen-var pat)))
(build-application
#f
(build-simple-lambda
#f
(list (syntax->datum pat))
#f
(list var)
'()
(expand
exp
(extend-env labels (list (cons 'syntax (cons var 0))) r)
(make-binding-wrap (list pat) labels '(()))
mod))
(list x))))
(gen-clause x keys (cdr clauses) r pat #t exp mod)))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(any any any))))
(if tmp
(apply (lambda (pat fender exp)
(gen-clause x keys (cdr clauses) r pat fender exp mod))
tmp)
(syntax-violation 'syntax-case "invalid clause" (car clauses))))))))))
(lambda (e r w s mod)
(let* ((e (source-wrap e w s mod))
(tmp-1 e)
(tmp ($sc-dispatch tmp-1 '(_ any each-any . each-any))))
(if tmp
(apply (lambda (val key m)
(if (and-map (lambda (x) (and (id? x) (not (ellipsis? x r mod)))) key)
(let ((x (gen-var 'tmp)))
(build-application
s
(build-simple-lambda
#f
(list 'tmp)
#f
(list x)
'()
(gen-syntax-case
(build-lexical-reference 'value #f 'tmp x)
key
m
r
mod))
(list (expand val r '(()) mod))))
(syntax-violation 'syntax-case "invalid literals list" e)))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))
(set! macroexpand
(lambda* (x #\optional (m 'e) (esew '(eval)))
(expand-top-sequence
(list x)
'()
'((top))
#f
m
esew
(cons 'hygiene (module-name (current-module))))))
(set! identifier? (lambda (x) (nonsymbol-id? x)))
(set! datum->syntax
(lambda (id datum)
(make-syntax-object
datum
(syntax-object-wrap id)
(syntax-object-module id))))
(set! syntax->datum (lambda (x) (strip x '(()))))
(set! syntax-source (lambda (x) (source-annotation x)))
(set! generate-temporaries
(lambda (ls)
(let ((x ls))
(if (not (list? x))
(syntax-violation 'generate-temporaries "invalid argument" x)))
(let ((mod (cons 'hygiene (module-name (current-module)))))
(map (lambda (x) (wrap (module-gensym "t") '((top)) mod)) ls))))
(set! free-identifier=?
(lambda (x y)
(let ((x x))
(if (not (nonsymbol-id? x))
(syntax-violation 'free-identifier=? "invalid argument" x)))
(let ((x y))
(if (not (nonsymbol-id? x))
(syntax-violation 'free-identifier=? "invalid argument" x)))
(free-id=? x y)))
(set! bound-identifier=?
(lambda (x y)
(let ((x x))
(if (not (nonsymbol-id? x))
(syntax-violation 'bound-identifier=? "invalid argument" x)))
(let ((x y))
(if (not (nonsymbol-id? x))
(syntax-violation 'bound-identifier=? "invalid argument" x)))
(bound-id=? x y)))
(set! syntax-violation
(lambda* (who message form #\optional (subform #f))
(let ((x who))
(if (not (let ((x x)) (or (not x) (string? x) (symbol? x))))
(syntax-violation 'syntax-violation "invalid argument" x)))
(let ((x message))
(if (not (string? x))
(syntax-violation 'syntax-violation "invalid argument" x)))
(throw 'syntax-error
who
message
(or (source-annotation subform) (source-annotation form))
(strip form '(()))
(and subform (strip subform '(()))))))
(letrec*
((syntax-module
(lambda (id)
(let ((x id))
(if (not (nonsymbol-id? x))
(syntax-violation 'syntax-module "invalid argument" x)))
(cdr (syntax-object-module id))))
(syntax-local-binding
(lambda (id)
(let ((x id))
(if (not (nonsymbol-id? x))
(syntax-violation 'syntax-local-binding "invalid argument" x)))
(with-transformer-environment
(lambda (e r w s rib mod)
(letrec*
((strip-anti-mark
(lambda (w)
(let ((ms (car w)) (s (cdr w)))
(if (and (pair? ms) (eq? (car ms) #f))
(cons (cdr ms) (if rib (cons rib (cdr s)) (cdr s)))
(cons ms (if rib (cons rib s) s)))))))
(call-with-values
(lambda ()
(resolve-identifier
(syntax-object-expression id)
(strip-anti-mark (syntax-object-wrap id))
r
(syntax-object-module id)))
(lambda (type value mod)
(let ((key type))
(cond ((memv key '(lexical)) (values 'lexical value))
((memv key '(macro)) (values 'macro value))
((memv key '(syntax)) (values 'pattern-variable value))
((memv key '(displaced-lexical)) (values 'displaced-lexical #f))
((memv key '(global)) (values 'global (cons value (cdr mod))))
((memv key '(ellipsis))
(values
'ellipsis
(make-syntax-object
(syntax-object-expression value)
(anti-mark (syntax-object-wrap value))
(syntax-object-module value))))
(else (values 'other #f)))))))))))
(syntax-locally-bound-identifiers
(lambda (id)
(let ((x id))
(if (not (nonsymbol-id? x))
(syntax-violation
'syntax-locally-bound-identifiers
"invalid argument"
x)))
(locally-bound-identifiers
(syntax-object-wrap id)
(syntax-object-module id)))))
(define! 'syntax-module syntax-module)
(define! 'syntax-local-binding syntax-local-binding)
(define!
'syntax-locally-bound-identifiers
syntax-locally-bound-identifiers))
(letrec*
((match-each
(lambda (e p w mod)
(cond ((pair? e)
(let ((first (match (car e) p w '() mod)))
(and first
(let ((rest (match-each (cdr e) p w mod)))
(and rest (cons first rest))))))
((null? e) '())
((syntax-object? e)
(match-each
(syntax-object-expression e)
p
(join-wraps w (syntax-object-wrap e))
(syntax-object-module e)))
(else #f))))
(match-each+
(lambda (e x-pat y-pat z-pat w r mod)
(let f ((e e) (w w))
(cond ((pair? e)
(call-with-values
(lambda () (f (cdr e) w))
(lambda (xr* y-pat r)
(if r
(if (null? y-pat)
(let ((xr (match (car e) x-pat w '() mod)))
(if xr (values (cons xr xr*) y-pat r) (values #f #f #f)))
(values '() (cdr y-pat) (match (car e) (car y-pat) w r mod)))
(values #f #f #f)))))
((syntax-object? e)
(f (syntax-object-expression e)
(join-wraps w (syntax-object-wrap e))))
(else (values '() y-pat (match e z-pat w r mod)))))))
(match-each-any
(lambda (e w mod)
(cond ((pair? e)
(let ((l (match-each-any (cdr e) w mod)))
(and l (cons (wrap (car e) w mod) l))))
((null? e) '())
((syntax-object? e)
(match-each-any
(syntax-object-expression e)
(join-wraps w (syntax-object-wrap e))
mod))
(else #f))))
(match-empty
(lambda (p r)
(cond ((null? p) r)
((eq? p '_) r)
((eq? p 'any) (cons '() r))
((pair? p) (match-empty (car p) (match-empty (cdr p) r)))
((eq? p 'each-any) (cons '() r))
(else
(let ((key (vector-ref p 0)))
(cond ((memv key '(each)) (match-empty (vector-ref p 1) r))
((memv key '(each+))
(match-empty
(vector-ref p 1)
(match-empty
(reverse (vector-ref p 2))
(match-empty (vector-ref p 3) r))))
((memv key '(free-id atom)) r)
((memv key '(vector)) (match-empty (vector-ref p 1) r))))))))
(combine
(lambda (r* r)
(if (null? (car r*)) r (cons (map car r*) (combine (map cdr r*) r)))))
(match*
(lambda (e p w r mod)
(cond ((null? p) (and (null? e) r))
((pair? p)
(and (pair? e)
(match (car e) (car p) w (match (cdr e) (cdr p) w r mod) mod)))
((eq? p 'each-any)
(let ((l (match-each-any e w mod))) (and l (cons l r))))
(else
(let ((key (vector-ref p 0)))
(cond ((memv key '(each))
(if (null? e)
(match-empty (vector-ref p 1) r)
(let ((l (match-each e (vector-ref p 1) w mod)))
(and l
(let collect ((l l))
(if (null? (car l)) r (cons (map car l) (collect (map cdr l)))))))))
((memv key '(each+))
(call-with-values
(lambda ()
(match-each+
e
(vector-ref p 1)
(vector-ref p 2)
(vector-ref p 3)
w
r
mod))
(lambda (xr* y-pat r)
(and r
(null? y-pat)
(if (null? xr*) (match-empty (vector-ref p 1) r) (combine xr* r))))))
((memv key '(free-id))
(and (id? e) (free-id=? (wrap e w mod) (vector-ref p 1)) r))
((memv key '(atom)) (and (equal? (vector-ref p 1) (strip e w)) r))
((memv key '(vector))
(and (vector? e) (match (vector->list e) (vector-ref p 1) w r mod)))))))))
(match (lambda (e p w r mod)
(cond ((not r) #f)
((eq? p '_) r)
((eq? p 'any) (cons (wrap e w mod) r))
((syntax-object? e)
(match*
(syntax-object-expression e)
p
(join-wraps w (syntax-object-wrap e))
r
(syntax-object-module e)))
(else (match* e p w r mod))))))
(set! $sc-dispatch
(lambda (e p)
(cond ((eq? p 'any) (list e))
((eq? p '_) '())
((syntax-object? e)
(match*
(syntax-object-expression e)
p
(syntax-object-wrap e)
'()
(syntax-object-module e)))
(else (match* e p '(()) '() #f)))))))
(define with-syntax
(make-syntax-transformer
'with-syntax
'macro
(lambda (x)
(let ((tmp x))
(let ((tmp-1 ($sc-dispatch tmp '(_ () any . each-any))))
(if tmp-1
(apply (lambda (e1 e2)
(cons '#(syntax-object let ((top)) (hygiene guile))
(cons '() (cons e1 e2))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ ((any any)) any . each-any))))
(if tmp-1
(apply (lambda (out in e1 e2)
(list '#(syntax-object syntax-case ((top)) (hygiene guile))
in
'()
(list out
(cons '#(syntax-object let ((top)) (hygiene guile))
(cons '() (cons e1 e2))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ #(each (any any)) any . each-any))))
(if tmp-1
(apply (lambda (out in e1 e2)
(list '#(syntax-object syntax-case ((top)) (hygiene guile))
(cons '#(syntax-object list ((top)) (hygiene guile)) in)
'()
(list out
(cons '#(syntax-object let ((top)) (hygiene guile))
(cons '() (cons e1 e2))))))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp)))))))))))
(define syntax-error
(make-syntax-transformer
'syntax-error
'macro
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(_ (any . any) any . each-any))))
(if (if tmp
(apply (lambda (keyword operands message arg)
(string? (syntax->datum message)))
tmp)
#f)
(apply (lambda (keyword operands message arg)
(syntax-violation
(syntax->datum keyword)
(string-join
(cons (syntax->datum message)
(map (lambda (x) (object->string (syntax->datum x))) arg)))
(if (syntax->datum keyword) (cons keyword operands) #f)))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ any . each-any))))
(if (if tmp
(apply (lambda (message arg) (string? (syntax->datum message))) tmp)
#f)
(apply (lambda (message arg)
(cons '#(syntax-object syntax-error ((top)) (hygiene guile))
(cons '(#f) (cons message arg))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))))
(define syntax-rules
(make-syntax-transformer
'syntax-rules
'macro
(lambda (xx)
(letrec*
((expand-clause
(lambda (clause)
(let ((tmp-1 clause))
(let ((tmp ($sc-dispatch
tmp-1
'((any . any)
(#(free-id #(syntax-object syntax-error ((top)) (hygiene guile)))
any
.
each-any)))))
(if (if tmp
(apply (lambda (keyword pattern message arg)
(string? (syntax->datum message)))
tmp)
#f)
(apply (lambda (keyword pattern message arg)
(list (cons '#(syntax-object dummy ((top)) (hygiene guile)) pattern)
(list '#(syntax-object syntax ((top)) (hygiene guile))
(cons '#(syntax-object syntax-error ((top)) (hygiene guile))
(cons (cons '#(syntax-object dummy ((top)) (hygiene guile)) pattern)
(cons message arg))))))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '((any . any) any))))
(if tmp
(apply (lambda (keyword pattern template)
(list (cons '#(syntax-object dummy ((top)) (hygiene guile)) pattern)
(list '#(syntax-object syntax ((top)) (hygiene guile)) template)))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))))
(expand-syntax-rules
(lambda (dots keys docstrings clauses)
(let ((tmp-1 (list keys docstrings clauses (map expand-clause clauses))))
(let ((tmp ($sc-dispatch
tmp-1
'(each-any each-any #(each ((any . any) any)) each-any))))
(if tmp
(apply (lambda (k docstring keyword pattern template clause)
(let ((tmp (cons '#(syntax-object lambda ((top)) (hygiene guile))
(cons '(#(syntax-object x ((top)) (hygiene guile)))
(append
docstring
(list (vector
'(#(syntax-object macro-type ((top)) (hygiene guile))
.
#(syntax-object syntax-rules ((top)) (hygiene guile)))
(cons '#(syntax-object patterns ((top)) (hygiene guile))
pattern))
(cons '#(syntax-object syntax-case ((top)) (hygiene guile))
(cons '#(syntax-object x ((top)) (hygiene guile))
(cons k clause)))))))))
(let ((form tmp))
(if dots
(let ((tmp dots))
(let ((dots tmp))
(list '#(syntax-object with-ellipsis ((top)) (hygiene guile))
dots
form)))
form))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
(let ((tmp xx))
(let ((tmp-1 ($sc-dispatch tmp '(_ each-any . #(each ((any . any) any))))))
(if tmp-1
(apply (lambda (k keyword pattern template)
(expand-syntax-rules
#f
k
'()
(map (lambda (tmp-bde397a-10fd tmp-bde397a-10fc tmp-bde397a-10fb)
(list (cons tmp-bde397a-10fb tmp-bde397a-10fc) tmp-bde397a-10fd))
template
pattern
keyword)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ each-any any . #(each ((any . any) any))))))
(if (if tmp-1
(apply (lambda (k docstring keyword pattern template)
(string? (syntax->datum docstring)))
tmp-1)
#f)
(apply (lambda (k docstring keyword pattern template)
(expand-syntax-rules
#f
k
(list docstring)
(map (lambda (tmp-bde397a-2 tmp-bde397a-1 tmp-bde397a)
(list (cons tmp-bde397a tmp-bde397a-1) tmp-bde397a-2))
template
pattern
keyword)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ any each-any . #(each ((any . any) any))))))
(if (if tmp-1
(apply (lambda (dots k keyword pattern template) (identifier? dots))
tmp-1)
#f)
(apply (lambda (dots k keyword pattern template)
(expand-syntax-rules
dots
k
'()
(map (lambda (tmp-bde397a-112f tmp-bde397a-112e tmp-bde397a-112d)
(list (cons tmp-bde397a-112d tmp-bde397a-112e) tmp-bde397a-112f))
template
pattern
keyword)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(_ any each-any any . #(each ((any . any) any))))))
(if (if tmp-1
(apply (lambda (dots k docstring keyword pattern template)
(if (identifier? dots) (string? (syntax->datum docstring)) #f))
tmp-1)
#f)
(apply (lambda (dots k docstring keyword pattern template)
(expand-syntax-rules
dots
k
(list docstring)
(map (lambda (tmp-bde397a-114e tmp-bde397a-114d tmp-bde397a-114c)
(list (cons tmp-bde397a-114c tmp-bde397a-114d) tmp-bde397a-114e))
template
pattern
keyword)))
tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))))))))))
(define define-syntax-rule
(make-syntax-transformer
'define-syntax-rule
'macro
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(_ (any . any) any))))
(if tmp
(apply (lambda (name pattern template)
(list '#(syntax-object define-syntax ((top)) (hygiene guile))
name
(list '#(syntax-object syntax-rules ((top)) (hygiene guile))
'()
(list (cons '#(syntax-object _ ((top)) (hygiene guile)) pattern)
template))))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ (any . any) any any))))
(if (if tmp
(apply (lambda (name pattern docstring template)
(string? (syntax->datum docstring)))
tmp)
#f)
(apply (lambda (name pattern docstring template)
(list '#(syntax-object define-syntax ((top)) (hygiene guile))
name
(list '#(syntax-object syntax-rules ((top)) (hygiene guile))
'()
docstring
(list (cons '#(syntax-object _ ((top)) (hygiene guile)) pattern)
template))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))))
(define let*
(make-syntax-transformer
'let*
'macro
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(any #(each (any any)) any . each-any))))
(if (if tmp
(apply (lambda (let* x v e1 e2) (and-map identifier? x)) tmp)
#f)
(apply (lambda (let* x v e1 e2)
(let f ((bindings (map list x v)))
(if (null? bindings)
(cons '#(syntax-object let ((top)) (hygiene guile))
(cons '() (cons e1 e2)))
(let ((tmp-1 (list (f (cdr bindings)) (car bindings))))
(let ((tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (body binding)
(list '#(syntax-object let ((top)) (hygiene guile))
(list binding)
body))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
(define quasiquote
(make-syntax-transformer
'quasiquote
'macro
(letrec*
((quasi (lambda (p lev)
(let ((tmp p))
(let ((tmp-1 ($sc-dispatch
tmp
'(#(free-id #(syntax-object unquote ((top)) (hygiene guile))) any))))
(if tmp-1
(apply (lambda (p)
(if (= lev 0)
(list "value" p)
(quasicons
'("quote" #(syntax-object unquote ((top)) (hygiene guile)))
(quasi (list p) (- lev 1)))))
tmp-1)
(let ((tmp-1 ($sc-dispatch
tmp
'(#(free-id #(syntax-object quasiquote ((top)) (hygiene guile))) any))))
(if tmp-1
(apply (lambda (p)
(quasicons
'("quote" #(syntax-object quasiquote ((top)) (hygiene guile)))
(quasi (list p) (+ lev 1))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if tmp-1
(apply (lambda (p q)
(let ((tmp-1 p))
(let ((tmp ($sc-dispatch
tmp-1
'(#(free-id #(syntax-object unquote ((top)) (hygiene guile)))
.
each-any))))
(if tmp
(apply (lambda (p)
(if (= lev 0)
(quasilist*
(map (lambda (tmp-bde397a-11b3)
(list "value" tmp-bde397a-11b3))
p)
(quasi q lev))
(quasicons
(quasicons
'("quote" #(syntax-object unquote ((top)) (hygiene guile)))
(quasi p (- lev 1)))
(quasi q lev))))
tmp)
(let ((tmp ($sc-dispatch
tmp-1
'(#(free-id
#(syntax-object unquote-splicing ((top)) (hygiene guile)))
.
each-any))))
(if tmp
(apply (lambda (p)
(if (= lev 0)
(quasiappend
(map (lambda (tmp-bde397a-11b8)
(list "value" tmp-bde397a-11b8))
p)
(quasi q lev))
(quasicons
(quasicons
'("quote"
#(syntax-object
unquote-splicing
((top))
(hygiene guile)))
(quasi p (- lev 1)))
(quasi q lev))))
tmp)
(quasicons (quasi p lev) (quasi q lev))))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '#(vector each-any))))
(if tmp-1
(apply (lambda (x) (quasivector (vquasi x lev))) tmp-1)
(let ((p tmp)) (list "quote" p)))))))))))))
(vquasi
(lambda (p lev)
(let ((tmp p))
(let ((tmp-1 ($sc-dispatch tmp '(any . any))))
(if tmp-1
(apply (lambda (p q)
(let ((tmp-1 p))
(let ((tmp ($sc-dispatch
tmp-1
'(#(free-id #(syntax-object unquote ((top)) (hygiene guile)))
.
each-any))))
(if tmp
(apply (lambda (p)
(if (= lev 0)
(quasilist*
(map (lambda (tmp-bde397a-11ce) (list "value" tmp-bde397a-11ce)) p)
(vquasi q lev))
(quasicons
(quasicons
'("quote" #(syntax-object unquote ((top)) (hygiene guile)))
(quasi p (- lev 1)))
(vquasi q lev))))
tmp)
(let ((tmp ($sc-dispatch
tmp-1
'(#(free-id #(syntax-object unquote-splicing ((top)) (hygiene guile)))
.
each-any))))
(if tmp
(apply (lambda (p)
(if (= lev 0)
(quasiappend
(map (lambda (tmp-bde397a-11d3) (list "value" tmp-bde397a-11d3)) p)
(vquasi q lev))
(quasicons
(quasicons
'("quote" #(syntax-object unquote-splicing ((top)) (hygiene guile)))
(quasi p (- lev 1)))
(vquasi q lev))))
tmp)
(quasicons (quasi p lev) (vquasi q lev))))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '())))
(if tmp-1
(apply (lambda () '("quote" ())) tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp))))))))
(quasicons
(lambda (x y)
(let ((tmp-1 (list x y)))
(let ((tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (x y)
(let ((tmp y))
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "quote") any))))
(if tmp-1
(apply (lambda (dy)
(let ((tmp x))
(let ((tmp ($sc-dispatch tmp '(#(atom "quote") any))))
(if tmp
(apply (lambda (dx) (list "quote" (cons dx dy))) tmp)
(if (null? dy) (list "list" x) (list "list*" x y))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list") . any))))
(if tmp-1
(apply (lambda (stuff) (cons "list" (cons x stuff))) tmp-1)
(let ((tmp ($sc-dispatch tmp '(#(atom "list*") . any))))
(if tmp
(apply (lambda (stuff) (cons "list*" (cons x stuff))) tmp)
(list "list*" x y)))))))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))
(quasiappend
(lambda (x y)
(let ((tmp y))
(let ((tmp ($sc-dispatch tmp '(#(atom "quote") ()))))
(if tmp
(apply (lambda ()
(if (null? x)
'("quote" ())
(if (null? (cdr x))
(car x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (p) (cons "append" p)) tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
tmp)
(if (null? x)
y
(let ((tmp-1 (list x y)))
(let ((tmp ($sc-dispatch tmp-1 '(each-any any))))
(if tmp
(apply (lambda (p y) (cons "append" (append p (list y)))) tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))))))
(quasilist*
(lambda (x y)
(let f ((x x)) (if (null? x) y (quasicons (car x) (f (cdr x)))))))
(quasivector
(lambda (x)
(let ((tmp x))
(let ((tmp ($sc-dispatch tmp '(#(atom "quote") each-any))))
(if tmp
(apply (lambda (x) (list "quote" (list->vector x))) tmp)
(let f ((y x)
(k (lambda (ls)
(let ((tmp-1 ls))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (t-bde397a-121c) (cons "vector" t-bde397a-121c)) tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
(let ((tmp y))
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "quote") each-any))))
(if tmp-1
(apply (lambda (y)
(k (map (lambda (tmp-bde397a) (list "quote" tmp-bde397a)) y)))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list") . each-any))))
(if tmp-1
(apply (lambda (y) (k y)) tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list*") . #(each+ any (any) ())))))
(if tmp-1
(apply (lambda (y z) (f z (lambda (ls) (k (append y ls))))) tmp-1)
(let ((else tmp))
(let ((tmp x))
(let ((t-bde397a tmp)) (list "list->vector" t-bde397a)))))))))))))))))
(emit (lambda (x)
(let ((tmp x))
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "quote") any))))
(if tmp-1
(apply (lambda (x) (list '#(syntax-object quote ((top)) (hygiene guile)) x))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list") . each-any))))
(if tmp-1
(apply (lambda (x)
(let ((tmp-1 (map emit x)))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (t-bde397a)
(cons '#(syntax-object list ((top)) (hygiene guile)) t-bde397a))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list*") . #(each+ any (any) ())))))
(if tmp-1
(apply (lambda (x y)
(let f ((x* x))
(if (null? x*)
(emit y)
(let ((tmp-1 (list (emit (car x*)) (f (cdr x*)))))
(let ((tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (t-bde397a-125a t-bde397a)
(list '#(syntax-object cons ((top)) (hygiene guile))
t-bde397a-125a
t-bde397a))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "append") . each-any))))
(if tmp-1
(apply (lambda (x)
(let ((tmp-1 (map emit x)))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (t-bde397a)
(cons '#(syntax-object append ((top)) (hygiene guile))
t-bde397a))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "vector") . each-any))))
(if tmp-1
(apply (lambda (x)
(let ((tmp-1 (map emit x)))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (t-bde397a)
(cons '#(syntax-object vector ((top)) (hygiene guile))
t-bde397a))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "list->vector") any))))
(if tmp-1
(apply (lambda (x)
(let ((tmp (emit x)))
(let ((t-bde397a-127e tmp))
(list '#(syntax-object list->vector ((top)) (hygiene guile))
t-bde397a-127e))))
tmp-1)
(let ((tmp-1 ($sc-dispatch tmp '(#(atom "value") any))))
(if tmp-1
(apply (lambda (x) x) tmp-1)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp)))))))))))))))))))
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(_ any))))
(if tmp
(apply (lambda (e) (emit (quasi e 0))) tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))))
(define include
(make-syntax-transformer
'include
'macro
(lambda (x)
(letrec*
((read-file
(lambda (fn dir k)
(let ((p (open-input-file
(if (absolute-file-name? fn)
fn
(if dir
(in-vicinity dir fn)
(syntax-violation
'include
"relative file name only allowed when the include form is in a file"
x))))))
(let ((enc (file-encoding p)))
(set-port-encoding! p (let ((t enc)) (if t t "UTF-8")))
(let f ((x (read p)) (result '()))
(if (eof-object? x)
(begin (close-input-port p) (reverse result))
(f (read p) (cons (datum->syntax k x) result)))))))))
(let ((src (syntax-source x)))
(let ((file (if src (assq-ref src 'filename) #f)))
(let ((dir (if (string? file) (dirname file) #f)))
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (k filename)
(let ((fn (syntax->datum filename)))
(let ((tmp-1 (read-file fn dir filename)))
(let ((tmp ($sc-dispatch tmp-1 'each-any)))
(if tmp
(apply (lambda (exp)
(cons '#(syntax-object begin ((top)) (hygiene guile)) exp))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1))))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))))))
(define include-from-path
(make-syntax-transformer
'include-from-path
'macro
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(any any))))
(if tmp
(apply (lambda (k filename)
(let ((fn (syntax->datum filename)))
(let ((tmp (datum->syntax
filename
(let ((t (%search-load-path fn)))
(if t
t
(syntax-violation
'include-from-path
"file not found in path"
x
filename))))))
(let ((fn tmp))
(list '#(syntax-object include ((top)) (hygiene guile)) fn)))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))
(define unquote
(make-syntax-transformer
'unquote
'macro
(lambda (x)
(syntax-violation
'unquote
"expression not valid outside of quasiquote"
x))))
(define unquote-splicing
(make-syntax-transformer
'unquote-splicing
'macro
(lambda (x)
(syntax-violation
'unquote-splicing
"expression not valid outside of quasiquote"
x))))
(define make-variable-transformer
(lambda (proc)
(if (procedure? proc)
(let ((trans (lambda (x) (proc x))))
(set-procedure-property! trans 'variable-transformer #t)
trans)
(error "variable transformer not a procedure" proc))))
(define identifier-syntax
(make-syntax-transformer
'identifier-syntax
'macro
(lambda (xx)
(let ((tmp-1 xx))
(let ((tmp ($sc-dispatch tmp-1 '(_ any))))
(if tmp
(apply (lambda (e)
(list '#(syntax-object lambda ((top)) (hygiene guile))
'(#(syntax-object x ((top)) (hygiene guile)))
'#((#(syntax-object macro-type ((top)) (hygiene guile))
.
#(syntax-object identifier-syntax ((top)) (hygiene guile))))
(list '#(syntax-object syntax-case ((top)) (hygiene guile))
'#(syntax-object x ((top)) (hygiene guile))
'()
(list '#(syntax-object id ((top)) (hygiene guile))
'(#(syntax-object identifier? ((top)) (hygiene guile))
(#(syntax-object syntax ((top)) (hygiene guile))
#(syntax-object id ((top)) (hygiene guile))))
(list '#(syntax-object syntax ((top)) (hygiene guile)) e))
(list '(#(syntax-object _ ((top)) (hygiene guile))
#(syntax-object x ((top)) (hygiene guile))
#(syntax-object ... ((top)) (hygiene guile)))
(list '#(syntax-object syntax ((top)) (hygiene guile))
(cons e
'(#(syntax-object x ((top)) (hygiene guile))
#(syntax-object ... ((top)) (hygiene guile)))))))))
tmp)
(let ((tmp ($sc-dispatch
tmp-1
'(_ (any any)
((#(free-id #(syntax-object set! ((top)) (hygiene guile))) any any)
any)))))
(if (if tmp
(apply (lambda (id exp1 var val exp2)
(if (identifier? id) (identifier? var) #f))
tmp)
#f)
(apply (lambda (id exp1 var val exp2)
(list '#(syntax-object make-variable-transformer ((top)) (hygiene guile))
(list '#(syntax-object lambda ((top)) (hygiene guile))
'(#(syntax-object x ((top)) (hygiene guile)))
'#((#(syntax-object macro-type ((top)) (hygiene guile))
.
#(syntax-object variable-transformer ((top)) (hygiene guile))))
(list '#(syntax-object syntax-case ((top)) (hygiene guile))
'#(syntax-object x ((top)) (hygiene guile))
'(#(syntax-object set! ((top)) (hygiene guile)))
(list (list '#(syntax-object set! ((top)) (hygiene guile)) var val)
(list '#(syntax-object syntax ((top)) (hygiene guile)) exp2))
(list (cons id
'(#(syntax-object x ((top)) (hygiene guile))
#(syntax-object ... ((top)) (hygiene guile))))
(list '#(syntax-object syntax ((top)) (hygiene guile))
(cons exp1
'(#(syntax-object x ((top)) (hygiene guile))
#(syntax-object ... ((top)) (hygiene guile))))))
(list id
(list '#(syntax-object identifier? ((top)) (hygiene guile))
(list '#(syntax-object syntax ((top)) (hygiene guile)) id))
(list '#(syntax-object syntax ((top)) (hygiene guile)) exp1))))))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))))
(define define*
(make-syntax-transformer
'define*
'macro
(lambda (x)
(let ((tmp-1 x))
(let ((tmp ($sc-dispatch tmp-1 '(_ (any . any) any . each-any))))
(if tmp
(apply (lambda (id args b0 b1)
(list '#(syntax-object define ((top)) (hygiene guile))
id
(cons '#(syntax-object lambda* ((top)) (hygiene guile))
(cons args (cons b0 b1)))))
tmp)
(let ((tmp ($sc-dispatch tmp-1 '(_ any any))))
(if (if tmp (apply (lambda (id val) (identifier? id)) tmp) #f)
(apply (lambda (id val)
(list '#(syntax-object define ((top)) (hygiene guile)) id val))
tmp)
(syntax-violation
#f
"source expression failed to match any pattern"
tmp-1)))))))))
;;;; -*-scheme-*-
;;;;
;;;; Copyright (C) 2001, 2003, 2006, 2009, 2010, 2011,
;;;; 2012, 2013, 2016 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Portable implementation of syntax-case
;;; Originally extracted from Chez Scheme Version 5.9f
;;; Authors: R. Kent Dybvig, Oscar Waddell, Bob Hieb, Carl Bruggeman
;;; Copyright (c) 1992-1997 Cadence Research Systems
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright notice in full. This software
;;; is provided AS IS, with NO WARRANTY, EITHER EXPRESS OR IMPLIED,
;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
;;; NATURE WHATSOEVER.
;;; Modified by Mikael Djurfeldt <djurfeldt@nada.kth.se> according
;;; to the ChangeLog distributed in the same directory as this file:
;;; 1997-08-19, 1997-09-03, 1997-09-10, 2000-08-13, 2000-08-24,
;;; 2000-09-12, 2001-03-08
;;; Modified by Andy Wingo <wingo@pobox.com> according to the Git
;;; revision control logs corresponding to this file: 2009, 2010.
;;; Modified by Mark H Weaver <mhw@netris.org> according to the Git
;;; revision control logs corresponding to this file: 2012, 2013.
;;; This code is based on "Syntax Abstraction in Scheme"
;;; by R. Kent Dybvig, Robert Hieb, and Carl Bruggeman.
;;; Lisp and Symbolic Computation 5:4, 295-326, 1992.
;;; <http://www.cs.indiana.edu/~dyb/pubs/LaSC-5-4-pp295-326.pdf>
;;; This file defines the syntax-case expander, macroexpand, and a set
;;; of associated syntactic forms and procedures. Of these, the
;;; following are documented in The Scheme Programming Language,
;;; Fourth Edition (R. Kent Dybvig, MIT Press, 2009), and in the
;;; R6RS:
;;;
;;; bound-identifier=?
;;; datum->syntax
;;; define-syntax
;;; syntax-parameterize
;;; free-identifier=?
;;; generate-temporaries
;;; identifier?
;;; identifier-syntax
;;; let-syntax
;;; letrec-syntax
;;; syntax
;;; syntax-case
;;; syntax->datum
;;; syntax-rules
;;; with-syntax
;;;
;;; Additionally, the expander provides definitions for a number of core
;;; Scheme syntactic bindings, such as `let', `lambda', and the like.
;;; The remaining exports are listed below:
;;;
;;; (macroexpand datum)
;;; if datum represents a valid expression, macroexpand returns an
;;; expanded version of datum in a core language that includes no
;;; syntactic abstractions. The core language includes begin,
;;; define, if, lambda, letrec, quote, and set!.
;;; (eval-when situations expr ...)
;;; conditionally evaluates expr ... at compile-time or run-time
;;; depending upon situations (see the Chez Scheme System Manual,
;;; Revision 3, for a complete description)
;;; (syntax-violation who message form [subform])
;;; used to report errors found during expansion
;;; ($sc-dispatch e p)
;;; used by expanded code to handle syntax-case matching
;;; This file is shipped along with an expanded version of itself,
;;; psyntax-pp.scm, which is loaded when psyntax.scm has not yet been
;;; compiled. In this way, psyntax bootstraps off of an expanded
;;; version of itself.
;;; This implementation of the expander sometimes uses syntactic
;;; abstractions when procedural abstractions would suffice. For
;;; example, we define top-wrap and top-marked? as
;;;
;;; (define-syntax top-wrap (identifier-syntax '((top))))
;;; (define-syntax top-marked?
;;; (syntax-rules ()
;;; ((_ w) (memq 'top (wrap-marks w)))))
;;;
;;; rather than
;;;
;;; (define top-wrap '((top)))
;;; (define top-marked?
;;; (lambda (w) (memq 'top (wrap-marks w))))
;;;
;;; On the other hand, we don't do this consistently; we define
;;; make-wrap, wrap-marks, and wrap-subst simply as
;;;
;;; (define make-wrap cons)
;;; (define wrap-marks car)
;;; (define wrap-subst cdr)
;;;
;;; In Chez Scheme, the syntactic and procedural forms of these
;;; abstractions are equivalent, since the optimizer consistently
;;; integrates constants and small procedures. This will be true of
;;; Guile as well, once we implement a proper inliner.
;;; Implementation notes:
;;; Objects with no standard print syntax, including objects containing
;;; cycles and syntax object, are allowed in quoted data as long as they
;;; are contained within a syntax form or produced by datum->syntax.
;;; Such objects are never copied.
;;; All identifiers that don't have macro definitions and are not bound
;;; lexically are assumed to be global variables.
;;; Top-level definitions of macro-introduced identifiers are allowed.
;;; This may not be appropriate for implementations in which the
;;; model is that bindings are created by definitions, as opposed to
;;; one in which initial values are assigned by definitions.
;;; Identifiers and syntax objects are implemented as vectors for
;;; portability. As a result, it is possible to "forge" syntax objects.
;;; The implementation of generate-temporaries assumes that it is
;;; possible to generate globally unique symbols (gensyms).
;;; The source location associated with incoming expressions is tracked
;;; via the source-properties mechanism, a weak map from expression to
;;; source information. At times the source is separated from the
;;; expression; see the note below about "efficiency and confusion".
;;; Bootstrapping:
;;; When changing syntax-object representations, it is necessary to support
;;; both old and new syntax-object representations in id-var-name. It
;;; should be sufficient to recognize old representations and treat
;;; them as not lexically bound.
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
(let ()
(define-syntax define-expansion-constructors
(lambda (x)
(syntax-case x ()
((_)
(let lp ((n 0) (out '()))
(if (< n (vector-length %expanded-vtables))
(lp (1+ n)
(let* ((vtable (vector-ref %expanded-vtables n))
(stem (struct-ref vtable (+ vtable-offset-user 0)))
(fields (struct-ref vtable (+ vtable-offset-user 2)))
(sfields (map (lambda (f) (datum->syntax x f)) fields))
(ctor (datum->syntax x (symbol-append 'make- stem))))
(cons #`(define (#,ctor #,@sfields)
(make-struct (vector-ref %expanded-vtables #,n) 0
#,@sfields))
out)))
#`(begin #,@(reverse out))))))))
(define-syntax define-expansion-accessors
(lambda (x)
(syntax-case x ()
((_ stem field ...)
(let lp ((n 0))
(let ((vtable (vector-ref %expanded-vtables n))
(stem (syntax->datum #'stem)))
(if (eq? (struct-ref vtable (+ vtable-offset-user 0)) stem)
#`(begin
(define (#,(datum->syntax x (symbol-append stem '?)) x)
(and (struct? x)
(eq? (struct-vtable x)
(vector-ref %expanded-vtables #,n))))
#,@(map
(lambda (f)
(let ((get (datum->syntax x (symbol-append stem '- f)))
(set (datum->syntax x (symbol-append 'set- stem '- f '!)))
(idx (list-index (struct-ref vtable
(+ vtable-offset-user 2))
f)))
#`(begin
(define (#,get x)
(struct-ref x #,idx))
(define (#,set x v)
(struct-set! x #,idx v)))))
(syntax->datum #'(field ...))))
(lp (1+ n)))))))))
(define-syntax define-structure
(lambda (x)
(define construct-name
(lambda (template-identifier . args)
(datum->syntax
template-identifier
(string->symbol
(apply string-append
(map (lambda (x)
(if (string? x)
x
(symbol->string (syntax->datum x))))
args))))))
(syntax-case x ()
((_ (name id1 ...))
(and-map identifier? #'(name id1 ...))
(with-syntax
((constructor (construct-name #'name "make-" #'name))
(predicate (construct-name #'name #'name "?"))
((access ...)
(map (lambda (x) (construct-name x #'name "-" x))
#'(id1 ...)))
((assign ...)
(map (lambda (x)
(construct-name x "set-" #'name "-" x "!"))
#'(id1 ...)))
(structure-length
(+ (length #'(id1 ...)) 1))
((index ...)
(let f ((i 1) (ids #'(id1 ...)))
(if (null? ids)
'()
(cons i (f (+ i 1) (cdr ids)))))))
#'(begin
(define constructor
(lambda (id1 ...)
(vector 'name id1 ... )))
(define predicate
(lambda (x)
(and (vector? x)
(= (vector-length x) structure-length)
(eq? (vector-ref x 0) 'name))))
(define access
(lambda (x)
(vector-ref x index)))
...
(define assign
(lambda (x update)
(vector-set! x index update)))
...))))))
(let ()
(define-expansion-constructors)
(define-expansion-accessors lambda meta)
;; hooks to nonportable run-time helpers
(begin
(define-syntax fx+ (identifier-syntax +))
(define-syntax fx- (identifier-syntax -))
(define-syntax fx= (identifier-syntax =))
(define-syntax fx< (identifier-syntax <))
(define top-level-eval-hook
(lambda (x mod)
(primitive-eval x)))
(define local-eval-hook
(lambda (x mod)
(primitive-eval x)))
;; Capture syntax-session-id before we shove it off into a module.
(define session-id
(let ((v (module-variable (current-module) 'syntax-session-id)))
(lambda ()
((variable-ref v)))))
(define put-global-definition-hook
(lambda (symbol type val)
(module-define! (current-module)
symbol
(make-syntax-transformer symbol type val))))
(define get-global-definition-hook
(lambda (symbol module)
(if (and (not module) (current-module))
(warn "module system is booted, we should have a module" symbol))
(let ((v (module-variable (if module
(resolve-module (cdr module))
(current-module))
symbol)))
(and v (variable-bound? v)
(let ((val (variable-ref v)))
(and (macro? val) (macro-type val)
(cons (macro-type val)
(macro-binding val)))))))))
(define (decorate-source e s)
(if (and s (supports-source-properties? e))
(set-source-properties! e s))
e)
(define (maybe-name-value! name val)
(if (lambda? val)
(let ((meta (lambda-meta val)))
(if (not (assq 'name meta))
(set-lambda-meta! val (acons 'name name meta))))))
;; output constructors
(define build-void
(lambda (source)
(make-void source)))
(define build-application
(lambda (source fun-exp arg-exps)
(make-application source fun-exp arg-exps)))
(define build-conditional
(lambda (source test-exp then-exp else-exp)
(make-conditional source test-exp then-exp else-exp)))
(define build-dynlet
(lambda (source fluids vals body)
(make-dynlet source fluids vals body)))
(define build-lexical-reference
(lambda (type source name var)
(make-lexical-ref source name var)))
(define build-lexical-assignment
(lambda (source name var exp)
(maybe-name-value! name exp)
(make-lexical-set source name var exp)))
(define (analyze-variable mod var modref-cont bare-cont)
(if (not mod)
(bare-cont var)
(let ((kind (car mod))
(mod (cdr mod)))
(case kind
((public) (modref-cont mod var #t))
((private) (if (not (equal? mod (module-name (current-module))))
(modref-cont mod var #f)
(bare-cont var)))
((bare) (bare-cont var))
((hygiene) (if (and (not (equal? mod (module-name (current-module))))
(module-variable (resolve-module mod) var))
(modref-cont mod var #f)
(bare-cont var)))
(else (syntax-violation #f "bad module kind" var mod))))))
(define build-global-reference
(lambda (source var mod)
(analyze-variable
mod var
(lambda (mod var public?)
(make-module-ref source mod var public?))
(lambda (var)
(make-toplevel-ref source var)))))
(define build-global-assignment
(lambda (source var exp mod)
(maybe-name-value! var exp)
(analyze-variable
mod var
(lambda (mod var public?)
(make-module-set source mod var public? exp))
(lambda (var)
(make-toplevel-set source var exp)))))
(define build-global-definition
(lambda (source var exp)
(maybe-name-value! var exp)
(make-toplevel-define source var exp)))
(define build-simple-lambda
(lambda (src req rest vars meta exp)
(make-lambda src
meta
;; hah, a case in which kwargs would be nice.
(make-lambda-case
;; src req opt rest kw inits vars body else
src req #f rest #f '() vars exp #f))))
(define build-case-lambda
(lambda (src meta body)
(make-lambda src meta body)))
(define build-lambda-case
;; req := (name ...)
;; opt := (name ...) | #f
;; rest := name | #f
;; kw := (allow-other-keys? (keyword name var) ...) | #f
;; inits: (init ...)
;; vars: (sym ...)
;; vars map to named arguments in the following order:
;; required, optional (positional), rest, keyword.
;; the body of a lambda: anything, already expanded
;; else: lambda-case | #f
(lambda (src req opt rest kw inits vars body else-case)
(make-lambda-case src req opt rest kw inits vars body else-case)))
(define build-primref
(lambda (src name)
(if (equal? (module-name (current-module)) '(guile))
(make-toplevel-ref src name)
(make-module-ref src '(guile) name #f))))
(define (build-data src exp)
(make-const src exp))
(define build-sequence
(lambda (src exps)
(if (null? (cdr exps))
(car exps)
(make-sequence src exps))))
(define build-let
(lambda (src ids vars val-exps body-exp)
(for-each maybe-name-value! ids val-exps)
(if (null? vars)
body-exp
(make-let src ids vars val-exps body-exp))))
(define build-named-let
(lambda (src ids vars val-exps body-exp)
(let ((f (car vars))
(f-name (car ids))
(vars (cdr vars))
(ids (cdr ids)))
(let ((proc (build-simple-lambda src ids #f vars '() body-exp)))
(maybe-name-value! f-name proc)
(for-each maybe-name-value! ids val-exps)
(make-letrec
src #f
(list f-name) (list f) (list proc)
(build-application src (build-lexical-reference 'fun src f-name f)
val-exps))))))
(define build-letrec
(lambda (src in-order? ids vars val-exps body-exp)
(if (null? vars)
body-exp
(begin
(for-each maybe-name-value! ids val-exps)
(make-letrec src in-order? ids vars val-exps body-exp)))))
(define-syntax-rule (build-lexical-var src id)
;; Use a per-module counter instead of the global counter of
;; 'gensym' so that the generated identifier is reproducible.
(module-gensym (symbol->string id)))
(define-structure (syntax-object expression wrap module))
(define-syntax no-source (identifier-syntax #f))
(define source-annotation
(lambda (x)
(let ((props (source-properties
(if (syntax-object? x)
(syntax-object-expression x)
x))))
(and (pair? props) props))))
(define-syntax-rule (arg-check pred? e who)
(let ((x e))
(if (not (pred? x)) (syntax-violation who "invalid argument" x))))
;; compile-time environments
;; wrap and environment comprise two level mapping.
;; wrap : id --> label
;; env : label --> <element>
;; environments are represented in two parts: a lexical part and a global
;; part. The lexical part is a simple list of associations from labels
;; to bindings. The global part is implemented by
;; {put,get}-global-definition-hook and associates symbols with
;; bindings.
;; global (assumed global variable) and displaced-lexical (see below)
;; do not show up in any environment; instead, they are fabricated by
;; lookup when it finds no other bindings.
;; <environment> ::= ((<label> . <binding>)*)
;; identifier bindings include a type and a value
;; <binding> ::= (macro . <procedure>) macros
;; (core . <procedure>) core forms
;; (module-ref . <procedure>) @ or @@
;; (begin) begin
;; (define) define
;; (define-syntax) define-syntax
;; (define-syntax-parameter) define-syntax-parameter
;; (local-syntax . rec?) let-syntax/letrec-syntax
;; (eval-when) eval-when
;; (syntax . (<var> . <level>)) pattern variables
;; (global) assumed global variable
;; (lexical . <var>) lexical variables
;; (ellipsis . <identifier>) custom ellipsis
;; (displaced-lexical) displaced lexicals
;; <level> ::= <nonnegative integer>
;; <var> ::= variable returned by build-lexical-var
;; a macro is a user-defined syntactic-form. a core is a
;; system-defined syntactic form. begin, define, define-syntax,
;; define-syntax-parameter, and eval-when are treated specially
;; since they are sensitive to whether the form is at top-level and
;; (except for eval-when) can denote valid internal definitions.
;; a pattern variable is a variable introduced by syntax-case and can
;; be referenced only within a syntax form.
;; any identifier for which no top-level syntax definition or local
;; binding of any kind has been seen is assumed to be a global
;; variable.
;; a lexical variable is a lambda- or letrec-bound variable.
;; an ellipsis binding is introduced by the 'with-ellipsis' special
;; form.
;; a displaced-lexical identifier is a lexical identifier removed from
;; it's scope by the return of a syntax object containing the identifier.
;; a displaced lexical can also appear when a letrec-syntax-bound
;; keyword is referenced on the rhs of one of the letrec-syntax clauses.
;; a displaced lexical should never occur with properly written macros.
(define-syntax make-binding
(syntax-rules (quote)
((_ type value) (cons type value))
((_ 'type) '(type))
((_ type) (cons type '()))))
(define-syntax-rule (binding-type x)
(car x))
(define-syntax-rule (binding-value x)
(cdr x))
(define-syntax null-env (identifier-syntax '()))
(define extend-env
(lambda (labels bindings r)
(if (null? labels)
r
(extend-env (cdr labels) (cdr bindings)
(cons (cons (car labels) (car bindings)) r)))))
(define extend-var-env
;; variant of extend-env that forms "lexical" binding
(lambda (labels vars r)
(if (null? labels)
r
(extend-var-env (cdr labels) (cdr vars)
(cons (cons (car labels) (make-binding 'lexical (car vars))) r)))))
;; we use a "macros only" environment in expansion of local macro
;; definitions so that their definitions can use local macros without
;; attempting to use other lexical identifiers.
(define macros-only-env
(lambda (r)
(if (null? r)
'()
(let ((a (car r)))
(if (memq (cadr a) '(macro ellipsis))
(cons a (macros-only-env (cdr r)))
(macros-only-env (cdr r)))))))
(define lookup
;; x may be a label or a symbol
;; although symbols are usually global, we check the environment first
;; anyway because a temporary binding may have been established by
;; fluid-let-syntax
(lambda (x r mod)
(cond
((assq x r) => cdr)
((symbol? x)
(or (get-global-definition-hook x mod) (make-binding 'global)))
(else (make-binding 'displaced-lexical)))))
(define global-extend
(lambda (type sym val)
(put-global-definition-hook sym type val)))
;; Conceptually, identifiers are always syntax objects. Internally,
;; however, the wrap is sometimes maintained separately (a source of
;; efficiency and confusion), so that symbols are also considered
;; identifiers by id?. Externally, they are always wrapped.
(define nonsymbol-id?
(lambda (x)
(and (syntax-object? x)
(symbol? (syntax-object-expression x)))))
(define id?
(lambda (x)
(cond
((symbol? x) #t)
((syntax-object? x) (symbol? (syntax-object-expression x)))
(else #f))))
(define-syntax-rule (id-sym-name e)
(let ((x e))
(if (syntax-object? x)
(syntax-object-expression x)
x)))
(define id-sym-name&marks
(lambda (x w)
(if (syntax-object? x)
(values
(syntax-object-expression x)
(join-marks (wrap-marks w) (wrap-marks (syntax-object-wrap x))))
(values x (wrap-marks w)))))
;; syntax object wraps
;; <wrap> ::= ((<mark> ...) . (<subst> ...))
;; <subst> ::= shift | <subs>
;; <subs> ::= #(ribcage #(<sym> ...) #(<mark> ...) #(<label> ...))
;; | #(ribcage (<sym> ...) (<mark> ...) (<label> ...))
(define-syntax make-wrap (identifier-syntax cons))
(define-syntax wrap-marks (identifier-syntax car))
(define-syntax wrap-subst (identifier-syntax cdr))
;; labels must be comparable with "eq?", have read-write invariance,
;; and distinct from symbols.
(define (gen-label)
(symbol->string (module-gensym "l")))
(define gen-labels
(lambda (ls)
(if (null? ls)
'()
(cons (gen-label) (gen-labels (cdr ls))))))
(define-structure (ribcage symnames marks labels))
(define-syntax empty-wrap (identifier-syntax '(())))
(define-syntax top-wrap (identifier-syntax '((top))))
(define-syntax-rule (top-marked? w)
(memq 'top (wrap-marks w)))
;; Marks must be comparable with "eq?" and distinct from pairs and
;; the symbol top. We do not use integers so that marks will remain
;; unique even across file compiles.
(define-syntax the-anti-mark (identifier-syntax #f))
(define anti-mark
(lambda (w)
(make-wrap (cons the-anti-mark (wrap-marks w))
(cons 'shift (wrap-subst w)))))
(define-syntax-rule (new-mark)
(module-gensym "m"))
;; make-empty-ribcage and extend-ribcage maintain list-based ribcages for
;; internal definitions, in which the ribcages are built incrementally
(define-syntax-rule (make-empty-ribcage)
(make-ribcage '() '() '()))
(define extend-ribcage!
;; must receive ids with complete wraps
(lambda (ribcage id label)
(set-ribcage-symnames! ribcage
(cons (syntax-object-expression id)
(ribcage-symnames ribcage)))
(set-ribcage-marks! ribcage
(cons (wrap-marks (syntax-object-wrap id))
(ribcage-marks ribcage)))
(set-ribcage-labels! ribcage
(cons label (ribcage-labels ribcage)))))
;; make-binding-wrap creates vector-based ribcages
(define make-binding-wrap
(lambda (ids labels w)
(if (null? ids)
w
(make-wrap
(wrap-marks w)
(cons
(let ((labelvec (list->vector labels)))
(let ((n (vector-length labelvec)))
(let ((symnamevec (make-vector n)) (marksvec (make-vector n)))
(let f ((ids ids) (i 0))
(if (not (null? ids))
(call-with-values
(lambda () (id-sym-name&marks (car ids) w))
(lambda (symname marks)
(vector-set! symnamevec i symname)
(vector-set! marksvec i marks)
(f (cdr ids) (fx+ i 1))))))
(make-ribcage symnamevec marksvec labelvec))))
(wrap-subst w))))))
(define smart-append
(lambda (m1 m2)
(if (null? m2)
m1
(append m1 m2))))
(define join-wraps
(lambda (w1 w2)
(let ((m1 (wrap-marks w1)) (s1 (wrap-subst w1)))
(if (null? m1)
(if (null? s1)
w2
(make-wrap
(wrap-marks w2)
(smart-append s1 (wrap-subst w2))))
(make-wrap
(smart-append m1 (wrap-marks w2))
(smart-append s1 (wrap-subst w2)))))))
(define join-marks
(lambda (m1 m2)
(smart-append m1 m2)))
(define same-marks?
(lambda (x y)
(or (eq? x y)
(and (not (null? x))
(not (null? y))
(eq? (car x) (car y))
(same-marks? (cdr x) (cdr y))))))
(define id-var-name
(lambda (id w)
(define-syntax-rule (first e)
;; Rely on Guile's multiple-values truncation.
e)
(define search
(lambda (sym subst marks)
(if (null? subst)
(values #f marks)
(let ((fst (car subst)))
(if (eq? fst 'shift)
(search sym (cdr subst) (cdr marks))
(let ((symnames (ribcage-symnames fst)))
(if (vector? symnames)
(search-vector-rib sym subst marks symnames fst)
(search-list-rib sym subst marks symnames fst))))))))
(define search-list-rib
(lambda (sym subst marks symnames ribcage)
(let f ((symnames symnames) (i 0))
(cond
((null? symnames) (search sym (cdr subst) marks))
((and (eq? (car symnames) sym)
(same-marks? marks (list-ref (ribcage-marks ribcage) i)))
(values (list-ref (ribcage-labels ribcage) i) marks))
(else (f (cdr symnames) (fx+ i 1)))))))
(define search-vector-rib
(lambda (sym subst marks symnames ribcage)
(let ((n (vector-length symnames)))
(let f ((i 0))
(cond
((fx= i n) (search sym (cdr subst) marks))
((and (eq? (vector-ref symnames i) sym)
(same-marks? marks (vector-ref (ribcage-marks ribcage) i)))
(values (vector-ref (ribcage-labels ribcage) i) marks))
(else (f (fx+ i 1))))))))
(cond
((symbol? id)
(or (first (search id (wrap-subst w) (wrap-marks w))) id))
((syntax-object? id)
(let ((id (syntax-object-expression id))
(w1 (syntax-object-wrap id)))
(let ((marks (join-marks (wrap-marks w) (wrap-marks w1))))
(call-with-values (lambda () (search id (wrap-subst w) marks))
(lambda (new-id marks)
(or new-id
(first (search id (wrap-subst w1) marks))
id))))))
(else (syntax-violation 'id-var-name "invalid id" id)))))
;; A helper procedure for syntax-locally-bound-identifiers, which
;; itself is a helper for transformer procedures.
;; `locally-bound-identifiers' returns a list of all bindings
;; visible to a syntax object with the given wrap. They are in
;; order from outer to inner.
;;
;; The purpose of this procedure is to give a transformer procedure
;; references on bound identifiers, that the transformer can then
;; introduce some of them in its output. As such, the identifiers
;; are anti-marked, so that rebuild-macro-output doesn't apply new
;; marks to them.
;;
(define locally-bound-identifiers
(lambda (w mod)
(define scan
(lambda (subst results)
(if (null? subst)
results
(let ((fst (car subst)))
(if (eq? fst 'shift)
(scan (cdr subst) results)
(let ((symnames (ribcage-symnames fst))
(marks (ribcage-marks fst)))
(if (vector? symnames)
(scan-vector-rib subst symnames marks results)
(scan-list-rib subst symnames marks results))))))))
(define scan-list-rib
(lambda (subst symnames marks results)
(let f ((symnames symnames) (marks marks) (results results))
(if (null? symnames)
(scan (cdr subst) results)
(f (cdr symnames) (cdr marks)
(cons (wrap (car symnames)
(anti-mark (make-wrap (car marks) subst))
mod)
results))))))
(define scan-vector-rib
(lambda (subst symnames marks results)
(let ((n (vector-length symnames)))
(let f ((i 0) (results results))
(if (fx= i n)
(scan (cdr subst) results)
(f (fx+ i 1)
(cons (wrap (vector-ref symnames i)
(anti-mark (make-wrap (vector-ref marks i) subst))
mod)
results)))))))
(scan (wrap-subst w) '())))
;; Returns three values: binding type, binding value, the module (for
;; resolving toplevel vars).
(define (resolve-identifier id w r mod)
(define (resolve-global var mod)
(let ((b (or (get-global-definition-hook var mod)
(make-binding 'global))))
(if (eq? (binding-type b) 'global)
(values 'global var mod)
(values (binding-type b) (binding-value b) mod))))
(define (resolve-lexical label mod)
(let ((b (or (assq-ref r label)
(make-binding 'displaced-lexical))))
(values (binding-type b) (binding-value b) mod)))
(let ((n (id-var-name id w)))
(cond
((symbol? n)
(resolve-global n (if (syntax-object? id)
(syntax-object-module id)
mod)))
((string? n)
(resolve-lexical n (if (syntax-object? id)
(syntax-object-module id)
mod)))
(else
(error "unexpected id-var-name" id w n)))))
(define transformer-environment
(make-fluid
(lambda (k)
(error "called outside the dynamic extent of a syntax transformer"))))
(define (with-transformer-environment k)
((fluid-ref transformer-environment) k))
;; free-id=? must be passed fully wrapped ids since (free-id=? x y)
;; may be true even if (free-id=? (wrap x w) (wrap y w)) is not.
(define free-id=?
(lambda (i j)
(and (eq? (id-sym-name i) (id-sym-name j)) ; accelerator
(eq? (id-var-name i empty-wrap) (id-var-name j empty-wrap)))))
;; bound-id=? may be passed unwrapped (or partially wrapped) ids as
;; long as the missing portion of the wrap is common to both of the ids
;; since (bound-id=? x y) iff (bound-id=? (wrap x w) (wrap y w))
(define bound-id=?
(lambda (i j)
(if (and (syntax-object? i) (syntax-object? j))
(and (eq? (syntax-object-expression i)
(syntax-object-expression j))
(same-marks? (wrap-marks (syntax-object-wrap i))
(wrap-marks (syntax-object-wrap j))))
(eq? i j))))
;; "valid-bound-ids?" returns #t if it receives a list of distinct ids.
;; valid-bound-ids? may be passed unwrapped (or partially wrapped) ids
;; as long as the missing portion of the wrap is common to all of the
;; ids.
(define valid-bound-ids?
(lambda (ids)
(and (let all-ids? ((ids ids))
(or (null? ids)
(and (id? (car ids))
(all-ids? (cdr ids)))))
(distinct-bound-ids? ids))))
;; distinct-bound-ids? expects a list of ids and returns #t if there are
;; no duplicates. It is quadratic on the length of the id list; long
;; lists could be sorted to make it more efficient. distinct-bound-ids?
;; may be passed unwrapped (or partially wrapped) ids as long as the
;; missing portion of the wrap is common to all of the ids.
(define distinct-bound-ids?
(lambda (ids)
(let distinct? ((ids ids))
(or (null? ids)
(and (not (bound-id-member? (car ids) (cdr ids)))
(distinct? (cdr ids)))))))
(define bound-id-member?
(lambda (x list)
(and (not (null? list))
(or (bound-id=? x (car list))
(bound-id-member? x (cdr list))))))
;; wrapping expressions and identifiers
(define wrap
(lambda (x w defmod)
(cond
((and (null? (wrap-marks w)) (null? (wrap-subst w))) x)
((syntax-object? x)
(make-syntax-object
(syntax-object-expression x)
(join-wraps w (syntax-object-wrap x))
(syntax-object-module x)))
((null? x) x)
(else (make-syntax-object x w defmod)))))
(define source-wrap
(lambda (x w s defmod)
(wrap (decorate-source x s) w defmod)))
;; expanding
(define expand-sequence
(lambda (body r w s mod)
(build-sequence s
(let dobody ((body body) (r r) (w w) (mod mod))
(if (null? body)
'()
(let ((first (expand (car body) r w mod)))
(cons first (dobody (cdr body) r w mod))))))))
;; At top-level, we allow mixed definitions and expressions. Like
;; expand-body we expand in two passes.
;;
;; First, from left to right, we expand just enough to know what
;; expressions are definitions, syntax definitions, and splicing
;; statements (`begin'). If we anything needs evaluating at
;; expansion-time, it is expanded directly.
;;
;; Otherwise we collect expressions to expand, in thunks, and then
;; expand them all at the end. This allows all syntax expanders
;; visible in a toplevel sequence to be visible during the
;; expansions of all normal definitions and expressions in the
;; sequence.
;;
(define expand-top-sequence
(lambda (body r w s m esew mod)
(define (scan body r w s m esew mod exps)
(cond
((null? body)
;; in reversed order
exps)
(else
(call-with-values
(lambda ()
(call-with-values
(lambda ()
(let ((e (car body)))
(syntax-type e r w (or (source-annotation e) s) #f mod #f)))
(lambda (type value form e w s mod)
(case type
((begin-form)
(syntax-case e ()
((_) exps)
((_ e1 e2 ...)
(scan #'(e1 e2 ...) r w s m esew mod exps))))
((local-syntax-form)
(expand-local-syntax value e r w s mod
(lambda (body r w s mod)
(scan body r w s m esew mod exps))))
((eval-when-form)
(syntax-case e ()
((_ (x ...) e1 e2 ...)
(let ((when-list (parse-when-list e #'(x ...)))
(body #'(e1 e2 ...)))
(cond
((eq? m 'e)
(if (memq 'eval when-list)
(scan body r w s
(if (memq 'expand when-list) 'c&e 'e)
'(eval)
mod exps)
(begin
(if (memq 'expand when-list)
(top-level-eval-hook
(expand-top-sequence body r w s 'e '(eval) mod)
mod))
(values exps))))
((memq 'load when-list)
(if (or (memq 'compile when-list)
(memq 'expand when-list)
(and (eq? m 'c&e) (memq 'eval when-list)))
(scan body r w s 'c&e '(compile load) mod exps)
(if (memq m '(c c&e))
(scan body r w s 'c '(load) mod exps)
(values exps))))
((or (memq 'compile when-list)
(memq 'expand when-list)
(and (eq? m 'c&e) (memq 'eval when-list)))
(top-level-eval-hook
(expand-top-sequence body r w s 'e '(eval) mod)
mod)
(values exps))
(else
(values exps)))))))
((define-syntax-form define-syntax-parameter-form)
(let ((n (id-var-name value w)) (r (macros-only-env r)))
(case m
((c)
(if (memq 'compile esew)
(let ((e (expand-install-global n (expand e r w mod))))
(top-level-eval-hook e mod)
(if (memq 'load esew)
(values (cons e exps))
(values exps)))
(if (memq 'load esew)
(values (cons (expand-install-global n (expand e r w mod))
exps))
(values exps))))
((c&e)
(let ((e (expand-install-global n (expand e r w mod))))
(top-level-eval-hook e mod)
(values (cons e exps))))
(else
(if (memq 'eval esew)
(top-level-eval-hook
(expand-install-global n (expand e r w mod))
mod))
(values exps)))))
((define-form)
(let* ((n (id-var-name value w))
;; Lookup the name in the module of the define form.
(type (binding-type (lookup n r mod))))
(case type
((global core macro module-ref)
;; affect compile-time environment (once we have booted)
(if (and (memq m '(c c&e))
(not (module-local-variable (current-module) n))
(current-module))
(let ((old (module-variable (current-module) n)))
;; use value of the same-named imported variable, if
;; any
(if (and (variable? old)
(variable-bound? old)
(not (macro? (variable-ref old))))
(module-define! (current-module) n (variable-ref old))
(module-add! (current-module) n (make-undefined-variable)))))
(values
(cons
(if (eq? m 'c&e)
(let ((x (build-global-definition s n (expand e r w mod))))
(top-level-eval-hook x mod)
x)
(lambda ()
(build-global-definition s n (expand e r w mod))))
exps)))
((displaced-lexical)
(syntax-violation #f "identifier out of context"
(source-wrap form w s mod)
(wrap value w mod)))
(else
(syntax-violation #f "cannot define keyword at top level"
(source-wrap form w s mod)
(wrap value w mod))))))
(else
(values (cons
(if (eq? m 'c&e)
(let ((x (expand-expr type value form e r w s mod)))
(top-level-eval-hook x mod)
x)
(lambda ()
(expand-expr type value form e r w s mod)))
exps)))))))
(lambda (exps)
(scan (cdr body) r w s m esew mod exps))))))
(call-with-values (lambda ()
(scan body r w s m esew mod '()))
(lambda (exps)
(if (null? exps)
(build-void s)
(build-sequence
s
(let lp ((in exps) (out '()))
(if (null? in) out
(let ((e (car in)))
(lp (cdr in)
(cons (if (procedure? e) (e) e) out)))))))))))
(define expand-install-global
(lambda (name e)
(build-global-definition
no-source
name
(build-application
no-source
(build-primref no-source 'make-syntax-transformer)
(list (build-data no-source name)
(build-data no-source 'macro)
e)))))
(define parse-when-list
(lambda (e when-list)
;; when-list is syntax'd version of list of situations
(let ((result (strip when-list empty-wrap)))
(let lp ((l result))
(if (null? l)
result
(if (memq (car l) '(compile load eval expand))
(lp (cdr l))
(syntax-violation 'eval-when "invalid situation" e
(car l))))))))
;; syntax-type returns seven values: type, value, form, e, w, s, and
;; mod. The first two are described in the table below.
;;
;; type value explanation
;; -------------------------------------------------------------------
;; core procedure core singleton
;; core-form procedure core form
;; module-ref procedure @ or @@ singleton
;; lexical name lexical variable reference
;; global name global variable reference
;; begin none begin keyword
;; define none define keyword
;; define-syntax none define-syntax keyword
;; define-syntax-parameter none define-syntax-parameter keyword
;; local-syntax rec? letrec-syntax/let-syntax keyword
;; eval-when none eval-when keyword
;; syntax level pattern variable
;; displaced-lexical none displaced lexical identifier
;; lexical-call name call to lexical variable
;; global-call name call to global variable
;; call none any other call
;; begin-form none begin expression
;; define-form id variable definition
;; define-syntax-form id syntax definition
;; define-syntax-parameter-form id syntax parameter definition
;; local-syntax-form rec? syntax definition
;; eval-when-form none eval-when form
;; constant none self-evaluating datum
;; other none anything else
;;
;; form is the entire form. For definition forms (define-form,
;; define-syntax-form, and define-syntax-parameter-form), e is the
;; rhs expression. For all others, e is the entire form. w is the
;; wrap for both form and e. s is the source for the entire form.
;; mod is the module for both form and e.
;;
;; syntax-type expands macros and unwraps as necessary to get to one
;; of the forms above. It also parses definition forms, although
;; perhaps this should be done by the consumer.
(define syntax-type
(lambda (e r w s rib mod for-car?)
(cond
((symbol? e)
(let* ((n (id-var-name e w))
(b (lookup n r mod))
(type (binding-type b)))
(case type
((lexical) (values type (binding-value b) e e w s mod))
((global) (values type n e e w s mod))
((macro)
(if for-car?
(values type (binding-value b) e e w s mod)
(syntax-type (expand-macro (binding-value b) e r w s rib mod)
r empty-wrap s rib mod #f)))
(else (values type (binding-value b) e e w s mod)))))
((pair? e)
(let ((first (car e)))
(call-with-values
(lambda () (syntax-type first r w s rib mod #t))
(lambda (ftype fval fform fe fw fs fmod)
(case ftype
((lexical)
(values 'lexical-call fval e e w s mod))
((global)
;; If we got here via an (@@ ...) expansion, we need to
;; make sure the fmod information is propagated back
;; correctly -- hence this consing.
(values 'global-call (make-syntax-object fval w fmod)
e e w s mod))
((macro)
(syntax-type (expand-macro fval e r w s rib mod)
r empty-wrap s rib mod for-car?))
((module-ref)
(call-with-values (lambda () (fval e r w))
(lambda (e r w s mod)
(syntax-type e r w s rib mod for-car?))))
((core)
(values 'core-form fval e e w s mod))
((local-syntax)
(values 'local-syntax-form fval e e w s mod))
((begin)
(values 'begin-form #f e e w s mod))
((eval-when)
(values 'eval-when-form #f e e w s mod))
((define)
(syntax-case e ()
((_ name val)
(id? #'name)
(values 'define-form #'name e #'val w s mod))
((_ (name . args) e1 e2 ...)
(and (id? #'name)
(valid-bound-ids? (lambda-var-list #'args)))
;; need lambda here...
(values 'define-form (wrap #'name w mod)
(wrap e w mod)
(decorate-source
(cons #'lambda (wrap #'(args e1 e2 ...) w mod))
s)
empty-wrap s mod))
((_ name)
(id? #'name)
(values 'define-form (wrap #'name w mod)
(wrap e w mod)
#'(if #f #f)
empty-wrap s mod))))
((define-syntax)
(syntax-case e ()
((_ name val)
(id? #'name)
(values 'define-syntax-form #'name e #'val w s mod))))
((define-syntax-parameter)
(syntax-case e ()
((_ name val)
(id? #'name)
(values 'define-syntax-parameter-form #'name e #'val w s mod))))
(else
(values 'call #f e e w s mod)))))))
((syntax-object? e)
(syntax-type (syntax-object-expression e)
r
(join-wraps w (syntax-object-wrap e))
(or (source-annotation e) s) rib
(or (syntax-object-module e) mod) for-car?))
((self-evaluating? e) (values 'constant #f e e w s mod))
(else (values 'other #f e e w s mod)))))
(define expand
(lambda (e r w mod)
(call-with-values
(lambda () (syntax-type e r w (source-annotation e) #f mod #f))
(lambda (type value form e w s mod)
(expand-expr type value form e r w s mod)))))
(define expand-expr
(lambda (type value form e r w s mod)
(case type
((lexical)
(build-lexical-reference 'value s e value))
((core core-form)
;; apply transformer
(value e r w s mod))
((module-ref)
(call-with-values (lambda () (value e r w))
(lambda (e r w s mod)
(expand e r w mod))))
((lexical-call)
(expand-application
(let ((id (car e)))
(build-lexical-reference 'fun (source-annotation id)
(if (syntax-object? id)
(syntax->datum id)
id)
value))
e r w s mod))
((global-call)
(expand-application
(build-global-reference (source-annotation (car e))
(if (syntax-object? value)
(syntax-object-expression value)
value)
(if (syntax-object? value)
(syntax-object-module value)
mod))
e r w s mod))
((constant) (build-data s (strip (source-wrap e w s mod) empty-wrap)))
((global) (build-global-reference s value mod))
((call) (expand-application (expand (car e) r w mod) e r w s mod))
((begin-form)
(syntax-case e ()
((_ e1 e2 ...) (expand-sequence #'(e1 e2 ...) r w s mod))
((_)
(if (include-deprecated-features)
(begin
(issue-deprecation-warning
"Sequences of zero expressions are deprecated. Use *unspecified*.")
(expand-void))
(syntax-violation #f "sequence of zero expressions"
(source-wrap e w s mod))))))
((local-syntax-form)
(expand-local-syntax value e r w s mod expand-sequence))
((eval-when-form)
(syntax-case e ()
((_ (x ...) e1 e2 ...)
(let ((when-list (parse-when-list e #'(x ...))))
(if (memq 'eval when-list)
(expand-sequence #'(e1 e2 ...) r w s mod)
(expand-void))))))
((define-form define-syntax-form define-syntax-parameter-form)
(syntax-violation #f "definition in expression context, where definitions are not allowed,"
(source-wrap form w s mod)))
((syntax)
(syntax-violation #f "reference to pattern variable outside syntax form"
(source-wrap e w s mod)))
((displaced-lexical)
(syntax-violation #f "reference to identifier outside its scope"
(source-wrap e w s mod)))
(else (syntax-violation #f "unexpected syntax"
(source-wrap e w s mod))))))
(define expand-application
(lambda (x e r w s mod)
(syntax-case e ()
((e0 e1 ...)
(build-application s x
(map (lambda (e) (expand e r w mod)) #'(e1 ...)))))))
;; (What follows is my interpretation of what's going on here -- Andy)
;;
;; A macro takes an expression, a tree, the leaves of which are identifiers
;; and datums. Identifiers are symbols along with a wrap and a module. For
;; efficiency, subtrees that share wraps and modules may be grouped as one
;; syntax object.
;;
;; Going into the expansion, the expression is given an anti-mark, which
;; logically propagates to all leaves. Then, in the new expression returned
;; from the transfomer, if we see an expression with an anti-mark, we know it
;; pertains to the original expression; conversely, expressions without the
;; anti-mark are known to be introduced by the transformer.
;;
;; OK, good until now. We know this algorithm does lexical scoping
;; appropriately because it's widely known in the literature, and psyntax is
;; widely used. But what about modules? Here we're on our own. What we do is
;; to mark the module of expressions produced by a macro as pertaining to the
;; module that was current when the macro was defined -- that is, free
;; identifiers introduced by a macro are scoped in the macro's module, not in
;; the expansion's module. Seems to work well.
;;
;; The only wrinkle is when we want a macro to expand to code in another
;; module, as is the case for the r6rs `library' form -- the body expressions
;; should be scoped relative the new module, the one defined by the macro.
;; For that, use `(@@ mod-name body)'.
;;
;; Part of the macro output will be from the site of the macro use and part
;; from the macro definition. We allow source information from the macro use
;; to pass through, but we annotate the parts coming from the macro with the
;; source location information corresponding to the macro use. It would be
;; really nice if we could also annotate introduced expressions with the
;; locations corresponding to the macro definition, but that is not yet
;; possible.
(define expand-macro
(lambda (p e r w s rib mod)
(define rebuild-macro-output
(lambda (x m)
(cond ((pair? x)
(decorate-source
(cons (rebuild-macro-output (car x) m)
(rebuild-macro-output (cdr x) m))
s))
((syntax-object? x)
(let ((w (syntax-object-wrap x)))
(let ((ms (wrap-marks w)) (ss (wrap-subst w)))
(if (and (pair? ms) (eq? (car ms) the-anti-mark))
;; output is from original text
(make-syntax-object
(syntax-object-expression x)
(make-wrap (cdr ms) (if rib (cons rib (cdr ss)) (cdr ss)))
(syntax-object-module x))
;; output introduced by macro
(make-syntax-object
(decorate-source (syntax-object-expression x) s)
(make-wrap (cons m ms)
(if rib
(cons rib (cons 'shift ss))
(cons 'shift ss)))
(syntax-object-module x))))))
((vector? x)
(let* ((n (vector-length x))
(v (decorate-source (make-vector n) s)))
(do ((i 0 (fx+ i 1)))
((fx= i n) v)
(vector-set! v i
(rebuild-macro-output (vector-ref x i) m)))))
((symbol? x)
(syntax-violation #f "encountered raw symbol in macro output"
(source-wrap e w (wrap-subst w) mod) x))
(else (decorate-source x s)))))
(with-fluids ((transformer-environment
(lambda (k) (k e r w s rib mod))))
(rebuild-macro-output (p (source-wrap e (anti-mark w) s mod))
(new-mark)))))
(define expand-body
;; In processing the forms of the body, we create a new, empty wrap.
;; This wrap is augmented (destructively) each time we discover that
;; the next form is a definition. This is done:
;;
;; (1) to allow the first nondefinition form to be a call to
;; one of the defined ids even if the id previously denoted a
;; definition keyword or keyword for a macro expanding into a
;; definition;
;; (2) to prevent subsequent definition forms (but unfortunately
;; not earlier ones) and the first nondefinition form from
;; confusing one of the bound identifiers for an auxiliary
;; keyword; and
;; (3) so that we do not need to restart the expansion of the
;; first nondefinition form, which is problematic anyway
;; since it might be the first element of a begin that we
;; have just spliced into the body (meaning if we restarted,
;; we'd really need to restart with the begin or the macro
;; call that expanded into the begin, and we'd have to give
;; up allowing (begin <defn>+ <expr>+), which is itself
;; problematic since we don't know if a begin contains only
;; definitions until we've expanded it).
;;
;; Before processing the body, we also create a new environment
;; containing a placeholder for the bindings we will add later and
;; associate this environment with each form. In processing a
;; let-syntax or letrec-syntax, the associated environment may be
;; augmented with local keyword bindings, so the environment may
;; be different for different forms in the body. Once we have
;; gathered up all of the definitions, we evaluate the transformer
;; expressions and splice into r at the placeholder the new variable
;; and keyword bindings. This allows let-syntax or letrec-syntax
;; forms local to a portion or all of the body to shadow the
;; definition bindings.
;;
;; Subforms of a begin, let-syntax, or letrec-syntax are spliced
;; into the body.
;;
;; outer-form is fully wrapped w/source
(lambda (body outer-form r w mod)
(let* ((r (cons '("placeholder" . (placeholder)) r))
(ribcage (make-empty-ribcage))
(w (make-wrap (wrap-marks w) (cons ribcage (wrap-subst w)))))
(let parse ((body (map (lambda (x) (cons r (wrap x w mod))) body))
(ids '()) (labels '())
(var-ids '()) (vars '()) (vals '()) (bindings '()))
(if (null? body)
(syntax-violation #f "no expressions in body" outer-form)
(let ((e (cdar body)) (er (caar body)))
(call-with-values
(lambda () (syntax-type e er empty-wrap (source-annotation e) ribcage mod #f))
(lambda (type value form e w s mod)
(case type
((define-form)
(let ((id (wrap value w mod)) (label (gen-label)))
(let ((var (gen-var id)))
(extend-ribcage! ribcage id label)
(parse (cdr body)
(cons id ids) (cons label labels)
(cons id var-ids)
(cons var vars) (cons (cons er (wrap e w mod)) vals)
(cons (make-binding 'lexical var) bindings)))))
((define-syntax-form define-syntax-parameter-form)
(let ((id (wrap value w mod))
(label (gen-label))
(trans-r (macros-only-env er)))
(extend-ribcage! ribcage id label)
;; As required by R6RS, evaluate the right-hand-sides of internal
;; syntax definition forms and add their transformers to the
;; compile-time environment immediately, so that the newly-defined
;; keywords may be used in definition context within the same
;; lexical contour.
(set-cdr! r (extend-env (list label)
(list (make-binding 'macro
(eval-local-transformer
(expand e trans-r w mod)
mod)))
(cdr r)))
(parse (cdr body) (cons id ids) labels var-ids vars vals bindings)))
((begin-form)
(syntax-case e ()
((_ e1 ...)
(parse (let f ((forms #'(e1 ...)))
(if (null? forms)
(cdr body)
(cons (cons er (wrap (car forms) w mod))
(f (cdr forms)))))
ids labels var-ids vars vals bindings))))
((local-syntax-form)
(expand-local-syntax value e er w s mod
(lambda (forms er w s mod)
(parse (let f ((forms forms))
(if (null? forms)
(cdr body)
(cons (cons er (wrap (car forms) w mod))
(f (cdr forms)))))
ids labels var-ids vars vals bindings))))
(else ; found a non-definition
(if (null? ids)
(build-sequence no-source
(map (lambda (x)
(expand (cdr x) (car x) empty-wrap mod))
(cons (cons er (source-wrap e w s mod))
(cdr body))))
(begin
(if (not (valid-bound-ids? ids))
(syntax-violation
#f "invalid or duplicate identifier in definition"
outer-form))
(set-cdr! r (extend-env labels bindings (cdr r)))
(build-letrec no-source #t
(reverse (map syntax->datum var-ids))
(reverse vars)
(map (lambda (x)
(expand (cdr x) (car x) empty-wrap mod))
(reverse vals))
(build-sequence no-source
(map (lambda (x)
(expand (cdr x) (car x) empty-wrap mod))
(cons (cons er (source-wrap e w s mod))
(cdr body)))))))))))))))))
(define expand-local-syntax
(lambda (rec? e r w s mod k)
(syntax-case e ()
((_ ((id val) ...) e1 e2 ...)
(let ((ids #'(id ...)))
(if (not (valid-bound-ids? ids))
(syntax-violation #f "duplicate bound keyword" e)
(let ((labels (gen-labels ids)))
(let ((new-w (make-binding-wrap ids labels w)))
(k #'(e1 e2 ...)
(extend-env
labels
(let ((w (if rec? new-w w))
(trans-r (macros-only-env r)))
(map (lambda (x)
(make-binding 'macro
(eval-local-transformer
(expand x trans-r w mod)
mod)))
#'(val ...)))
r)
new-w
s
mod))))))
(_ (syntax-violation #f "bad local syntax definition"
(source-wrap e w s mod))))))
(define eval-local-transformer
(lambda (expanded mod)
(let ((p (local-eval-hook expanded mod)))
(if (procedure? p)
p
(syntax-violation #f "nonprocedure transformer" p)))))
(define expand-void
(lambda ()
(build-void no-source)))
(define ellipsis?
(lambda (e r mod)
(and (nonsymbol-id? e)
;; If there is a binding for the special identifier
;; #{ $sc-ellipsis }# in the lexical environment of E,
;; and if the associated binding type is 'ellipsis',
;; then the binding's value specifies the custom ellipsis
;; identifier within that lexical environment, and the
;; comparison is done using 'bound-id=?'.
(let* ((id (make-syntax-object '#{ $sc-ellipsis }
(syntax-object-wrap e)
(syntax-object-module e)))
(n (id-var-name id empty-wrap))
(b (lookup n r mod)))
(if (eq? (binding-type b) 'ellipsis)
(bound-id=? e (binding-value b))
(free-id=? e #'(... ...)))))))
(define lambda-formals
(lambda (orig-args)
(define (req args rreq)
(syntax-case args ()
(()
(check (reverse rreq) #f))
((a . b) (id? #'a)
(req #'b (cons #'a rreq)))
(r (id? #'r)
(check (reverse rreq) #'r))
(else
(syntax-violation 'lambda "invalid argument list" orig-args args))))
(define (check req rest)
(cond
((distinct-bound-ids? (if rest (cons rest req) req))
(values req #f rest #f))
(else
(syntax-violation 'lambda "duplicate identifier in argument list"
orig-args))))
(req orig-args '())))
(define expand-simple-lambda
(lambda (e r w s mod req rest meta body)
(let* ((ids (if rest (append req (list rest)) req))
(vars (map gen-var ids))
(labels (gen-labels ids)))
(build-simple-lambda
s
(map syntax->datum req) (and rest (syntax->datum rest)) vars
meta
(expand-body body (source-wrap e w s mod)
(extend-var-env labels vars r)
(make-binding-wrap ids labels w)
mod)))))
(define lambda*-formals
(lambda (orig-args)
(define (req args rreq)
(syntax-case args ()
(()
(check (reverse rreq) '() #f '()))
((a . b) (id? #'a)
(req #'b (cons #'a rreq)))
((a . b) (eq? (syntax->datum #'a) #\optional)
(opt #'b (reverse rreq) '()))
((a . b) (eq? (syntax->datum #'a) #\key)
(key #'b (reverse rreq) '() '()))
((a b) (eq? (syntax->datum #'a) #\rest)
(rest #'b (reverse rreq) '() '()))
(r (id? #'r)
(rest #'r (reverse rreq) '() '()))
(else
(syntax-violation 'lambda* "invalid argument list" orig-args args))))
(define (opt args req ropt)
(syntax-case args ()
(()
(check req (reverse ropt) #f '()))
((a . b) (id? #'a)
(opt #'b req (cons #'(a #f) ropt)))
(((a init) . b) (id? #'a)
(opt #'b req (cons #'(a init) ropt)))
((a . b) (eq? (syntax->datum #'a) #\key)
(key #'b req (reverse ropt) '()))
((a b) (eq? (syntax->datum #'a) #\rest)
(rest #'b req (reverse ropt) '()))
(r (id? #'r)
(rest #'r req (reverse ropt) '()))
(else
(syntax-violation 'lambda* "invalid optional argument list"
orig-args args))))
(define (key args req opt rkey)
(syntax-case args ()
(()
(check req opt #f (cons #f (reverse rkey))))
((a . b) (id? #'a)
(with-syntax ((k (symbol->keyword (syntax->datum #'a))))
(key #'b req opt (cons #'(k a #f) rkey))))
(((a init) . b) (id? #'a)
(with-syntax ((k (symbol->keyword (syntax->datum #'a))))
(key #'b req opt (cons #'(k a init) rkey))))
(((a init k) . b) (and (id? #'a)
(keyword? (syntax->datum #'k)))
(key #'b req opt (cons #'(k a init) rkey)))
((aok) (eq? (syntax->datum #'aok) #\allow-other-keys)
(check req opt #f (cons #t (reverse rkey))))
((aok a b) (and (eq? (syntax->datum #'aok) #\allow-other-keys)
(eq? (syntax->datum #'a) #\rest))
(rest #'b req opt (cons #t (reverse rkey))))
((aok . r) (and (eq? (syntax->datum #'aok) #\allow-other-keys)
(id? #'r))
(rest #'r req opt (cons #t (reverse rkey))))
((a b) (eq? (syntax->datum #'a) #\rest)
(rest #'b req opt (cons #f (reverse rkey))))
(r (id? #'r)
(rest #'r req opt (cons #f (reverse rkey))))
(else
(syntax-violation 'lambda* "invalid keyword argument list"
orig-args args))))
(define (rest args req opt kw)
(syntax-case args ()
(r (id? #'r)
(check req opt #'r kw))
(else
(syntax-violation 'lambda* "invalid rest argument"
orig-args args))))
(define (check req opt rest kw)
(cond
((distinct-bound-ids?
(append req (map car opt) (if rest (list rest) '())
(if (pair? kw) (map cadr (cdr kw)) '())))
(values req opt rest kw))
(else
(syntax-violation 'lambda* "duplicate identifier in argument list"
orig-args))))
(req orig-args '())))
(define expand-lambda-case
(lambda (e r w s mod get-formals clauses)
(define (parse-req req opt rest kw body)
(let ((vars (map gen-var req))
(labels (gen-labels req)))
(let ((r* (extend-var-env labels vars r))
(w* (make-binding-wrap req labels w)))
(parse-opt (map syntax->datum req)
opt rest kw body (reverse vars) r* w* '() '()))))
(define (parse-opt req opt rest kw body vars r* w* out inits)
(cond
((pair? opt)
(syntax-case (car opt) ()
((id i)
(let* ((v (gen-var #'id))
(l (gen-labels (list v)))
(r** (extend-var-env l (list v) r*))
(w** (make-binding-wrap (list #'id) l w*)))
(parse-opt req (cdr opt) rest kw body (cons v vars)
r** w** (cons (syntax->datum #'id) out)
(cons (expand #'i r* w* mod) inits))))))
(rest
(let* ((v (gen-var rest))
(l (gen-labels (list v)))
(r* (extend-var-env l (list v) r*))
(w* (make-binding-wrap (list rest) l w*)))
(parse-kw req (if (pair? out) (reverse out) #f)
(syntax->datum rest)
(if (pair? kw) (cdr kw) kw)
body (cons v vars) r* w*
(if (pair? kw) (car kw) #f)
'() inits)))
(else
(parse-kw req (if (pair? out) (reverse out) #f) #f
(if (pair? kw) (cdr kw) kw)
body vars r* w*
(if (pair? kw) (car kw) #f)
'() inits))))
(define (parse-kw req opt rest kw body vars r* w* aok out inits)
(cond
((pair? kw)
(syntax-case (car kw) ()
((k id i)
(let* ((v (gen-var #'id))
(l (gen-labels (list v)))
(r** (extend-var-env l (list v) r*))
(w** (make-binding-wrap (list #'id) l w*)))
(parse-kw req opt rest (cdr kw) body (cons v vars)
r** w** aok
(cons (list (syntax->datum #'k)
(syntax->datum #'id)
v)
out)
(cons (expand #'i r* w* mod) inits))))))
(else
(parse-body req opt rest
(if (or aok (pair? out)) (cons aok (reverse out)) #f)
body (reverse vars) r* w* (reverse inits) '()))))
(define (parse-body req opt rest kw body vars r* w* inits meta)
(syntax-case body ()
((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
(parse-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
(append meta
`((documentation
. ,(syntax->datum #'docstring))))))
((#((k . v) ...) e1 e2 ...)
(parse-body req opt rest kw #'(e1 e2 ...) vars r* w* inits
(append meta (syntax->datum #'((k . v) ...)))))
((e1 e2 ...)
(values meta req opt rest kw inits vars
(expand-body #'(e1 e2 ...) (source-wrap e w s mod)
r* w* mod)))))
(syntax-case clauses ()
(() (values '() #f))
(((args e1 e2 ...) (args* e1* e2* ...) ...)
(call-with-values (lambda () (get-formals #'args))
(lambda (req opt rest kw)
(call-with-values (lambda ()
(parse-req req opt rest kw #'(e1 e2 ...)))
(lambda (meta req opt rest kw inits vars body)
(call-with-values
(lambda ()
(expand-lambda-case e r w s mod get-formals
#'((args* e1* e2* ...) ...)))
(lambda (meta* else*)
(values
(append meta meta*)
(build-lambda-case s req opt rest kw inits vars
body else*))))))))))))
;; data
;; strips syntax-objects down to top-wrap
;;
;; since only the head of a list is annotated by the reader, not each pair
;; in the spine, we also check for pairs whose cars are annotated in case
;; we've been passed the cdr of an annotated list
(define strip
(lambda (x w)
(if (top-marked? w)
x
(let f ((x x))
(cond
((syntax-object? x)
(strip (syntax-object-expression x) (syntax-object-wrap x)))
((pair? x)
(let ((a (f (car x))) (d (f (cdr x))))
(if (and (eq? a (car x)) (eq? d (cdr x)))
x
(cons a d))))
((vector? x)
(let ((old (vector->list x)))
(let ((new (map f old)))
;; inlined and-map with two args
(let lp ((l1 old) (l2 new))
(if (null? l1)
x
(if (eq? (car l1) (car l2))
(lp (cdr l1) (cdr l2))
(list->vector new)))))))
(else x))))))
;; lexical variables
(define gen-var
(lambda (id)
(let ((id (if (syntax-object? id) (syntax-object-expression id) id)))
(build-lexical-var no-source id))))
;; appears to return a reversed list
(define lambda-var-list
(lambda (vars)
(let lvl ((vars vars) (ls '()) (w empty-wrap))
(cond
((pair? vars) (lvl (cdr vars) (cons (wrap (car vars) w #f) ls) w))
((id? vars) (cons (wrap vars w #f) ls))
((null? vars) ls)
((syntax-object? vars)
(lvl (syntax-object-expression vars)
ls
(join-wraps w (syntax-object-wrap vars))))
;; include anything else to be caught by subsequent error
;; checking
(else (cons vars ls))))))
;; core transformers
(global-extend 'local-syntax 'letrec-syntax #t)
(global-extend 'local-syntax 'let-syntax #f)
(global-extend 'core 'syntax-parameterize
(lambda (e r w s mod)
(syntax-case e ()
((_ ((var val) ...) e1 e2 ...)
(valid-bound-ids? #'(var ...))
(let ((names (map (lambda (x) (id-var-name x w)) #'(var ...))))
(for-each
(lambda (id n)
(case (binding-type (lookup n r mod))
((displaced-lexical)
(syntax-violation 'syntax-parameterize
"identifier out of context"
e
(source-wrap id w s mod)))))
#'(var ...)
names)
(expand-body
#'(e1 e2 ...)
(source-wrap e w s mod)
(extend-env
names
(let ((trans-r (macros-only-env r)))
(map (lambda (x)
(make-binding 'macro
(eval-local-transformer (expand x trans-r w mod)
mod)))
#'(val ...)))
r)
w
mod)))
(_ (syntax-violation 'syntax-parameterize "bad syntax"
(source-wrap e w s mod))))))
(global-extend 'core 'quote
(lambda (e r w s mod)
(syntax-case e ()
((_ e) (build-data s (strip #'e w)))
(_ (syntax-violation 'quote "bad syntax"
(source-wrap e w s mod))))))
(global-extend 'core 'syntax
(let ()
(define gen-syntax
(lambda (src e r maps ellipsis? mod)
(if (id? e)
(let ((label (id-var-name e empty-wrap)))
;; Mod does not matter, we are looking to see if
;; the id is lexical syntax.
(let ((b (lookup label r mod)))
(if (eq? (binding-type b) 'syntax)
(call-with-values
(lambda ()
(let ((var.lev (binding-value b)))
(gen-ref src (car var.lev) (cdr var.lev) maps)))
(lambda (var maps) (values `(ref ,var) maps)))
(if (ellipsis? e r mod)
(syntax-violation 'syntax "misplaced ellipsis" src)
(values `(quote ,e) maps)))))
(syntax-case e ()
((dots e)
(ellipsis? #'dots r mod)
(gen-syntax src #'e r maps (lambda (e r mod) #f) mod))
((x dots . y)
;; this could be about a dozen lines of code, except that we
;; choose to handle #'(x ... ...) forms
(ellipsis? #'dots r mod)
(let f ((y #'y)
(k (lambda (maps)
(call-with-values
(lambda ()
(gen-syntax src #'x r
(cons '() maps) ellipsis? mod))
(lambda (x maps)
(if (null? (car maps))
(syntax-violation 'syntax "extra ellipsis"
src)
(values (gen-map x (car maps))
(cdr maps))))))))
(syntax-case y ()
((dots . y)
(ellipsis? #'dots r mod)
(f #'y
(lambda (maps)
(call-with-values
(lambda () (k (cons '() maps)))
(lambda (x maps)
(if (null? (car maps))
(syntax-violation 'syntax "extra ellipsis" src)
(values (gen-mappend x (car maps))
(cdr maps))))))))
(_ (call-with-values
(lambda () (gen-syntax src y r maps ellipsis? mod))
(lambda (y maps)
(call-with-values
(lambda () (k maps))
(lambda (x maps)
(values (gen-append x y) maps)))))))))
((x . y)
(call-with-values
(lambda () (gen-syntax src #'x r maps ellipsis? mod))
(lambda (x maps)
(call-with-values
(lambda () (gen-syntax src #'y r maps ellipsis? mod))
(lambda (y maps) (values (gen-cons x y) maps))))))
(#(e1 e2 ...)
(call-with-values
(lambda ()
(gen-syntax src #'(e1 e2 ...) r maps ellipsis? mod))
(lambda (e maps) (values (gen-vector e) maps))))
(_ (values `(quote ,e) maps))))))
(define gen-ref
(lambda (src var level maps)
(if (fx= level 0)
(values var maps)
(if (null? maps)
(syntax-violation 'syntax "missing ellipsis" src)
(call-with-values
(lambda () (gen-ref src var (fx- level 1) (cdr maps)))
(lambda (outer-var outer-maps)
(let ((b (assq outer-var (car maps))))
(if b
(values (cdr b) maps)
(let ((inner-var (gen-var 'tmp)))
(values inner-var
(cons (cons (cons outer-var inner-var)
(car maps))
outer-maps)))))))))))
(define gen-mappend
(lambda (e map-env)
`(apply (primitive append) ,(gen-map e map-env))))
(define gen-map
(lambda (e map-env)
(let ((formals (map cdr map-env))
(actuals (map (lambda (x) `(ref ,(car x))) map-env)))
(cond
((eq? (car e) 'ref)
;; identity map equivalence:
;; (map (lambda (x) x) y) == y
(car actuals))
((and-map
(lambda (x) (and (eq? (car x) 'ref) (memq (cadr x) formals)))
(cdr e))
;; eta map equivalence:
;; (map (lambda (x ...) (f x ...)) y ...) == (map f y ...)
`(map (primitive ,(car e))
,@(map (let ((r (map cons formals actuals)))
(lambda (x) (cdr (assq (cadr x) r))))
(cdr e))))
(else `(map (lambda ,formals ,e) ,@actuals))))))
(define gen-cons
(lambda (x y)
(case (car y)
((quote)
(if (eq? (car x) 'quote)
`(quote (,(cadr x) . ,(cadr y)))
(if (eq? (cadr y) '())
`(list ,x)
`(cons ,x ,y))))
((list) `(list ,x ,@(cdr y)))
(else `(cons ,x ,y)))))
(define gen-append
(lambda (x y)
(if (equal? y '(quote ()))
x
`(append ,x ,y))))
(define gen-vector
(lambda (x)
(cond
((eq? (car x) 'list) `(vector ,@(cdr x)))
((eq? (car x) 'quote) `(quote #(,@(cadr x))))
(else `(list->vector ,x)))))
(define regen
(lambda (x)
(case (car x)
((ref) (build-lexical-reference 'value no-source (cadr x) (cadr x)))
((primitive) (build-primref no-source (cadr x)))
((quote) (build-data no-source (cadr x)))
((lambda)
(if (list? (cadr x))
(build-simple-lambda no-source (cadr x) #f (cadr x) '() (regen (caddr x)))
(error "how did we get here" x)))
(else (build-application no-source
(build-primref no-source (car x))
(map regen (cdr x)))))))
(lambda (e r w s mod)
(let ((e (source-wrap e w s mod)))
(syntax-case e ()
((_ x)
(call-with-values
(lambda () (gen-syntax e #'x r '() ellipsis? mod))
(lambda (e maps) (regen e))))
(_ (syntax-violation 'syntax "bad `syntax' form" e)))))))
(global-extend 'core 'lambda
(lambda (e r w s mod)
(syntax-case e ()
((_ args e1 e2 ...)
(call-with-values (lambda () (lambda-formals #'args))
(lambda (req opt rest kw)
(let lp ((body #'(e1 e2 ...)) (meta '()))
(syntax-case body ()
((docstring e1 e2 ...) (string? (syntax->datum #'docstring))
(lp #'(e1 e2 ...)
(append meta
`((documentation
. ,(syntax->datum #'docstring))))))
((#((k . v) ...) e1 e2 ...)
(lp #'(e1 e2 ...)
(append meta (syntax->datum #'((k . v) ...)))))
(_ (expand-simple-lambda e r w s mod req rest meta body)))))))
(_ (syntax-violation 'lambda "bad lambda" e)))))
(global-extend 'core 'lambda*
(lambda (e r w s mod)
(syntax-case e ()
((_ args e1 e2 ...)
(call-with-values
(lambda ()
(expand-lambda-case e r w s mod
lambda*-formals #'((args e1 e2 ...))))
(lambda (meta lcase)
(build-case-lambda s meta lcase))))
(_ (syntax-violation 'lambda "bad lambda*" e)))))
(global-extend 'core 'case-lambda
(lambda (e r w s mod)
(define (build-it meta clauses)
(call-with-values
(lambda ()
(expand-lambda-case e r w s mod
lambda-formals
clauses))
(lambda (meta* lcase)
(build-case-lambda s (append meta meta*) lcase))))
(syntax-case e ()
((_ (args e1 e2 ...) ...)
(build-it '() #'((args e1 e2 ...) ...)))
((_ docstring (args e1 e2 ...) ...)
(string? (syntax->datum #'docstring))
(build-it `((documentation
. ,(syntax->datum #'docstring)))
#'((args e1 e2 ...) ...)))
(_ (syntax-violation 'case-lambda "bad case-lambda" e)))))
(global-extend 'core 'case-lambda*
(lambda (e r w s mod)
(define (build-it meta clauses)
(call-with-values
(lambda ()
(expand-lambda-case e r w s mod
lambda*-formals
clauses))
(lambda (meta* lcase)
(build-case-lambda s (append meta meta*) lcase))))
(syntax-case e ()
((_ (args e1 e2 ...) ...)
(build-it '() #'((args e1 e2 ...) ...)))
((_ docstring (args e1 e2 ...) ...)
(string? (syntax->datum #'docstring))
(build-it `((documentation
. ,(syntax->datum #'docstring)))
#'((args e1 e2 ...) ...)))
(_ (syntax-violation 'case-lambda "bad case-lambda*" e)))))
(global-extend 'core 'with-ellipsis
(lambda (e r w s mod)
(syntax-case e ()
((_ dots e1 e2 ...)
(id? #'dots)
(let ((id (if (symbol? #'dots)
'#{ $sc-ellipsis }
(make-syntax-object '#{ $sc-ellipsis }
(syntax-object-wrap #'dots)
(syntax-object-module #'dots)))))
(let ((ids (list id))
(labels (list (gen-label)))
(bindings (list (make-binding 'ellipsis (source-wrap #'dots w s mod)))))
(let ((nw (make-binding-wrap ids labels w))
(nr (extend-env labels bindings r)))
(expand-body #'(e1 e2 ...) (source-wrap e nw s mod) nr nw mod)))))
(_ (syntax-violation 'with-ellipsis "bad syntax"
(source-wrap e w s mod))))))
(global-extend 'core 'let
(let ()
(define (expand-let e r w s mod constructor ids vals exps)
(if (not (valid-bound-ids? ids))
(syntax-violation 'let "duplicate bound variable" e)
(let ((labels (gen-labels ids))
(new-vars (map gen-var ids)))
(let ((nw (make-binding-wrap ids labels w))
(nr (extend-var-env labels new-vars r)))
(constructor s
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) vals)
(expand-body exps (source-wrap e nw s mod)
nr nw mod))))))
(lambda (e r w s mod)
(syntax-case e ()
((_ ((id val) ...) e1 e2 ...)
(and-map id? #'(id ...))
(expand-let e r w s mod
build-let
#'(id ...)
#'(val ...)
#'(e1 e2 ...)))
((_ f ((id val) ...) e1 e2 ...)
(and (id? #'f) (and-map id? #'(id ...)))
(expand-let e r w s mod
build-named-let
#'(f id ...)
#'(val ...)
#'(e1 e2 ...)))
(_ (syntax-violation 'let "bad let" (source-wrap e w s mod)))))))
(global-extend 'core 'letrec
(lambda (e r w s mod)
(syntax-case e ()
((_ ((id val) ...) e1 e2 ...)
(and-map id? #'(id ...))
(let ((ids #'(id ...)))
(if (not (valid-bound-ids? ids))
(syntax-violation 'letrec "duplicate bound variable" e)
(let ((labels (gen-labels ids))
(new-vars (map gen-var ids)))
(let ((w (make-binding-wrap ids labels w))
(r (extend-var-env labels new-vars r)))
(build-letrec s #f
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) #'(val ...))
(expand-body #'(e1 e2 ...)
(source-wrap e w s mod) r w mod)))))))
(_ (syntax-violation 'letrec "bad letrec" (source-wrap e w s mod))))))
(global-extend 'core 'letrec*
(lambda (e r w s mod)
(syntax-case e ()
((_ ((id val) ...) e1 e2 ...)
(and-map id? #'(id ...))
(let ((ids #'(id ...)))
(if (not (valid-bound-ids? ids))
(syntax-violation 'letrec* "duplicate bound variable" e)
(let ((labels (gen-labels ids))
(new-vars (map gen-var ids)))
(let ((w (make-binding-wrap ids labels w))
(r (extend-var-env labels new-vars r)))
(build-letrec s #t
(map syntax->datum ids)
new-vars
(map (lambda (x) (expand x r w mod)) #'(val ...))
(expand-body #'(e1 e2 ...)
(source-wrap e w s mod) r w mod)))))))
(_ (syntax-violation 'letrec* "bad letrec*" (source-wrap e w s mod))))))
(global-extend 'core 'set!
(lambda (e r w s mod)
(syntax-case e ()
((_ id val)
(id? #'id)
(let ((n (id-var-name #'id w))
;; Lookup id in its module
(id-mod (if (syntax-object? #'id)
(syntax-object-module #'id)
mod)))
(let ((b (lookup n r id-mod)))
(case (binding-type b)
((lexical)
(build-lexical-assignment s
(syntax->datum #'id)
(binding-value b)
(expand #'val r w mod)))
((global)
(build-global-assignment s n (expand #'val r w mod) id-mod))
((macro)
(let ((p (binding-value b)))
(if (procedure-property p 'variable-transformer)
;; As syntax-type does, call expand-macro with
;; the mod of the expression. Hmm.
(expand (expand-macro p e r w s #f mod) r empty-wrap mod)
(syntax-violation 'set! "not a variable transformer"
(wrap e w mod)
(wrap #'id w id-mod)))))
((displaced-lexical)
(syntax-violation 'set! "identifier out of context"
(wrap #'id w mod)))
(else (syntax-violation 'set! "bad set!"
(source-wrap e w s mod)))))))
((_ (head tail ...) val)
(call-with-values
(lambda () (syntax-type #'head r empty-wrap no-source #f mod #t))
(lambda (type value formform ee ww ss modmod)
(case type
((module-ref)
(let ((val (expand #'val r w mod)))
(call-with-values (lambda () (value #'(head tail ...) r w))
(lambda (e r w s* mod)
(syntax-case e ()
(e (id? #'e)
(build-global-assignment s (syntax->datum #'e)
val mod)))))))
(else
(build-application s
(expand #'(setter head) r w mod)
(map (lambda (e) (expand e r w mod))
#'(tail ... val))))))))
(_ (syntax-violation 'set! "bad set!" (source-wrap e w s mod))))))
(global-extend 'module-ref '@
(lambda (e r w)
(syntax-case e ()
((_ (mod ...) id)
(and (and-map id? #'(mod ...)) (id? #'id))
;; Strip the wrap from the identifier and return top-wrap
;; so that the identifier will not be captured by lexicals.
(values (syntax->datum #'id) r top-wrap #f
(syntax->datum
#'(public mod ...)))))))
(global-extend 'module-ref '@@
(lambda (e r w)
(define remodulate
(lambda (x mod)
(cond ((pair? x)
(cons (remodulate (car x) mod)
(remodulate (cdr x) mod)))
((syntax-object? x)
(make-syntax-object
(remodulate (syntax-object-expression x) mod)
(syntax-object-wrap x)
;; hither the remodulation
mod))
((vector? x)
(let* ((n (vector-length x)) (v (make-vector n)))
(do ((i 0 (fx+ i 1)))
((fx= i n) v)
(vector-set! v i (remodulate (vector-ref x i) mod)))))
(else x))))
(syntax-case e (@@)
((_ (mod ...) id)
(and (and-map id? #'(mod ...)) (id? #'id))
;; Strip the wrap from the identifier and return top-wrap
;; so that the identifier will not be captured by lexicals.
(values (syntax->datum #'id) r top-wrap #f
(syntax->datum
#'(private mod ...))))
((_ @@ (mod ...) exp)
(and-map id? #'(mod ...))
;; This is a special syntax used to support R6RS library forms.
;; Unlike the syntax above, the last item is not restricted to
;; be a single identifier, and the syntax objects are kept
;; intact, with only their module changed.
(let ((mod (syntax->datum #'(private mod ...))))
(values (remodulate #'exp mod)
r w (source-annotation #'exp)
mod))))))
(global-extend 'core 'if
(lambda (e r w s mod)
(syntax-case e ()
((_ test then)
(build-conditional
s
(expand #'test r w mod)
(expand #'then r w mod)
(build-void no-source)))
((_ test then else)
(build-conditional
s
(expand #'test r w mod)
(expand #'then r w mod)
(expand #'else r w mod))))))
(global-extend 'core 'with-fluids
(lambda (e r w s mod)
(syntax-case e ()
((_ ((fluid val) ...) b b* ...)
(build-dynlet
s
(map (lambda (x) (expand x r w mod)) #'(fluid ...))
(map (lambda (x) (expand x r w mod)) #'(val ...))
(expand-body #'(b b* ...)
(source-wrap e w s mod) r w mod))))))
(global-extend 'begin 'begin '())
(global-extend 'define 'define '())
(global-extend 'define-syntax 'define-syntax '())
(global-extend 'define-syntax-parameter 'define-syntax-parameter '())
(global-extend 'eval-when 'eval-when '())
(global-extend 'core 'syntax-case
(let ()
(define convert-pattern
;; accepts pattern & keys
;; returns $sc-dispatch pattern & ids
(lambda (pattern keys ellipsis?)
(define cvt*
(lambda (p* n ids)
(syntax-case p* ()
((x . y)
(call-with-values
(lambda () (cvt* #'y n ids))
(lambda (y ids)
(call-with-values
(lambda () (cvt #'x n ids))
(lambda (x ids)
(values (cons x y) ids))))))
(_ (cvt p* n ids)))))
(define (v-reverse x)
(let loop ((r '()) (x x))
(if (not (pair? x))
(values r x)
(loop (cons (car x) r) (cdr x)))))
(define cvt
(lambda (p n ids)
(if (id? p)
(cond
((bound-id-member? p keys)
(values (vector 'free-id p) ids))
((free-id=? p #'_)
(values '_ ids))
(else
(values 'any (cons (cons p n) ids))))
(syntax-case p ()
((x dots)
(ellipsis? (syntax dots))
(call-with-values
(lambda () (cvt (syntax x) (fx+ n 1) ids))
(lambda (p ids)
(values (if (eq? p 'any) 'each-any (vector 'each p))
ids))))
((x dots . ys)
(ellipsis? (syntax dots))
(call-with-values
(lambda () (cvt* (syntax ys) n ids))
(lambda (ys ids)
(call-with-values
(lambda () (cvt (syntax x) (+ n 1) ids))
(lambda (x ids)
(call-with-values
(lambda () (v-reverse ys))
(lambda (ys e)
(values `#(each+ ,x ,ys ,e)
ids))))))))
((x . y)
(call-with-values
(lambda () (cvt (syntax y) n ids))
(lambda (y ids)
(call-with-values
(lambda () (cvt (syntax x) n ids))
(lambda (x ids)
(values (cons x y) ids))))))
(() (values '() ids))
(#(x ...)
(call-with-values
(lambda () (cvt (syntax (x ...)) n ids))
(lambda (p ids) (values (vector 'vector p) ids))))
(x (values (vector 'atom (strip p empty-wrap)) ids))))))
(cvt pattern 0 '())))
(define build-dispatch-call
(lambda (pvars exp y r mod)
(let ((ids (map car pvars)) (levels (map cdr pvars)))
(let ((labels (gen-labels ids)) (new-vars (map gen-var ids)))
(build-application no-source
(build-primref no-source 'apply)
(list (build-simple-lambda no-source (map syntax->datum ids) #f new-vars '()
(expand exp
(extend-env
labels
(map (lambda (var level)
(make-binding 'syntax `(,var . ,level)))
new-vars
(map cdr pvars))
r)
(make-binding-wrap ids labels empty-wrap)
mod))
y))))))
(define gen-clause
(lambda (x keys clauses r pat fender exp mod)
(call-with-values
(lambda () (convert-pattern pat keys (lambda (e) (ellipsis? e r mod))))
(lambda (p pvars)
(cond
((not (and-map (lambda (x) (not (ellipsis? (car x) r mod))) pvars))
(syntax-violation 'syntax-case "misplaced ellipsis" pat))
((not (distinct-bound-ids? (map car pvars)))
(syntax-violation 'syntax-case "duplicate pattern variable" pat))
(else
(let ((y (gen-var 'tmp)))
;; fat finger binding and references to temp variable y
(build-application no-source
(build-simple-lambda no-source (list 'tmp) #f (list y) '()
(let ((y (build-lexical-reference 'value no-source
'tmp y)))
(build-conditional no-source
(syntax-case fender ()
(#t y)
(_ (build-conditional no-source
y
(build-dispatch-call pvars fender y r mod)
(build-data no-source #f))))
(build-dispatch-call pvars exp y r mod)
(gen-syntax-case x keys clauses r mod))))
(list (if (eq? p 'any)
(build-application no-source
(build-primref no-source 'list)
(list x))
(build-application no-source
(build-primref no-source '$sc-dispatch)
(list x (build-data no-source p)))))))))))))
(define gen-syntax-case
(lambda (x keys clauses r mod)
(if (null? clauses)
(build-application no-source
(build-primref no-source 'syntax-violation)
(list (build-data no-source #f)
(build-data no-source
"source expression failed to match any pattern")
x))
(syntax-case (car clauses) ()
((pat exp)
(if (and (id? #'pat)
(and-map (lambda (x) (not (free-id=? #'pat x)))
(cons #'(... ...) keys)))
(if (free-id=? #'pat #'_)
(expand #'exp r empty-wrap mod)
(let ((labels (list (gen-label)))
(var (gen-var #'pat)))
(build-application no-source
(build-simple-lambda
no-source (list (syntax->datum #'pat)) #f (list var)
'()
(expand #'exp
(extend-env labels
(list (make-binding 'syntax `(,var . 0)))
r)
(make-binding-wrap #'(pat)
labels empty-wrap)
mod))
(list x))))
(gen-clause x keys (cdr clauses) r
#'pat #t #'exp mod)))
((pat fender exp)
(gen-clause x keys (cdr clauses) r
#'pat #'fender #'exp mod))
(_ (syntax-violation 'syntax-case "invalid clause"
(car clauses)))))))
(lambda (e r w s mod)
(let ((e (source-wrap e w s mod)))
(syntax-case e ()
((_ val (key ...) m ...)
(if (and-map (lambda (x) (and (id? x) (not (ellipsis? x r mod))))
#'(key ...))
(let ((x (gen-var 'tmp)))
;; fat finger binding and references to temp variable x
(build-application s
(build-simple-lambda no-source (list 'tmp) #f (list x) '()
(gen-syntax-case (build-lexical-reference 'value no-source
'tmp x)
#'(key ...) #'(m ...)
r
mod))
(list (expand #'val r empty-wrap mod))))
(syntax-violation 'syntax-case "invalid literals list" e))))))))
;; The portable macroexpand seeds expand-top's mode m with 'e (for
;; evaluating) and esew (which stands for "eval syntax expanders
;; when") with '(eval). In Chez Scheme, m is set to 'c instead of e
;; if we are compiling a file, and esew is set to
;; (eval-syntactic-expanders-when), which defaults to the list
;; '(compile load eval). This means that, by default, top-level
;; syntactic definitions are evaluated immediately after they are
;; expanded, and the expanded definitions are also residualized into
;; the object file if we are compiling a file.
(set! macroexpand
(lambda* (x #\optional (m 'e) (esew '(eval)))
(expand-top-sequence (list x) null-env top-wrap #f m esew
(cons 'hygiene (module-name (current-module))))))
(set! identifier?
(lambda (x)
(nonsymbol-id? x)))
(set! datum->syntax
(lambda (id datum)
(make-syntax-object datum (syntax-object-wrap id)
(syntax-object-module id))))
(set! syntax->datum
;; accepts any object, since syntax objects may consist partially
;; or entirely of unwrapped, nonsymbolic data
(lambda (x)
(strip x empty-wrap)))
(set! syntax-source
(lambda (x) (source-annotation x)))
(set! generate-temporaries
(lambda (ls)
(arg-check list? ls 'generate-temporaries)
(let ((mod (cons 'hygiene (module-name (current-module)))))
(map (lambda (x)
(wrap (module-gensym "t") top-wrap mod))
ls))))
(set! free-identifier=?
(lambda (x y)
(arg-check nonsymbol-id? x 'free-identifier=?)
(arg-check nonsymbol-id? y 'free-identifier=?)
(free-id=? x y)))
(set! bound-identifier=?
(lambda (x y)
(arg-check nonsymbol-id? x 'bound-identifier=?)
(arg-check nonsymbol-id? y 'bound-identifier=?)
(bound-id=? x y)))
(set! syntax-violation
(lambda* (who message form #\optional subform)
(arg-check (lambda (x) (or (not x) (string? x) (symbol? x)))
who 'syntax-violation)
(arg-check string? message 'syntax-violation)
(throw 'syntax-error who message
(or (source-annotation subform)
(source-annotation form))
(strip form empty-wrap)
(and subform (strip subform empty-wrap)))))
(let ()
(define (syntax-module id)
(arg-check nonsymbol-id? id 'syntax-module)
(cdr (syntax-object-module id)))
(define (syntax-local-binding id)
(arg-check nonsymbol-id? id 'syntax-local-binding)
(with-transformer-environment
(lambda (e r w s rib mod)
(define (strip-anti-mark w)
(let ((ms (wrap-marks w)) (s (wrap-subst w)))
(if (and (pair? ms) (eq? (car ms) the-anti-mark))
;; output is from original text
(make-wrap (cdr ms) (if rib (cons rib (cdr s)) (cdr s)))
;; output introduced by macro
(make-wrap ms (if rib (cons rib s) s)))))
(call-with-values (lambda ()
(resolve-identifier
(syntax-object-expression id)
(strip-anti-mark (syntax-object-wrap id))
r
(syntax-object-module id)))
(lambda (type value mod)
(case type
((lexical) (values 'lexical value))
((macro) (values 'macro value))
((syntax) (values 'pattern-variable value))
((displaced-lexical) (values 'displaced-lexical #f))
((global) (values 'global (cons value (cdr mod))))
((ellipsis)
(values 'ellipsis
(make-syntax-object (syntax-object-expression value)
(anti-mark (syntax-object-wrap value))
(syntax-object-module value))))
(else (values 'other #f))))))))
(define (syntax-locally-bound-identifiers id)
(arg-check nonsymbol-id? id 'syntax-locally-bound-identifiers)
(locally-bound-identifiers (syntax-object-wrap id)
(syntax-object-module id)))
;; Using define! instead of set! to avoid warnings at
;; compile-time, after the variables are stolen away into (system
;; syntax). See the end of boot-9.scm.
;;
(define! 'syntax-module syntax-module)
(define! 'syntax-local-binding syntax-local-binding)
(define! 'syntax-locally-bound-identifiers syntax-locally-bound-identifiers))
;; $sc-dispatch expects an expression and a pattern. If the expression
;; matches the pattern a list of the matching expressions for each
;; "any" is returned. Otherwise, #f is returned. (This use of #f will
;; not work on r4rs implementations that violate the ieee requirement
;; that #f and () be distinct.)
;; The expression is matched with the pattern as follows:
;; pattern: matches:
;; () empty list
;; any anything
;; (<pattern>1 . <pattern>2) (<pattern>1 . <pattern>2)
;; each-any (any*)
;; #(free-id <key>) <key> with free-identifier=?
;; #(each <pattern>) (<pattern>*)
;; #(each+ p1 (p2_1 ... p2_n) p3) (p1* (p2_n ... p2_1) . p3)
;; #(vector <pattern>) (list->vector <pattern>)
;; #(atom <object>) <object> with "equal?"
;; Vector cops out to pair under assumption that vectors are rare. If
;; not, should convert to:
;; #(vector <pattern>*) #(<pattern>*)
(let ()
(define match-each
(lambda (e p w mod)
(cond
((pair? e)
(let ((first (match (car e) p w '() mod)))
(and first
(let ((rest (match-each (cdr e) p w mod)))
(and rest (cons first rest))))))
((null? e) '())
((syntax-object? e)
(match-each (syntax-object-expression e)
p
(join-wraps w (syntax-object-wrap e))
(syntax-object-module e)))
(else #f))))
(define match-each+
(lambda (e x-pat y-pat z-pat w r mod)
(let f ((e e) (w w))
(cond
((pair? e)
(call-with-values (lambda () (f (cdr e) w))
(lambda (xr* y-pat r)
(if r
(if (null? y-pat)
(let ((xr (match (car e) x-pat w '() mod)))
(if xr
(values (cons xr xr*) y-pat r)
(values #f #f #f)))
(values
'()
(cdr y-pat)
(match (car e) (car y-pat) w r mod)))
(values #f #f #f)))))
((syntax-object? e)
(f (syntax-object-expression e)
(join-wraps w (syntax-object-wrap e))))
(else
(values '() y-pat (match e z-pat w r mod)))))))
(define match-each-any
(lambda (e w mod)
(cond
((pair? e)
(let ((l (match-each-any (cdr e) w mod)))
(and l (cons (wrap (car e) w mod) l))))
((null? e) '())
((syntax-object? e)
(match-each-any (syntax-object-expression e)
(join-wraps w (syntax-object-wrap e))
mod))
(else #f))))
(define match-empty
(lambda (p r)
(cond
((null? p) r)
((eq? p '_) r)
((eq? p 'any) (cons '() r))
((pair? p) (match-empty (car p) (match-empty (cdr p) r)))
((eq? p 'each-any) (cons '() r))
(else
(case (vector-ref p 0)
((each) (match-empty (vector-ref p 1) r))
((each+) (match-empty (vector-ref p 1)
(match-empty
(reverse (vector-ref p 2))
(match-empty (vector-ref p 3) r))))
((free-id atom) r)
((vector) (match-empty (vector-ref p 1) r)))))))
(define combine
(lambda (r* r)
(if (null? (car r*))
r
(cons (map car r*) (combine (map cdr r*) r)))))
(define match*
(lambda (e p w r mod)
(cond
((null? p) (and (null? e) r))
((pair? p)
(and (pair? e) (match (car e) (car p) w
(match (cdr e) (cdr p) w r mod)
mod)))
((eq? p 'each-any)
(let ((l (match-each-any e w mod))) (and l (cons l r))))
(else
(case (vector-ref p 0)
((each)
(if (null? e)
(match-empty (vector-ref p 1) r)
(let ((l (match-each e (vector-ref p 1) w mod)))
(and l
(let collect ((l l))
(if (null? (car l))
r
(cons (map car l) (collect (map cdr l)))))))))
((each+)
(call-with-values
(lambda ()
(match-each+ e (vector-ref p 1) (vector-ref p 2) (vector-ref p 3) w r mod))
(lambda (xr* y-pat r)
(and r
(null? y-pat)
(if (null? xr*)
(match-empty (vector-ref p 1) r)
(combine xr* r))))))
((free-id) (and (id? e) (free-id=? (wrap e w mod) (vector-ref p 1)) r))
((atom) (and (equal? (vector-ref p 1) (strip e w)) r))
((vector)
(and (vector? e)
(match (vector->list e) (vector-ref p 1) w r mod))))))))
(define match
(lambda (e p w r mod)
(cond
((not r) #f)
((eq? p '_) r)
((eq? p 'any) (cons (wrap e w mod) r))
((syntax-object? e)
(match*
(syntax-object-expression e)
p
(join-wraps w (syntax-object-wrap e))
r
(syntax-object-module e)))
(else (match* e p w r mod)))))
(set! $sc-dispatch
(lambda (e p)
(cond
((eq? p 'any) (list e))
((eq? p '_) '())
((syntax-object? e)
(match* (syntax-object-expression e)
p (syntax-object-wrap e) '() (syntax-object-module e)))
(else (match* e p empty-wrap '() #f))))))))
(define-syntax with-syntax
(lambda (x)
(syntax-case x ()
((_ () e1 e2 ...)
#'(let () e1 e2 ...))
((_ ((out in)) e1 e2 ...)
#'(syntax-case in ()
(out (let () e1 e2 ...))))
((_ ((out in) ...) e1 e2 ...)
#'(syntax-case (list in ...) ()
((out ...) (let () e1 e2 ...)))))))
(define-syntax syntax-error
(lambda (x)
(syntax-case x ()
;; Extended internal syntax which provides the original form
;; as the first operand, for improved error reporting.
((_ (keyword . operands) message arg ...)
(string? (syntax->datum #'message))
(syntax-violation (syntax->datum #'keyword)
(string-join (cons (syntax->datum #'message)
(map (lambda (x)
(object->string
(syntax->datum x)))
#'(arg ...))))
(and (syntax->datum #'keyword)
#'(keyword . operands))))
;; Standard R7RS syntax
((_ message arg ...)
(string? (syntax->datum #'message))
#'(syntax-error (#f) message arg ...)))))
(define-syntax syntax-rules
(lambda (xx)
(define (expand-clause clause)
;; Convert a 'syntax-rules' clause into a 'syntax-case' clause.
(syntax-case clause (syntax-error)
;; If the template is a 'syntax-error' form, use the extended
;; internal syntax, which adds the original form as the first
;; operand for improved error reporting.
(((keyword . pattern) (syntax-error message arg ...))
(string? (syntax->datum #'message))
#'((dummy . pattern) #'(syntax-error (dummy . pattern) message arg ...)))
;; Normal case
(((keyword . pattern) template)
#'((dummy . pattern) #'template))))
(define (expand-syntax-rules dots keys docstrings clauses)
(with-syntax
(((k ...) keys)
((docstring ...) docstrings)
((((keyword . pattern) template) ...) clauses)
((clause ...) (map expand-clause clauses)))
(with-syntax
((form #'(lambda (x)
docstring ... ; optional docstring
#((macro-type . syntax-rules)
(patterns pattern ...)) ; embed patterns as procedure metadata
(syntax-case x (k ...)
clause ...))))
(if dots
(with-syntax ((dots dots))
#'(with-ellipsis dots form))
#'form))))
(syntax-case xx ()
((_ (k ...) ((keyword . pattern) template) ...)
(expand-syntax-rules #f #'(k ...) #'() #'(((keyword . pattern) template) ...)))
((_ (k ...) docstring ((keyword . pattern) template) ...)
(string? (syntax->datum #'docstring))
(expand-syntax-rules #f #'(k ...) #'(docstring) #'(((keyword . pattern) template) ...)))
((_ dots (k ...) ((keyword . pattern) template) ...)
(identifier? #'dots)
(expand-syntax-rules #'dots #'(k ...) #'() #'(((keyword . pattern) template) ...)))
((_ dots (k ...) docstring ((keyword . pattern) template) ...)
(and (identifier? #'dots) (string? (syntax->datum #'docstring)))
(expand-syntax-rules #'dots #'(k ...) #'(docstring) #'(((keyword . pattern) template) ...))))))
(define-syntax define-syntax-rule
(lambda (x)
(syntax-case x ()
((_ (name . pattern) template)
#'(define-syntax name
(syntax-rules ()
((_ . pattern) template))))
((_ (name . pattern) docstring template)
(string? (syntax->datum #'docstring))
#'(define-syntax name
(syntax-rules ()
docstring
((_ . pattern) template)))))))
(define-syntax let*
(lambda (x)
(syntax-case x ()
((let* ((x v) ...) e1 e2 ...)
(and-map identifier? #'(x ...))
(let f ((bindings #'((x v) ...)))
(if (null? bindings)
#'(let () e1 e2 ...)
(with-syntax ((body (f (cdr bindings)))
(binding (car bindings)))
#'(let (binding) body))))))))
(define-syntax quasiquote
(let ()
(define (quasi p lev)
(syntax-case p (unquote quasiquote)
((unquote p)
(if (= lev 0)
#'("value" p)
(quasicons #'("quote" unquote) (quasi #'(p) (- lev 1)))))
((quasiquote p) (quasicons #'("quote" quasiquote) (quasi #'(p) (+ lev 1))))
((p . q)
(syntax-case #'p (unquote unquote-splicing)
((unquote p ...)
(if (= lev 0)
(quasilist* #'(("value" p) ...) (quasi #'q lev))
(quasicons
(quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
(quasi #'q lev))))
((unquote-splicing p ...)
(if (= lev 0)
(quasiappend #'(("value" p) ...) (quasi #'q lev))
(quasicons
(quasicons #'("quote" unquote-splicing) (quasi #'(p ...) (- lev 1)))
(quasi #'q lev))))
(_ (quasicons (quasi #'p lev) (quasi #'q lev)))))
(#(x ...) (quasivector (vquasi #'(x ...) lev)))
(p #'("quote" p))))
(define (vquasi p lev)
(syntax-case p ()
((p . q)
(syntax-case #'p (unquote unquote-splicing)
((unquote p ...)
(if (= lev 0)
(quasilist* #'(("value" p) ...) (vquasi #'q lev))
(quasicons
(quasicons #'("quote" unquote) (quasi #'(p ...) (- lev 1)))
(vquasi #'q lev))))
((unquote-splicing p ...)
(if (= lev 0)
(quasiappend #'(("value" p) ...) (vquasi #'q lev))
(quasicons
(quasicons
#'("quote" unquote-splicing)
(quasi #'(p ...) (- lev 1)))
(vquasi #'q lev))))
(_ (quasicons (quasi #'p lev) (vquasi #'q lev)))))
(() #'("quote" ()))))
(define (quasicons x y)
(with-syntax ((x x) (y y))
(syntax-case #'y ()
(("quote" dy)
(syntax-case #'x ()
(("quote" dx) #'("quote" (dx . dy)))
(_ (if (null? #'dy) #'("list" x) #'("list*" x y)))))
(("list" . stuff) #'("list" x . stuff))
(("list*" . stuff) #'("list*" x . stuff))
(_ #'("list*" x y)))))
(define (quasiappend x y)
(syntax-case y ()
(("quote" ())
(cond
((null? x) #'("quote" ()))
((null? (cdr x)) (car x))
(else (with-syntax (((p ...) x)) #'("append" p ...)))))
(_
(cond
((null? x) y)
(else (with-syntax (((p ...) x) (y y)) #'("append" p ... y)))))))
(define (quasilist* x y)
(let f ((x x))
(if (null? x)
y
(quasicons (car x) (f (cdr x))))))
(define (quasivector x)
(syntax-case x ()
(("quote" (x ...)) #'("quote" #(x ...)))
(_
(let f ((y x) (k (lambda (ls) #`("vector" #,@ls))))
(syntax-case y ()
(("quote" (y ...)) (k #'(("quote" y) ...)))
(("list" y ...) (k #'(y ...)))
(("list*" y ... z) (f #'z (lambda (ls) (k (append #'(y ...) ls)))))
(else #`("list->vector" #,x)))))))
(define (emit x)
(syntax-case x ()
(("quote" x) #''x)
(("list" x ...) #`(list #,@(map emit #'(x ...))))
;; could emit list* for 3+ arguments if implementation supports
;; list*
(("list*" x ... y)
(let f ((x* #'(x ...)))
(if (null? x*)
(emit #'y)
#`(cons #,(emit (car x*)) #,(f (cdr x*))))))
(("append" x ...) #`(append #,@(map emit #'(x ...))))
(("vector" x ...) #`(vector #,@(map emit #'(x ...))))
(("list->vector" x) #`(list->vector #,(emit #'x)))
(("value" x) #'x)))
(lambda (x)
(syntax-case x ()
;; convert to intermediate language, combining introduced (but
;; not unquoted source) quote expressions where possible and
;; choosing optimal construction code otherwise, then emit
;; Scheme code corresponding to the intermediate language forms.
((_ e) (emit (quasi #'e 0)))))))
(define-syntax include
(lambda (x)
(define read-file
(lambda (fn dir k)
(let* ((p (open-input-file
(cond ((absolute-file-name? fn)
fn)
(dir
(in-vicinity dir fn))
(else
(syntax-violation
'include
"relative file name only allowed when the include form is in a file"
x)))))
(enc (file-encoding p)))
;; Choose the input encoding deterministically.
(set-port-encoding! p (or enc "UTF-8"))
(let f ((x (read p))
(result '()))
(if (eof-object? x)
(begin
(close-input-port p)
(reverse result))
(f (read p)
(cons (datum->syntax k x) result)))))))
(let* ((src (syntax-source x))
(file (and src (assq-ref src 'filename)))
(dir (and (string? file) (dirname file))))
(syntax-case x ()
((k filename)
(let ((fn (syntax->datum #'filename)))
(with-syntax (((exp ...) (read-file fn dir #'filename)))
#'(begin exp ...))))))))
(define-syntax include-from-path
(lambda (x)
(syntax-case x ()
((k filename)
(let ((fn (syntax->datum #'filename)))
(with-syntax ((fn (datum->syntax
#'filename
(or (%search-load-path fn)
(syntax-violation 'include-from-path
"file not found in path"
x #'filename)))))
#'(include fn)))))))
(define-syntax unquote
(lambda (x)
(syntax-violation 'unquote
"expression not valid outside of quasiquote"
x)))
(define-syntax unquote-splicing
(lambda (x)
(syntax-violation 'unquote-splicing
"expression not valid outside of quasiquote"
x)))
(define (make-variable-transformer proc)
(if (procedure? proc)
(let ((trans (lambda (x)
#((macro-type . variable-transformer))
(proc x))))
(set-procedure-property! trans 'variable-transformer #t)
trans)
(error "variable transformer not a procedure" proc)))
(define-syntax identifier-syntax
(lambda (xx)
(syntax-case xx (set!)
((_ e)
#'(lambda (x)
#((macro-type . identifier-syntax))
(syntax-case x ()
(id
(identifier? #'id)
#'e)
((_ x (... ...))
#'(e x (... ...))))))
((_ (id exp1) ((set! var val) exp2))
(and (identifier? #'id) (identifier? #'var))
#'(make-variable-transformer
(lambda (x)
#((macro-type . variable-transformer))
(syntax-case x (set!)
((set! var val) #'exp2)
((id x (... ...)) #'(exp1 x (... ...)))
(id (identifier? #'id) #'exp1))))))))
(define-syntax define*
(lambda (x)
(syntax-case x ()
((_ (id . args) b0 b1 ...)
#'(define id (lambda* args b0 b1 ...)))
((_ id val) (identifier? #'id)
#'(define id val)))))
;;;; q.scm --- Queues
;;;;
;;;; Copyright (C) 1995, 2001, 2004, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; Q: Based on the interface to
;;;
;;; "queue.scm" Queues/Stacks for Scheme
;;; Written by Andrew Wilcox (awilcox@astro.psu.edu) on April 1, 1992.
;;; {Q}
;;;
;;; A list is just a bunch of cons pairs that follows some constrains,
;;; right? Association lists are the same. Hash tables are just
;;; vectors and association lists. You can print them, read them,
;;; write them as constants, pun them off as other data structures
;;; etc. This is good. This is lisp. These structures are fast and
;;; compact and easy to manipulate arbitrarily because of their
;;; simple, regular structure and non-disjointedness (associations
;;; being lists and so forth).
;;;
;;; So I figured, queues should be the same -- just a "subtype" of cons-pair
;;; structures in general.
;;;
;;; A queue is a cons pair:
;;; ( <the-q> . <last-pair> )
;;;
;;; <the-q> is a list of things in the q. New elements go at the end
;;; of that list.
;;;
;;; <last-pair> is #f if the q is empty, and otherwise is the last
;;; pair of <the-q>.
;;;
;;; q's print nicely, but alas, they do not read well because the
;;; eq?-ness of <last-pair> and (last-pair <the-q>) is lost by read.
;;;
;;; All the functions that aren't explicitly defined to return
;;; something else (a queue element; a boolean value) return the queue
;;; object itself.
;;; Code:
(define-module (ice-9 q)
\:export (sync-q! make-q q? q-empty? q-empty-check q-front q-rear
q-remove! q-push! enq! q-pop! deq! q-length))
;;; sync-q!
;;; The procedure
;;;
;;; (sync-q! q)
;;;
;;; recomputes and resets the <last-pair> component of a queue.
;;;
(define (sync-q! q)
(set-cdr! q (if (pair? (car q)) (last-pair (car q))
#f))
q)
;;; make-q
;;; return a new q.
;;;
(define (make-q) (cons '() #f))
;;; q? obj
;;; Return true if obj is a Q.
;;; An object is a queue if it is equal? to '(() . #f)
;;; or it is a pair P with (list? (car P))
;;; and (eq? (cdr P) (last-pair (car P))).
;;;
(define (q? obj)
(and (pair? obj)
(if (pair? (car obj))
(eq? (cdr obj) (last-pair (car obj)))
(and (null? (car obj))
(not (cdr obj))))))
;;; q-empty? obj
;;;
(define (q-empty? obj) (null? (car obj)))
;;; q-empty-check q
;;; Throw a q-empty exception if Q is empty.
(define (q-empty-check q) (if (q-empty? q) (throw 'q-empty q)))
;;; q-front q
;;; Return the first element of Q.
(define (q-front q) (q-empty-check q) (caar q))
;;; q-rear q
;;; Return the last element of Q.
(define (q-rear q) (q-empty-check q) (cadr q))
;;; q-remove! q obj
;;; Remove all occurences of obj from Q.
(define (q-remove! q obj)
(set-car! q (delq! obj (car q)))
(sync-q! q))
;;; q-push! q obj
;;; Add obj to the front of Q
(define (q-push! q obj)
(let ((h (cons obj (car q))))
(set-car! q h)
(or (cdr q) (set-cdr! q h)))
q)
;;; enq! q obj
;;; Add obj to the rear of Q
(define (enq! q obj)
(let ((h (cons obj '())))
(if (null? (car q))
(set-car! q h)
(set-cdr! (cdr q) h))
(set-cdr! q h))
q)
;;; q-pop! q
;;; Take the front of Q and return it.
(define (q-pop! q)
(q-empty-check q)
(let ((it (caar q))
(next (cdar q)))
(if (null? next)
(set-cdr! q #f))
(set-car! q next)
it))
;;; deq! q
;;; Take the front of Q and return it.
(define deq! q-pop!)
;;; q-length q
;;; Return the number of enqueued elements.
;;;
(define (q-length q) (length (car q)))
;;; q.scm ends here
;; Quasisyntax in terms of syntax-case.
;;
;; Code taken from
;; <http://www.het.brown.edu/people/andre/macros/index.html>;
;; Copyright (c) 2006 Andre van Tonder. All Rights Reserved.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;=========================================================
;;
;; To make nested unquote-splicing behave in a useful way,
;; the R5RS-compatible extension of quasiquote in appendix B
;; of the following paper is here ported to quasisyntax:
;;
;; Alan Bawden - Quasiquotation in Lisp
;; http://citeseer.ist.psu.edu/bawden99quasiquotation.html
;;
;; The algorithm converts a quasisyntax expression to an
;; equivalent with-syntax expression.
;; For example:
;;
;; (quasisyntax (set! #,a #,b))
;; ==> (with-syntax ((t0 a)
;; (t1 b))
;; (syntax (set! t0 t1)))
;;
;; (quasisyntax (list #,@args))
;; ==> (with-syntax (((t ...) args))
;; (syntax (list t ...)))
;;
;; Note that quasisyntax is expanded first, before any
;; ellipses act. For example:
;;
;; (quasisyntax (f ((b #,a) ...))
;; ==> (with-syntax ((t a))
;; (syntax (f ((b t) ...))))
;;
;; so that
;;
;; (let-syntax ((test-ellipses-over-unsyntax
;; (lambda (e)
;; (let ((a (syntax a)))
;; (with-syntax (((b ...) (syntax (1 2 3))))
;; (quasisyntax
;; (quote ((b #,a) ...))))))))
;; (test-ellipses-over-unsyntax))
;;
;; ==> ((1 a) (2 a) (3 a))
(define-syntax quasisyntax
(lambda (e)
;; Expand returns a list of the form
;; [template[t/e, ...] (replacement ...)]
;; Here template[t/e ...] denotes the original template
;; with unquoted expressions e replaced by fresh
;; variables t, followed by the appropriate ellipses
;; if e is also spliced.
;; The second part of the return value is the list of
;; replacements, each of the form (t e) if e is just
;; unquoted, or ((t ...) e) if e is also spliced.
;; This will be the list of bindings of the resulting
;; with-syntax expression.
(define (expand x level)
(syntax-case x (quasisyntax unsyntax unsyntax-splicing)
((quasisyntax e)
(with-syntax (((k _) x) ;; original identifier must be copied
((e* reps) (expand (syntax e) (+ level 1))))
(syntax ((k e*) reps))))
((unsyntax e)
(= level 0)
(with-syntax (((t) (generate-temporaries '(t))))
(syntax (t ((t e))))))
(((unsyntax e ...) . r)
(= level 0)
(with-syntax (((r* (rep ...)) (expand (syntax r) 0))
((t ...) (generate-temporaries (syntax (e ...)))))
(syntax ((t ... . r*)
((t e) ... rep ...)))))
(((unsyntax-splicing e ...) . r)
(= level 0)
(with-syntax (((r* (rep ...)) (expand (syntax r) 0))
((t ...) (generate-temporaries (syntax (e ...)))))
(with-syntax ((((t ...) ...) (syntax ((t (... ...)) ...))))
(syntax ((t ... ... . r*)
(((t ...) e) ... rep ...))))))
((k . r)
(and (> level 0)
(identifier? (syntax k))
(or (free-identifier=? (syntax k) (syntax unsyntax))
(free-identifier=? (syntax k) (syntax unsyntax-splicing))))
(with-syntax (((r* reps) (expand (syntax r) (- level 1))))
(syntax ((k . r*) reps))))
((h . t)
(with-syntax (((h* (rep1 ...)) (expand (syntax h) level))
((t* (rep2 ...)) (expand (syntax t) level)))
(syntax ((h* . t*)
(rep1 ... rep2 ...)))))
(#(e ...)
(with-syntax ((((e* ...) reps)
(expand (vector->list (syntax #(e ...))) level)))
(syntax (#(e* ...) reps))))
(other
(syntax (other ())))))
(syntax-case e ()
((_ template)
(with-syntax (((template* replacements) (expand (syntax template) 0)))
(syntax
(with-syntax replacements (syntax template*))))))))
(define-syntax unsyntax
(lambda (e)
(syntax-violation 'unsyntax "Invalid expression" e)))
(define-syntax unsyntax-splicing
(lambda (e)
(syntax-violation 'unsyntax "Invalid expression" e)))
;;;; r4rs.scm --- definitions needed for libguile to be R4RS compliant
;;;; Jim Blandy <jimb@cyclic.com> --- October 1996
;;;; Copyright (C) 1996, 1997, 1998, 2000, 2001, 2006, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(eval-when (compile)
(set-current-module (resolve-module '(guile))))
;;;; apply and call-with-current-continuation
;;; The deal with these is that they are the procedural wrappers around the
;;; primitives of Guile's language. There are about 20 different kinds of
;;; expression in Guile, and e.g. @apply is one of them. (It has to be that way
;;; to preserve tail recursion.)
;;;
;;; Usually we recognize (apply foo bar) to be an instance of @apply, but in the
;;; case that apply is passed to apply, or we're bootstrapping, we need a
;;; trampoline -- and here they are.
(define (apply fun . args)
(@apply fun (apply:nconc2last args)))
(define (call-with-current-continuation proc)
(@call-with-current-continuation proc))
(define (call-with-values producer consumer)
(@call-with-values producer consumer))
(define (dynamic-wind in thunk out)
"All three arguments must be 0-argument procedures.
Guard @var{in} is called, then @var{thunk}, then
guard @var{out}.
If, any time during the execution of @var{thunk}, the
continuation of the @code{dynamic_wind} expression is escaped
non-locally, @var{out} is called. If the continuation of
the dynamic-wind is re-entered, @var{in} is called. Thus
@var{in} and @var{out} may be called any number of
times.
@lisp
(define x 'normal-binding)
@result{} x
(define a-cont
(call-with-current-continuation
(lambda (escape)
(let ((old-x x))
(dynamic-wind
;; in-guard:
;;
(lambda () (set! x 'special-binding))
;; thunk
;;
(lambda () (display x) (newline)
(call-with-current-continuation escape)
(display x) (newline)
x)
;; out-guard:
;;
(lambda () (set! x old-x)))))))
;; Prints:
special-binding
;; Evaluates to:
@result{} a-cont
x
@result{} normal-binding
(a-cont #f)
;; Prints:
special-binding
;; Evaluates to:
@result{} a-cont ;; the value of the (define a-cont...)
x
@result{} normal-binding
a-cont
@result{} special-binding
@end lisp"
(@dynamic-wind in (thunk) out))
;;;; Basic Port Code
;;; Specifically, the parts of the low-level port code that are written in
;;; Scheme rather than C.
;;;
;;; WARNING: the parts of this interface that refer to file ports
;;; are going away. It would be gone already except that it is used
;;; "internally" in a few places.
;;; OPEN_READ, OPEN_WRITE, and OPEN_BOTH are used to request the
;;; proper mode to open files in.
;;;
;;; If we want to support systems that do CRLF->LF translation, like
;;; Windows, then we should have a symbol in scmconfig.h made visible
;;; to the Scheme level that we can test here, and autoconf magic to
;;; #define it when appropriate. Windows will probably just have a
;;; hand-generated scmconfig.h file.
(define OPEN_READ "r")
(define OPEN_WRITE "w")
(define OPEN_BOTH "r+")
(define *null-device* "/dev/null")
(define (open-input-file str)
"Takes a string naming an existing file and returns an input port
capable of delivering characters from the file. If the file
cannot be opened, an error is signalled."
(open-file str OPEN_READ))
(define (open-output-file str)
"Takes a string naming an output file to be created and returns an
output port capable of writing characters to a new file by that
name. If the file cannot be opened, an error is signalled. If a
file with the given name already exists, the effect is unspecified."
(open-file str OPEN_WRITE))
(define (open-io-file str)
"Open file with name STR for both input and output."
(open-file str OPEN_BOTH))
(define (call-with-input-file str proc)
"PROC should be a procedure of one argument, and STR should be a
string naming a file. The file must
already exist. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-input-file str)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-input-port p)
(apply values vals)))))
(define (call-with-output-file str proc)
"PROC should be a procedure of one argument, and STR should be a
string naming a file. The behaviour is unspecified if the file
already exists. These procedures call PROC
with one argument: the port obtained by opening the named file for
input or output. If the file cannot be opened, an error is
signalled. If the procedure returns, then the port is closed
automatically and the values yielded by the procedure are returned.
If the procedure does not return, then the port will not be closed
automatically unless it is possible to prove that the port will
never again be used for a read or write operation."
(let ((p (open-output-file str)))
(call-with-values
(lambda () (proc p))
(lambda vals
(close-output-port p)
(apply values vals)))))
(define (with-input-from-port port thunk)
(let* ((swaports (lambda () (set! port (set-current-input-port port)))))
(dynamic-wind swaports thunk swaports)))
(define (with-output-to-port port thunk)
(let* ((swaports (lambda () (set! port (set-current-output-port port)))))
(dynamic-wind swaports thunk swaports)))
(define (with-error-to-port port thunk)
(let* ((swaports (lambda () (set! port (set-current-error-port port)))))
(dynamic-wind swaports thunk swaports)))
(define (with-input-from-file file thunk)
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The file must already exist. The file is opened for
input, an input port connected to it is made
the default value returned by `current-input-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-input-file file
(lambda (p) (with-input-from-port p thunk))))
(define (with-output-to-file file thunk)
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-output-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-output-to-port p thunk))))
(define (with-error-to-file file thunk)
"THUNK must be a procedure of no arguments, and FILE must be a
string naming a file. The effect is unspecified if the file already exists.
The file is opened for output, an output port connected to it is made
the default value returned by `current-error-port',
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed and the previous
default is restored. Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-output-file file
(lambda (p) (with-error-to-port p thunk))))
(define (with-input-from-string string thunk)
"THUNK must be a procedure of no arguments.
The test of STRING is opened for
input, an input port connected to it is made,
and the THUNK is called with no arguments.
When the THUNK returns, the port is closed.
Returns the values yielded by THUNK. If an
escape procedure is used to escape from the continuation of these
procedures, their behavior is implementation dependent."
(call-with-input-string string
(lambda (p) (with-input-from-port p thunk))))
(define (with-output-to-string thunk)
"Calls THUNK and returns its output as a string."
(call-with-output-string
(lambda (p) (with-output-to-port p thunk))))
(define (with-error-to-string thunk)
"Calls THUNK and returns its error output as a string."
(call-with-output-string
(lambda (p) (with-error-to-port p thunk))))
(define the-eof-object (call-with-input-string "" (lambda (p) (read-char p))))
;;;; Copyright (C) 2000, 2001, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; R5RS bindings
(define-module (ice-9 r5rs)
\:export (scheme-report-environment
;;transcript-on
;;transcript-off
)
\:re-export (interaction-environment
call-with-input-file call-with-output-file
with-input-from-file with-output-to-file
open-input-file open-output-file
close-input-port close-output-port
load))
(module-use! (module-public-interface (current-module))
(resolve-interface '(ice-9 safe-r5rs)))
(define scheme-report-interface (module-public-interface (current-module)))
(define (scheme-report-environment n)
(if (not (= n 5))
(scm-error 'misc-error 'scheme-report-environment
"~A is not a valid version"
(list n)
'()))
scheme-report-interface)
;;; r6rs-libraries.scm --- Support for the R6RS `library' and `import' forms
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;; This file is included from boot-9.scm and assumes the existence of (and
;; expands into) procedures and syntactic forms defined therein.
(define (resolve-r6rs-interface import-spec)
(define (make-custom-interface mod)
(let ((iface (make-module)))
(set-module-kind! iface 'custom-interface)
(set-module-name! iface (module-name mod))
iface))
(define (sym? x) (symbol? (syntax->datum x)))
(syntax-case import-spec (library only except prefix rename srfi)
;; (srfi n ...) -> (srfi srfi-n ...)
((library (srfi colon-n rest ... (version ...)))
(and (and-map sym? #'(srfi rest ...))
(symbol? (syntax->datum #'colon-n))
(eqv? (string-ref (symbol->string (syntax->datum #'colon-n)) 0) #\:))
(let ((srfi-n (string->symbol
(string-append
"srfi-"
(substring (symbol->string (syntax->datum #'colon-n))
1)))))
(resolve-r6rs-interface
(syntax-case #'(rest ...) ()
(()
#`(library (srfi #,srfi-n (version ...))))
((name rest ...)
;; SRFI 97 says that the first identifier after the colon-n
;; is used for the libraries name, so it must be ignored.
#`(library (srfi #,srfi-n rest ... (version ...))))))))
((library (name name* ... (version ...)))
(and-map sym? #'(name name* ...))
(resolve-interface (syntax->datum #'(name name* ...))
#\version (syntax->datum #'(version ...))))
((library (name name* ...))
(and-map sym? #'(name name* ...))
(resolve-r6rs-interface #'(library (name name* ... ()))))
((only import-set identifier ...)
(and-map sym? #'(identifier ...))
(let* ((mod (resolve-r6rs-interface #'import-set))
(iface (make-custom-interface mod)))
(for-each (lambda (sym)
(module-add! iface sym
(or (module-local-variable mod sym)
(error "no binding `~A' in module ~A"
sym mod))))
(syntax->datum #'(identifier ...)))
iface))
((except import-set identifier ...)
(and-map sym? #'(identifier ...))
(let* ((mod (resolve-r6rs-interface #'import-set))
(iface (make-custom-interface mod)))
(module-for-each (lambda (sym var) (module-add! iface sym var)) mod)
(for-each (lambda (sym)
(if (module-local-variable iface sym)
(module-remove! iface sym)
(error "no binding `~A' in module ~A" sym mod)))
(syntax->datum #'(identifier ...)))
iface))
((prefix import-set identifier)
(sym? #'identifier)
(let* ((mod (resolve-r6rs-interface #'import-set))
(iface (make-custom-interface mod))
(pre (syntax->datum #'identifier)))
(module-for-each (lambda (sym var)
(module-add! iface (symbol-append pre sym) var))
mod)
iface))
((rename import-set (from to) ...)
(and (and-map sym? #'(from ...)) (and-map sym? #'(to ...)))
(let* ((mod (resolve-r6rs-interface #'import-set))
(iface (make-custom-interface mod)))
(module-for-each (lambda (sym var) (module-add! iface sym var)) mod)
(let lp ((in (syntax->datum #'((from . to) ...))) (out '()))
(cond
((null? in)
(for-each
(lambda (pair)
(if (module-local-variable iface (car pair))
(error "duplicate binding for `~A' in module ~A"
(car pair) mod)
(module-add! iface (car pair) (cdr pair))))
out)
iface)
(else
(let ((var (or (module-local-variable mod (caar in))
(error "no binding `~A' in module ~A"
(caar in) mod))))
(module-remove! iface (caar in))
(lp (cdr in) (acons (cdar in) var out))))))))
((name name* ... (version ...))
(and-map sym? #'(name name* ...))
(resolve-r6rs-interface #'(library (name name* ... (version ...)))))
((name name* ...)
(and-map sym? #'(name name* ...))
(resolve-r6rs-interface #'(library (name name* ... ()))))))
(define-syntax library
(lambda (stx)
(define (compute-exports ifaces specs)
(define (re-export? sym)
(or-map (lambda (iface) (module-local-variable iface sym)) ifaces))
(define (replace? sym)
(module-local-variable the-scm-module sym))
(let lp ((specs specs) (e '()) (r '()) (x '()))
(syntax-case specs (rename)
(() (values e r x))
(((rename (from to) ...) . rest)
(and (and-map identifier? #'(from ...))
(and-map identifier? #'(to ...)))
(let lp2 ((in #'((from . to) ...)) (e e) (r r) (x x))
(syntax-case in ()
(() (lp #'rest e r x))
(((from . to) . in)
(cond
((re-export? (syntax->datum #'from))
(lp2 #'in e (cons #'(from . to) r) x))
((replace? (syntax->datum #'from))
(lp2 #'in e r (cons #'(from . to) x)))
(else
(lp2 #'in (cons #'(from . to) e) r x)))))))
((id . rest)
(identifier? #'id)
(let ((sym (syntax->datum #'id)))
(cond
((re-export? sym)
(lp #'rest e (cons #'id r) x))
((replace? sym)
(lp #'rest e r (cons #'id x)))
(else
(lp #'rest (cons #'id e) r x))))))))
(syntax-case stx (export import)
((_ (name name* ...)
(export espec ...)
(import ispec ...)
body ...)
(and-map identifier? #'(name name* ...))
;; Add () as the version.
#'(library (name name* ... ())
(export espec ...)
(import ispec ...)
body ...))
((_ (name name* ... (version ...))
(export espec ...)
(import ispec ...)
body ...)
(and-map identifier? #'(name name* ...))
(call-with-values
(lambda ()
(compute-exports
(map (lambda (im)
(syntax-case im (for)
((for import-set import-level ...)
(resolve-r6rs-interface #'import-set))
(import-set (resolve-r6rs-interface #'import-set))))
#'(ispec ...))
#'(espec ...)))
(lambda (exports re-exports replacements)
(with-syntax (((e ...) exports)
((r ...) re-exports)
((x ...) replacements))
;; It would be nice to push the module that was current before the
;; definition, and pop it after the library definition, but I
;; actually can't see a way to do that. Helper procedures perhaps,
;; around a fluid that is rebound in save-module-excursion? Patches
;; welcome!
#'(begin
(define-module (name name* ...)
#\pure
#\version (version ...))
(import ispec)
...
(export e ...)
(re-export r ...)
(export! x ...)
(@@ @@ (name name* ...) body)
...))))))))
(define-syntax import
(lambda (stx)
(define (strip-for import-set)
(syntax-case import-set (for)
((for import-set import-level ...)
#'import-set)
(import-set
#'import-set)))
(syntax-case stx ()
((_ import-set ...)
(with-syntax (((library-reference ...) (map strip-for #'(import-set ...))))
#'(eval-when (expand load eval)
(let ((iface (resolve-r6rs-interface 'library-reference)))
(call-with-deferred-observers
(lambda ()
(module-use-interfaces! (current-module) (list iface)))))
...
(if #f #f)))))))
;;; installed-scm-file
;;;; Copyright (C) 1997, 1999, 2000, 2001, 2006, 2010, 2013,
;;;; 2014 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; This is the Scheme part of the module for delimited I/O. It's
;;; similar to (scsh rdelim) but somewhat incompatible.
(define-module (ice-9 rdelim)
#\export (read-line
read-line!
read-delimited
read-delimited!
read-string
read-string!
%read-delimited!
%read-line
write-line))
(%init-rdelim-builtins)
(define* (read-line! string #\optional (port current-input-port))
;; corresponds to SCM_LINE_INCREMENTORS in libguile.
(define scm-line-incrementors "\n")
(let* ((rv (%read-delimited! scm-line-incrementors
string
#t
port))
(terminator (car rv))
(nchars (cdr rv)))
(cond ((and (= nchars 0)
(eof-object? terminator))
terminator)
((not terminator) #f)
(else nchars))))
(define* (read-delimited! delims buf #\optional
(port (current-input-port)) (handle-delim 'trim)
(start 0) (end (string-length buf)))
(let* ((rv (%read-delimited! delims
buf
(not (eq? handle-delim 'peek))
port
start
end))
(terminator (car rv))
(nchars (cdr rv)))
(cond ((or (not terminator) ; buffer filled
(eof-object? terminator))
(if (zero? nchars)
(if (eq? handle-delim 'split)
(cons terminator terminator)
terminator)
(if (eq? handle-delim 'split)
(cons nchars terminator)
nchars)))
(else
(case handle-delim
((trim peek) nchars)
((concat) (string-set! buf (+ nchars start) terminator)
(+ nchars 1))
((split) (cons nchars terminator))
(else (error "unexpected handle-delim value: "
handle-delim)))))))
(define* (read-delimited delims #\optional (port (current-input-port))
(handle-delim 'trim))
(let loop ((substrings '())
(total-chars 0)
(buf-size 100)) ; doubled each time through.
(let* ((buf (make-string buf-size))
(rv (%read-delimited! delims
buf
(not (eq? handle-delim 'peek))
port))
(terminator (car rv))
(nchars (cdr rv))
(new-total (+ total-chars nchars)))
(cond
((not terminator)
;; buffer filled.
(loop (cons (substring buf 0 nchars) substrings)
new-total
(* buf-size 2)))
((and (eof-object? terminator) (zero? new-total))
(if (eq? handle-delim 'split)
(cons terminator terminator)
terminator))
(else
(let ((joined
(string-concatenate-reverse
(cons (substring buf 0 nchars) substrings))))
(case handle-delim
((concat)
(if (eof-object? terminator)
joined
(string-append joined (string terminator))))
((trim peek) joined)
((split) (cons joined terminator))
(else (error "unexpected handle-delim value: "
handle-delim)))))))))
(define-syntax-rule (check-arg exp message arg ...)
(unless exp
(error message arg ...)))
(define (index? n)
(and (integer? n) (exact? n) (>= n 0)))
(define* (read-string! buf #\optional
(port (current-input-port))
(start 0) (end (string-length buf)))
"Read all of the characters out of PORT and write them to BUF.
Returns the number of characters read.
This function only reads out characters from PORT if it will be able to
write them to BUF. That is to say, if BUF is smaller than the number of
available characters, then BUF will be filled, and characters will be
left in the port."
(check-arg (string? buf) "not a string" buf)
(check-arg (index? start) "bad index" start)
(check-arg (index? end) "bad index" end)
(check-arg (<= start end) "start beyond end" start end)
(check-arg (<= end (string-length buf)) "end beyond string length" end)
(let lp ((n start))
(if (< n end)
(let ((c (read-char port)))
(if (eof-object? c)
(- n start)
(begin
(string-set! buf n c)
(lp (1+ n)))))
(- n start))))
(define* read-string
(case-lambda*
"Read all of the characters out of PORT and return them as a string.
If the COUNT argument is present, treat it as a limit to the number of
characters to read. By default, there is no limit."
((#\optional (port (current-input-port)))
;; Fast path.
;; This creates more garbage than using 'string-set!' as in
;; 'read-string!', but currently that is faster nonetheless.
(let loop ((chars '()))
(let ((char (read-char port)))
(if (eof-object? char)
(list->string (reverse! chars))
(loop (cons char chars))))))
((port count)
;; Slower path.
(let loop ((chars '())
(total 0))
(let ((char (read-char port)))
(if (or (eof-object? char) (>= total count))
(list->string (reverse chars))
(loop (cons char chars) (+ 1 total))))))))
;;; read-line [PORT [HANDLE-DELIM]] reads a newline-terminated string
;;; from PORT. The return value depends on the value of HANDLE-DELIM,
;;; which may be one of the symbols `trim', `concat', `peek' and
;;; `split'. If it is `trim' (the default), the trailing newline is
;;; removed and the string is returned. If `concat', the string is
;;; returned with the trailing newline intact. If `peek', the newline
;;; is left in the input port buffer and the string is returned. If
;;; `split', the newline is split from the string and read-line
;;; returns a pair consisting of the truncated string and the newline.
(define* (read-line #\optional (port (current-input-port))
(handle-delim 'trim))
(let* ((line/delim (%read-line port))
(line (car line/delim))
(delim (cdr line/delim)))
(case handle-delim
((trim) line)
((split) line/delim)
((concat) (if (and (string? line) (char? delim))
(string-append line (string delim))
line))
((peek) (if (char? delim)
(unread-char delim port))
line)
(else
(error "unexpected handle-delim value: " handle-delim)))))
;;;; SRFI-8
;;; Copyright (C) 2000, 2001, 2004, 2006, 2010, 2011 Free Software Foundation, Inc.
;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 receive)
#\export (receive))
(define-syntax-rule (receive vars vals . body)
(call-with-values (lambda () vals)
(lambda vars . body)))
(cond-expand-provide (current-module) '(srfi-8))
;;;; Copyright (C) 1997, 1999, 2001, 2004, 2005, 2006, 2008, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; These procedures are exported:
;; (match:count match)
;; (match:string match)
;; (match:prefix match)
;; (match:suffix match)
;; (regexp-match? match)
;; (regexp-quote string)
;; (match:start match . submatch-num)
;; (match:end match . submatch-num)
;; (match:substring match . submatch-num)
;; (string-match pattern str . start)
;; (regexp-substitute port match . items)
;; (fold-matches regexp string init proc . flags)
;; (list-matches regexp string . flags)
;; (regexp-substitute/global port regexp string . items)
;;; Code:
;;;; POSIX regex support functions.
(define-module (ice-9 regex)
#\export (match:count match:string match:prefix match:suffix
regexp-match? regexp-quote match:start match:end match:substring
string-match regexp-substitute fold-matches list-matches
regexp-substitute/global))
;; References:
;;
;; POSIX spec:
;; http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap09.html
;;; FIXME:
;;; It is not clear what should happen if a `match' function
;;; is passed a `match number' which is out of bounds for the
;;; regexp match: return #f, or throw an error? These routines
;;; throw an out-of-range error.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; These procedures are not defined in SCSH, but I found them useful.
(define (match:count match)
(- (vector-length match) 1))
(define (match:string match)
(vector-ref match 0))
(define (match:prefix match)
(substring (match:string match) 0 (match:start match 0)))
(define (match:suffix match)
(substring (match:string match) (match:end match 0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; SCSH compatibility routines.
(define (regexp-match? match)
(and (vector? match)
(string? (vector-ref match 0))
(let loop ((i 1))
(cond ((>= i (vector-length match)) #t)
((and (pair? (vector-ref match i))
(integer? (car (vector-ref match i)))
(integer? (cdr (vector-ref match i))))
(loop (+ 1 i)))
(else #f)))))
;; * . \ ^ $ and [ are special in both regexp/basic and regexp/extended and
;; can be backslash escaped.
;;
;; ( ) + ? { } and | are special in regexp/extended so must be quoted. But
;; that can't be done with a backslash since in regexp/basic where they're
;; not special, adding a backslash makes them become special. Character
;; class forms [(] etc are used instead.
;;
;; ) is not special when not preceded by a (, and * and ? are not special at
;; the start of a string, but we quote all of these always, so the result
;; can be concatenated or merged into some larger regexp.
;;
;; ] is not special outside a [ ] character class, so doesn't need to be
;; quoted.
;;
(define (regexp-quote string)
(call-with-output-string
(lambda (p)
(string-for-each (lambda (c)
(case c
((#\* #\. #\\ #\^ #\$ #\[)
(write-char #\\ p)
(write-char c p))
((#\( #\) #\+ #\? #\{ #\} #\|)
(write-char #\[ p)
(write-char c p)
(write-char #\] p))
(else
(write-char c p))))
string))))
(define* (match:start match #\optional (n 0))
(let ((start (car (vector-ref match (1+ n)))))
(if (= start -1) #f start)))
(define* (match:end match #\optional (n 0))
(let* ((end (cdr (vector-ref match (1+ n)))))
(if (= end -1) #f end)))
(define* (match:substring match #\optional (n 0))
(let* ((start (match:start match n))
(end (match:end match n)))
(and start end (substring (match:string match) start end))))
(define (string-match pattern str . args)
(let ((rx (make-regexp pattern))
(start (if (pair? args) (car args) 0)))
(regexp-exec rx str start)))
(define (regexp-substitute port match . items)
;; If `port' is #f, send output to a string.
(if (not port)
(call-with-output-string
(lambda (p)
(apply regexp-substitute p match items)))
;; Otherwise, process each substitution argument in `items'.
(for-each (lambda (obj)
(cond ((string? obj) (display obj port))
((integer? obj) (display (match:substring match obj) port))
((eq? 'pre obj) (display (match:prefix match) port))
((eq? 'post obj) (display (match:suffix match) port))
(else (error 'wrong-type-arg obj))))
items)))
;;; If we call fold-matches, below, with a regexp that can match the
;;; empty string, it's not obvious what "all the matches" means. How
;;; many empty strings are there in the string "a"? Our answer:
;;;
;;; This function applies PROC to every non-overlapping, maximal
;;; match of REGEXP in STRING.
;;;
;;; "non-overlapping": There are two non-overlapping matches of "" in
;;; "a" --- one before the `a', and one after. There are three
;;; non-overlapping matches of "q|x*" in "aqb": the empty strings
;;; before `a' and after `b', and `q'. The two empty strings before
;;; and after `q' don't count, because they overlap with the match of
;;; "q".
;;;
;;; "maximal": There are three distinct maximal matches of "x*" in
;;; "axxxb": one before the `a', one covering `xxx', and one after the
;;; `b'. Around or within `xxx', only the match covering all three
;;; x's counts, because the rest are not maximal.
(define* (fold-matches regexp string init proc #\optional (flags 0))
(let ((regexp (if (regexp? regexp) regexp (make-regexp regexp))))
(let loop ((start 0)
(value init)
(abuts #f)) ; True if start abuts a previous match.
(define bol (if (zero? start) 0 regexp/notbol))
(let ((m (if (> start (string-length string)) #f
(regexp-exec regexp string start (logior flags bol)))))
(cond
((not m) value)
((and (= (match:start m) (match:end m)) abuts)
;; We matched an empty string, but that would overlap the
;; match immediately before. Try again at a position
;; further to the right.
(loop (+ start 1) value #f))
(else
(loop (match:end m) (proc m value) #t)))))))
(define* (list-matches regexp string #\optional (flags 0))
(reverse! (fold-matches regexp string '() cons flags)))
(define (regexp-substitute/global port regexp string . items)
;; If `port' is #f, send output to a string.
(if (not port)
(call-with-output-string
(lambda (p)
(apply regexp-substitute/global p regexp string items)))
;; Walk the set of non-overlapping, maximal matches.
(let next-match ((matches (list-matches regexp string))
(start 0))
(if (null? matches)
(display (substring string start) port)
(let ((m (car matches)))
;; Process all of the items for this match. Don't use
;; for-each, because we need to make sure 'post at the
;; end of the item list is a tail call.
(let next-item ((items items))
(define (do-item item)
(cond
((string? item) (display item port))
((integer? item) (display (match:substring m item) port))
((procedure? item) (display (item m) port))
((eq? item 'pre)
(display
(substring string start (match:start m))
port))
((eq? item 'post)
(next-match (cdr matches) (match:end m)))
(else (error 'wrong-type-arg item))))
(if (pair? items)
(if (null? (cdr items))
(do-item (car items)) ; This is a tail call.
(begin
(do-item (car items)) ; This is not.
(next-item (cdr items)))))))))))
;;;; runq.scm --- the runq data structure
;;;;
;;;; Copyright (C) 1996, 2001, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; One way to schedule parallel computations in a serial environment is
;;; to explicitly divide each task up into small, finite execution time,
;;; strips. Then you interleave the execution of strips from various
;;; tasks to achieve a kind of parallelism. Runqs are a handy data
;;; structure for this style of programming.
;;;
;;; We use thunks (nullary procedures) and lists of thunks to represent
;;; strips. By convention, the return value of a strip-thunk must either
;;; be another strip or the value #f.
;;;
;;; A runq is a procedure that manages a queue of strips. Called with no
;;; arguments, it processes one strip from the queue. Called with
;;; arguments, the arguments form a control message for the queue. The
;;; first argument is a symbol which is the message selector.
;;;
;;; A strip is processed this way: If the strip is a thunk, the thunk is
;;; called -- if it returns a strip, that strip is added back to the
;;; queue. To process a strip which is a list of thunks, the CAR of that
;;; list is called. After a call to that CAR, there are 0, 1, or 2 strips
;;; -- perhaps one returned by the thunk, and perhaps the CDR of the
;;; original strip if that CDR is not nil. The runq puts whichever of
;;; these strips exist back on the queue. (The exact order in which
;;; strips are put back on the queue determines the scheduling behavior of
;;; a particular queue -- it's a parameter.)
;;; Code:
(define-module (ice-9 runq)
\:use-module (ice-9 q)
\:export (runq-control make-void-runq make-fair-runq
make-exclusive-runq make-subordinate-runq-to strip-sequence
fair-strip-subtask))
;;;;
;;; (runq-control q msg . args)
;;;
;;; processes in the default way the control messages that
;;; can be sent to a runq. Q should be an ordinary
;;; Q (see utils/q.scm).
;;;
;;; The standard runq messages are:
;;;
;;; 'add! strip0 strip1... ;; to enqueue one or more strips
;;; 'enqueue! strip0 strip1... ;; to enqueue one or more strips
;;; 'push! strip0 ... ;; add strips to the front of the queue
;;; 'empty? ;; true if it is
;;; 'length ;; how many strips in the queue?
;;; 'kill! ;; empty the queue
;;; else ;; throw 'not-understood
;;;
(define (runq-control q msg . args)
(case msg
((add!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
((enqueue!) (for-each (lambda (t) (enq! q t)) args) '*unspecified*)
((push!) (for-each (lambda (t) (q-push! q t)) args) '*unspecified*)
((empty?) (q-empty? q))
((length) (q-length q))
((kill!) (set! q (make-q)))
(else (throw 'not-understood msg args))))
(define (run-strip thunk) (catch #t thunk (lambda ign (warn 'runq-strip thunk ign) #f)))
;;;;
;;; make-void-runq
;;;
;;; Make a runq that discards all messages except "length", for which
;;; it returns 0.
;;;
(define (make-void-runq)
(lambda opts
(and opts
(apply-to-args opts
(lambda (msg . args)
(case msg
((length) 0)
(else #f)))))))
;;;;
;;; (make-fair-runq)
;;;
;;; Returns a runq procedure.
;;; Called with no arguments, the procedure processes one strip from the queue.
;;; Called with arguments, it uses runq-control.
;;;
;;; In a fair runq, if a strip returns a new strip X, X is added
;;; to the end of the queue, meaning it will be the last to execute
;;; of all the remaining procedures.
;;;
(define (make-fair-runq)
(letrec ((q (make-q))
(self
(lambda ctl
(if ctl
(apply runq-control q ctl)
(and (not (q-empty? q))
(let ((next-strip (deq! q)))
(cond
((procedure? next-strip) (let ((k (run-strip next-strip)))
(and k (enq! q k))))
((pair? next-strip) (let ((k (run-strip (car next-strip))))
(and k (enq! q k)))
(if (not (null? (cdr next-strip)))
(enq! q (cdr next-strip)))))
self))))))
self))
;;;;
;;; (make-exclusive-runq)
;;;
;;; Returns a runq procedure.
;;; Called with no arguments, the procedure processes one strip from the queue.
;;; Called with arguments, it uses runq-control.
;;;
;;; In an exclusive runq, if a strip W returns a new strip X, X is added
;;; to the front of the queue, meaning it will be the next to execute
;;; of all the remaining procedures.
;;;
;;; An exception to this occurs if W was the CAR of a list of strips.
;;; In that case, after the return value of W is pushed onto the front
;;; of the queue, the CDR of the list of strips is pushed in front
;;; of that (if the CDR is not nil). This way, the rest of the thunks
;;; in the list that contained W have priority over the return value of W.
;;;
(define (make-exclusive-runq)
(letrec ((q (make-q))
(self
(lambda ctl
(if ctl
(apply runq-control q ctl)
(and (not (q-empty? q))
(let ((next-strip (deq! q)))
(cond
((procedure? next-strip) (let ((k (run-strip next-strip)))
(and k (q-push! q k))))
((pair? next-strip) (let ((k (run-strip (car next-strip))))
(and k (q-push! q k)))
(if (not (null? (cdr next-strip)))
(q-push! q (cdr next-strip)))))
self))))))
self))
;;;;
;;; (make-subordinate-runq-to superior basic-inferior)
;;;
;;; Returns a runq proxy for the runq basic-inferior.
;;;
;;; The proxy watches for operations on the basic-inferior that cause
;;; a transition from a queue length of 0 to a non-zero length and
;;; vice versa. While the basic-inferior queue is not empty,
;;; the proxy installs a task on the superior runq. Each strip
;;; of that task processes N strips from the basic-inferior where
;;; N is the length of the basic-inferior queue when the proxy
;;; strip is entered. [Countless scheduling variations are possible.]
;;;
(define (make-subordinate-runq-to superior-runq basic-runq)
(let ((runq-task (cons #f #f)))
(set-car! runq-task
(lambda ()
(if (basic-runq 'empty?)
(set-cdr! runq-task #f)
(do ((n (basic-runq 'length) (1- n)))
((<= n 0) #f)
(basic-runq)))))
(letrec ((self
(lambda ctl
(if (not ctl)
(let ((answer (basic-runq)))
(self 'empty?)
answer)
(begin
(case (car ctl)
((suspend) (set-cdr! runq-task #f))
(else (let ((answer (apply basic-runq ctl)))
(if (and (not (cdr runq-task)) (not (basic-runq 'empty?)))
(begin
(set-cdr! runq-task runq-task)
(superior-runq 'add! runq-task)))
answer))))))))
self)))
;;;;
;;; (define fork-strips (lambda args args))
;;; Return a strip that starts several strips in
;;; parallel. If this strip is enqueued on a fair
;;; runq, strips of the parallel subtasks will run
;;; round-robin style.
;;;
;;;;
;;; (strip-sequence . strips)
;;;
;;; Returns a new strip which is the concatenation of the argument strips.
;;;
(define (strip-sequence . strips)
(lambda ()
(let loop ((st (let ((a strips)) (set! strips #f) a)))
(and (not (null? st))
(let ((then ((car st))))
(if then
(lambda () (loop (cons then (cdr st))))
(lambda () (loop (cdr st)))))))))
;;;;
;;; (fair-strip-subtask . initial-strips)
;;;
;;; Returns a new strip which is the synchronos, fair,
;;; parallel execution of the argument strips.
;;;
;;;
;;;
(define (fair-strip-subtask . initial-strips)
(let ((st (make-fair-runq)))
(apply st 'add! initial-strips)
st))
;;; runq.scm ends here
;;; installed-scm-file
;;;; Copyright (C) 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; This is the Scheme part of (ice-9 rw), which is a subset of
;;; (scsh rw).
(define-module (ice-9 rw)
\:export (read-string!/partial write-string/partial))
(%init-rw-builtins)
;;;; Copyright (C) 2000, 2001, 2004, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; Safe subset of R5RS bindings
(define-module (ice-9 safe-r5rs)
\:re-export (eqv? eq? equal?
number? complex? real? rational? integer?
exact? inexact?
= < > <= >=
zero? positive? negative? odd? even?
max min
+ * - /
abs
quotient remainder modulo
gcd lcm
numerator denominator
rationalize
floor ceiling truncate round
exp log sin cos tan asin acos atan
sqrt
expt
make-rectangular make-polar real-part imag-part magnitude angle
exact->inexact inexact->exact
number->string string->number
boolean?
not
pair?
cons car cdr
set-car! set-cdr!
caar cadr cdar cddr
caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
null?
list?
list
length
append
reverse
list-tail list-ref
memq memv member
assq assv assoc
symbol?
symbol->string string->symbol
char?
char=? char<? char>? char<=? char>=?
char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=?
char-alphabetic? char-numeric? char-whitespace?
char-upper-case? char-lower-case?
char->integer integer->char
char-upcase
char-downcase
string?
make-string
string
string-length
string-ref string-set!
string=? string-ci=?
string<? string>? string<=? string>=?
string-ci<? string-ci>? string-ci<=? string-ci>=?
substring
string-length
string-append
string->list list->string
string-copy string-fill!
vector?
make-vector
vector
vector-length
vector-ref vector-set!
vector->list list->vector
vector-fill!
procedure?
apply
map
for-each
force
call-with-current-continuation
values
call-with-values
dynamic-wind
eval
input-port? output-port?
current-input-port current-output-port
read
read-char
peek-char
eof-object?
char-ready?
write
display
newline
write-char
;;transcript-on
;;transcript-off
)
\:export (null-environment))
(define null-interface (resolve-interface '(ice-9 null)))
(module-use! (module-public-interface (current-module))
null-interface)
(define (null-environment n)
(if (not (= n 5))
(scm-error 'misc-error 'null-environment
"~A is not a valid version"
(list n)
'()))
;; Note that we need to create a *fresh* interface
(let ((interface (make-module 31)))
(set-module-kind! interface 'interface)
(module-use! interface null-interface)
interface))
;;;; Copyright (C) 2000, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; Safe subset of R5RS bindings
(define-module (ice-9 safe)
\:export (safe-environment make-safe-module))
(define safe-r5rs-interface (resolve-interface '(ice-9 safe-r5rs)))
(define (safe-environment n)
(if (not (= n 5))
(scm-error 'misc-error 'safe-environment
"~A is not a valid version"
(list n)
'()))
safe-r5rs-interface)
(define (make-safe-module)
(make-module 1021 (list safe-r5rs-interface)))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
;;;; Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;; An older approack to debugging, in which the user installs a pre-unwind
;;; handler that saves the stack at the time of the error. The last stack can
;;; then be debugged later.
;;;
;;; Code:
(define-module (ice-9 save-stack)
;; Replace deprecated root-module bindings, if present.
#\replace (stack-saved?
the-last-stack
save-stack))
;; FIXME: stack-saved? is broken in the presence of threads.
(define stack-saved? #f)
(define the-last-stack (make-fluid))
(define (save-stack . narrowing)
(if (not stack-saved?)
(begin
(let ((stacks (fluid-ref %stacks)))
(fluid-set! the-last-stack
;; (make-stack obj inner outer inner outer ...)
;;
;; In this case, cut away the make-stack frame, the
;; save-stack frame, and then narrow as specified by the
;; user, delimited by the nearest start-stack invocation,
;; if any.
(apply make-stack #t
2
(if (pair? stacks) (cdar stacks) 0)
narrowing)))
(set! stack-saved? #t))))
;;;; Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010
;;;; Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 scm-style-repl)
#\use-module (ice-9 save-stack)
#\export (scm-repl-silent
scm-repl-print-unspecified
scm-repl-verbose
scm-repl-prompt)
;; #\replace, as with deprecated code enabled these will be in the root env
#\replace (assert-repl-silence
assert-repl-print-unspecified
assert-repl-verbosity
default-pre-unwind-handler
bad-throw
error-catching-loop
error-catching-repl
scm-style-repl
handle-system-error))
(define scm-repl-silent #f)
(define (assert-repl-silence v) (set! scm-repl-silent v))
(define scm-repl-print-unspecified #f)
(define (assert-repl-print-unspecified v) (set! scm-repl-print-unspecified v))
(define scm-repl-verbose #f)
(define (assert-repl-verbosity v) (set! scm-repl-verbose v))
(define scm-repl-prompt "guile> ")
;; bad-throw is the hook that is called upon a throw to a an unhandled
;; key (unless the throw has four arguments, in which case
;; it's usually interpreted as an error throw.)
;; If the key has a default handler (a throw-handler-default property),
;; it is applied to the throw.
;;
(define (bad-throw key . args)
(let ((default (symbol-property key 'throw-handler-default)))
(or (and default (apply default key args))
(apply error "unhandled-exception:" key args))))
(define (default-pre-unwind-handler key . args)
;; Narrow by two more frames: this one, and the throw handler.
(save-stack 2)
(apply throw key args))
(define has-shown-debugger-hint? #f)
(define (error-catching-loop thunk)
(let ((status #f)
(interactive #t))
(define (loop first)
(let ((next
(catch #t
(lambda ()
(call-with-unblocked-asyncs
(lambda ()
(first)
;; This line is needed because mark
;; doesn't do closures quite right.
;; Unreferenced locals should be
;; collected.
(set! first #f)
(let loop ((v (thunk)))
(loop (thunk)))
#f)))
(lambda (key . args)
(case key
((quit)
(set! status args)
#f)
((switch-repl)
(apply throw 'switch-repl args))
((abort)
;; This is one of the closures that require
;; (set! first #f) above
;;
(lambda ()
(run-hook abort-hook)
(force-output (current-output-port))
(display "ABORT: " (current-error-port))
(write args (current-error-port))
(newline (current-error-port))
(if interactive
(begin
(if (and
(not has-shown-debugger-hint?)
(not (memq 'backtrace
(debug-options-interface)))
(stack? (fluid-ref the-last-stack)))
(begin
(newline (current-error-port))
(display
"Type \"(backtrace)\" to get more information or \"(debug)\" to enter the debugger.\n"
(current-error-port))
(set! has-shown-debugger-hint? #t)))
(force-output (current-error-port)))
(begin
(primitive-exit 1)))
(set! stack-saved? #f)))
(else
;; This is the other cons-leak closure...
(lambda ()
(cond ((= (length args) 4)
(apply handle-system-error key args))
(else
(apply bad-throw key args)))))))
default-pre-unwind-handler)))
(if next (loop next) status)))
(set! ensure-batch-mode! (lambda ()
(set! interactive #f)
(restore-signals)))
(set! batch-mode? (lambda () (not interactive)))
(call-with-blocked-asyncs
(lambda () (loop (lambda () #t))))))
(define (error-catching-repl r e p)
(error-catching-loop
(lambda ()
(call-with-values (lambda () (e (r)))
(lambda the-values (for-each p the-values))))))
(define (scm-style-repl)
(letrec (
(start-gc-rt #f)
(start-rt #f)
(repl-report-start-timing (lambda ()
(set! start-gc-rt (gc-run-time))
(set! start-rt (get-internal-run-time))))
(repl-report (lambda ()
(display ";;; ")
(display (inexact->exact
(* 1000 (/ (- (get-internal-run-time) start-rt)
internal-time-units-per-second))))
(display " msec (")
(display (inexact->exact
(* 1000 (/ (- (gc-run-time) start-gc-rt)
internal-time-units-per-second))))
(display " msec in gc)\n")))
(consume-trailing-whitespace
(lambda ()
(let ((ch (peek-char)))
(cond
((eof-object? ch))
((or (char=? ch #\space) (char=? ch #\tab))
(read-char)
(consume-trailing-whitespace))
((char=? ch #\newline)
(read-char))))))
(-read (lambda ()
(let ((val
(let ((prompt (cond ((string? scm-repl-prompt)
scm-repl-prompt)
((thunk? scm-repl-prompt)
(scm-repl-prompt))
(scm-repl-prompt "> ")
(else ""))))
(repl-reader prompt))))
;; As described in R4RS, the READ procedure updates the
;; port to point to the first character past the end of
;; the external representation of the object. This
;; means that it doesn't consume the newline typically
;; found after an expression. This means that, when
;; debugging Guile with GDB, GDB gets the newline, which
;; it often interprets as a "continue" command, making
;; breakpoints kind of useless. So, consume any
;; trailing newline here, as well as any whitespace
;; before it.
;; But not if EOF, for control-D.
(if (not (eof-object? val))
(consume-trailing-whitespace))
(run-hook after-read-hook)
(if (eof-object? val)
(begin
(repl-report-start-timing)
(if scm-repl-verbose
(begin
(newline)
(display ";;; EOF -- quitting")
(newline)))
(quit 0)))
val)))
(-eval (lambda (sourc)
(repl-report-start-timing)
(run-hook before-eval-hook sourc)
(let ((val (start-stack 'repl-stack
;; If you change this procedure
;; (primitive-eval), please also
;; modify the repl-stack case in
;; save-stack so that stack cutting
;; continues to work.
(primitive-eval sourc))))
(run-hook after-eval-hook sourc)
val)))
(-print (let ((maybe-print (lambda (result)
(if (or scm-repl-print-unspecified
(not (unspecified? result)))
(begin
(write result)
(newline))))))
(lambda (result)
(if (not scm-repl-silent)
(begin
(run-hook before-print-hook result)
(maybe-print result)
(run-hook after-print-hook result)
(if scm-repl-verbose
(repl-report))
(force-output))))))
(-quit (lambda (args)
(if scm-repl-verbose
(begin
(display ";;; QUIT executed, repl exitting")
(newline)
(repl-report)))
args)))
(let ((status (error-catching-repl -read
-eval
-print)))
(-quit status))))
(define (handle-system-error key . args)
(let ((cep (current-error-port)))
(cond ((not (stack? (fluid-ref the-last-stack))))
((memq 'backtrace (debug-options-interface))
(let ((highlights (if (or (eq? key 'wrong-type-arg)
(eq? key 'out-of-range))
(list-ref args 3)
'())))
(run-hook before-backtrace-hook)
(newline cep)
(display "Backtrace:\n")
(display-backtrace (fluid-ref the-last-stack) cep
#f #f highlights)
(newline cep)
(run-hook after-backtrace-hook))))
(run-hook before-error-hook)
(apply display-error (fluid-ref the-last-stack) cep args)
(run-hook after-error-hook)
(force-output cep)
(throw 'abort key)))
;;;; Copyright (C) 2003, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; (serialize FORM1 ...) and (parallelize FORM1 ...) are useful when
;; you don't trust the thread safety of most of your program, but
;; where you have some section(s) of code which you consider can run
;; in parallel to other sections.
;;
;; They "flag" (with dynamic extent) sections of code to be of
;; "serial" or "parallel" nature and have the single effect of
;; preventing a serial section from being run in parallel with any
;; serial section (including itself).
;;
;; Both serialize and parallelize can be nested. If so, the
;; inner-most construct is in effect.
;;
;; NOTE 1: A serial section can run in parallel with a parallel
;; section.
;;
;; NOTE 2: If a serial section S is "interrupted" by a parallel
;; section P in the following manner: S = S1 P S2, S2 is not
;; guaranteed to be resumed by the same thread that previously
;; executed S1.
;;
;; WARNING: Spawning new threads within a serial section have
;; undefined effects. It is OK, though, to spawn threads in unflagged
;; sections of code where neither serialize or parallelize is in
;; effect.
;;
;; A typical usage is when Guile is used as scripting language in some
;; application doing heavy computations. If each thread is
;; encapsulated with a serialize form, you can then put a parallelize
;; form around the code performing the heavy computations (typically a
;; C code primitive), enabling the computations to run in parallel
;; while the scripting code runs single-threadedly.
;;
;;; Code:
(define-module (ice-9 serialize)
\:use-module (ice-9 threads)
\:export (call-with-serialization
call-with-parallelization)
\:export-syntax (serialize
parallelize))
(define serialization-mutex (make-mutex))
(define admin-mutex (make-mutex))
(define owner #f)
(define (call-with-serialization thunk)
(let ((outer-owner #f))
(dynamic-wind
(lambda ()
(lock-mutex admin-mutex)
(set! outer-owner owner)
(if (not (eqv? outer-owner (dynamic-root)))
(begin
(unlock-mutex admin-mutex)
(lock-mutex serialization-mutex)
(set! owner (dynamic-root)))
(unlock-mutex admin-mutex)))
thunk
(lambda ()
(lock-mutex admin-mutex)
(if (not (eqv? outer-owner (dynamic-root)))
(begin
(set! owner #f)
(unlock-mutex serialization-mutex)))
(unlock-mutex admin-mutex)))))
(define-macro (serialize . forms)
`(call-with-serialization (lambda () ,@forms)))
(define (call-with-parallelization thunk)
(let ((outer-owner #f))
(dynamic-wind
(lambda ()
(lock-mutex admin-mutex)
(set! outer-owner owner)
(if (eqv? outer-owner (dynamic-root))
(begin
(set! owner #f)
(unlock-mutex serialization-mutex)))
(unlock-mutex admin-mutex))
thunk
(lambda ()
(lock-mutex admin-mutex)
(if (eqv? outer-owner (dynamic-root))
(begin
(unlock-mutex admin-mutex)
(lock-mutex serialization-mutex)
(set! owner outer-owner))
(unlock-mutex admin-mutex))))))
(define-macro (parallelize . forms)
`(call-with-parallelization (lambda () ,@forms)))
;;;; Copyright (C) 1997, 2000, 2001, 2003, 2006, 2009, 2010, 2011,
;;;; 2012 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 session)
#\use-module (ice-9 documentation)
#\use-module (ice-9 regex)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 match)
#\export (help
add-value-help-handler! remove-value-help-handler!
add-name-help-handler! remove-name-help-handler!
apropos-hook
apropos apropos-internal apropos-fold apropos-fold-accessible
apropos-fold-exported apropos-fold-all source arity
procedure-arguments
module-commentary))
(define *value-help-handlers*
`(,(lambda (name value)
(object-documentation value))))
(define (add-value-help-handler! proc)
"Adds a handler for performing `help' on a value.
`proc' will be called as (PROC NAME VALUE). `proc' should return #t to
indicate that it has performed help, a string to override the default
object documentation, or #f to try the other handlers, potentially
falling back on the normal behavior for `help'."
(set! *value-help-handlers* (cons proc *value-help-handlers*)))
(define (remove-value-help-handler! proc)
"Removes a handler for performing `help' on a value."
(set! *value-help-handlers* (delete! proc *value-help-handlers*)))
(define (try-value-help name value)
(or-map (lambda (proc) (proc name value)) *value-help-handlers*))
(define *name-help-handlers* '())
(define (add-name-help-handler! proc)
"Adds a handler for performing `help' on a name.
`proc' will be called with the unevaluated name as its argument. That is
to say, when the user calls `(help FOO)', the name is FOO, exactly as
the user types it.
`proc' should return #t to indicate that it has performed help, a string
to override the default object documentation, or #f to try the other
handlers, potentially falling back on the normal behavior for `help'."
(set! *name-help-handlers* (cons proc *name-help-handlers*)))
(define (remove-name-help-handler! proc)
"Removes a handler for performing `help' on a name."
(set! *name-help-handlers* (delete! proc *name-help-handlers*)))
(define (try-name-help name)
(or-map (lambda (proc) (proc name)) *name-help-handlers*))
;;; Documentation
;;;
(define-macro (help . exp)
"(help [NAME])
Prints useful information. Try `(help)'."
(cond ((not (= (length exp) 1))
(help-usage)
'(begin))
((not (provided? 'regex))
(display "`help' depends on the `regex' feature.
You don't seem to have regular expressions installed.\n")
'(begin))
(else
(let ((name (car exp))
(not-found (lambda (type x)
(simple-format #t "No ~A found for ~A\n"
type x))))
(cond
;; User-specified
((try-name-help name)
=> (lambda (x) (if (not (eq? x #t)) (display x))))
;; SYMBOL
((symbol? name)
(help-doc name
(simple-format
#f "^~A$"
(regexp-quote (symbol->string name)))))
;; "STRING"
((string? name)
(help-doc name name))
;; (unquote SYMBOL)
((and (list? name)
(= (length name) 2)
(eq? (car name) 'unquote))
(let ((doc (try-value-help (cadr name)
(module-ref (current-module)
(cadr name)))))
(cond ((not doc) (not-found 'documentation (cadr name)))
((eq? doc #t)) ;; pass
(else (write-line doc)))))
;; (quote SYMBOL)
((and (list? name)
(= (length name) 2)
(eq? (car name) 'quote)
(symbol? (cadr name)))
(cond ((search-documentation-files (cadr name))
=> write-line)
(else (not-found 'documentation (cadr name)))))
;; (SYM1 SYM2 ...)
((and (list? name)
(and-map symbol? name)
(not (null? name))
(not (eq? (car name) 'quote)))
(cond ((module-commentary name)
=> (lambda (doc)
(display name) (write-line " commentary:")
(write-line doc)))
(else (not-found 'commentary name))))
;; unrecognized
(else
(help-usage)))
'(begin)))))
(define (module-filename name) ; fixme: better way? / done elsewhere?
(let* ((name (map symbol->string name))
(reverse-name (reverse name))
(leaf (car reverse-name))
(dir-hint-module-name (reverse (cdr reverse-name)))
(dir-hint (apply string-append
(map (lambda (elt)
(string-append elt "/"))
dir-hint-module-name))))
(%search-load-path (in-vicinity dir-hint leaf))))
(define (module-commentary name)
(cond ((module-filename name) => file-commentary)
(else #f)))
(define (help-doc term regexp)
(let ((entries (apropos-fold (lambda (module name object data)
(cons (list module
name
(try-value-help name object)
(cond ((procedure? object)
"a procedure")
(else
"an object")))
data))
'()
regexp
apropos-fold-exported))
(module car)
(name cadr)
(doc caddr)
(type cadddr))
(cond ((not (null? entries))
(let ((first? #t)
(undocumented-entries '())
(documented-entries '())
(documentations '()))
(for-each (lambda (entry)
(let ((entry-summary (simple-format
#f "~S: ~S\n"
(module-name (module entry))
(name entry))))
(if (doc entry)
(begin
(set! documented-entries
(cons entry-summary documented-entries))
;; *fixme*: Use `describe' when we have GOOPS?
(set! documentations
(cons (simple-format
#f "`~S' is ~A in the ~S module.\n\n~A\n"
(name entry)
(type entry)
(module-name (module entry))
(doc entry))
documentations)))
(set! undocumented-entries
(cons entry-summary
undocumented-entries)))))
entries)
(if (and (not (null? documented-entries))
(or (> (length documented-entries) 1)
(not (null? undocumented-entries))))
(begin
(display "Documentation found for:\n")
(for-each (lambda (entry) (display entry))
documented-entries)
(set! first? #f)))
(for-each (lambda (entry)
(if first?
(set! first? #f)
(newline))
(display entry))
documentations)
(if (not (null? undocumented-entries))
(begin
(if first?
(set! first? #f)
(newline))
(display "No documentation found for:\n")
(for-each (lambda (entry) (display entry))
undocumented-entries)))))
((search-documentation-files term)
=> (lambda (doc)
(write-line "Documentation from file:")
(write-line doc)))
(else
;; no matches
(display "Did not find any object ")
(simple-format #t
(if (symbol? term)
"named `~A'\n"
"matching regexp \"~A\"\n")
term)))))
(define (help-usage)
(display "Usage: (help NAME) gives documentation about objects named NAME (a symbol)
(help REGEXP) ditto for objects with names matching REGEXP (a string)
(help 'NAME) gives documentation for NAME, even if it is not an object
(help ,EXPR) gives documentation for object returned by EXPR
(help (my module)) gives module commentary for `(my module)'
(help) gives this text
`help' searches among bindings exported from loaded modules, while
`apropos' searches among bindings visible from the \"current\" module.
Examples: (help help)
(help cons)
(help \"output-string\")
Other useful sources of helpful information:
(apropos STRING)
(arity PROCEDURE)
(name PROCEDURE-OR-MACRO)
(source PROCEDURE-OR-MACRO)
Tools:
(backtrace) ;show backtrace from last error
(debug) ;enter the debugger
(trace [PROCEDURE]) ;trace procedure (no arg => show)
(untrace [PROCEDURE]) ;untrace (no arg => untrace all)
(OPTIONSET-options 'full) ;display option information
(OPTIONSET-enable 'OPTION)
(OPTIONSET-disable 'OPTION)
(OPTIONSET-set! OPTION VALUE)
where OPTIONSET is one of debug, read, eval, print
"))
;;; {Apropos}
;;;
;;; Author: Roland Orre <orre@nada.kth.se>
;;;
;; Two arguments: the module, and the pattern, as a string.
;;
(define apropos-hook (make-hook 2))
(define (apropos rgx . options)
"Search for bindings: apropos regexp {options= 'full 'shadow 'value}"
(run-hook apropos-hook (current-module) rgx)
(if (zero? (string-length rgx))
"Empty string not allowed"
(let* ((match (make-regexp rgx))
(uses (module-uses (current-module)))
(modules (cons (current-module)
(if (and (not (null? uses))
(eq? (module-name (car uses))
'duplicates))
(cdr uses)
uses)))
(separator #\tab)
(shadow (member 'shadow options))
(value (member 'value options)))
(cond ((member 'full options)
(set! shadow #t)
(set! value #t)))
(for-each
(lambda (module)
(let* ((name (module-name module))
(obarray (module-obarray module)))
;; XXX - should use hash-fold here
(hash-for-each
(lambda (symbol variable)
(cond ((regexp-exec match (symbol->string symbol))
(display name)
(display ": ")
(display symbol)
(cond ((variable-bound? variable)
(let ((val (variable-ref variable)))
(cond ((or (procedure? val) value)
(display separator)
(display val)))))
(else
(display separator)
(display "(unbound)")))
(if (and shadow
(not (eq? (module-ref module symbol)
(module-ref (current-module) symbol))))
(display " shadowed"))
(newline))))
obarray)))
modules))))
(define (apropos-internal rgx)
"Return a list of accessible variable names."
(apropos-fold (lambda (module name var data)
(cons name data))
'()
rgx
(apropos-fold-accessible (current-module))))
(define (apropos-fold proc init rgx folder)
"Folds PROCEDURE over bindings matching third arg REGEXP.
Result is
(PROCEDURE MODULE1 NAME1 VALUE1
(PROCEDURE MODULE2 NAME2 VALUE2
...
(PROCEDURE MODULEn NAMEn VALUEn INIT)))
where INIT is the second arg to `apropos-fold'.
Fourth arg FOLDER is one of
(apropos-fold-accessible MODULE) ;fold over bindings accessible in MODULE
apropos-fold-exported ;fold over all exported bindings
apropos-fold-all ;fold over all bindings"
(run-hook apropos-hook (current-module) rgx)
(let ((match (make-regexp rgx))
(recorded (make-hash-table)))
(let ((fold-module
(lambda (module data)
(let* ((obarray-filter
(lambda (name val data)
(if (and (regexp-exec match (symbol->string name))
(not (hashq-get-handle recorded name)))
(begin
(hashq-set! recorded name #t)
(proc module name val data))
data)))
(module-filter
(lambda (name var data)
(if (variable-bound? var)
(obarray-filter name (variable-ref var) data)
data))))
(cond (module (hash-fold module-filter
data
(module-obarray module)))
(else data))))))
(folder fold-module init))))
(define (make-fold-modules init-thunk traverse extract)
"Return procedure capable of traversing a forest of modules.
The forest traversed is the image of the forest generated by root
modules returned by INIT-THUNK and the generator TRAVERSE.
It is an image under the mapping EXTRACT."
(lambda (fold-module init)
(let* ((table (make-hash-table 31))
(first? (lambda (obj)
(let* ((handle (hash-create-handle! table obj #t))
(first? (cdr handle)))
(set-cdr! handle #f)
first?))))
(let rec ((data init)
(modules (init-thunk)))
(do ((modules modules (cdr modules))
(data data (if (first? (car modules))
(rec (fold-module (extract (car modules)) data)
(traverse (car modules)))
data)))
((null? modules) data))))))
(define (apropos-fold-accessible module)
(make-fold-modules (lambda () (list module))
module-uses
identity))
(define (root-modules)
(submodules (resolve-module '() #f)))
(define (submodules mod)
(hash-map->list (lambda (k v) v) (module-submodules mod)))
(define apropos-fold-exported
(make-fold-modules root-modules submodules module-public-interface))
(define apropos-fold-all
(make-fold-modules root-modules submodules identity))
(define (source obj)
(cond ((procedure? obj) (procedure-source obj))
((macro? obj) (procedure-source (macro-transformer obj)))
(else #f)))
(define (arity obj)
(define (display-arg-list arg-list)
(display #\`)
(display (car arg-list))
(let loop ((ls (cdr arg-list)))
(cond ((null? ls)
(display #\'))
((not (pair? ls))
(display "', the rest in `")
(display ls)
(display #\'))
(else
(if (pair? (cdr ls))
(display "', `")
(display "' and `"))
(display (car ls))
(loop (cdr ls))))))
(define (display-arg-list/summary arg-list type)
(let ((len (length arg-list)))
(display len)
(display " ")
(display type)
(if (> len 1)
(display " arguments: ")
(display " argument: "))
(display-arg-list arg-list)))
(cond
((procedure-property obj 'arglist)
=> (lambda (arglist)
(let ((required-args (car arglist))
(optional-args (cadr arglist))
(keyword-args (caddr arglist))
(allow-other-keys? (cadddr arglist))
(rest-arg (car (cddddr arglist)))
(need-punctuation #f))
(cond ((not (null? required-args))
(display-arg-list/summary required-args "required")
(set! need-punctuation #t)))
(cond ((not (null? optional-args))
(if need-punctuation (display ", "))
(display-arg-list/summary optional-args "optional")
(set! need-punctuation #t)))
(cond ((not (null? keyword-args))
(if need-punctuation (display ", "))
(display-arg-list/summary keyword-args "keyword")
(set! need-punctuation #t)))
(cond (allow-other-keys?
(if need-punctuation (display ", "))
(display "other keywords allowed")
(set! need-punctuation #t)))
(cond (rest-arg
(if need-punctuation (display ", "))
(display "the rest in `")
(display rest-arg)
(display "'"))))))
(else
(let ((arity (procedure-minimum-arity obj)))
(display (car arity))
(cond ((caddr arity)
(display " or more"))
((not (zero? (cadr arity)))
(display " required and ")
(display (cadr arity))
(display " optional")))
(if (and (not (caddr arity))
(= (car arity) 1)
(<= (cadr arity) 1))
(display " argument")
(display " arguments")))))
(display ".\n"))
(define (procedure-arguments proc)
"Return an alist describing the arguments that `proc' accepts, or `#f'
if the information cannot be obtained.
The alist keys that are currently defined are `required', `optional',
`keyword', `allow-other-keys?', and `rest'."
(cond
((procedure-property proc 'arglist)
=> (match-lambda
((req opt keyword aok? rest)
`((required . ,(if (number? req)
(make-list req '_)
req))
(optional . ,(if (number? opt)
(make-list opt '_)
opt))
(keyword . ,keyword)
(allow-other-keys? . ,aok?)
(rest . ,rest)))))
((procedure-source proc)
=> cadr)
(((@ (system vm program) program?) proc)
((@ (system vm program) program-arguments-alist) proc))
(else #f)))
;;; session.scm ends here
;;;; slib.scm --- definitions needed to get SLIB to work with Guile
;;;;
;;;; Copyright (C) 1997, 1998, 2000, 2001, 2002, 2003, 2004, 2006, 2007, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Look for slib.init in the $datadir, in /usr/share, and finally in
;;; the load path. It's not usually in the load path on common distros,
;;; but it could be if the user put it there. The init file takes care
;;; of defining the module.
(let ((try-load (lambda (dir)
(let ((init (string-append dir "/slib/guile.init")))
(and (file-exists? init)
(begin
(load init)
#t))))))
(or (try-load (assq-ref %guile-build-info 'datadir))
(try-load "/usr/share")
(load-from-path "slib/guile.init")))
;;; installed-scm-file
;;;; Copyright (C) 2001, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 stack-catch)
#\use-module (ice-9 save-stack)
#\export (stack-catch))
(define (stack-catch key thunk handler)
"Like @code{catch}, invoke @var{thunk} in the dynamic context of
@var{handler} for exceptions matching @var{key}, but also save the
current stack state in the @var{the-last-stack} fluid, for the purpose
of debugging or re-throwing of an error. If thunk throws to the
symbol @var{key}, then @var{handler} is invoked this way:\n
@example
(handler key args ...)
@end example\n
@var{key} is a symbol or #t.\n
@var{thunk} takes no arguments. If @var{thunk} returns normally, that
is the return value of @code{catch}.\n
Handler is invoked outside the scope of its own @code{catch}. If
@var{handler} again throws to the same key, a new handler from further
up the call chain is invoked.\n
If the key is @code{#t}, then a throw to @emph{any} symbol will match
this call to @code{catch}."
(catch key
thunk
handler
(lambda (key . args)
;; Narrow by two more frames: this one, and the throw handler.
(save-stack 2)
(apply throw key args))))
;;;; streams.scm --- general lazy streams
;;;; -*- Scheme -*-
;;;; Copyright (C) 1999, 2001, 2004, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;; the basic stream operations are inspired by
;; (i.e. ripped off) Scheme48's `stream' package,
;; modulo stream-empty? -> stream-null? renaming.
(define-module (ice-9 streams)
\:export (make-stream
stream-car stream-cdr stream-null?
list->stream vector->stream port->stream
stream->list stream->reversed-list
stream->list&length stream->reversed-list&length
stream->vector
stream-fold stream-for-each stream-map))
;; Use:
;;
;; (make-stream producer initial-state)
;; - PRODUCER is a function of one argument, the current state.
;; it should return either a pair or an atom (i.e. anything that
;; is not a pair). if PRODUCER returns a pair, then the car of the pair
;; is the stream's head value, and the cdr is the state to be fed
;; to PRODUCER later. if PRODUCER returns an atom, then the stream is
;; considered depleted.
;;
;; (stream-car stream)
;; (stream-cdr stream)
;; (stream-null? stream)
;; - yes.
;;
;; (list->stream list)
;; (vector->stream vector)
;; - make a stream with the same contents as LIST/VECTOR.
;;
;; (port->stream port read)
;; - makes a stream of values which are obtained by READing from PORT.
;;
;; (stream->list stream)
;; - returns a list with the same contents as STREAM.
;;
;; (stream->reversed-list stream)
;; - as above, except the contents are in reversed order.
;;
;; (stream->list&length stream)
;; (stream->reversed-list&length stream)
;; - multiple-valued versions of the above two, the second value is the
;; length of the resulting list (so you get it for free).
;;
;; (stream->vector stream)
;; - yes.
;;
;; (stream-fold proc init stream0 ...)
;; - PROC must take (+ 1 <number-of-stream-arguments>) arguments, like this:
;; (PROC car0 ... init). *NOTE*: the INIT argument is last, not first.
;; I don't have any preference either way, but it's consistent with
;; `fold[lr]' procedures from SRFI-1. PROC is applied to successive
;; elements of the given STREAM(s) and to the value of the previous
;; invocation (INIT on the first invocation). the last result from PROC
;; is returned.
;;
;; (stream-for-each proc stream0 ...)
;; - like `for-each' we all know and love.
;;
;; (stream-map proc stream0 ...)
;; - like `map', except returns a stream of results, and not a list.
;; Code:
(define (make-stream m state)
(delay
(let ((o (m state)))
(if (pair? o)
(cons (car o)
(make-stream m (cdr o)))
'()))))
(define (stream-car stream)
"Returns the first element in STREAM. This is equivalent to `car'."
(car (force stream)))
(define (stream-cdr stream)
"Returns the first tail of STREAM. Equivalent to `(force (cdr STREAM))'."
(cdr (force stream)))
(define (stream-null? stream)
"Returns `#t' if STREAM is the end-of-stream marker; otherwise
returns `#f'. This is equivalent to `null?', but should be used
whenever testing for the end of a stream."
(null? (force stream)))
(define (list->stream l)
"Returns a newly allocated stream whose elements are the elements of
LIST. Equivalent to `(apply stream LIST)'."
(make-stream
(lambda (l) l)
l))
(define (vector->stream v)
(make-stream
(let ((len (vector-length v)))
(lambda (i)
(or (= i len)
(cons (vector-ref v i) (+ 1 i)))))
0))
(define (stream->reversed-list&length stream)
(let loop ((s stream) (acc '()) (len 0))
(if (stream-null? s)
(values acc len)
(loop (stream-cdr s) (cons (stream-car s) acc) (+ 1 len)))))
(define (stream->reversed-list stream)
(call-with-values
(lambda () (stream->reversed-list&length stream))
(lambda (l len) l)))
(define (stream->list&length stream)
(call-with-values
(lambda () (stream->reversed-list&length stream))
(lambda (l len) (values (reverse! l) len))))
(define (stream->list stream)
"Returns a newly allocated list whose elements are the elements of STREAM.
If STREAM has infinite length this procedure will not terminate."
(reverse! (stream->reversed-list stream)))
(define (stream->vector stream)
(call-with-values
(lambda () (stream->reversed-list&length stream))
(lambda (l len)
(let ((v (make-vector len)))
(let loop ((i 0) (l l))
(if (not (null? l))
(begin
(vector-set! v (- len i 1) (car l))
(loop (+ 1 i) (cdr l)))))
v))))
(define (stream-fold f init stream . rest)
(if (null? rest) ;fast path
(stream-fold-one f init stream)
(stream-fold-many f init (cons stream rest))))
(define (stream-fold-one f r stream)
(if (stream-null? stream)
r
(stream-fold-one f (f (stream-car stream) r) (stream-cdr stream))))
(define (stream-fold-many f r streams)
(if (or-map stream-null? streams)
r
(stream-fold-many f
(apply f (let recur ((cars
(map stream-car streams)))
(if (null? cars)
(list r)
(cons (car cars)
(recur (cdr cars))))))
(map stream-cdr streams))))
(define (stream-for-each f stream . rest)
(if (null? rest) ;fast path
(stream-for-each-one f stream)
(stream-for-each-many f (cons stream rest))))
(define (stream-for-each-one f stream)
(if (not (stream-null? stream))
(begin
(f (stream-car stream))
(stream-for-each-one f (stream-cdr stream)))))
(define (stream-for-each-many f streams)
(if (not (or-map stream-null? streams))
(begin
(apply f (map stream-car streams))
(stream-for-each-many f (map stream-cdr streams)))))
(define (stream-map f stream . rest)
"Returns a newly allocated stream, each element being the result of
invoking F with the corresponding elements of the STREAMs
as its arguments."
(if (null? rest) ;fast path
(make-stream (lambda (s)
(or (stream-null? s)
(cons (f (stream-car s)) (stream-cdr s))))
stream)
(make-stream (lambda (streams)
(or (or-map stream-null? streams)
(cons (apply f (map stream-car streams))
(map stream-cdr streams))))
(cons stream rest))))
(define (port->stream port read)
(make-stream (lambda (p)
(let ((o (read p)))
(or (eof-object? o)
(cons o p))))
port))
;;; streams.scm ends here
;;;; string-fun.scm --- string manipulation functions
;;;;
;;;; Copyright (C) 1995, 1996, 1997, 1999, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 string-fun)
\:export (split-after-char split-before-char split-discarding-char
split-after-char-last split-before-char-last
split-discarding-char-last split-before-predicate
split-after-predicate split-discarding-predicate
separate-fields-discarding-char separate-fields-after-char
separate-fields-before-char string-prefix-predicate string-prefix=?
sans-surrounding-whitespace sans-trailing-whitespace
sans-leading-whitespace sans-final-newline has-trailing-newline?))
;;;;
;;;
;;; Various string funcitons, particularly those that take
;;; advantage of the "shared substring" capability.
;;;
;;; {String Fun: Dividing Strings Into Fields}
;;;
;;; The names of these functions are very regular.
;;; Here is a grammar of a call to one of these:
;;;
;;; <string-function-invocation>
;;; := (<action>-<seperator-disposition>-<seperator-determination> <seperator-param> <str> <ret>)
;;;
;;; <str> = the string
;;;
;;; <ret> = The continuation. String functions generally return
;;; multiple values by passing them to this procedure.
;;;
;;; <action> = split
;;; | separate-fields
;;;
;;; "split" means to divide a string into two parts.
;;; <ret> will be called with two arguments.
;;;
;;; "separate-fields" means to divide a string into as many
;;; parts as possible. <ret> will be called with
;;; however many fields are found.
;;;
;;; <seperator-disposition> = before
;;; | after
;;; | discarding
;;;
;;; "before" means to leave the seperator attached to
;;; the beginning of the field to its right.
;;; "after" means to leave the seperator attached to
;;; the end of the field to its left.
;;; "discarding" means to discard seperators.
;;;
;;; Other dispositions might be handy. For example, "isolate"
;;; could mean to treat the separator as a field unto itself.
;;;
;;; <seperator-determination> = char
;;; | predicate
;;;
;;; "char" means to use a particular character as field seperator.
;;; "predicate" means to check each character using a particular predicate.
;;;
;;; Other determinations might be handy. For example, "character-set-member".
;;;
;;; <seperator-param> = A parameter that completes the meaning of the determinations.
;;; For example, if the determination is "char", then this parameter
;;; says which character. If it is "predicate", the parameter is the
;;; predicate.
;;;
;;;
;;; For example:
;;;
;;; (separate-fields-discarding-char #\, "foo, bar, baz, , bat" list)
;;; => ("foo" " bar" " baz" " " " bat")
;;;
;;; (split-after-char #\- 'an-example-of-split list)
;;; => ("an-" "example-of-split")
;;;
;;; As an alternative to using a determination "predicate", or to trying to do anything
;;; complicated with these functions, consider using regular expressions.
;;;
(define (split-after-char char str ret)
(let ((end (cond
((string-index str char) => 1+)
(else (string-length str)))))
(ret (substring str 0 end)
(substring str end))))
(define (split-before-char char str ret)
(let ((end (or (string-index str char)
(string-length str))))
(ret (substring str 0 end)
(substring str end))))
(define (split-discarding-char char str ret)
(let ((end (string-index str char)))
(if (not end)
(ret str "")
(ret (substring str 0 end)
(substring str (1+ end))))))
(define (split-after-char-last char str ret)
(let ((end (cond
((string-rindex str char) => 1+)
(else 0))))
(ret (substring str 0 end)
(substring str end))))
(define (split-before-char-last char str ret)
(let ((end (or (string-rindex str char) 0)))
(ret (substring str 0 end)
(substring str end))))
(define (split-discarding-char-last char str ret)
(let ((end (string-rindex str char)))
(if (not end)
(ret str "")
(ret (substring str 0 end)
(substring str (1+ end))))))
(define (split-before-predicate pred str ret)
(let loop ((n 0))
(cond
((= n (string-length str)) (ret str ""))
((not (pred (string-ref str n))) (loop (1+ n)))
(else (ret (substring str 0 n)
(substring str n))))))
(define (split-after-predicate pred str ret)
(let loop ((n 0))
(cond
((= n (string-length str)) (ret str ""))
((not (pred (string-ref str n))) (loop (1+ n)))
(else (ret (substring str 0 (1+ n))
(substring str (1+ n)))))))
(define (split-discarding-predicate pred str ret)
(let loop ((n 0))
(cond
((= n (string-length str)) (ret str ""))
((not (pred (string-ref str n))) (loop (1+ n)))
(else (ret (substring str 0 n)
(substring str (1+ n)))))))
(define (separate-fields-discarding-char ch str ret)
(let loop ((fields '())
(str str))
(cond
((string-rindex str ch)
=> (lambda (w) (loop (cons (substring str (+ 1 w)) fields)
(substring str 0 w))))
(else (apply ret str fields)))))
(define (separate-fields-after-char ch str ret)
(reverse
(let loop ((fields '())
(str str))
(cond
((string-index str ch)
=> (lambda (w) (loop (cons (substring str 0 (+ 1 w)) fields)
(substring str (+ 1 w)))))
(else (apply ret str fields))))))
(define (separate-fields-before-char ch str ret)
(let loop ((fields '())
(str str))
(cond
((string-rindex str ch)
=> (lambda (w) (loop (cons (substring str w) fields)
(substring str 0 w))))
(else (apply ret str fields)))))
;;; {String Fun: String Prefix Predicates}
;;;
;;; Very simple:
;;;
;;; (define-public ((string-prefix-predicate pred?) prefix str)
;;; (and (<= (string-length prefix) (string-length str))
;;; (pred? prefix (substring str 0 (string-length prefix)))))
;;;
;;; (define-public string-prefix=? (string-prefix-predicate string=?))
;;;
(define (string-prefix-predicate pred?)
(lambda (prefix str)
(and (<= (string-length prefix) (string-length str))
(pred? prefix (substring str 0 (string-length prefix))))))
(define string-prefix=? (string-prefix-predicate string=?))
;;; {String Fun: Strippers}
;;;
;;; <stripper> = sans-<removable-part>
;;;
;;; <removable-part> = surrounding-whitespace
;;; | trailing-whitespace
;;; | leading-whitespace
;;; | final-newline
;;;
(define (sans-surrounding-whitespace s)
(let ((st 0)
(end (string-length s)))
(while (and (< st (string-length s))
(char-whitespace? (string-ref s st)))
(set! st (1+ st)))
(while (and (< 0 end)
(char-whitespace? (string-ref s (1- end))))
(set! end (1- end)))
(if (< end st)
""
(substring s st end))))
(define (sans-trailing-whitespace s)
(let ((st 0)
(end (string-length s)))
(while (and (< 0 end)
(char-whitespace? (string-ref s (1- end))))
(set! end (1- end)))
(if (< end st)
""
(substring s st end))))
(define (sans-leading-whitespace s)
(let ((st 0)
(end (string-length s)))
(while (and (< st (string-length s))
(char-whitespace? (string-ref s st)))
(set! st (1+ st)))
(if (< end st)
""
(substring s st end))))
(define (sans-final-newline str)
(cond
((= 0 (string-length str))
str)
((char=? #\nl (string-ref str (1- (string-length str))))
(substring str 0 (1- (string-length str))))
(else str)))
;;; {String Fun: has-trailing-newline?}
;;;
(define (has-trailing-newline? str)
(and (< 0 (string-length str))
(char=? #\nl (string-ref str (1- (string-length str))))))
;;; {String Fun: with-regexp-parts}
;;; This relies on the older, hairier regexp interface, which we don't
;;; particularly want to implement, and it's not used anywhere, so
;;; we're just going to drop it for now.
;;; (define-public (with-regexp-parts regexp fields str return fail)
;;; (let ((parts (regexec regexp str fields)))
;;; (if (number? parts)
;;; (fail parts)
;;; (apply return parts))))
;;;; Copyright (C) 1997, 2000, 2001, 2002, 2003, 2006, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 syncase)
;; FIXME re-export other procs
#\export (datum->syntax-object syntax-object->datum
sc-expand))
(issue-deprecation-warning
"Syntax-case macros are now a part of Guile core; importing (ice-9 syncase) is no longer necessary.")
(define datum->syntax-object datum->syntax)
(define syntax-object->datum syntax->datum)
(define sc-expand macroexpand)
;;; Hack to make syncase macros work in the slib module
;; FIXME wingo is this still necessary?
;; (let ((m (nested-ref the-root-module '(%app modules ice-9 slib))))
;; (if m
;; (set-object-property! (module-local-variable m 'define)
;; '*sc-expander*
;; '(define))))
;; Copyright (C) 1991, 1992, 1993, 1994, 1995, 2006 Free Software Foundation, Inc.
;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;; "test.scm" Test correctness of scheme implementations.
;;; Author: Aubrey Jaffer
;;; Modified: Mikael Djurfeldt (Removed tests which Guile deliberately
;;; won't pass. Made the tests (test-cont), (test-sc4), and
;;; (test-delay) start to run automatically.
;;; This includes examples from
;;; William Clinger and Jonathan Rees, editors.
;;; Revised^4 Report on the Algorithmic Language Scheme
;;; and the IEEE specification.
;;; The input tests read this file expecting it to be named
;;; "test.scm", so you'll have to run it from the ice-9 source
;;; directory, or copy this file elsewhere
;;; Files `tmp1', `tmp2' and `tmp3' will be created in the course of running
;;; these tests. You may need to delete them in order to run
;;; "test.scm" more than once.
;;; There are three optional tests:
;;; (TEST-CONT) tests multiple returns from call-with-current-continuation
;;;
;;; (TEST-SC4) tests procedures required by R4RS but not by IEEE
;;;
;;; (TEST-DELAY) tests DELAY and FORCE, which are not required by
;;; either standard.
;;; If you are testing a R3RS version which does not have `list?' do:
;;; (define list? #f)
;;; send corrections or additions to jaffer@ai.mit.edu or
;;; Aubrey Jaffer, 84 Pleasant St., Wakefield MA 01880, USA
(define cur-section '())(define errs '())
(define SECTION (lambda args
(display "SECTION") (write args) (newline)
(set! cur-section args) #t))
(define record-error (lambda (e) (set! errs (cons (list cur-section e) errs))))
(define test
(lambda (expect fun . args)
(write (cons fun args))
(display " ==> ")
((lambda (res)
(write res)
(newline)
(cond ((not (equal? expect res))
(record-error (list res expect (cons fun args)))
(display " BUT EXPECTED ")
(write expect)
(newline)
#f)
(else #t)))
(if (procedure? fun) (apply fun args) (car args)))))
(define (report-errs)
(newline)
(if (null? errs) (display "Passed all tests")
(begin
(display "errors were:")
(newline)
(display "(SECTION (got expected (call)))")
(newline)
(for-each (lambda (l) (write l) (newline))
errs)))
(newline))
(SECTION 2 1);; test that all symbol characters are supported.
;'(+ - ... !.. $.+ %.- &.! *.: /:. :+. <-. =. >. ?. ~. _. ^.)
(SECTION 3 4)
(define disjoint-type-functions
(list boolean? char? null? number? pair? procedure? string? symbol? vector?))
(define type-examples
(list
#t #f #\a '() 9739 '(test) record-error "test" "" 'test '#() '#(a b c) ))
(define i 1)
(for-each (lambda (x) (display (make-string i #\space))
(set! i (+ 3 i))
(write x)
(newline))
disjoint-type-functions)
(define type-matrix
(map (lambda (x)
(let ((t (map (lambda (f) (f x)) disjoint-type-functions)))
(write t)
(write x)
(newline)
t))
type-examples))
(SECTION 4 1 2)
(test '(quote a) 'quote (quote 'a))
(test '(quote a) 'quote ''a)
(SECTION 4 1 3)
(test 12 (if #f + *) 3 4)
(SECTION 4 1 4)
(test 8 (lambda (x) (+ x x)) 4)
(define reverse-subtract
(lambda (x y) (- y x)))
(test 3 reverse-subtract 7 10)
(define add4
(let ((x 4))
(lambda (y) (+ x y))))
(test 10 add4 6)
(test '(3 4 5 6) (lambda x x) 3 4 5 6)
(test '(5 6) (lambda (x y . z) z) 3 4 5 6)
(SECTION 4 1 5)
(test 'yes 'if (if (> 3 2) 'yes 'no))
(test 'no 'if (if (> 2 3) 'yes 'no))
(test '1 'if (if (> 3 2) (- 3 2) (+ 3 2)))
(SECTION 4 1 6)
(define x 2)
(test 3 'define (+ x 1))
(set! x 4)
(test 5 'set! (+ x 1))
(SECTION 4 2 1)
(test 'greater 'cond (cond ((> 3 2) 'greater)
((< 3 2) 'less)))
(test 'equal 'cond (cond ((> 3 3) 'greater)
((< 3 3) 'less)
(else 'equal)))
(test 2 'cond (cond ((assv 'b '((a 1) (b 2))) => cadr)
(else #f)))
(test 'composite 'case (case (* 2 3)
((2 3 5 7) 'prime)
((1 4 6 8 9) 'composite)))
(test 'consonant 'case (case (car '(c d))
((a e i o u) 'vowel)
((w y) 'semivowel)
(else 'consonant)))
(test #t 'and (and (= 2 2) (> 2 1)))
(test #f 'and (and (= 2 2) (< 2 1)))
(test '(f g) 'and (and 1 2 'c '(f g)))
(test #t 'and (and))
(test #t 'or (or (= 2 2) (> 2 1)))
(test #t 'or (or (= 2 2) (< 2 1)))
(test #f 'or (or #f #f #f))
(test #f 'or (or))
(test '(b c) 'or (or (memq 'b '(a b c)) (+ 3 0)))
(SECTION 4 2 2)
(test 6 'let (let ((x 2) (y 3)) (* x y)))
(test 35 'let (let ((x 2) (y 3)) (let ((x 7) (z (+ x y))) (* z x))))
(test 70 'let* (let ((x 2) (y 3)) (let* ((x 7) (z (+ x y))) (* z x))))
(test #t 'letrec (letrec ((even?
(lambda (n) (if (zero? n) #t (odd? (- n 1)))))
(odd?
(lambda (n) (if (zero? n) #f (even? (- n 1))))))
(even? 88)))
(define x 34)
(test 5 'let (let ((x 3)) (define x 5) x))
(test 34 'let x)
(test 6 'let (let () (define x 6) x))
(test 34 'let x)
(test 7 'let* (let* ((x 3)) (define x 7) x))
(test 34 'let* x)
(test 8 'let* (let* () (define x 8) x))
(test 34 'let* x)
(test 9 'letrec (letrec () (define x 9) x))
(test 34 'letrec x)
(test 10 'letrec (letrec ((x 3)) (define x 10) x))
(test 34 'letrec x)
(SECTION 4 2 3)
(define x 0)
(test 6 'begin (begin (set! x 5) (+ x 1)))
(SECTION 4 2 4)
(test '#(0 1 2 3 4) 'do (do ((vec (make-vector 5))
(i 0 (+ i 1)))
((= i 5) vec)
(vector-set! vec i i)))
(test 25 'do (let ((x '(1 3 5 7 9)))
(do ((x x (cdr x))
(sum 0 (+ sum (car x))))
((null? x) sum))))
(test 1 'let (let foo () 1))
(test '((6 1 3) (-5 -2)) 'let
(let loop ((numbers '(3 -2 1 6 -5))
(nonneg '())
(neg '()))
(cond ((null? numbers) (list nonneg neg))
((negative? (car numbers))
(loop (cdr numbers)
nonneg
(cons (car numbers) neg)))
(else
(loop (cdr numbers)
(cons (car numbers) nonneg)
neg)))))
(SECTION 4 2 6)
(test '(list 3 4) 'quasiquote `(list ,(+ 1 2) 4))
(test '(list a (quote a)) 'quasiquote (let ((name 'a)) `(list ,name ',name)))
(test '(a 3 4 5 6 b) 'quasiquote `(a ,(+ 1 2) ,@(map abs '(4 -5 6)) b))
(test '((foo 7) . cons)
'quasiquote
`((foo ,(- 10 3)) ,@(cdr '(c)) . ,(car '(cons))))
;;; sqt is defined here because not all implementations are required to
;;; support it.
(define (sqt x)
(do ((i 0 (+ i 1)))
((> (* i i) x) (- i 1))))
(test '#(10 5 2 4 3 8) 'quasiquote `#(10 5 ,(sqt 4) ,@(map sqt '(16 9)) 8))
(test 5 'quasiquote `,(+ 2 3))
(test '(a `(b ,(+ 1 2) ,(foo 4 d) e) f)
'quasiquote `(a `(b ,(+ 1 2) ,(foo ,(+ 1 3) d) e) f))
(test '(a `(b ,x ,'y d) e) 'quasiquote
(let ((name1 'x) (name2 'y)) `(a `(b ,,name1 ,',name2 d) e)))
(test '(list 3 4) 'quasiquote (quasiquote (list (unquote (+ 1 2)) 4)))
(test '`(list ,(+ 1 2) 4) 'quasiquote '(quasiquote (list (unquote (+ 1 2)) 4)))
(SECTION 5 2 1)
(define add3 (lambda (x) (+ x 3)))
(test 6 'define (add3 3))
(define first car)
(test 1 'define (first '(1 2)))
(SECTION 5 2 2)
(test 45 'define
(let ((x 5))
(define foo (lambda (y) (bar x y)))
(define bar (lambda (a b) (+ (* a b) a)))
(foo (+ x 3))))
(define x 34)
(define (foo) (define x 5) x)
(test 5 foo)
(test 34 'define x)
(define foo (lambda () (define x 5) x))
(test 5 foo)
(test 34 'define x)
(define (foo x) ((lambda () (define x 5) x)) x)
(test 88 foo 88)
(test 4 foo 4)
(test 34 'define x)
(SECTION 6 1)
(test #f not #t)
(test #f not 3)
(test #f not (list 3))
(test #t not #f)
(test #f not '())
(test #f not (list))
(test #f not 'nil)
(test #t boolean? #f)
(test #f boolean? 0)
(test #f boolean? '())
(SECTION 6 2)
(test #t eqv? 'a 'a)
(test #f eqv? 'a 'b)
(test #t eqv? 2 2)
(test #t eqv? '() '())
(test #t eqv? '10000 '10000)
(test #f eqv? (cons 1 2)(cons 1 2))
(test #f eqv? (lambda () 1) (lambda () 2))
(test #f eqv? #f 'nil)
(let ((p (lambda (x) x)))
(test #t eqv? p p))
(define gen-counter
(lambda ()
(let ((n 0))
(lambda () (set! n (+ n 1)) n))))
(let ((g (gen-counter))) (test #t eqv? g g))
(test #f eqv? (gen-counter) (gen-counter))
(letrec ((f (lambda () (if (eqv? f g) 'f 'both)))
(g (lambda () (if (eqv? f g) 'g 'both))))
(test #f eqv? f g))
(test #t eq? 'a 'a)
(test #f eq? (list 'a) (list 'a))
(test #t eq? '() '())
(test #t eq? car car)
(let ((x '(a))) (test #t eq? x x))
(let ((x '#())) (test #t eq? x x))
(let ((x (lambda (x) x))) (test #t eq? x x))
(test #t equal? 'a 'a)
(test #t equal? '(a) '(a))
(test #t equal? '(a (b) c) '(a (b) c))
(test #t equal? "abc" "abc")
(test #t equal? 2 2)
(test #t equal? (make-vector 5 'a) (make-vector 5 'a))
(SECTION 6 3)
(test '(a b c d e) 'dot '(a . (b . (c . (d . (e . ()))))))
(define x (list 'a 'b 'c))
(define y x)
(and list? (test #t list? y))
(set-cdr! x 4)
(test '(a . 4) 'set-cdr! x)
(test #t eqv? x y)
(test '(a b c . d) 'dot '(a . (b . (c . d))))
(and list? (test #f list? y))
(and list? (let ((x (list 'a))) (set-cdr! x x) (test #f 'list? (list? x))))
(test #t pair? '(a . b))
(test #t pair? '(a . 1))
(test #t pair? '(a b c))
(test #f pair? '())
(test #f pair? '#(a b))
(test '(a) cons 'a '())
(test '((a) b c d) cons '(a) '(b c d))
(test '("a" b c) cons "a" '(b c))
(test '(a . 3) cons 'a 3)
(test '((a b) . c) cons '(a b) 'c)
(test 'a car '(a b c))
(test '(a) car '((a) b c d))
(test 1 car '(1 . 2))
(test '(b c d) cdr '((a) b c d))
(test 2 cdr '(1 . 2))
(test '(a 7 c) list 'a (+ 3 4) 'c)
(test '() list)
(test 3 length '(a b c))
(test 3 length '(a (b) (c d e)))
(test 0 length '())
(test '(x y) append '(x) '(y))
(test '(a b c d) append '(a) '(b c d))
(test '(a (b) (c)) append '(a (b)) '((c)))
(test '() append)
(test '(a b c . d) append '(a b) '(c . d))
(test 'a append '() 'a)
(test '(c b a) reverse '(a b c))
(test '((e (f)) d (b c) a) reverse '(a (b c) d (e (f))))
(test 'c list-ref '(a b c d) 2)
(test '(a b c) memq 'a '(a b c))
(test '(b c) memq 'b '(a b c))
(test '#f memq 'a '(b c d))
(test '#f memq (list 'a) '(b (a) c))
(test '((a) c) member (list 'a) '(b (a) c))
(test '(101 102) memv 101 '(100 101 102))
(define e '((a 1) (b 2) (c 3)))
(test '(a 1) assq 'a e)
(test '(b 2) assq 'b e)
(test #f assq 'd e)
(test #f assq (list 'a) '(((a)) ((b)) ((c))))
(test '((a)) assoc (list 'a) '(((a)) ((b)) ((c))))
(test '(5 7) assv 5 '((2 3) (5 7) (11 13)))
(SECTION 6 4)
(test #t symbol? 'foo)
(test #t symbol? (car '(a b)))
(test #f symbol? "bar")
(test #t symbol? 'nil)
(test #f symbol? '())
(test #f symbol? #f)
;;; But first, what case are symbols in? Determine the standard case:
(define char-standard-case char-upcase)
(if (string=? (symbol->string 'A) "a")
(set! char-standard-case char-downcase))
;;; Not for Guile
;(test #t 'standard-case
; (string=? (symbol->string 'a) (symbol->string 'A)))
;(test #t 'standard-case
; (or (string=? (symbol->string 'a) "A")
; (string=? (symbol->string 'A) "a")))
(define (str-copy s)
(let ((v (make-string (string-length s))))
(do ((i (- (string-length v) 1) (- i 1)))
((< i 0) v)
(string-set! v i (string-ref s i)))))
(define (string-standard-case s)
(set! s (str-copy s))
(do ((i 0 (+ 1 i))
(sl (string-length s)))
((>= i sl) s)
(string-set! s i (char-standard-case (string-ref s i)))))
;;; Not for Guile
;(test (string-standard-case "flying-fish") symbol->string 'flying-fish)
;(test (string-standard-case "martin") symbol->string 'Martin)
(test "Malvina" symbol->string (string->symbol "Malvina"))
;;; Not for Guile
;(test #t 'standard-case (eq? 'a 'A))
(define x (string #\a #\b))
(define y (string->symbol x))
(string-set! x 0 #\c)
(test "cb" 'string-set! x)
(test "ab" symbol->string y)
(test y string->symbol "ab")
;;; Not for Guile
;(test #t eq? 'mISSISSIppi 'mississippi)
;(test #f 'string->symbol (eq? 'bitBlt (string->symbol "bitBlt")))
(test 'JollyWog string->symbol (symbol->string 'JollyWog))
(SECTION 6 5 5)
(test #t number? 3)
(test #t complex? 3)
(test #t real? 3)
(test #t rational? 3)
(test #t integer? 3)
(test #t exact? 3)
(test #f inexact? 3)
(test #t = 22 22 22)
(test #t = 22 22)
(test #f = 34 34 35)
(test #f = 34 35)
(test #t > 3 -6246)
(test #f > 9 9 -2424)
(test #t >= 3 -4 -6246)
(test #t >= 9 9)
(test #f >= 8 9)
(test #t < -1 2 3 4 5 6 7 8)
(test #f < -1 2 3 4 4 5 6 7)
(test #t <= -1 2 3 4 5 6 7 8)
(test #t <= -1 2 3 4 4 5 6 7)
(test #f < 1 3 2)
(test #f >= 1 3 2)
(test #t zero? 0)
(test #f zero? 1)
(test #f zero? -1)
(test #f zero? -100)
(test #t positive? 4)
(test #f positive? -4)
(test #f positive? 0)
(test #f negative? 4)
(test #t negative? -4)
(test #f negative? 0)
(test #t odd? 3)
(test #f odd? 2)
(test #f odd? -4)
(test #t odd? -1)
(test #f even? 3)
(test #t even? 2)
(test #t even? -4)
(test #f even? -1)
(test 38 max 34 5 7 38 6)
(test -24 min 3 5 5 330 4 -24)
(test 7 + 3 4)
(test '3 + 3)
(test 0 +)
(test 4 * 4)
(test 1 *)
(test -1 - 3 4)
(test -3 - 3)
(test 7 abs -7)
(test 7 abs 7)
(test 0 abs 0)
(test 5 quotient 35 7)
(test -5 quotient -35 7)
(test -5 quotient 35 -7)
(test 5 quotient -35 -7)
(test 1 modulo 13 4)
(test 1 remainder 13 4)
(test 3 modulo -13 4)
(test -1 remainder -13 4)
(test -3 modulo 13 -4)
(test 1 remainder 13 -4)
(test -1 modulo -13 -4)
(test -1 remainder -13 -4)
(define (divtest n1 n2)
(= n1 (+ (* n2 (quotient n1 n2))
(remainder n1 n2))))
(test #t divtest 238 9)
(test #t divtest -238 9)
(test #t divtest 238 -9)
(test #t divtest -238 -9)
(test 4 gcd 0 4)
(test 4 gcd -4 0)
(test 4 gcd 32 -36)
(test 0 gcd)
(test 288 lcm 32 -36)
(test 1 lcm)
;;;;From: fred@sce.carleton.ca (Fred J Kaudel)
;;; Modified by jaffer.
(define (test-inexact)
(define f3.9 (string->number "3.9"))
(define f4.0 (string->number "4.0"))
(define f-3.25 (string->number "-3.25"))
(define f.25 (string->number ".25"))
(define f4.5 (string->number "4.5"))
(define f3.5 (string->number "3.5"))
(define f0.0 (string->number "0.0"))
(define f0.8 (string->number "0.8"))
(define f1.0 (string->number "1.0"))
(define wto write-test-obj)
(define dto display-test-obj)
(define lto load-test-obj)
(newline)
(display ";testing inexact numbers; ")
(newline)
(SECTION 6 5 5)
(test #t inexact? f3.9)
(test #t 'inexact? (inexact? (max f3.9 4)))
(test f4.0 'max (max f3.9 4))
(test f4.0 'exact->inexact (exact->inexact 4))
(test (- f4.0) round (- f4.5))
(test (- f4.0) round (- f3.5))
(test (- f4.0) round (- f3.9))
(test f0.0 round f0.0)
(test f0.0 round f.25)
(test f1.0 round f0.8)
(test f4.0 round f3.5)
(test f4.0 round f4.5)
(set! write-test-obj (list f.25 f-3.25));.25 inexact errors less likely.
(set! display-test-obj (list f.25 f-3.25));.3 often has such errors (~10^-13)
(set! load-test-obj (list 'define 'foo (list 'quote write-test-obj)))
(test #t call-with-output-file
"tmp3"
(lambda (test-file)
(write-char #\; test-file)
(display write-test-obj test-file)
(newline test-file)
(write load-test-obj test-file)
(output-port? test-file)))
(check-test-file "tmp3")
(set! write-test-obj wto)
(set! display-test-obj dto)
(set! load-test-obj lto)
(let ((x (string->number "4195835.0"))
(y (string->number "3145727.0")))
(test #t 'pentium-fdiv-bug (> f1.0 (- x (* (/ x y) y)))))
(report-errs))
(define (test-bignum)
(define tb
(lambda (n1 n2)
(= n1 (+ (* n2 (quotient n1 n2))
(remainder n1 n2)))))
(newline)
(display ";testing bignums; ")
(newline)
(SECTION 6 5 5)
(test 0 modulo -2177452800 86400)
(test 0 modulo 2177452800 -86400)
(test 0 modulo 2177452800 86400)
(test 0 modulo -2177452800 -86400)
(test #t 'remainder (tb 281474976710655 65535))
(test #t 'remainder (tb 281474976710654 65535))
(SECTION 6 5 6)
(test 281474976710655 string->number "281474976710655")
(test "281474976710655" number->string 281474976710655)
(report-errs))
(SECTION 6 5 6)
(test "0" number->string 0)
(test "100" number->string 100)
(test "100" number->string 256 16)
(test 100 string->number "100")
(test 256 string->number "100" 16)
(test #f string->number "")
(test #f string->number ".")
(test #f string->number "d")
(test #f string->number "D")
(test #f string->number "i")
(test #f string->number "I")
(test #f string->number "3i")
(test #f string->number "3I")
(test #f string->number "33i")
(test #f string->number "33I")
(test #f string->number "3.3i")
(test #f string->number "3.3I")
(test #f string->number "-")
(test #f string->number "+")
(SECTION 6 6)
(test #t eqv? '#\space #\Space)
(test #t eqv? #\space '#\Space)
(test #t char? #\a)
(test #t char? #\()
(test #t char? #\space)
(test #t char? '#\newline)
(test #f char=? #\A #\B)
(test #f char=? #\a #\b)
(test #f char=? #\9 #\0)
(test #t char=? #\A #\A)
(test #t char<? #\A #\B)
(test #t char<? #\a #\b)
(test #f char<? #\9 #\0)
(test #f char<? #\A #\A)
(test #f char>? #\A #\B)
(test #f char>? #\a #\b)
(test #t char>? #\9 #\0)
(test #f char>? #\A #\A)
(test #t char<=? #\A #\B)
(test #t char<=? #\a #\b)
(test #f char<=? #\9 #\0)
(test #t char<=? #\A #\A)
(test #f char>=? #\A #\B)
(test #f char>=? #\a #\b)
(test #t char>=? #\9 #\0)
(test #t char>=? #\A #\A)
(test #f char-ci=? #\A #\B)
(test #f char-ci=? #\a #\B)
(test #f char-ci=? #\A #\b)
(test #f char-ci=? #\a #\b)
(test #f char-ci=? #\9 #\0)
(test #t char-ci=? #\A #\A)
(test #t char-ci=? #\A #\a)
(test #t char-ci<? #\A #\B)
(test #t char-ci<? #\a #\B)
(test #t char-ci<? #\A #\b)
(test #t char-ci<? #\a #\b)
(test #f char-ci<? #\9 #\0)
(test #f char-ci<? #\A #\A)
(test #f char-ci<? #\A #\a)
(test #f char-ci>? #\A #\B)
(test #f char-ci>? #\a #\B)
(test #f char-ci>? #\A #\b)
(test #f char-ci>? #\a #\b)
(test #t char-ci>? #\9 #\0)
(test #f char-ci>? #\A #\A)
(test #f char-ci>? #\A #\a)
(test #t char-ci<=? #\A #\B)
(test #t char-ci<=? #\a #\B)
(test #t char-ci<=? #\A #\b)
(test #t char-ci<=? #\a #\b)
(test #f char-ci<=? #\9 #\0)
(test #t char-ci<=? #\A #\A)
(test #t char-ci<=? #\A #\a)
(test #f char-ci>=? #\A #\B)
(test #f char-ci>=? #\a #\B)
(test #f char-ci>=? #\A #\b)
(test #f char-ci>=? #\a #\b)
(test #t char-ci>=? #\9 #\0)
(test #t char-ci>=? #\A #\A)
(test #t char-ci>=? #\A #\a)
(test #t char-alphabetic? #\a)
(test #t char-alphabetic? #\A)
(test #t char-alphabetic? #\z)
(test #t char-alphabetic? #\Z)
(test #f char-alphabetic? #\0)
(test #f char-alphabetic? #\9)
(test #f char-alphabetic? #\space)
(test #f char-alphabetic? #\;)
(test #f char-numeric? #\a)
(test #f char-numeric? #\A)
(test #f char-numeric? #\z)
(test #f char-numeric? #\Z)
(test #t char-numeric? #\0)
(test #t char-numeric? #\9)
(test #f char-numeric? #\space)
(test #f char-numeric? #\;)
(test #f char-whitespace? #\a)
(test #f char-whitespace? #\A)
(test #f char-whitespace? #\z)
(test #f char-whitespace? #\Z)
(test #f char-whitespace? #\0)
(test #f char-whitespace? #\9)
(test #t char-whitespace? #\space)
(test #f char-whitespace? #\;)
(test #f char-upper-case? #\0)
(test #f char-upper-case? #\9)
(test #f char-upper-case? #\space)
(test #f char-upper-case? #\;)
(test #f char-lower-case? #\0)
(test #f char-lower-case? #\9)
(test #f char-lower-case? #\space)
(test #f char-lower-case? #\;)
(test #\. integer->char (char->integer #\.))
(test #\A integer->char (char->integer #\A))
(test #\a integer->char (char->integer #\a))
(test #\A char-upcase #\A)
(test #\A char-upcase #\a)
(test #\a char-downcase #\A)
(test #\a char-downcase #\a)
(SECTION 6 7)
(test #t string? "The word \"recursion\\\" has many meanings.")
(test #t string? "")
(define f (make-string 3 #\*))
(test "?**" 'string-set! (begin (string-set! f 0 #\?) f))
(test "abc" string #\a #\b #\c)
(test "" string)
(test 3 string-length "abc")
(test #\a string-ref "abc" 0)
(test #\c string-ref "abc" 2)
(test 0 string-length "")
(test "" substring "ab" 0 0)
(test "" substring "ab" 1 1)
(test "" substring "ab" 2 2)
(test "a" substring "ab" 0 1)
(test "b" substring "ab" 1 2)
(test "ab" substring "ab" 0 2)
(test "foobar" string-append "foo" "bar")
(test "foo" string-append "foo")
(test "foo" string-append "foo" "")
(test "foo" string-append "" "foo")
(test "" string-append)
(test "" make-string 0)
(test #t string=? "" "")
(test #f string<? "" "")
(test #f string>? "" "")
(test #t string<=? "" "")
(test #t string>=? "" "")
(test #t string-ci=? "" "")
(test #f string-ci<? "" "")
(test #f string-ci>? "" "")
(test #t string-ci<=? "" "")
(test #t string-ci>=? "" "")
(test #f string=? "A" "B")
(test #f string=? "a" "b")
(test #f string=? "9" "0")
(test #t string=? "A" "A")
(test #t string<? "A" "B")
(test #t string<? "a" "b")
(test #f string<? "9" "0")
(test #f string<? "A" "A")
(test #f string>? "A" "B")
(test #f string>? "a" "b")
(test #t string>? "9" "0")
(test #f string>? "A" "A")
(test #t string<=? "A" "B")
(test #t string<=? "a" "b")
(test #f string<=? "9" "0")
(test #t string<=? "A" "A")
(test #f string>=? "A" "B")
(test #f string>=? "a" "b")
(test #t string>=? "9" "0")
(test #t string>=? "A" "A")
(test #f string-ci=? "A" "B")
(test #f string-ci=? "a" "B")
(test #f string-ci=? "A" "b")
(test #f string-ci=? "a" "b")
(test #f string-ci=? "9" "0")
(test #t string-ci=? "A" "A")
(test #t string-ci=? "A" "a")
(test #t string-ci<? "A" "B")
(test #t string-ci<? "a" "B")
(test #t string-ci<? "A" "b")
(test #t string-ci<? "a" "b")
(test #f string-ci<? "9" "0")
(test #f string-ci<? "A" "A")
(test #f string-ci<? "A" "a")
(test #f string-ci>? "A" "B")
(test #f string-ci>? "a" "B")
(test #f string-ci>? "A" "b")
(test #f string-ci>? "a" "b")
(test #t string-ci>? "9" "0")
(test #f string-ci>? "A" "A")
(test #f string-ci>? "A" "a")
(test #t string-ci<=? "A" "B")
(test #t string-ci<=? "a" "B")
(test #t string-ci<=? "A" "b")
(test #t string-ci<=? "a" "b")
(test #f string-ci<=? "9" "0")
(test #t string-ci<=? "A" "A")
(test #t string-ci<=? "A" "a")
(test #f string-ci>=? "A" "B")
(test #f string-ci>=? "a" "B")
(test #f string-ci>=? "A" "b")
(test #f string-ci>=? "a" "b")
(test #t string-ci>=? "9" "0")
(test #t string-ci>=? "A" "A")
(test #t string-ci>=? "A" "a")
(SECTION 6 8)
(test #t vector? '#(0 (2 2 2 2) "Anna"))
(test #t vector? '#())
(test '#(a b c) vector 'a 'b 'c)
(test '#() vector)
(test 3 vector-length '#(0 (2 2 2 2) "Anna"))
(test 0 vector-length '#())
(test 8 vector-ref '#(1 1 2 3 5 8 13 21) 5)
(test '#(0 ("Sue" "Sue") "Anna") 'vector-set
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
(vector-set! vec 1 '("Sue" "Sue"))
vec))
(test '#(hi hi) make-vector 2 'hi)
(test '#() make-vector 0)
(test '#() make-vector 0 'a)
(SECTION 6 9)
(test #t procedure? car)
(test #f procedure? 'car)
(test #t procedure? (lambda (x) (* x x)))
(test #f procedure? '(lambda (x) (* x x)))
(test #t call-with-current-continuation procedure?)
(test 7 apply + (list 3 4))
(test 7 apply (lambda (a b) (+ a b)) (list 3 4))
(test 17 apply + 10 (list 3 4))
(test '() apply list '())
(define compose (lambda (f g) (lambda args (f (apply g args)))))
(test 30 (compose sqt *) 12 75)
(test '(b e h) map cadr '((a b) (d e) (g h)))
(test '(5 7 9) map + '(1 2 3) '(4 5 6))
(test '#(0 1 4 9 16) 'for-each
(let ((v (make-vector 5)))
(for-each (lambda (i) (vector-set! v i (* i i)))
'(0 1 2 3 4))
v))
(test -3 call-with-current-continuation
(lambda (exit)
(for-each (lambda (x) (if (negative? x) (exit x)))
'(54 0 37 -3 245 19))
#t))
(define list-length
(lambda (obj)
(call-with-current-continuation
(lambda (return)
(letrec ((r (lambda (obj) (cond ((null? obj) 0)
((pair? obj) (+ (r (cdr obj)) 1))
(else (return #f))))))
(r obj))))))
(test 4 list-length '(1 2 3 4))
(test #f list-length '(a b . c))
(test '() map cadr '())
;;; This tests full conformance of call-with-current-continuation. It
;;; is a separate test because some schemes do not support call/cc
;;; other than escape procedures. I am indebted to
;;; raja@copper.ucs.indiana.edu (Raja Sooriamurthi) for fixing this
;;; code. The function leaf-eq? compares the leaves of 2 arbitrary
;;; trees constructed of conses.
(define (next-leaf-generator obj eot)
(letrec ((return #f)
(cont (lambda (x)
(recur obj)
(set! cont (lambda (x) (return eot)))
(cont #f)))
(recur (lambda (obj)
(if (pair? obj)
(for-each recur obj)
(call-with-current-continuation
(lambda (c)
(set! cont c)
(return obj)))))))
(lambda () (call-with-current-continuation
(lambda (ret) (set! return ret) (cont #f))))))
(define (leaf-eq? x y)
(let* ((eot (list 'eot))
(xf (next-leaf-generator x eot))
(yf (next-leaf-generator y eot)))
(letrec ((loop (lambda (x y)
(cond ((not (eq? x y)) #f)
((eq? eot x) #t)
(else (loop (xf) (yf)))))))
(loop (xf) (yf)))))
(define (test-cont)
(newline)
(display ";testing continuations; ")
(newline)
(SECTION 6 9)
(test #t leaf-eq? '(a (b (c))) '((a) b c))
(test #f leaf-eq? '(a (b (c))) '((a) b c d))
(report-errs))
;;; Test Optional R4RS DELAY syntax and FORCE procedure
(define (test-delay)
(newline)
(display ";testing DELAY and FORCE; ")
(newline)
(SECTION 6 9)
(test 3 'delay (force (delay (+ 1 2))))
(test '(3 3) 'delay (let ((p (delay (+ 1 2))))
(list (force p) (force p))))
(test 2 'delay (letrec ((a-stream
(letrec ((next (lambda (n)
(cons n (delay (next (+ n 1)))))))
(next 0)))
(head car)
(tail (lambda (stream) (force (cdr stream)))))
(head (tail (tail a-stream)))))
(letrec ((count 0)
(p (delay (begin (set! count (+ count 1))
(if (> count x)
count
(force p)))))
(x 5))
(test 6 force p)
(set! x 10)
(test 6 force p))
(test 3 'force
(letrec ((p (delay (if c 3 (begin (set! c #t) (+ (force p) 1)))))
(c #f))
(force p)))
(report-errs))
(SECTION 6 10 1)
(test #t input-port? (current-input-port))
(test #t output-port? (current-output-port))
(test #t call-with-input-file "test.scm" input-port?)
(define this-file (open-input-file "test.scm"))
(test #t input-port? this-file)
(SECTION 6 10 2)
(test #\; peek-char this-file)
(test #\; read-char this-file)
(test '(define cur-section '()) read this-file)
(test #\( peek-char this-file)
(test '(define errs '()) read this-file)
(close-input-port this-file)
(close-input-port this-file)
(define (check-test-file name)
(define test-file (open-input-file name))
(test #t 'input-port?
(call-with-input-file
name
(lambda (test-file)
(test load-test-obj read test-file)
(test #t eof-object? (peek-char test-file))
(test #t eof-object? (read-char test-file))
(input-port? test-file))))
(test #\; read-char test-file)
(test display-test-obj read test-file)
(test load-test-obj read test-file)
(close-input-port test-file))
(SECTION 6 10 3)
(define write-test-obj
'(#t #f #\a () 9739 -3 . #((test) "te \" \" st" "" test #() b c)))
(define display-test-obj
'(#t #f a () 9739 -3 . #((test) te " " st test #() b c)))
(define load-test-obj
(list 'define 'foo (list 'quote write-test-obj)))
(test #t call-with-output-file
"tmp1"
(lambda (test-file)
(write-char #\; test-file)
(display write-test-obj test-file)
(newline test-file)
(write load-test-obj test-file)
(output-port? test-file)))
(check-test-file "tmp1")
(define test-file (open-output-file "tmp2"))
(write-char #\; test-file)
(display write-test-obj test-file)
(newline test-file)
(write load-test-obj test-file)
(test #t output-port? test-file)
(close-output-port test-file)
(check-test-file "tmp2")
(define (test-sc4)
(newline)
(display ";testing scheme 4 functions; ")
(newline)
(SECTION 6 7)
(test '(#\P #\space #\l) string->list "P l")
(test '() string->list "")
(test "1\\\"" list->string '(#\1 #\\ #\"))
(test "" list->string '())
(SECTION 6 8)
(test '(dah dah didah) vector->list '#(dah dah didah))
(test '() vector->list '#())
(test '#(dididit dah) list->vector '(dididit dah))
(test '#() list->vector '())
(SECTION 6 10 4)
(load "tmp1")
(test write-test-obj 'load foo)
(report-errs))
(report-errs)
(if (and (string->number "0.0") (inexact? (string->number "0.0")))
(test-inexact))
(let ((n (string->number "281474976710655")))
(if (and n (exact? n))
(test-bignum)))
(newline)
(test-cont)
(newline)
(test-sc4)
(newline)
(test-delay)
(newline)
"last item in file"
;;;; Copyright (C) 1996, 1998, 2001, 2002, 2003, 2006, 2010, 2011,
;;;; 2012 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;; ----------------------------------------------------------------
;;;; threads.scm -- User-level interface to Guile's thread system
;;;; 4 March 1996, Anthony Green <green@cygnus.com>
;;;; Modified 5 October 1996, MDJ <djurfeldt@nada.kth.se>
;;;; Modified 6 April 2001, ttn
;;;; ----------------------------------------------------------------
;;;;
;;; Commentary:
;; This module is documented in the Guile Reference Manual.
;; Briefly, one procedure is exported: `%thread-handler';
;; as well as four macros: `make-thread', `begin-thread',
;; `with-mutex' and `monitor'.
;;; Code:
(define-module (ice-9 threads)
#\use-module (ice-9 futures)
#\use-module (ice-9 match)
#\export (begin-thread
parallel
letpar
make-thread
with-mutex
monitor
par-map
par-for-each
n-par-map
n-par-for-each
n-for-each-par-map
%thread-handler))
;;; Macros first, so that the procedures expand correctly.
(define-syntax-rule (begin-thread e0 e1 ...)
(call-with-new-thread
(lambda () e0 e1 ...)
%thread-handler))
(define-syntax parallel
(lambda (x)
(syntax-case x ()
((_ e0 ...)
(with-syntax (((tmp0 ...) (generate-temporaries (syntax (e0 ...)))))
#'(let ((tmp0 (future e0))
...)
(values (touch tmp0) ...)))))))
(define-syntax-rule (letpar ((v e) ...) b0 b1 ...)
(call-with-values
(lambda () (parallel e ...))
(lambda (v ...)
b0 b1 ...)))
(define-syntax-rule (make-thread proc arg ...)
(call-with-new-thread
(lambda () (proc arg ...))
%thread-handler))
(define-syntax-rule (with-mutex m e0 e1 ...)
(let ((x m))
(dynamic-wind
(lambda () (lock-mutex x))
(lambda () (begin e0 e1 ...))
(lambda () (unlock-mutex x)))))
(define-syntax-rule (monitor first rest ...)
(with-mutex (make-mutex)
first rest ...))
(define (par-mapper mapper cons)
(lambda (proc . lists)
(let loop ((lists lists))
(match lists
(((heads tails ...) ...)
(let ((tail (future (loop tails)))
(head (apply proc heads)))
(cons head (touch tail))))
(_
'())))))
(define par-map (par-mapper map cons))
(define par-for-each (par-mapper for-each (const *unspecified*)))
(define (n-par-map n proc . arglists)
(let* ((m (make-mutex))
(threads '())
(results (make-list (length (car arglists))))
(result results))
(do ((i 0 (+ 1 i)))
((= i n)
(for-each join-thread threads)
results)
(set! threads
(cons (begin-thread
(let loop ()
(lock-mutex m)
(if (null? result)
(unlock-mutex m)
(let ((args (map car arglists))
(my-result result))
(set! arglists (map cdr arglists))
(set! result (cdr result))
(unlock-mutex m)
(set-car! my-result (apply proc args))
(loop)))))
threads)))))
(define (n-par-for-each n proc . arglists)
(let ((m (make-mutex))
(threads '()))
(do ((i 0 (+ 1 i)))
((= i n)
(for-each join-thread threads))
(set! threads
(cons (begin-thread
(let loop ()
(lock-mutex m)
(if (null? (car arglists))
(unlock-mutex m)
(let ((args (map car arglists)))
(set! arglists (map cdr arglists))
(unlock-mutex m)
(apply proc args)
(loop)))))
threads)))))
;;; The following procedure is motivated by the common and important
;;; case where a lot of work should be done, (not too much) in parallel,
;;; but the results need to be handled serially (for example when
;;; writing them to a file).
;;;
(define (n-for-each-par-map n s-proc p-proc . arglists)
"Using N parallel processes, apply S-PROC in serial order on the results
of applying P-PROC on ARGLISTS."
(let* ((m (make-mutex))
(threads '())
(no-result '(no-value))
(results (make-list (length (car arglists)) no-result))
(result results))
(do ((i 0 (+ 1 i)))
((= i n)
(for-each join-thread threads))
(set! threads
(cons (begin-thread
(let loop ()
(lock-mutex m)
(cond ((null? results)
(unlock-mutex m))
((not (eq? (car results) no-result))
(let ((arg (car results)))
;; stop others from choosing to process results
(set-car! results no-result)
(unlock-mutex m)
(s-proc arg)
(lock-mutex m)
(set! results (cdr results))
(unlock-mutex m)
(loop)))
((null? result)
(unlock-mutex m))
(else
(let ((args (map car arglists))
(my-result result))
(set! arglists (map cdr arglists))
(set! result (cdr result))
(unlock-mutex m)
(set-car! my-result (apply p-proc args))
(loop))))))
threads)))))
(define (thread-handler tag . args)
(let ((n (length args))
(p (current-error-port)))
(display "In thread:" p)
(newline p)
(if (>= n 3)
(display-error #f
p
(car args)
(cadr args)
(caddr args)
(if (= n 4)
(cadddr args)
'()))
(begin
(display "uncaught throw to " p)
(display tag p)
(display ": " p)
(display args p)
(newline p)))
#f))
;;; Set system thread handler
(define %thread-handler thread-handler)
;;; threads.scm ends here
;;;; Copyright (C) 2001, 2004, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;; This module exports a single macro: `time'.
;; Usage: (time exp)
;;
;; Example:
;; guile> (time (sleep 3))
;; clock utime stime cutime cstime gctime
;; 3.01 0.00 0.00 0.00 0.00 0.00
;; 0
;;; Code:
(define-module (ice-9 time)
\:use-module (ice-9 format)
\:export (time))
(define (time-proc proc)
(let* ((gc-start (gc-run-time))
(tms-start (times))
(result (proc))
(tms-end (times))
(gc-end (gc-run-time)))
;; FIXME: We would probably like format ~f to accept rationals, but
;; currently it doesn't so we force to a flonum with exact->inexact.
(define (get proc start end)
(exact->inexact (/ (- (proc end) (proc start)) internal-time-units-per-second)))
(display "clock utime stime cutime cstime gctime\n")
(format #t "~5,2F ~5,2F ~5,2F ~6,2F ~6,2F ~6,2F\n"
(get tms:clock tms-start tms-end)
(get tms:utime tms-start tms-end)
(get tms:stime tms-start tms-end)
(get tms:cutime tms-start tms-end)
(get tms:cstime tms-start tms-end)
(get identity gc-start gc-end))
result))
(define-macro (time exp)
`((@@ (ice-9 time) time-proc) (lambda () ,exp)))
;;; time.scm ends here
;;; -*- mode: scheme; coding: utf-8; -*-
;;;; Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
;;;; 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 top-repl)
#\use-module (ice-9 top-repl)
#\use-module ((system repl repl) #\select (start-repl))
;; #\replace, as with deprecated code enabled these will be in the root env
#\replace (top-repl))
(define call-with-sigint
(if (not (provided? 'posix))
(lambda (thunk) (thunk))
(lambda (thunk)
(let ((handler #f))
(dynamic-wind
(lambda ()
(set! handler
(sigaction SIGINT
(lambda (sig)
(scm-error 'signal #f "User interrupt" '()
(list sig))))))
thunk
(lambda ()
(if handler
;; restore Scheme handler, SIG_IGN or SIG_DFL.
(sigaction SIGINT (car handler) (cdr handler))
;; restore original C handler.
(sigaction SIGINT #f))))))))
(define (top-repl)
(let ((guile-user-module (resolve-module '(guile-user))))
;; Use some convenient modules (in reverse order)
(set-current-module guile-user-module)
(process-use-modules
(append
'(((ice-9 r5rs))
((ice-9 session)))
(if (provided? 'regex)
'(((ice-9 regex)))
'())
(if (provided? 'threads)
'(((ice-9 threads)))
'())))
(call-with-sigint
(lambda ()
(and (defined? 'setlocale)
(catch 'system-error
(lambda ()
(setlocale LC_ALL ""))
(lambda (key subr fmt args errno)
(format (current-error-port)
"warning: failed to install locale: ~a~%"
(strerror (car errno))))))
(let ((status (start-repl (current-language))))
(run-hook exit-hook)
status)))))
;; unicode
;;;; Copyright (C) 2014 Free Software Foundation, Inc.
;;;;
;;;; This library is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Lesser General Public License as
;;;; published by the Free Software Foundation, either version 3 of the
;;;; License, or (at your option) any later version.
;;;;
;;;; This library 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 Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library. If not, see
;;;; <http://www.gnu.org/licenses/>.
;;;;
(define-module (ice-9 unicode)
#\export (formal-name->char
char->formal-name))
(eval-when (expand load eval)
(load-extension (string-append "libguile-" (effective-version))
"scm_init_unicode"))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (ice-9 vlist)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (srfi srfi-26)
#\use-module (ice-9 format)
#\export (vlist? vlist-cons vlist-head vlist-tail vlist-null?
vlist-null list->vlist vlist-ref vlist-drop vlist-take
vlist-length vlist-fold vlist-fold-right vlist-map
vlist-unfold vlist-unfold-right vlist-append
vlist-reverse vlist-filter vlist-delete vlist->list
vlist-for-each
block-growth-factor
vhash? vhash-cons vhash-consq vhash-consv
vhash-assoc vhash-assq vhash-assv
vhash-delete vhash-delq vhash-delv
vhash-fold vhash-fold-right
vhash-fold* vhash-foldq* vhash-foldv*
alist->vhash))
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;;
;;; Commentary:
;;;
;;; This module provides an implementations of vlists, a functional list-like
;;; data structure described by Phil Bagwell in "Fast Functional Lists,
;;; Hash-Lists, Dequeues and Variable-Length Arrays", EPFL Technical Report,
;;; 2002.
;;;
;;; The idea is to store vlist elements in increasingly large contiguous blocks
;;; (implemented as vectors here). These blocks are linked to one another using
;;; a pointer to the next block (called `block-base' here) and an offset within
;;; that block (`block-offset' here). The size of these blocks form a geometric
;;; series with ratio `block-growth-factor'.
;;;
;;; In the best case (e.g., using a vlist returned by `list->vlist'),
;;; elements from the first half of an N-element vlist are accessed in O(1)
;;; (assuming `block-growth-factor' is 2), and `vlist-length' takes only
;;; O(ln(N)). Furthermore, the data structure improves data locality since
;;; vlist elements are adjacent, which plays well with caches.
;;;
;;; Code:
;;;
;;; VList Blocks and Block Descriptors.
;;;
(define block-growth-factor
(make-fluid 2))
(define-inlinable (make-block base offset size hash-tab?)
;; Return a block (and block descriptor) of SIZE elements pointing to
;; BASE at OFFSET. If HASH-TAB? is true, we also reserve space for a
;; "hash table". Note: We use `next-free' instead of `last-used' as
;; suggested by Bagwell.
(if hash-tab?
(vector (make-vector (* size 3) #f)
base offset size 0)
(vector (make-vector size)
base offset size 0)))
(define-syntax-rule (define-block-accessor name index)
(define-inlinable (name block)
(vector-ref block index)))
(define-block-accessor block-content 0)
(define-block-accessor block-base 1)
(define-block-accessor block-offset 2)
(define-block-accessor block-size 3)
(define-block-accessor block-next-free 4)
(define-inlinable (block-hash-table? block)
(< (block-size block) (vector-length (block-content block))))
(define-inlinable (set-block-next-free! block next-free)
(vector-set! block 4 next-free))
(define-inlinable (block-append! block value offset)
;; This is not thread-safe. To fix it, see Section 2.8 of the paper.
(and (< offset (block-size block))
(= offset (block-next-free block))
(begin
(set-block-next-free! block (1+ offset))
(vector-set! (block-content block) offset value)
#t)))
;; Return the item at slot OFFSET.
(define-inlinable (block-ref content offset)
(vector-ref content offset))
;; Return the offset of the next item in the hash bucket, after the one
;; at OFFSET.
(define-inlinable (block-hash-table-next-offset content size offset)
(vector-ref content (+ size size offset)))
;; Save the offset of the next item in the hash bucket, after the one
;; at OFFSET.
(define-inlinable (block-hash-table-set-next-offset! content size offset
next-offset)
(vector-set! content (+ size size offset) next-offset))
;; Returns the index of the last entry stored in CONTENT with
;; SIZE-modulo hash value KHASH.
(define-inlinable (block-hash-table-ref content size khash)
(vector-ref content (+ size khash)))
(define-inlinable (block-hash-table-set! content size khash offset)
(vector-set! content (+ size khash) offset))
;; Add hash table information for the item recently added at OFFSET,
;; with SIZE-modulo hash KHASH.
(define-inlinable (block-hash-table-add! content size khash offset)
(block-hash-table-set-next-offset! content size offset
(block-hash-table-ref content size khash))
(block-hash-table-set! content size khash offset))
(define block-null
;; The null block.
(make-block #f 0 0 #f))
;;;
;;; VLists.
;;;
(define-record-type <vlist>
;; A vlist is just a base+offset pair pointing to a block.
;; XXX: Allocating a <vlist> record in addition to the block at each
;; `vlist-cons' call is inefficient. However, Bagwell's hack to avoid it
;; (Section 2.2) would require GC_ALL_INTERIOR_POINTERS, which would be a
;; performance hit for everyone.
(make-vlist base offset)
vlist?
(base vlist-base)
(offset vlist-offset))
(set-record-type-printer! <vlist>
(lambda (vl port)
(cond ((vlist-null? vl)
(format port "#<vlist ()>"))
((vhash? vl)
(format port "#<vhash ~x ~a pairs>"
(object-address vl)
(vlist-length vl)))
(else
(format port "#<vlist ~a>"
(vlist->list vl))))))
(define vlist-null
;; The empty vlist.
(make-vlist block-null 0))
;; Asserting that something is a vlist is actually a win if your next
;; step is to call record accessors, because that causes CSE to
;; eliminate the type checks in those accessors.
;;
(define-inlinable (assert-vlist val)
(unless (vlist? val)
(throw 'wrong-type-arg
#f
"Not a vlist: ~S"
(list val)
(list val))))
(define-inlinable (block-cons item vlist hash-tab?)
(let ((base (vlist-base vlist))
(offset (1+ (vlist-offset vlist))))
(cond
((block-append! base item offset)
;; Fast path: We added the item directly to the block.
(make-vlist base offset))
(else
;; Slow path: Allocate a new block.
(let* ((size (block-size base))
(base (make-block
base
(1- offset)
(cond
((zero? size) 1)
((< offset size) 1) ;; new vlist head
(else (* (fluid-ref block-growth-factor) size)))
hash-tab?)))
(set-block-next-free! base 1)
(vector-set! (block-content base) 0 item)
(make-vlist base 0))))))
(define (vlist-cons item vlist)
"Return a new vlist with ITEM as its head and VLIST as its
tail."
;; Note: Although the result of `vlist-cons' on a vhash is a valid
;; vlist, it is not a valid vhash. The new item does not get a hash
;; table entry. If we allocate a new block, the new block will not
;; have a hash table. Perhaps we can do something more sensible here,
;; but this is a hot function, so there are performance impacts.
(assert-vlist vlist)
(block-cons item vlist #f))
(define (vlist-head vlist)
"Return the head of VLIST."
(assert-vlist vlist)
(let ((base (vlist-base vlist))
(offset (vlist-offset vlist)))
(block-ref (block-content base) offset)))
(define (vlist-tail vlist)
"Return the tail of VLIST."
(assert-vlist vlist)
(let ((base (vlist-base vlist))
(offset (vlist-offset vlist)))
(if (> offset 0)
(make-vlist base (- offset 1))
(make-vlist (block-base base)
(block-offset base)))))
(define (vlist-null? vlist)
"Return true if VLIST is empty."
(assert-vlist vlist)
(let ((base (vlist-base vlist)))
(and (not (block-base base))
(= 0 (block-size base)))))
;;;
;;; VList Utilities.
;;;
(define (list->vlist lst)
"Return a new vlist whose contents correspond to LST."
(vlist-reverse (fold vlist-cons vlist-null lst)))
(define (vlist-fold proc init vlist)
"Fold over VLIST, calling PROC for each element."
;; FIXME: Handle multiple lists.
(assert-vlist vlist)
(let loop ((base (vlist-base vlist))
(offset (vlist-offset vlist))
(result init))
(if (eq? base block-null)
result
(let* ((next (- offset 1))
(done? (< next 0)))
(loop (if done? (block-base base) base)
(if done? (block-offset base) next)
(proc (block-ref (block-content base) offset) result))))))
(define (vlist-fold-right proc init vlist)
"Fold over VLIST, calling PROC for each element, starting from
the last element."
(assert-vlist vlist)
(let loop ((index (1- (vlist-length vlist)))
(result init))
(if (< index 0)
result
(loop (1- index)
(proc (vlist-ref vlist index) result)))))
(define (vlist-reverse vlist)
"Return a new VLIST whose content are those of VLIST in reverse
order."
(vlist-fold vlist-cons vlist-null vlist))
(define (vlist-map proc vlist)
"Map PROC over the elements of VLIST and return a new vlist."
(vlist-fold (lambda (item result)
(vlist-cons (proc item) result))
vlist-null
(vlist-reverse vlist)))
(define (vlist->list vlist)
"Return a new list whose contents match those of VLIST."
(vlist-fold-right cons '() vlist))
(define (vlist-ref vlist index)
"Return the element at index INDEX in VLIST."
(assert-vlist vlist)
(let loop ((index index)
(base (vlist-base vlist))
(offset (vlist-offset vlist)))
(if (<= index offset)
(block-ref (block-content base) (- offset index))
(loop (- index offset 1)
(block-base base)
(block-offset base)))))
(define (vlist-drop vlist count)
"Return a new vlist that does not contain the COUNT first elements of
VLIST."
(assert-vlist vlist)
(let loop ((count count)
(base (vlist-base vlist))
(offset (vlist-offset vlist)))
(if (<= count offset)
(make-vlist base (- offset count))
(loop (- count offset 1)
(block-base base)
(block-offset base)))))
(define (vlist-take vlist count)
"Return a new vlist that contains only the COUNT first elements of
VLIST."
(let loop ((count count)
(vlist vlist)
(result vlist-null))
(if (= 0 count)
(vlist-reverse result)
(loop (- count 1)
(vlist-tail vlist)
(vlist-cons (vlist-head vlist) result)))))
(define (vlist-filter pred vlist)
"Return a new vlist containing all the elements from VLIST that
satisfy PRED."
(vlist-fold-right (lambda (e v)
(if (pred e)
(vlist-cons e v)
v))
vlist-null
vlist))
(define* (vlist-delete x vlist #\optional (equal? equal?))
"Return a new vlist corresponding to VLIST without the elements
EQUAL? to X."
(vlist-filter (lambda (e)
(not (equal? e x)))
vlist))
(define (vlist-length vlist)
"Return the length of VLIST."
(assert-vlist vlist)
(let loop ((base (vlist-base vlist))
(len (vlist-offset vlist)))
(if (eq? base block-null)
len
(loop (block-base base)
(+ len 1 (block-offset base))))))
(define* (vlist-unfold p f g seed
#\optional (tail-gen (lambda (x) vlist-null)))
"Return a new vlist. See the description of SRFI-1 `unfold' for details."
(let uf ((seed seed))
(if (p seed)
(tail-gen seed)
(vlist-cons (f seed)
(uf (g seed))))))
(define* (vlist-unfold-right p f g seed #\optional (tail vlist-null))
"Return a new vlist. See the description of SRFI-1 `unfold-right' for
details."
(let uf ((seed seed) (lis tail))
(if (p seed)
lis
(uf (g seed) (vlist-cons (f seed) lis)))))
(define (vlist-append . vlists)
"Append the given lists."
(if (null? vlists)
vlist-null
(fold-right (lambda (vlist result)
(vlist-fold-right (lambda (e v)
(vlist-cons e v))
result
vlist))
vlist-null
vlists)))
(define (vlist-for-each proc vlist)
"Call PROC on each element of VLIST. The result is unspecified."
(vlist-fold (lambda (item x)
(proc item))
(if #f #f)
vlist))
;;;
;;; Hash Lists, aka. `VHash'.
;;;
;; Assume keys K1 and K2, H = hash(K1) = hash(K2), and two values V1 and V2
;; associated with K1 and K2, respectively. The resulting layout is a
;; follows:
;;
;; ,--------------------.
;; 0| ,-> (K1 . V1) | Vlist array
;; 1| | |
;; 2| | (K2 . V2) |
;; 3| | |
;; size +-|------------------+
;; 0| | | Hash table
;; 1| | |
;; 2| +-- O <------------- H
;; 3| | |
;; size * 2 +-|------------------+
;; 0| `-> 2 | Chain links
;; 1| |
;; 2| #f |
;; 3| |
;; size * 3 `--------------------'
;;
;; The backing store for the vhash is partitioned into three areas: the
;; vlist part, the hash table part, and the chain links part. In this
;; example we have a hash H which, when indexed into the hash table
;; part, indicates that a value with this hash can be found at offset 0
;; in the vlist part. The corresponding index (in this case, 0) of the
;; chain links array holds the index of the next element in this block
;; with this hash value, or #f if we reached the end of the chain.
;;
;; This API potentially requires users to repeat which hash function and
;; which equality predicate to use. This can lead to unpredictable
;; results if they are used in consistenly, e.g., between `vhash-cons'
;; and `vhash-assoc', which is undesirable, as argued in
;; http://savannah.gnu.org/bugs/?22159 . OTOH, two arguments can be
;; made in favor of this API:
;;
;; - It's consistent with how alists are handled in SRFI-1.
;;
;; - In practice, users will probably consistenly use either the `q',
;; the `v', or the plain variant (`vlist-cons' and `vlist-assoc'
;; without any optional argument), i.e., they will rarely explicitly
;; pass a hash function or equality predicate.
(define (vhash? obj)
"Return true if OBJ is a hash list."
(and (vlist? obj)
(block-hash-table? (vlist-base obj))))
(define* (vhash-cons key value vhash #\optional (hash hash))
"Return a new hash list based on VHASH where KEY is associated
with VALUE. Use HASH to compute KEY's hash."
(assert-vlist vhash)
;; We should also assert that it is a hash table. Need to check the
;; performance impacts of that. Also, vlist-null is a valid hash
;; table, which does not pass vhash?. A bug, perhaps.
(let* ((vhash (block-cons (cons key value) vhash #t))
(base (vlist-base vhash))
(offset (vlist-offset vhash))
(size (block-size base))
(khash (hash key size))
(content (block-content base)))
(block-hash-table-add! content size khash offset)
vhash))
(define vhash-consq (cut vhash-cons <> <> <> hashq))
(define vhash-consv (cut vhash-cons <> <> <> hashv))
(define-inlinable (%vhash-fold* proc init key vhash equal? hash)
;; Fold over all the values associated with KEY in VHASH.
(define (visit-block base max-offset result)
(let* ((size (block-size base))
(content (block-content base))
(khash (hash key size)))
(let loop ((offset (block-hash-table-ref content size khash))
(result result))
(if offset
(loop (block-hash-table-next-offset content size offset)
(if (and (<= offset max-offset)
(equal? key (car (block-ref content offset))))
(proc (cdr (block-ref content offset)) result)
result))
(let ((next-block (block-base base)))
(if (> (block-size next-block) 0)
(visit-block next-block (block-offset base) result)
result))))))
(assert-vlist vhash)
(if (> (block-size (vlist-base vhash)) 0)
(visit-block (vlist-base vhash)
(vlist-offset vhash)
init)
init))
(define* (vhash-fold* proc init key vhash
#\optional (equal? equal?) (hash hash))
"Fold over all the values associated with KEY in VHASH, with each
call to PROC having the form ‘(proc value result)’, where
RESULT is the result of the previous call to PROC and INIT the
value of RESULT for the first call to PROC."
(%vhash-fold* proc init key vhash equal? hash))
(define (vhash-foldq* proc init key vhash)
"Same as ‘vhash-fold*’, but using ‘hashq’ and ‘eq?’."
(%vhash-fold* proc init key vhash eq? hashq))
(define (vhash-foldv* proc init key vhash)
"Same as ‘vhash-fold*’, but using ‘hashv’ and ‘eqv?’."
(%vhash-fold* proc init key vhash eqv? hashv))
(define-inlinable (%vhash-assoc key vhash equal? hash)
;; A specialization of `vhash-fold*' that stops when the first value
;; associated with KEY is found or when the end-of-list is reached. Inline to
;; make sure `vhash-assq' gets to use the `eq?' instruction instead of calling
;; the `eq?' subr.
(define (visit-block base max-offset)
(let* ((size (block-size base))
(content (block-content base))
(khash (hash key size)))
(let loop ((offset (block-hash-table-ref content size khash)))
(if offset
(if (and (<= offset max-offset)
(equal? key (car (block-ref content offset))))
(block-ref content offset)
(loop (block-hash-table-next-offset content size offset)))
(let ((next-block (block-base base)))
(and (> (block-size next-block) 0)
(visit-block next-block (block-offset base))))))))
(assert-vlist vhash)
(and (> (block-size (vlist-base vhash)) 0)
(visit-block (vlist-base vhash)
(vlist-offset vhash))))
(define* (vhash-assoc key vhash #\optional (equal? equal?) (hash hash))
"Return the first key/value pair from VHASH whose key is equal to
KEY according to the EQUAL? equality predicate."
(%vhash-assoc key vhash equal? hash))
(define (vhash-assq key vhash)
"Return the first key/value pair from VHASH whose key is ‘eq?’ to
KEY."
(%vhash-assoc key vhash eq? hashq))
(define (vhash-assv key vhash)
"Return the first key/value pair from VHASH whose key is ‘eqv?’ to
KEY."
(%vhash-assoc key vhash eqv? hashv))
(define* (vhash-delete key vhash #\optional (equal? equal?) (hash hash))
"Remove all associations from VHASH with KEY, comparing keys
with EQUAL?."
(if (vhash-assoc key vhash equal? hash)
(vlist-fold (lambda (k+v result)
(let ((k (car k+v))
(v (cdr k+v)))
(if (equal? k key)
result
(vhash-cons k v result hash))))
vlist-null
vhash)
vhash))
(define vhash-delq (cut vhash-delete <> <> eq? hashq))
(define vhash-delv (cut vhash-delete <> <> eqv? hashv))
(define (vhash-fold proc init vhash)
"Fold over the key/pair elements of VHASH from left to right, with
each call to PROC having the form ‘(PROC key value result)’,
where RESULT is the result of the previous call to PROC and
INIT the value of RESULT for the first call to PROC."
(vlist-fold (lambda (key+value result)
(proc (car key+value) (cdr key+value)
result))
init
vhash))
(define (vhash-fold-right proc init vhash)
"Fold over the key/pair elements of VHASH from right to left, with
each call to PROC having the form ‘(PROC key value result)’,
where RESULT is the result of the previous call to PROC and
INIT the value of RESULT for the first call to PROC."
(vlist-fold-right (lambda (key+value result)
(proc (car key+value) (cdr key+value)
result))
init
vhash))
(define* (alist->vhash alist #\optional (hash hash))
"Return the vhash corresponding to ALIST, an association list."
(fold-right (lambda (pair result)
(vhash-cons (car pair) (cdr pair) result hash))
vlist-null
alist))
;;; vlist.scm ends here
;;; installed-scm-file
;;;; Copyright (C) 2003, 2006, 2014 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (ice-9 weak-vector)
\:export (make-weak-vector list->weak-vector weak-vector weak-vector?
weak-vector-length weak-vector-ref weak-vector-set!
make-weak-key-alist-vector
make-weak-value-alist-vector
make-doubly-weak-alist-vector
weak-key-alist-vector?
weak-value-alist-vector?
doubly-weak-alist-vector?) ; C
)
(%init-weaks-builtins) ; defined in libguile/weaks.c
;;; Guile Virtual Machine Assembly
;; Copyright (C) 2001, 2009, 2010, 2011 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language assembly)
#\use-module (rnrs bytevectors)
#\use-module (system base pmatch)
#\use-module (system vm instruction)
#\use-module ((srfi srfi-1) #\select (fold))
#\export (byte-length
addr+ align-program align-code align-block
assembly-pack assembly-unpack
object->assembly assembly->object))
;; len, metalen
(define *program-header-len* (+ 4 4))
;; lengths are encoded in 3 bytes
(define *len-len* 3)
(define (byte-length assembly)
(pmatch assembly
((,inst . _) (guard (>= (instruction-length inst) 0))
(+ 1 (instruction-length inst)))
((load-number ,str)
(+ 1 *len-len* (string-length str)))
((load-string ,str)
(+ 1 *len-len* (string-length str)))
((load-wide-string ,str)
(+ 1 *len-len* (* 4 (string-length str))))
((load-symbol ,str)
(+ 1 *len-len* (string-length str)))
((load-array ,bv)
(+ 1 *len-len* (bytevector-length bv)))
((load-program ,labels ,len ,meta . ,code)
(+ 1 *program-header-len* len (if meta (1- (byte-length meta)) 0)))
(,label (guard (not (pair? label)))
0)
(else (error "unknown instruction" assembly))))
(define *program-alignment* 8)
(define (addr+ addr code)
(fold (lambda (x len) (+ (byte-length x) len))
addr
code))
(define (code-alignment addr alignment header-len)
(make-list (modulo (- alignment
(modulo (+ addr header-len) alignment))
alignment)
'(nop)))
(define (align-block addr)
'())
(define (align-code code addr alignment header-len)
`(,@(code-alignment addr alignment header-len)
,code))
(define (align-program prog addr)
(align-code prog addr *program-alignment* 1))
;;;
;;; Code compress/decompression
;;;
(define *abbreviations*
'(((make-int8 0) . (make-int8:0))
((make-int8 1) . (make-int8:1))))
(define *expansions*
(map (lambda (x) (cons (cdr x) (car x))) *abbreviations*))
(define (assembly-pack code)
(or (assoc-ref *abbreviations* code)
code))
(define (assembly-unpack code)
(or (assoc-ref *expansions* code)
code))
;;;
;;; Encoder/decoder
;;;
(define (object->assembly x)
(cond ((eq? x #t) `(make-true))
((eq? x #f) `(make-false))
((eq? x #nil) `(make-nil))
((null? x) `(make-eol))
((and (integer? x) (exact? x))
(cond ((and (<= -128 x) (< x 128))
(assembly-pack `(make-int8 ,(modulo x 256))))
((and (<= -32768 x) (< x 32768))
(let ((n (if (< x 0) (+ x 65536) x)))
`(make-int16 ,(quotient n 256) ,(modulo n 256))))
((and (<= 0 x #xffffffffffffffff))
`(make-uint64 ,@(bytevector->u8-list
(let ((bv (make-bytevector 8)))
(bytevector-u64-set! bv 0 x (endianness big))
bv))))
((and (<= 0 (+ x #x8000000000000000) #x7fffffffffffffff))
`(make-int64 ,@(bytevector->u8-list
(let ((bv (make-bytevector 8)))
(bytevector-s64-set! bv 0 x (endianness big))
bv))))
(else #f)))
((char? x)
(cond ((<= (char->integer x) #xff)
`(make-char8 ,(char->integer x)))
(else
`(make-char32 ,(char->integer x)))))
(else #f)))
(define (assembly->object code)
(pmatch code
((make-true) #t)
((make-false) #f) ;; FIXME: Same as the `else' case!
((make-nil) #nil)
((make-eol) '())
((make-int8 ,n)
(if (< n 128) n (- n 256)))
((make-int16 ,n1 ,n2)
(let ((n (+ (* n1 256) n2)))
(if (< n 32768) n (- n 65536))))
((make-uint64 ,n1 ,n2 ,n3 ,n4 ,n5 ,n6 ,n7 ,n8)
(bytevector-u64-ref
(u8-list->bytevector (list n1 n2 n3 n4 n5 n6 n7 n8))
0
(endianness big)))
((make-int64 ,n1 ,n2 ,n3 ,n4 ,n5 ,n6 ,n7 ,n8)
(bytevector-s64-ref
(u8-list->bytevector (list n1 n2 n3 n4 n5 n6 n7 n8))
0
(endianness big)))
((make-char8 ,n)
(integer->char n))
((make-char32 ,n1 ,n2 ,n3 ,n4)
(integer->char (+ (* n1 #x1000000)
(* n2 #x10000)
(* n3 #x100)
n4)))
((load-string ,s) s)
((load-symbol ,s) (string->symbol s))
(else #f)))
;;; Guile VM assembler
;; Copyright (C) 2001, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language assembly compile-bytecode)
#\use-module (system base pmatch)
#\use-module (system base target)
#\use-module (language assembly)
#\use-module (system vm instruction)
#\use-module (rnrs bytevectors)
#\use-module ((srfi srfi-1) #\select (fold))
#\export (compile-bytecode))
(define (compile-bytecode assembly env . opts)
(define-syntax-rule (define-inline1 (proc arg) body body* ...)
(define-syntax proc
(syntax-rules ()
((_ (arg-expr (... ...)))
(let ((x (arg-expr (... ...))))
(proc x)))
((_ arg)
(begin body body* ...)))))
(define (fill-bytecode bv target-endianness)
(let ((pos 0))
(define-inline1 (write-byte b)
(bytevector-u8-set! bv pos b)
(set! pos (1+ pos)))
(define u32-bv (make-bytevector 4))
(define-inline1 (write-int24-be x)
(bytevector-s32-set! u32-bv 0 x (endianness big))
(bytevector-u8-set! bv pos (bytevector-u8-ref u32-bv 1))
(bytevector-u8-set! bv (+ pos 1) (bytevector-u8-ref u32-bv 2))
(bytevector-u8-set! bv (+ pos 2) (bytevector-u8-ref u32-bv 3))
(set! pos (+ pos 3)))
(define-inline1 (write-uint32-be x)
(bytevector-u32-set! bv pos x (endianness big))
(set! pos (+ pos 4)))
(define-inline1 (write-uint32 x)
(bytevector-u32-set! bv pos x target-endianness)
(set! pos (+ pos 4)))
(define-inline1 (write-loader-len len)
(bytevector-u8-set! bv pos (ash len -16))
(bytevector-u8-set! bv (+ pos 1) (logand (ash len -8) 255))
(bytevector-u8-set! bv (+ pos 2) (logand len 255))
(set! pos (+ pos 3)))
(define-inline1 (write-latin1-string s)
(let ((len (string-length s)))
(write-loader-len len)
(let lp ((i 0))
(if (< i len)
(begin
(bytevector-u8-set! bv (+ pos i)
(char->integer (string-ref s i)))
(lp (1+ i)))))
(set! pos (+ pos len))))
(define-inline1 (write-bytevector bv*)
(let ((len (bytevector-length bv*)))
(write-loader-len len)
(bytevector-copy! bv* 0 bv pos len)
(set! pos (+ pos len))))
(define-inline1 (write-wide-string s)
(write-bytevector (string->utf32 s target-endianness)))
(define-inline1 (write-break label)
(let ((offset (- (assq-ref labels label) (+ (get-addr) 3))))
(cond ((>= offset (ash 1 23)) (error "jump too far forward" offset))
((< offset (- (ash 1 23))) (error "jump too far backwards" offset))
(else (write-int24-be offset)))))
(define (write-bytecode asm labels address emit-opcode?)
;; Write ASM's bytecode to BV. If EMIT-OPCODE? is false, don't
;; emit bytecode for the first opcode encountered. Assume code
;; starts at ADDRESS (an integer). LABELS is assumed to be an
;; alist mapping labels to addresses.
(define get-addr
(let ((start pos))
(lambda ()
(+ address (- pos start)))))
(define (write-break label)
(let ((offset (- (assq-ref labels label) (+ (get-addr) 3))))
(cond ((>= offset (ash 1 23)) (error "jump too far forward" offset))
((< offset (- (ash 1 23))) (error "jump too far backwards" offset))
(else (write-int24-be offset)))))
(let ((inst (car asm))
(args (cdr asm)))
(let ((opcode (instruction->opcode inst))
(len (instruction-length inst)))
(if emit-opcode?
(write-byte opcode))
(pmatch asm
((load-program ,labels ,length ,meta . ,code)
(write-uint32 length)
(write-uint32 (if meta (1- (byte-length meta)) 0))
(fold (lambda (asm address)
(let ((start pos))
(write-bytecode asm labels address #t)
(+ address (- pos start))))
0
code)
(if meta
;; Don't emit the `load-program' byte for metadata. Note that
;; META's bytecode meets the alignment requirements of
;; `scm_objcode', thanks to the alignment computed in `(language
;; assembly)'.
(write-bytecode meta '() 0 #f)))
((make-char32 ,x) (write-uint32-be x))
((load-number ,str) (write-latin1-string str))
((load-string ,str) (write-latin1-string str))
((load-wide-string ,str) (write-wide-string str))
((load-symbol ,str) (write-latin1-string str))
((load-array ,bv) (write-bytevector bv))
((br ,l) (write-break l))
((br-if ,l) (write-break l))
((br-if-not ,l) (write-break l))
((br-if-eq ,l) (write-break l))
((br-if-not-eq ,l) (write-break l))
((br-if-null ,l) (write-break l))
((br-if-not-null ,l) (write-break l))
((br-if-nargs-ne ,hi ,lo ,l) (write-byte hi) (write-byte lo) (write-break l))
((br-if-nargs-lt ,hi ,lo ,l) (write-byte hi) (write-byte lo) (write-break l))
((br-if-nargs-gt ,hi ,lo ,l) (write-byte hi) (write-byte lo) (write-break l))
((bind-optionals/shuffle-or-br ,nreq-hi ,nreq-lo
,nreq-and-nopt-hi ,nreq-and-nopt-lo
,ntotal-hi ,ntotal-lo
,l)
(write-byte nreq-hi)
(write-byte nreq-lo)
(write-byte nreq-and-nopt-hi)
(write-byte nreq-and-nopt-lo)
(write-byte ntotal-hi)
(write-byte ntotal-lo)
(write-break l))
((mv-call ,n ,l) (write-byte n) (write-break l))
((prompt ,escape-only? ,l) (write-byte escape-only?) (write-break l))
(else
(cond
((< len 0)
(error "unhanded variable-length instruction" asm))
((not (= (length args) len))
(error "bad number of args to instruction" asm len))
(else
(for-each (lambda (x) (write-byte x)) args))))))))
;; Don't emit the `load-program' byte.
(write-bytecode assembly '() 0 #f)
(if (= pos (bytevector-length bv))
(values bv env env)
(error "failed to fill bytevector" bv pos
(bytevector-length bv)))))
(pmatch assembly
((load-program ,labels ,length ,meta . ,code)
(fill-bytecode (make-bytevector (+ 4 4 length
(if meta
(1- (byte-length meta))
0)))
(target-endianness)))
(else (error "bad assembly" assembly))))
;;; Guile VM code converters
;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language assembly decompile-bytecode)
#\use-module (system vm instruction)
#\use-module (system base pmatch)
#\use-module (srfi srfi-4)
#\use-module (rnrs bytevectors)
#\use-module (language assembly)
#\use-module ((system vm objcode) #\select (byte-order))
#\export (decompile-bytecode))
(define (decompile-bytecode x env opts)
(let ((i 0) (size (u8vector-length x)))
(define (pop)
(let ((b (cond ((< i size) (u8vector-ref x i))
((= i size) #f)
(else (error "tried to decode too many bytes")))))
(if b (set! i (1+ i)))
b))
(let ((ret (decode-load-program pop)))
(if (= i size)
(values ret env)
(error "bad bytecode: only decoded ~a out of ~a bytes" i size)))))
(define (br-instruction? x)
(memq x '(br br-if br-if-not br-if-eq br-if-not-eq br-if-null br-if-not-null)))
(define (br-nargs-instruction? x)
(memq x '(br-if-nargs-ne br-if-nargs-lt br-if-nargs-gt br-if-nargs-lt/non-kw)))
(define (bytes->s24 a b c)
(let ((x (+ (ash a 16) (ash b 8) c)))
(if (zero? (logand (ash 1 23) x))
x
(- x (ash 1 24)))))
;; FIXME: this is a little-endian disassembly!!!
(define (decode-load-program pop)
(let* ((a (pop)) (b (pop)) (c (pop)) (d (pop))
(e (pop)) (f (pop)) (g (pop)) (h (pop))
(len (+ a (ash b 8) (ash c 16) (ash d 24)))
(metalen (+ e (ash f 8) (ash g 16) (ash h 24)))
(labels '())
(i 0))
(define (ensure-label rel1 rel2 rel3)
(let ((where (+ i (bytes->s24 rel1 rel2 rel3))))
(or (assv-ref labels where)
(begin
(let ((l (gensym ":L")))
(set! labels (acons where l labels))
l)))))
(define (sub-pop) ;; ...records. ha. ha.
(let ((b (cond ((< i len) (pop))
((= i len) #f)
(else (error "tried to decode too many bytes")))))
(if b (set! i (1+ i)))
b))
(let lp ((out '()))
(cond ((> i len)
(error "error decoding program -- read too many bytes" out))
((= i len)
`(load-program ,(map (lambda (x) (cons (cdr x) (car x)))
(reverse labels))
,len
,(if (zero? metalen) #f (decode-load-program pop))
,@(reverse! out)))
(else
(let ((exp (decode-bytecode sub-pop)))
(pmatch exp
((,br ,rel1 ,rel2 ,rel3) (guard (br-instruction? br))
(lp (cons `(,br ,(ensure-label rel1 rel2 rel3)) out)))
((,br ,hi ,lo ,rel1 ,rel2 ,rel3) (guard (br-nargs-instruction? br))
(lp (cons `(,br ,hi ,lo ,(ensure-label rel1 rel2 rel3)) out)))
((bind-optionals/shuffle-or-br ,nreq-hi ,nreq-lo
,nreq-and-nopt-hi ,nreq-and-nopt-lo
,ntotal-hi ,ntotal-lo
,rel1 ,rel2 ,rel3)
(lp (cons `(bind-optionals/shuffle-or-br
,nreq-hi ,nreq-lo
,nreq-and-nopt-hi ,nreq-and-nopt-lo
,ntotal-hi ,ntotal-lo
,(ensure-label rel1 rel2 rel3))
out)))
((mv-call ,n ,rel1 ,rel2 ,rel3)
(lp (cons `(mv-call ,n ,(ensure-label rel1 rel2 rel3)) out)))
((prompt ,n0 ,rel1 ,rel2 ,rel3)
(lp (cons `(prompt ,n0 ,(ensure-label rel1 rel2 rel3)) out)))
(else
(lp (cons exp out))))))))))
(define (decode-bytecode pop)
(and=> (pop)
(lambda (opcode)
(let ((inst (opcode->instruction opcode)))
(cond
((eq? inst 'load-program)
(decode-load-program pop))
((< (instruction-length inst) 0)
;; the negative length indicates a variable length
;; instruction
(let* ((make-sequence
(if (or (memq inst '(load-array load-wide-string)))
make-bytevector
make-string))
(sequence-set!
(if (or (memq inst '(load-array load-wide-string)))
bytevector-u8-set!
(lambda (str pos value)
(string-set! str pos (integer->char value)))))
(len (let* ((a (pop)) (b (pop)) (c (pop)))
(+ (ash a 16) (ash b 8) c)))
(seq (make-sequence len)))
(let lp ((i 0))
(if (= i len)
`(,inst ,(if (eq? inst 'load-wide-string)
(utf32->string seq (native-endianness))
seq))
(begin
(sequence-set! seq i (pop))
(lp (1+ i)))))))
(else
;; fixed length
(let lp ((n (instruction-length inst)) (out (list inst)))
(if (zero? n)
(reverse! out)
(lp (1- n) (cons (pop) out))))))))))
;;; Guile VM code converters
;; Copyright (C) 2001, 2009, 2010, 2012, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language assembly disassemble)
#\use-module (ice-9 format)
#\use-module (srfi srfi-1)
#\use-module (system vm instruction)
#\use-module (system vm program)
#\use-module (system base pmatch)
#\use-module (language assembly)
#\use-module (system base compile)
#\export (disassemble))
(define (disassemble x)
(format #t "Disassembly of ~A:\n\n" x)
(call-with-values
(lambda () (decompile x #\from 'value #\to 'assembly))
disassemble-load-program))
(define (disassemble-load-program asm env)
(pmatch asm
((load-program ,labels ,len ,meta . ,code)
(let ((objs (and env (assq-ref env 'objects)))
(free-vars (and env (assq-ref env 'free-vars)))
(meta (and env (assq-ref env 'meta)))
(blocs (and env (assq-ref env 'blocs)))
(srcs (and env (assq-ref env 'sources))))
(let lp ((pos 0) (code code) (programs '()))
(cond
((null? code)
(newline)
(for-each
(lambda (sym+asm)
(format #t "Embedded program ~A:\n\n" (car sym+asm))
(disassemble-load-program (cdr sym+asm) '()))
(reverse! programs)))
(else
(let* ((asm (car code))
(len (byte-length asm))
(end (+ pos len)))
(pmatch asm
((load-program . _)
(let ((sym (gensym "")))
(print-info pos `(load-program ,sym) #f #f)
(lp (+ pos (byte-length asm)) (cdr code)
(acons sym asm programs))))
((nop)
(lp (+ pos (byte-length asm)) (cdr code) programs))
(else
(print-info pos asm
;; FIXME: code-annotation for whether it's
;; an arg or not, currently passing nargs=-1
(code-annotation end asm objs -1 blocs
labels)
(and=> (and srcs (assq end srcs)) source->string))
(lp (+ pos (byte-length asm)) (cdr code) programs)))))))
(if (pair? free-vars)
(disassemble-free-vars free-vars))
(if meta
(disassemble-meta meta))
;; Disassemble other bytecode in it
;; FIXME: something about the module.
(if objs
(for-each
(lambda (x)
(if (program? x)
(begin (display "----------------------------------------\n")
(disassemble x))))
(cdr (vector->list objs))))))
(else
(error "bad load-program form" asm))))
(define (disassemble-free-vars free-vars)
(display "Free variables:\n\n")
(fold (lambda (free-var i)
(print-info i free-var #f #f)
(+ 1 i))
0
free-vars))
(define-macro (unless test . body)
`(if (not ,test) (begin ,@body)))
(define *uninteresting-props* '(name))
(define (disassemble-meta meta)
(let ((props (filter (lambda (x)
(not (memq (car x) *uninteresting-props*)))
(cdddr meta))))
(unless (null? props)
(display "Properties:\n\n")
(for-each (lambda (x) (print-info #f x #f #f)) props)
(newline))))
(define (source->string src)
(format #f "~a:~a:~a" (or (source:file src) "(unknown file)")
(source:line-for-user src) (source:column src)))
(define (make-int16 byte1 byte2)
(+ (* byte1 256) byte2))
(define (code-annotation end-addr code objs nargs blocs labels)
(let* ((code (assembly-unpack code))
(inst (car code))
(args (cdr code)))
(case inst
((list vector)
(list "~a element~:p" (apply make-int16 args)))
((br br-if br-if-eq br-if-not br-if-not-eq br-if-not-null br-if-null)
(list "-> ~A" (assq-ref labels (car args))))
((br-if-nargs-ne br-if-nargs-lt br-if-nargs-gt)
(list "-> ~A" (assq-ref labels (caddr args))))
((bind-optionals/shuffle-or-br)
(list "-> ~A" (assq-ref labels (car (last-pair args)))))
((object-ref)
(and objs (list "~s" (vector-ref objs (car args)))))
((local-ref local-boxed-ref local-set local-boxed-set)
(and blocs
(let lp ((bindings (list-ref blocs (car args))))
(and (pair? bindings)
(let ((b (car bindings)))
(if (and (< (binding:start (car bindings)) end-addr)
(>= (binding:end (car bindings)) end-addr))
(list "`~a'~@[ (arg)~]"
(binding:name b) (< (binding:index b) nargs))
(lp (cdr bindings))))))))
((assert-nargs-ee/locals assert-nargs-ge/locals)
(list "~a arg~:p, ~a local~:p"
(logand (car args) #x7) (ash (car args) -3)))
((free-ref free-boxed-ref free-boxed-set)
;; FIXME: we can do better than this
(list "(closure variable)"))
((toplevel-ref toplevel-set)
(and objs
(let ((v (vector-ref objs (car args))))
(if (and (variable? v) (variable-bound? v))
(list "~s" (variable-ref v))
(list "`~s'" v)))))
((mv-call)
(list "MV -> ~A" (assq-ref labels (cadr args))))
((prompt)
;; the H is for handler
(list "H -> ~A" (assq-ref labels (cadr args))))
(else
(and=> (assembly->object code)
(lambda (obj) (list "~s" obj)))))))
;; i am format's daddy.
(define (print-info addr info extra src)
(format #t "~4@S ~32S~@[;; ~1{~@?~}~]~@[~61t at ~a~]\n" addr info extra src))
;;; Guile Virtual Machine Assembly
;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language assembly spec)
#\use-module (system base language)
#\use-module (language assembly compile-bytecode)
#\use-module (language assembly decompile-bytecode)
#\export (assembly))
(define-language assembly
#\title "Guile Virtual Machine Assembly Language"
#\reader (lambda (port env) (read port))
#\printer write
#\parser read ;; fixme: make a verifier?
#\compilers `((bytecode . ,compile-bytecode))
#\decompilers `((bytecode . ,decompile-bytecode))
#\for-humans? #f
)
;;; Brainfuck for GNU Guile
;; Copyright (C) 2009, 2013 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language brainfuck compile-scheme)
#\export (compile-scheme))
;; Compilation of Brainfuck to Scheme is pretty straight-forward. For all of
;; brainfuck's instructions, there are basic representations in Scheme we
;; only have to generate.
;;
;; Brainfuck's pointer and data-tape are stored in the variables pointer and
;; tape, where tape is a vector of integer values initially set to zero. Pointer
;; starts out at position 0.
;; Our tape is thus of finite length, with an address range of 0..n for
;; some defined upper bound n depending on the length of our tape.
;; Define the length to use for the tape.
(define tape-size 30000)
;; This compiles a whole brainfuck program. This constructs a Scheme code like:
;; (let ((pointer 0)
;; (tape (make-vector tape-size 0)))
;; (begin
;; <body>
;; (write-char #\newline)))
;;
;; So first the pointer and tape variables are set up correctly, then the
;; program's body is executed in this context, and finally we output an
;; additional newline character in case the program does not output one.
;;
;; TODO: Find out and explain the details about env, the three return values and
;; how to use the options. Implement options to set the tape-size, maybe.
(define (compile-scheme exp env opts)
(values
`(let ((pointer 0)
(tape (make-vector ,tape-size 0)))
,@(compile-body (cdr exp))
(write-char #\newline))
env
env))
;; Compile a list of instructions to get a list of Scheme codes. As we always
;; strip off the car of the instructions-list and cons the result onto the
;; result-list, it will get out in reversed order first; so we have to (reverse)
;; it on return.
(define (compile-body instructions)
(let iterate ((cur instructions)
(result '()))
(if (null? cur)
(reverse result)
(let ((compiled (compile-instruction (car cur))))
(iterate (cdr cur) (cons compiled result))))))
;; Compile a single instruction to Scheme, using the direct representations
;; all of Brainfuck's instructions have.
(define (compile-instruction ins)
(case (car ins)
;; Pointer moval >< is done simply by something like:
;; (set! pointer (+ pointer +-1))
((<bf-move>)
(let ((dir (cadr ins)))
`(set! pointer (+ pointer ,dir))))
;; Cell increment +- is done as:
;; (vector-set! tape pointer (+ (vector-ref tape pointer) +-1))
((<bf-increment>)
(let ((inc (cadr ins)))
`(vector-set! tape pointer (+ (vector-ref tape pointer) ,inc))))
;; Output . is done by converting the cell's integer value to a character
;; first and then printing out this character:
;; (write-char (integer->char (vector-ref tape pointer)))
((<bf-print>)
'(write-char (integer->char (vector-ref tape pointer))))
;; Input , is done similarly, read in a character, get its ASCII code and
;; store it into the current cell:
;; (vector-set! tape pointer (char->integer (read-char)))
((<bf-read>)
'(vector-set! tape pointer (char->integer (read-char))))
;; For loops [...] we use a named let construction to execute the body until
;; the current cell gets zero. The body is compiled via a recursive call
;; back to (compile-body).
;; (let iterate ()
;; (if (not (= (vector-ref! tape pointer) 0))
;; (begin
;; <body>
;; (iterate))))
((<bf-loop>)
`(let iterate ()
(if (not (= (vector-ref tape pointer) 0))
(begin
,@(compile-body (cdr ins))
(iterate)))))
(else (error "unknown brainfuck instruction " (car ins)))))
;;; Brainfuck for GNU Guile
;; Copyright (C) 2009 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary:
;; Brainfuck is a simple language that mostly mimics the operations of a
;; Turing machine. This file implements a compiler from Brainfuck to
;; Guile's Tree-IL.
;;; Code:
(define-module (language brainfuck compile-tree-il)
#\use-module (system base pmatch)
#\use-module (language tree-il)
#\export (compile-tree-il))
;; Compilation of Brainfuck is pretty straight-forward. For all of
;; brainfuck's instructions, there are basic representations in Tree-IL
;; we only have to generate.
;;
;; Brainfuck's pointer and data-tape are stored in the variables pointer and
;; tape, where tape is a vector of integer values initially set to zero. Pointer
;; starts out at position 0.
;; Our tape is thus of finite length, with an address range of 0..n for
;; some defined upper bound n depending on the length of our tape.
;; Define the length to use for the tape.
(define tape-size 30000)
;; This compiles a whole brainfuck program. This constructs a Tree-IL
;; code equivalent to Scheme code like this:
;;
;; (let ((pointer 0)
;; (tape (make-vector tape-size 0)))
;; (begin
;; <body>
;; (write-char #\newline)))
;;
;; So first the pointer and tape variables are set up correctly, then the
;; program's body is executed in this context, and finally we output an
;; additional newline character in case the program does not output one.
;;
;; The fact that we are compiling to Guile primitives gives this
;; implementation a number of interesting characteristics. First, the
;; values of the tape cells do not underflow or overflow. We could make
;; them do otherwise via compiling calls to "modulo" at certain points.
;;
;; In addition, tape overruns or underruns will be detected, and will
;; throw an error, whereas a number of Brainfuck compilers do not detect
;; this.
;;
;; Note that we're generating the S-expression representation of
;; Tree-IL, then using parse-tree-il to turn it into the actual Tree-IL
;; data structures. This makes the compiler more pleasant to look at,
;; but we do lose is the ability to propagate source information. Since
;; Brainfuck is so obtuse anyway, this shouldn't matter ;-)
;;
;; `compile-tree-il' takes as its input the read expression, the
;; environment, and some compile options. It returns the compiled
;; expression, the environment appropriate for the next pass of the
;; compiler -- in our case, just the environment unchanged -- and the
;; continuation environment.
;;
;; The normal use of a continuation environment is if compiling one
;; expression changes the environment, and that changed environment
;; should be passed to the next compiled expression -- for example,
;; changing the current module. But Brainfuck is incapable of that, so
;; for us, the continuation environment is just the same environment we
;; got in.
;;
;; FIXME: perhaps use options or the env to set the tape-size?
(define (compile-tree-il exp env opts)
(values
(parse-tree-il
`(let (pointer tape) (pointer tape)
((const 0)
(apply (primitive make-vector) (const ,tape-size) (const 0)))
,(compile-body exp)))
env
env))
;; Compile a list of instructions to a Tree-IL expression.
(define (compile-body instructions)
(let lp ((in instructions) (out '()))
(define (emit x)
(lp (cdr in) (cons x out)))
(cond
((null? in)
;; No more input, build our output.
(cond
((null? out) '(void)) ; no output
((null? (cdr out)) (car out)) ; single expression
(else `(begin ,@(reverse out)))) ; sequence
)
(else
(pmatch (car in)
;; Pointer moves >< are done simply by something like:
;; (set! pointer (+ pointer +-1))
((<bf-move> ,dir)
(emit `(set! (lexical pointer)
(apply (primitive +) (lexical pointer) (const ,dir)))))
;; Cell increment +- is done as:
;; (vector-set! tape pointer (+ (vector-ref tape pointer) +-1))
((<bf-increment> ,inc)
(emit `(apply (primitive vector-set!) (lexical tape) (lexical pointer)
(apply (primitive +)
(apply (primitive vector-ref)
(lexical tape) (lexical pointer))
(const ,inc)))))
;; Output . is done by converting the cell's integer value to a
;; character first and then printing out this character:
;; (write-char (integer->char (vector-ref tape pointer)))
((<bf-print>)
(emit `(apply (primitive write-char)
(apply (primitive integer->char)
(apply (primitive vector-ref)
(lexical tape) (lexical pointer))))))
;; Input , is done similarly, read in a character, get its ASCII
;; code and store it into the current cell:
;; (vector-set! tape pointer (char->integer (read-char)))
((<bf-read>)
(emit `(apply (primitive vector-set!)
(lexical tape) (lexical pointer)
(apply (primitive char->integer)
(apply (primitive read-char))))))
;; For loops [...] we use a letrec construction to execute the body until
;; the current cell gets zero. The body is compiled via a recursive call
;; back to (compile-body).
;; (let iterate ()
;; (if (not (= (vector-ref! tape pointer) 0))
;; (begin
;; <body>
;; (iterate))))
;;
;; Indeed, letrec is the only way we have to loop in Tree-IL.
;; Note that this does not mean that the closure must actually
;; be created; later passes can compile tail-recursive letrec
;; calls into inline code with gotos. Admittedly, that part of
;; the compiler is not yet in place, but it will be, and in the
;; meantime the code is still reasonably efficient.
((<bf-loop> . ,body)
(let ((iterate (gensym)))
(emit `(letrec (iterate) (,iterate)
((lambda ()
(lambda-case
((() #f #f #f () ())
(if (apply (primitive =)
(apply (primitive vector-ref)
(lexical tape) (lexical pointer))
(const 0))
(void)
(begin ,(compile-body body)
(apply (lexical ,iterate)))))
#f)))
(apply (lexical ,iterate))))))
(else (error "unknown brainfuck instruction" (car in))))))))
;;; Brainfuck for GNU Guile.
;; Copyright (C) 2009, 2013 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code:
(define-module (language brainfuck parse)
#\export (read-brainfuck))
; Purpose of the parse module is to read in brainfuck in text form and produce
; the corresponding tree representing the brainfuck code.
;
; Each object (representing basically a single instruction) is structured like:
; (<instruction> [arguments])
; where <instruction> is a symbolic name representing the type of instruction
; and the optional arguments represent further data (for instance, the body of
; a [...] loop as a number of nested instructions).
; While reading a number of instructions in sequence, all of them are cons'ed
; onto a list of instructions; thus this list gets out in reverse order.
; Additionally, for "comment characters" (everything not an instruction) we
; generate <bf-nop> NOP instructions.
;
; This routine reverses a list of instructions and removes all <bf-nop>'s on the
; way to fix these two issues for a read-in list.
(define (reverse-without-nops lst)
(let iterate ((cur lst)
(result '()))
(if (null? cur)
result
(let ((head (car cur))
(tail (cdr cur)))
(if (eq? (car head) '<bf-nop>)
(iterate tail result)
(iterate tail (cons head result)))))))
; Read in a set of instructions until a terminating ] character is found (or
; end of file is reached). This is used both for loop bodies and whole
; programs, so that a program has to be either terminated by EOF or an
; additional ], too.
;
; For instance, the basic program so just echo one character would be:
; ,.]
(define (read-brainfuck p)
(let iterate ((parsed '()))
(let ((chr (read-char p)))
(cond
((eof-object? chr)
(let ((parsed (reverse-without-nops parsed)))
(if (null? parsed)
chr ;; pass on the EOF object
parsed)))
((eqv? chr #\])
(reverse-without-nops parsed))
(else
(iterate (cons (process-input-char chr p) parsed)))))))
; This routine processes a single character of input and builds the
; corresponding instruction. Loop bodies are read by recursively calling
; back (read-brainfuck).
;
; For the poiner movement commands >< and the cell increment/decrement +-
; commands, we only use one instruction form each and specify the direction of
; the pointer/value increment using an argument to the instruction form.
(define (process-input-char chr p)
(case chr
((#\>) '(<bf-move> 1))
((#\<) '(<bf-move> -1))
((#\+) '(<bf-increment> 1))
((#\-) '(<bf-increment> -1))
((#\.) '(<bf-print>))
((#\,) '(<bf-read>))
((#\[) `(<bf-loop> ,@(read-brainfuck p)))
(else '(<bf-nop>))))
;;; Brainfuck for GNU Guile.
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code:
(define-module (language brainfuck spec)
#\use-module (language brainfuck compile-tree-il)
#\use-module (language brainfuck compile-scheme)
#\use-module (language brainfuck parse)
#\use-module (system base language)
#\export (brainfuck))
; The new language is integrated into Guile via this (define-language)
; specification in the special module (language [lang] spec).
; Provided is a parser-routine in #\reader, a output routine in #\printer
; and one or more compiler routines (as target-language - routine pairs)
; in #\compilers. This is the basic set of fields needed to specify a new
; language.
(define-language brainfuck
#\title "Brainfuck"
#\reader (lambda (port env) (read-brainfuck port))
#\compilers `((tree-il . ,compile-tree-il)
(scheme . ,compile-scheme))
#\printer write
)
;;; Guile Lowlevel Intermediate Language
;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language bytecode spec)
#\use-module (system base language)
#\use-module (system vm objcode)
#\export (bytecode))
(define (compile-objcode x e opts)
(values (bytecode->objcode x) e e))
(define (decompile-objcode x e opts)
(values (objcode->bytecode x) e))
(define-language bytecode
#\title "Guile Bytecode Vectors"
#\reader (lambda (port env) (read port))
#\printer write
#\compilers `((objcode . ,compile-objcode))
#\decompilers `((objcode . ,decompile-objcode))
#\for-humans? #f
)
;;; ECMAScript for Guile
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript array)
#\use-module (oop goops)
#\use-module (language ecmascript base)
#\use-module (language ecmascript function)
#\export (*array-prototype* new-array))
(define-class <js-array-object> (<js-object>)
(vector #\init-value #() #\accessor js-array-vector #\init-keyword #\vector))
(define (new-array . vals)
(let ((o (make <js-array-object> #\class "Array"
#\prototype *array-prototype*)))
(pput o 'length (length vals))
(let ((vect (js-array-vector o)))
(let lp ((i 0) (vals vals))
(cond ((not (null? vals))
(vector-set! vect i (car vals))
(lp (1+ i) (cdr vals)))
(else o))))))
(define *array-prototype* (make <js-object> #\class "Array"
#\value new-array
#\constructor new-array))
(hashq-set! *program-wrappers* new-array *array-prototype*)
(pput *array-prototype* 'prototype *array-prototype*)
(pput *array-prototype* 'constructor new-array)
(define-method (pget (o <js-array-object>) p)
(cond ((and (integer? p) (exact? p) (>= p 0))
(let ((v (js-array-vector o)))
(if (< p (vector-length v))
(vector-ref v p)
(next-method))))
((or (and (symbol? p) (eq? p 'length))
(and (string? p) (string=? p "length")))
(vector-length (js-array-vector o)))
(else (next-method))))
(define-method (pput (o <js-array-object>) p v)
(cond ((and (integer? p) (exact? p) (>= 0 p))
(let ((vect (js-array-vector o)))
(if (< p (vector-length vect))
(vector-set! vect p v)
;; Fixme: round up to powers of 2?
(let ((new (make-vector (1+ p) 0)))
(vector-move-left! vect 0 (vector-length vect) new 0)
(set! (js-array-vector o) new)
(vector-set! new p v)))))
((or (and (symbol? p) (eq? p 'length))
(and (string? p) (string=? p "length")))
(let ((vect (js-array-vector o)))
(let ((new (make-vector (->uint32 v) 0)))
(vector-move-left! vect 0 (min (vector-length vect) (->uint32 v))
new 0)
(set! (js-array-vector o) new))))
(else (next-method))))
(define-js-method *array-prototype* (toString)
(format #f "~A" (js-array-vector this)))
(define-js-method *array-prototype* (concat . rest)
(let* ((len (apply + (->uint32 (pget this 'length))
(map (lambda (x) (->uint32 (pget x 'length)))
rest)))
(rv (make-vector len 0)))
(let lp ((objs (cons this rest)) (i 0))
(cond ((null? objs) (make <js-array-object> #\class "Array"
#\prototype *array-prototype*
#\vector rv))
((is-a? (car objs) <js-array-object>)
(let ((v (js-array-vector (car objs))))
(vector-move-left! v 0 (vector-length v)
rv i)
(lp (cdr objs) (+ i (vector-length v)))))
(else
(error "generic array concats not yet implemented"))))))
(define-js-method *array-prototype* (join . separator)
(let lp ((i (1- (->uint32 (pget this 'length)))) (l '()))
(if (< i 0)
(string-join l (if separator (->string (car separator)) ","))
(lp (1+ i)
(cons (->string (pget this i)) l)))))
(define-js-method *array-prototype* (pop)
(let ((len (->uint32 (pget this 'length))))
(if (zero? len)
*undefined*
(let ((ret (pget this (1- len))))
(pput this 'length (1- len))
ret))))
(define-js-method *array-prototype* (push . args)
(let lp ((args args))
(if (null? args)
(->uint32 (pget this 'length))
(begin (pput this (->uint32 (pget this 'length)) (car args))
(lp (cdr args))))))
;;; ECMAScript for Guile
;; Copyright (C) 2009, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript base)
#\use-module (oop goops)
#\export (*undefined* *this*
<js-object> *object-prototype*
js-prototype js-props js-prop-attrs js-value js-constructor js-class
pget prop-keys prop-attrs prop-has-attr? pput has-property? pdel
object->string object->number object->value/string
object->value/number object->value
->primitive ->boolean ->number ->integer ->int32 ->uint32
->uint16 ->string ->object
call/this* call/this lambda/this define-js-method
new-object new))
(define *undefined* ((@@ (oop goops) make-unbound)))
(define *this* (make-fluid))
(define-class <js-object> ()
(prototype #\getter js-prototype #\init-keyword #\prototype
#\init-thunk (lambda () *object-prototype*))
(props #\getter js-props #\init-form (make-hash-table 7))
(prop-attrs #\getter js-prop-attrs #\init-value #f)
(value #\getter js-value #\init-value #f #\init-keyword #\value)
(constructor #\getter js-constructor #\init-value #f #\init-keyword #\constructor)
(class #\getter js-class #\init-value "Object" #\init-keyword #\class))
(define-method (prop-keys (o <js-object>))
(hash-map->list (lambda (k v) k) (js-props o)))
(define-method (pget (o <js-object>) (p <string>))
(pget o (string->symbol p)))
(define-method (pget (o <js-object>) p)
(let ((h (hashq-get-handle (js-props o) p)))
(if h
(cdr h)
(let ((proto (js-prototype o)))
(if proto
(pget proto p)
*undefined*)))))
(define-method (prop-attrs (o <js-object>) p)
(or (let ((attrs (js-prop-attrs o)))
(and attrs (hashq-ref (js-prop-attrs o) p)))
(let ((proto (js-prototype o)))
(if proto
(prop-attrs proto p)
'()))))
(define-method (prop-has-attr? (o <js-object>) p attr)
(memq attr (prop-attrs o p)))
(define-method (pput (o <js-object>) p v)
(if (prop-has-attr? o p 'ReadOnly)
(throw 'ReferenceError o p)
(hashq-set! (js-props o) p v)))
(define-method (pput (o <js-object>) (p <string>) v)
(pput o (string->symbol p) v))
(define-method (pdel (o <js-object>) p)
(if (prop-has-attr? o p 'DontDelete)
#f
(begin
(pput o p *undefined*)
#t)))
(define-method (pdel (o <js-object>) (p <string>) v)
(pdel o (string->symbol p)))
(define-method (has-property? (o <js-object>) p)
(if (hashq-get-handle (js-props o) p)
#t
(let ((proto (js-prototype o)))
(if proto
(has-property? proto p)
#f))))
(define (call/this* this f)
(with-fluid* *this* this f))
(define-macro (call/this this f . args)
`(with-fluid* *this* ,this (lambda () (,f . ,args))))
(define-macro (lambda/this formals . body)
`(lambda ,formals (let ((this (fluid-ref *this*))) . ,body)))
(define-macro (define-js-method object name-and-args . body)
`(pput ,object ',(car name-and-args) (lambda/this ,(cdr name-and-args) . ,body)))
(define *object-prototype* #f)
(set! *object-prototype* (make <js-object>))
(define-js-method *object-prototype* (toString)
(format #f "[object ~A]" (js-class this)))
(define-js-method *object-prototype* (toLocaleString . args)
((pget *object-prototype* 'toString)))
(define-js-method *object-prototype* (valueOf)
this)
(define-js-method *object-prototype* (hasOwnProperty p)
(and (hashq-get-handle (js-props this) p) #t))
(define-js-method *object-prototype* (isPrototypeOf v)
(eq? this (js-prototype v)))
(define-js-method *object-prototype* (propertyIsEnumerable p)
(and (hashq-get-handle (js-props this) p)
(not (prop-has-attr? this p 'DontEnum))))
(define (object->string o error?)
(let ((toString (pget o 'toString)))
(if (procedure? toString)
(let ((x (call/this o toString)))
(if (and error? (is-a? x <js-object>))
(throw 'TypeError o 'default-value)
x))
(if error?
(throw 'TypeError o 'default-value)
o))))
(define (object->number o error?)
(let ((valueOf (pget o 'valueOf)))
(if (procedure? valueOf)
(let ((x (call/this o valueOf)))
(if (and error? (is-a? x <js-object>))
(throw 'TypeError o 'default-value)
x))
(if error?
(throw 'TypeError o 'default-value)
o))))
(define (object->value/string o)
(if (is-a? o <js-object>)
(object->number o #t)
o))
(define (object->value/number o)
(if (is-a? o <js-object>)
(object->string o #t)
o))
(define (object->value o)
;; FIXME: if it's a date, we should try numbers first
(object->value/string o))
(define (->primitive x)
(if (is-a? x <js-object>)
(object->value x)
x))
(define (->boolean x)
(not (or (not x) (null? x) (eq? x *undefined*)
(and (number? x) (or (zero? x) (nan? x)))
(and (string? x) (= (string-length x) 0)))))
(define (->number x)
(cond ((number? x) x)
((boolean? x) (if x 1 0))
((null? x) 0)
((eq? x *undefined*) +nan.0)
((is-a? x <js-object>) (object->number x #t))
((string? x) (string->number x))
(else (throw 'TypeError x '->number))))
(define (->integer x)
(let ((n (->number x)))
(cond ((nan? n) 0)
((zero? n) n)
((inf? n) n)
(else (inexact->exact (round n))))))
(define (->int32 x)
(let ((n (->number x)))
(if (or (nan? n) (zero? n) (inf? n))
0
(let ((m (logand (1- (ash 1 32)) (inexact->exact (round n)))))
(if (negative? n)
(- m (ash 1 32))
m)))))
(define (->uint32 x)
(let ((n (->number x)))
(if (or (nan? n) (zero? n) (inf? n))
0
(logand (1- (ash 1 32)) (inexact->exact (round n))))))
(define (->uint16 x)
(let ((n (->number x)))
(if (or (nan? n) (zero? n) (inf? n))
0
(logand (1- (ash 1 16)) (inexact->exact (round n))))))
(define (->string x)
(cond ((eq? x *undefined*) "undefined")
((null? x) "null")
((boolean? x) (if x "true" "false"))
((string? x) x)
((number? x)
(cond ((nan? x) "NaN")
((zero? x) "0")
((inf? x) "Infinity")
(else (number->string x))))
(else (->string (object->value/string x)))))
(define (->object x)
(cond ((eq? x *undefined*) (throw 'TypeError x '->object))
((null? x) (throw 'TypeError x '->object))
((boolean? x) (make <js-object> #\prototype Boolean #\value x))
((number? x) (make <js-object> #\prototype String #\value x))
((string? x) (make <js-object> #\prototype Number #\value x))
(else x)))
(define (new-object . pairs)
(let ((o (make <js-object>)))
(map (lambda (pair)
(pput o (car pair) (cdr pair)))
pairs)
o))
(slot-set! *object-prototype* 'constructor new-object)
(define-method (new o . initargs)
(let ((ctor (js-constructor o)))
(if (not ctor)
(throw 'TypeError 'new o)
(let ((o (make <js-object>
#\prototype (or (js-prototype o) *object-prototype*))))
(let ((new-o (call/this o apply ctor initargs)))
(if (is-a? new-o <js-object>)
new-o
o))))))
;;; ECMAScript for Guile
;; Copyright (C) 2009, 2011 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript compile-tree-il)
#\use-module (language tree-il)
#\use-module (ice-9 receive)
#\use-module (system base pmatch)
#\use-module (srfi srfi-1)
#\export (compile-tree-il))
(define-syntax-rule (-> (type arg ...))
`(type ,arg ...))
(define-syntax-rule (@implv sym)
(-> (@ '(language ecmascript impl) 'sym)))
(define-syntax-rule (@impl sym arg ...)
(-> (apply (@implv sym) arg ...)))
(define (empty-lexical-environment)
'())
(define (econs name gensym env)
(acons name (-> (lexical name gensym)) env))
(define (lookup name env)
(or (assq-ref env name)
(-> (toplevel name))))
(define (compile-tree-il exp env opts)
(values
(parse-tree-il
(-> (begin (@impl js-init)
(comp exp (empty-lexical-environment)))))
env
env))
(define (location x)
(and (pair? x)
(let ((props (source-properties x)))
(and (not (null? props))
props))))
;; for emacs:
;; (put 'pmatch/source 'scheme-indent-function 1)
(define-syntax-rule (pmatch/source x clause ...)
(let ((x x))
(let ((res (pmatch x
clause ...)))
(let ((loc (location x)))
(if loc
(set-source-properties! res (location x))))
res)))
(define current-return-tag (make-parameter #f))
(define (return expr)
(-> (abort (or (current-return-tag) (error "return outside function"))
(list expr)
(-> (const '())))))
(define (with-return-prompt body-thunk)
(let ((tag (gensym "return")))
(parameterize ((current-return-tag
(-> (lexical 'return tag))))
(-> (let '(return) (list tag)
(list (-> (apply (-> (primitive 'make-prompt-tag)))))
(-> (prompt (current-return-tag)
(body-thunk)
(let ((val (gensym "val")))
(-> (lambda-case
`(((k val) #f #f #f () (,(gensym) ,val))
,(-> (lexical 'val val)))))))))))))
(define (comp x e)
(let ((l (location x)))
(define (let1 what proc)
(let ((sym (gensym)))
(-> (let (list sym) (list sym) (list what)
(proc sym)))))
(define (begin1 what proc)
(let1 what (lambda (v)
(-> (begin (proc v)
(-> (lexical v v)))))))
(pmatch/source x
(null
;; FIXME, null doesn't have much relation to EOL...
(-> (const '())))
(true
(-> (const #t)))
(false
(-> (const #f)))
((number ,num)
(-> (const num)))
((string ,str)
(-> (const str)))
(this
(@impl get-this))
((+ ,a)
(-> (apply (-> (primitive '+))
(@impl ->number (comp a e))
(-> (const 0)))))
((- ,a)
(-> (apply (-> (primitive '-)) (-> (const 0)) (comp a e))))
((~ ,a)
(@impl bitwise-not (comp a e)))
((! ,a)
(@impl logical-not (comp a e)))
((+ ,a ,b)
(-> (apply (-> (primitive '+)) (comp a e) (comp b e))))
((- ,a ,b)
(-> (apply (-> (primitive '-)) (comp a e) (comp b e))))
((/ ,a ,b)
(-> (apply (-> (primitive '/)) (comp a e) (comp b e))))
((* ,a ,b)
(-> (apply (-> (primitive '*)) (comp a e) (comp b e))))
((% ,a ,b)
(@impl mod (comp a e) (comp b e)))
((<< ,a ,b)
(@impl shift (comp a e) (comp b e)))
((>> ,a ,b)
(@impl shift (comp a e) (comp `(- ,b) e)))
((< ,a ,b)
(-> (apply (-> (primitive '<)) (comp a e) (comp b e))))
((<= ,a ,b)
(-> (apply (-> (primitive '<=)) (comp a e) (comp b e))))
((> ,a ,b)
(-> (apply (-> (primitive '>)) (comp a e) (comp b e))))
((>= ,a ,b)
(-> (apply (-> (primitive '>=)) (comp a e) (comp b e))))
((in ,a ,b)
(@impl has-property? (comp a e) (comp b e)))
((== ,a ,b)
(-> (apply (-> (primitive 'equal?)) (comp a e) (comp b e))))
((!= ,a ,b)
(-> (apply (-> (primitive 'not))
(-> (apply (-> (primitive 'equal?))
(comp a e) (comp b e))))))
((=== ,a ,b)
(-> (apply (-> (primitive 'eqv?)) (comp a e) (comp b e))))
((!== ,a ,b)
(-> (apply (-> (primitive 'not))
(-> (apply (-> (primitive 'eqv?))
(comp a e) (comp b e))))))
((& ,a ,b)
(@impl band (comp a e) (comp b e)))
((^ ,a ,b)
(@impl bxor (comp a e) (comp b e)))
((bor ,a ,b)
(@impl bior (comp a e) (comp b e)))
((and ,a ,b)
(-> (if (@impl ->boolean (comp a e))
(comp b e)
(-> (const #f)))))
((or ,a ,b)
(let1 (comp a e)
(lambda (v)
(-> (if (@impl ->boolean (-> (lexical v v)))
(-> (lexical v v))
(comp b e))))))
((if ,test ,then ,else)
(-> (if (@impl ->boolean (comp test e))
(comp then e)
(comp else e))))
((if ,test ,then)
(-> (if (@impl ->boolean (comp test e))
(comp then e)
(@implv *undefined*))))
((postinc (ref ,foo))
(begin1 (comp `(ref ,foo) e)
(lambda (var)
(-> (set! (lookup foo e)
(-> (apply (-> (primitive '+))
(-> (lexical var var))
(-> (const 1)))))))))
((postinc (pref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(begin1 (@impl pget
(-> (lexical objvar objvar))
(-> (const prop)))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (const prop))
(-> (apply (-> (primitive '+))
(-> (lexical tmpvar tmpvar))
(-> (const 1))))))))))
((postinc (aref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(let1 (comp prop e)
(lambda (propvar)
(begin1 (@impl pget
(-> (lexical objvar objvar))
(-> (lexical propvar propvar)))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (lexical propvar propvar))
(-> (apply (-> (primitive '+))
(-> (lexical tmpvar tmpvar))
(-> (const 1))))))))))))
((postdec (ref ,foo))
(begin1 (comp `(ref ,foo) e)
(lambda (var)
(-> (set (lookup foo e)
(-> (apply (-> (primitive '-))
(-> (lexical var var))
(-> (const 1)))))))))
((postdec (pref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(begin1 (@impl pget
(-> (lexical objvar objvar))
(-> (const prop)))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (const prop))
(-> (apply (-> (primitive '-))
(-> (lexical tmpvar tmpvar))
(-> (const 1))))))))))
((postdec (aref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(let1 (comp prop e)
(lambda (propvar)
(begin1 (@impl pget
(-> (lexical objvar objvar))
(-> (lexical propvar propvar)))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (lexical propvar propvar))
(-> (inline
'- (-> (lexical tmpvar tmpvar))
(-> (const 1))))))))))))
((preinc (ref ,foo))
(let ((v (lookup foo e)))
(-> (begin
(-> (set! v
(-> (apply (-> (primitive '+))
v
(-> (const 1))))))
v))))
((preinc (pref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(begin1 (-> (apply (-> (primitive '+))
(@impl pget
(-> (lexical objvar objvar))
(-> (const prop)))
(-> (const 1))))
(lambda (tmpvar)
(@impl pput (-> (lexical objvar objvar))
(-> (const prop))
(-> (lexical tmpvar tmpvar))))))))
((preinc (aref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(let1 (comp prop e)
(lambda (propvar)
(begin1 (-> (apply (-> (primitive '+))
(@impl pget
(-> (lexical objvar objvar))
(-> (lexical propvar propvar)))
(-> (const 1))))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (lexical propvar propvar))
(-> (lexical tmpvar tmpvar))))))))))
((predec (ref ,foo))
(let ((v (lookup foo e)))
(-> (begin
(-> (set! v
(-> (apply (-> (primitive '-))
v
(-> (const 1))))))
v))))
((predec (pref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(begin1 (-> (apply (-> (primitive '-))
(@impl pget
(-> (lexical objvar objvar))
(-> (const prop)))
(-> (const 1))))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (const prop))
(-> (lexical tmpvar tmpvar))))))))
((predec (aref ,obj ,prop))
(let1 (comp obj e)
(lambda (objvar)
(let1 (comp prop e)
(lambda (propvar)
(begin1 (-> (apply (-> (primitive '-))
(@impl pget
(-> (lexical objvar objvar))
(-> (lexical propvar propvar)))
(-> (const 1))))
(lambda (tmpvar)
(@impl pput
(-> (lexical objvar objvar))
(-> (lexical propvar propvar))
(-> (lexical tmpvar tmpvar))))))))))
((ref ,id)
(lookup id e))
((var . ,forms)
`(begin
,@(map (lambda (form)
(pmatch form
((,x ,y)
(-> (define x (comp y e))))
((,x)
(-> (define x (@implv *undefined*))))
(else (error "bad var form" form))))
forms)))
((begin)
(-> (void)))
((begin ,form)
(comp form e))
((begin . ,forms)
`(begin ,@(map (lambda (x) (comp x e)) forms)))
((lambda ,formals ,body)
(let ((syms (map (lambda (x)
(gensym (string-append (symbol->string x) " ")))
formals)))
`(lambda ()
(lambda-case
((() ,formals #f #f ,(map (lambda (x) (@implv *undefined*)) formals) ,syms)
,(with-return-prompt
(lambda ()
(comp-body e body formals syms))))))))
((call/this ,obj ,prop . ,args)
(@impl call/this*
obj
(-> (lambda '()
`(lambda-case
((() #f #f #f () ())
(apply ,(@impl pget obj prop) ,@args)))))))
((call (pref ,obj ,prop) ,args)
(comp `(call/this ,(comp obj e)
,(-> (const prop))
,@(map (lambda (x) (comp x e)) args))
e))
((call (aref ,obj ,prop) ,args)
(comp `(call/this ,(comp obj e)
,(comp prop e)
,@(map (lambda (x) (comp x e)) args))
e))
((call ,proc ,args)
`(apply ,(comp proc e)
,@(map (lambda (x) (comp x e)) args)))
((return ,expr)
(return (comp expr e)))
((array . ,args)
`(apply ,(@implv new-array)
,@(map (lambda (x) (comp x e)) args)))
((object . ,args)
`(apply ,(@implv new-object)
,@(map (lambda (x)
(pmatch x
((,prop ,val)
(-> (apply (-> (primitive 'cons))
(-> (const prop))
(comp val e))))
(else
(error "bad prop-val pair" x))))
args)))
((pref ,obj ,prop)
(@impl pget
(comp obj e)
(-> (const prop))))
((aref ,obj ,index)
(@impl pget
(comp obj e)
(comp index e)))
((= (ref ,name) ,val)
(let ((v (lookup name e)))
(-> (begin
(-> (set! v (comp val e)))
v))))
((= (pref ,obj ,prop) ,val)
(@impl pput
(comp obj e)
(-> (const prop))
(comp val e)))
((= (aref ,obj ,prop) ,val)
(@impl pput
(comp obj e)
(comp prop e)
(comp val e)))
((+= ,what ,val)
(comp `(= ,what (+ ,what ,val)) e))
((-= ,what ,val)
(comp `(= ,what (- ,what ,val)) e))
((/= ,what ,val)
(comp `(= ,what (/ ,what ,val)) e))
((*= ,what ,val)
(comp `(= ,what (* ,what ,val)) e))
((%= ,what ,val)
(comp `(= ,what (% ,what ,val)) e))
((>>= ,what ,val)
(comp `(= ,what (>> ,what ,val)) e))
((<<= ,what ,val)
(comp `(= ,what (<< ,what ,val)) e))
((>>>= ,what ,val)
(comp `(= ,what (>>> ,what ,val)) e))
((&= ,what ,val)
(comp `(= ,what (& ,what ,val)) e))
((bor= ,what ,val)
(comp `(= ,what (bor ,what ,val)) e))
((^= ,what ,val)
(comp `(= ,what (^ ,what ,val)) e))
((new ,what ,args)
(@impl new
(map (lambda (x) (comp x e))
(cons what args))))
((delete (pref ,obj ,prop))
(@impl pdel
(comp obj e)
(-> (const prop))))
((delete (aref ,obj ,prop))
(@impl pdel
(comp obj e)
(comp prop e)))
((void ,expr)
(-> (begin
(comp expr e)
(@implv *undefined*))))
((typeof ,expr)
(@impl typeof
(comp expr e)))
((do ,statement ,test)
(let ((%loop (gensym "%loop "))
(%continue (gensym "%continue ")))
(let ((e (econs '%loop %loop (econs '%continue %continue e))))
(-> (letrec '(%loop %continue) (list %loop %continue)
(list (-> (lambda '()
(-> (lambda-case
`((() #f #f #f () ())
,(-> (begin
(comp statement e)
(-> (apply (-> (lexical '%continue %continue)))))))))))
(-> (lambda '()
(-> (lambda-case
`((() #f #f #f () ())
,(-> (if (@impl ->boolean (comp test e))
(-> (apply (-> (lexical '%loop %loop))))
(@implv *undefined*)))))))))
(-> (apply (-> (lexical '%loop %loop)))))))))
((while ,test ,statement)
(let ((%continue (gensym "%continue ")))
(let ((e (econs '%continue %continue e)))
(-> (letrec '(%continue) (list %continue)
(list (-> (lambda '()
(-> (lambda-case
`((() #f #f #f () ())
,(-> (if (@impl ->boolean (comp test e))
(-> (begin (comp statement e)
(-> (apply (-> (lexical '%continue %continue))))))
(@implv *undefined*)))))))))
(-> (apply (-> (lexical '%continue %continue)))))))))
((for ,init ,test ,inc ,statement)
(let ((%continue (gensym "%continue ")))
(let ((e (econs '%continue %continue e)))
(-> (letrec '(%continue) (list %continue)
(list (-> (lambda '()
(-> (lambda-case
`((() #f #f #f () ())
,(-> (if (if test
(@impl ->boolean (comp test e))
(comp 'true e))
(-> (begin (comp statement e)
(comp (or inc '(begin)) e)
(-> (apply (-> (lexical '%continue %continue))))))
(@implv *undefined*)))))))))
(-> (begin (comp (or init '(begin)) e)
(-> (apply (-> (lexical '%continue %continue)))))))))))
((for-in ,var ,object ,statement)
(let ((%enum (gensym "%enum "))
(%continue (gensym "%continue ")))
(let ((e (econs '%enum %enum (econs '%continue %continue e))))
(-> (letrec '(%enum %continue) (list %enum %continue)
(list (@impl make-enumerator (comp object e))
(-> (lambda '()
(-> (lambda-case
`((() #f #f #f () ())
(-> (if (@impl ->boolean
(@impl pget
(-> (lexical '%enum %enum))
(-> (const 'length))))
(-> (begin
(comp `(= ,var (call/this ,(-> (lexical '%enum %enum))
,(-> (const 'pop))))
e)
(comp statement e)
(-> (apply (-> (lexical '%continue %continue))))))
(@implv *undefined*)))))))))
(-> (apply (-> (lexical '%continue %continue)))))))))
((block ,x)
(comp x e))
(else
(error "compilation not yet implemented:" x)))))
(define (comp-body e body formals formal-syms)
(define (process)
(let lp ((in body) (out '()) (rvars '()))
(pmatch in
(((var (,x) . ,morevars) . ,rest)
(lp `((var . ,morevars) . ,rest)
out
(if (or (memq x rvars) (memq x formals))
rvars
(cons x rvars))))
(((var (,x ,y) . ,morevars) . ,rest)
(lp `((var . ,morevars) . ,rest)
`((= (ref ,x) ,y) . ,out)
(if (or (memq x rvars) (memq x formals))
rvars
(cons x rvars))))
(((var) . ,rest)
(lp rest out rvars))
((,x . ,rest) (guard (and (pair? x) (eq? (car x) 'lambda)))
(lp rest
(cons x out)
rvars))
((,x . ,rest) (guard (pair? x))
(receive (sub-out rvars)
(lp x '() rvars)
(lp rest
(cons sub-out out)
rvars)))
((,x . ,rest)
(lp rest
(cons x out)
rvars))
(()
(values (reverse! out)
rvars)))))
(receive (out rvars)
(process)
(let* ((names (reverse rvars))
(syms (map (lambda (x)
(gensym (string-append (symbol->string x) " ")))
names))
(e (fold econs (fold econs e formals formal-syms) names syms)))
(-> (let names syms (map (lambda (x) (@implv *undefined*)) names)
(comp out e))))))
;;; ECMAScript for Guile
;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript function)
#\use-module (oop goops)
#\use-module (language ecmascript base)
#\export (*function-prototype* *program-wrappers*))
(define-class <js-program-wrapper> (<js-object>))
(define *program-wrappers* (make-doubly-weak-hash-table 31))
(define *function-prototype* (make <js-object> #\class "Function"
#\value (lambda args *undefined*)))
(define-js-method *function-prototype* (toString)
(format #f "~A" (js-value this)))
(define-js-method *function-prototype* (apply this-arg array)
(cond ((or (null? array) (eq? array *undefined*))
(call/this this-arg (js-value this)))
((is-a? array <js-array-object>)
(call/this this-arg
(lambda ()
(apply (js-value this)
(vector->list (js-array-vector array))))))
(else
(throw 'TypeError 'apply array))))
(define-js-method *function-prototype* (call this-arg . args)
(call/this this-arg
(lambda ()
(apply (js-value this) args))))
(define-method (pget (o <applicable>) p)
(let ((wrapper (hashq-ref *program-wrappers* o)))
(if wrapper
(pget wrapper p)
(pget *function-prototype* p))))
(define-method (pput (o <applicable>) p v)
(let ((wrapper (hashq-ref *program-wrappers* o)))
(if wrapper
(pput wrapper p v)
(let ((wrapper (make <js-program-wrapper> #\value o #\class "Function"
#\prototype *function-prototype*)))
(hashq-set! *program-wrappers* o wrapper)
(pput wrapper p v)))))
(define-method (js-prototype (o <applicable>))
(let ((wrapper (hashq-ref *program-wrappers* o)))
(if wrapper
(js-prototype wrapper)
#f)))
(define-method (js-constructor (o <applicable>))
(let ((wrapper (hashq-ref *program-wrappers* o)))
(if wrapper
(js-constructor wrapper)
#f)))
;;; ECMAScript for Guile
;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript impl)
#\use-module (oop goops)
#\use-module (language ecmascript base)
#\use-module (language ecmascript function)
#\use-module (language ecmascript array)
#\re-export (*undefined* *this* call/this*
pget pput pdel has-property?
->boolean ->number
new-object new new-array)
#\export (js-init get-this
typeof
bitwise-not logical-not
shift
mod
band bxor bior
make-enumerator))
(define-class <js-module-object> (<js-object>)
(module #\init-form (current-module) #\init-keyword #\module
#\getter js-module))
(define-method (pget (o <js-module-object>) (p <string>))
(pget o (string->symbol p)))
(define-method (pget (o <js-module-object>) (p <symbol>))
(let ((v (module-variable (js-module o) p)))
(if v
(variable-ref v)
(next-method))))
(define-method (pput (o <js-module-object>) (p <string>) v)
(pput o (string->symbol p) v))
(define-method (pput (o <js-module-object>) (p <symbol>) v)
(module-define! (js-module o) p v))
(define-method (prop-attrs (o <js-module-object>) (p <symbol>))
(cond ((module-local-variable (js-module o) p) '())
((module-variable (js-module o) p) '(DontDelete ReadOnly))
(else (next-method))))
(define-method (prop-attrs (o <js-module-object>) (p <string>))
(prop-attrs o (string->symbol p)))
(define-method (prop-keys (o <js-module-object>))
(append (hash-map->list (lambda (k v) k) (module-obarray (js-module o)))
(next-method)))
;; we could make a renamer, but having obj['foo-bar'] should be enough
(define (js-require modstr)
(make <js-module-object> #\module
(resolve-interface (map string->symbol (string-split modstr #\.)))))
(define-class <js-global-object> (<js-module-object>))
(define-method (js-module (o <js-global-object>))
(current-module))
(define (init-js-bindings! mod)
(module-define! mod 'NaN +nan.0)
(module-define! mod 'Infinity +inf.0)
(module-define! mod 'undefined *undefined*)
(module-define! mod 'require js-require)
;; isNAN, isFinite, parseFloat, parseInt, eval
;; decodeURI, decodeURIComponent, encodeURI, encodeURIComponent
;; Object Function Array String Boolean Number Date RegExp Error EvalError
;; RangeError ReferenceError SyntaxError TypeError URIError
(module-define! mod 'Object *object-prototype*)
(module-define! mod 'Array *array-prototype*))
(define (js-init)
(cond ((get-this))
(else
(fluid-set! *this* (make <js-global-object>))
(init-js-bindings! (current-module)))))
(define (get-this)
(fluid-ref *this*))
(define (typeof x)
(cond ((eq? x *undefined*) "undefined")
((null? x) "object")
((boolean? x) "boolean")
((number? x) "number")
((string? x) "string")
((procedure? x) "function")
((is-a? x <js-object>) "object")
(else "scm")))
(define bitwise-not lognot)
(define (logical-not x)
(not (->boolean (->primitive x))))
(define shift ash)
(define band logand)
(define bxor logxor)
(define bior logior)
(define mod modulo)
(define-method (+ (a <string>) (b <string>))
(string-append a b))
(define-method (+ (a <string>) b)
(string-append a (->string b)))
(define-method (+ a (b <string>))
(string-append (->string a) b))
(define-method (+ a b)
(+ (->number a) (->number b)))
(define-method (- a b)
(- (->number a) (->number b)))
(define-method (* a b)
(* (->number a) (->number b)))
(define-method (/ a b)
(/ (->number a) (->number b)))
(define-method (< a b)
(< (->number a) (->number b)))
(define-method (< (a <string>) (b <string>))
(string< a b))
(define-method (<= a b)
(<= (->number a) (->number b)))
(define-method (<= (a <string>) (b <string>))
(string<= a b))
(define-method (>= a b)
(>= (->number a) (->number b)))
(define-method (>= (a <string>) (b <string>))
(string>= a b))
(define-method (> a b)
(> (->number a) (->number b)))
(define-method (> (a <string>) (b <string>))
(string> a b))
(define (obj-and-prototypes o)
(if o
(cons o (obj-and-prototypes (js-prototype o)))
'()))
(define (make-enumerator obj)
(let ((props (make-hash-table 23)))
(for-each (lambda (o)
(for-each (lambda (k) (hashq-set! props k #t))
(prop-keys o)))
(obj-and-prototypes obj))
(apply new-array (filter (lambda (p)
(not (prop-has-attr? obj p 'DontEnum)))
(hash-map->list (lambda (k v) k) props)))))
;;; ECMAScript for Guile
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript parse)
#\use-module (system base lalr)
#\use-module (language ecmascript tokenize)
#\export (read-ecmascript read-ecmascript/1 make-parser))
(define* (syntax-error message #\optional token)
(if (lexical-token? token)
(throw 'syntax-error #f message
(and=> (lexical-token-source token)
source-location->source-properties)
(or (lexical-token-value token)
(lexical-token-category token))
#f)
(throw 'syntax-error #f message #f token #f)))
(define (read-ecmascript port)
(let ((parse (make-parser)))
(parse (make-tokenizer port) syntax-error)))
(define (read-ecmascript/1 port)
(let ((parse (make-parser)))
(parse (make-tokenizer/1 port) syntax-error)))
(define *eof-object*
(call-with-input-string "" read-char))
(define (make-parser)
;; Return a fresh ECMAScript parser. Parsers produced by `lalr-scm' are now
;; stateful (e.g., they won't invoke the tokenizer any more once it has
;; returned `*eoi*'), hence the need to instantiate new parsers.
(lalr-parser
;; terminal (i.e. input) token types
(lbrace rbrace lparen rparen lbracket rbracket dot semicolon comma <
> <= >= == != === !== + - * % ++ -- << >> >>> & bor ^ ! ~ && or ?
colon = += -= *= %= <<= >>= >>>= &= bor= ^= / /=
break else new var case finally return void catch for switch while
continue function this with default if throw delete in try do
instanceof typeof null true false
Identifier StringLiteral NumericLiteral RegexpLiteral)
(Program (SourceElements) \: $1
(*eoi*) \: *eof-object*)
;;
;; Verily, here we define statements. Expressions are defined
;; afterwards.
;;
(SourceElement (Statement) \: $1
(FunctionDeclaration) \: $1)
(FunctionDeclaration (function Identifier lparen rparen lbrace FunctionBody rbrace) \: `(var (,$2 (lambda () ,$6)))
(function Identifier lparen FormalParameterList rparen lbrace FunctionBody rbrace) \: `(var (,$2 (lambda ,$4 ,$7))))
(FunctionExpression (function lparen rparen lbrace FunctionBody rbrace) \: `(lambda () ,$5)
(function Identifier lparen rparen lbrace FunctionBody rbrace) \: `(lambda () ,$6)
(function lparen FormalParameterList rparen lbrace FunctionBody rbrace) \: `(lambda ,$3 ,$6)
(function Identifier lparen FormalParameterList rparen lbrace FunctionBody rbrace) \: `(lambda ,$4 ,$7))
(FormalParameterList (Identifier) \: `(,$1)
(FormalParameterList comma Identifier) \: `(,@$1 ,$3))
(SourceElements (SourceElement) \: $1
(SourceElements SourceElement) \: (if (and (pair? $1) (eq? (car $1) 'begin))
`(begin ,@(cdr $1) ,$2)
`(begin ,$1 ,$2)))
(FunctionBody (SourceElements) \: $1
() \: '(begin))
(Statement (Block) \: $1
(VariableStatement) \: $1
(EmptyStatement) \: $1
(ExpressionStatement) \: $1
(IfStatement) \: $1
(IterationStatement) \: $1
(ContinueStatement) \: $1
(BreakStatement) \: $1
(ReturnStatement) \: $1
(WithStatement) \: $1
(LabelledStatement) \: $1
(SwitchStatement) \: $1
(ThrowStatement) \: $1
(TryStatement) \: $1)
(Block (lbrace StatementList rbrace) \: `(block ,$2))
(StatementList (Statement) \: $1
(StatementList Statement) \: (if (and (pair? $1) (eq? (car $1) 'begin))
`(begin ,@(cdr $1) ,$2)
`(begin ,$1 ,$2)))
(VariableStatement (var VariableDeclarationList) \: `(var ,@$2))
(VariableDeclarationList (VariableDeclaration) \: `(,$1)
(VariableDeclarationList comma VariableDeclaration) \: `(,@$1 ,$2))
(VariableDeclarationListNoIn (VariableDeclarationNoIn) \: `(,$1)
(VariableDeclarationListNoIn comma VariableDeclarationNoIn) \: `(,@$1 ,$2))
(VariableDeclaration (Identifier) \: `(,$1)
(Identifier Initialiser) \: `(,$1 ,$2))
(VariableDeclarationNoIn (Identifier) \: `(,$1)
(Identifier Initialiser) \: `(,$1 ,$2))
(Initialiser (= AssignmentExpression) \: $2)
(InitialiserNoIn (= AssignmentExpressionNoIn) \: $2)
(EmptyStatement (semicolon) \: '(begin))
(ExpressionStatement (Expression semicolon) \: $1)
(IfStatement (if lparen Expression rparen Statement else Statement) \: `(if ,$3 ,$5 ,$7)
(if lparen Expression rparen Statement) \: `(if ,$3 ,$5))
(IterationStatement (do Statement while lparen Expression rparen semicolon) \: `(do ,$2 ,$5)
(while lparen Expression rparen Statement) \: `(while ,$3 ,$5)
(for lparen semicolon semicolon rparen Statement) \: `(for #f #f #f ,$6)
(for lparen semicolon semicolon Expression rparen Statement) \: `(for #f #f ,$5 ,$7)
(for lparen semicolon Expression semicolon rparen Statement) \: `(for #f ,$4 #f ,$7)
(for lparen semicolon Expression semicolon Expression rparen Statement) \: `(for #f ,$4 ,$6 ,$8)
(for lparen ExpressionNoIn semicolon semicolon rparen Statement) \: `(for ,$3 #f #f ,$7)
(for lparen ExpressionNoIn semicolon semicolon Expression rparen Statement) \: `(for ,$3 #f ,$6 ,$8)
(for lparen ExpressionNoIn semicolon Expression semicolon rparen Statement) \: `(for ,$3 ,$5 #f ,$8)
(for lparen ExpressionNoIn semicolon Expression semicolon Expression rparen Statement) \: `(for ,$3 ,$5 ,$7 ,$9)
(for lparen var VariableDeclarationListNoIn semicolon semicolon rparen Statement) \: `(for (var ,@$4) #f #f ,$8)
(for lparen var VariableDeclarationListNoIn semicolon semicolon Expression rparen Statement) \: `(for (var ,@$4) #f ,$7 ,$9)
(for lparen var VariableDeclarationListNoIn semicolon Expression semicolon rparen Statement) \: `(for (var ,@$4) ,$6 #f ,$9)
(for lparen var VariableDeclarationListNoIn semicolon Expression semicolon Expression rparen Statement) \: `(for (var ,@$4) ,$6 ,$8 ,$10)
(for lparen LeftHandSideExpression in Expression rparen Statement) \: `(for-in ,$3 ,$5 ,$7)
(for lparen var VariableDeclarationNoIn in Expression rparen Statement) \: `(begin (var ,$4) (for-in (ref ,@$4) ,$6 ,$8)))
(ContinueStatement (continue Identifier semicolon) \: `(continue ,$2)
(continue semicolon) \: `(continue))
(BreakStatement (break Identifier semicolon) \: `(break ,$2)
(break semicolon) \: `(break))
(ReturnStatement (return Expression semicolon) \: `(return ,$2)
(return semicolon) \: `(return))
(WithStatement (with lparen Expression rparen Statement) \: `(with ,$3 ,$5))
(SwitchStatement (switch lparen Expression rparen CaseBlock) \: `(switch ,$3 ,@$5))
(CaseBlock (lbrace rbrace) \: '()
(lbrace CaseClauses rbrace) \: $2
(lbrace CaseClauses DefaultClause rbrace) \: `(,@$2 ,@$3)
(lbrace DefaultClause rbrace) \: `(,$2)
(lbrace DefaultClause CaseClauses rbrace) \: `(,@$2 ,@$3))
(CaseClauses (CaseClause) \: `(,$1)
(CaseClauses CaseClause) \: `(,@$1 ,$2))
(CaseClause (case Expression colon) \: `(case ,$2)
(case Expression colon StatementList) \: `(case ,$2 ,$4))
(DefaultClause (default colon) \: `(default)
(default colon StatementList) \: `(default ,$3))
(LabelledStatement (Identifier colon Statement) \: `(label ,$1 ,$3))
(ThrowStatement (throw Expression semicolon) \: `(throw ,$2))
(TryStatement (try Block Catch) \: `(try ,$2 ,$3 #f)
(try Block Finally) \: `(try ,$2 #f ,$3)
(try Block Catch Finally) \: `(try ,$2 ,$3 ,$4))
(Catch (catch lparen Identifier rparen Block) \: `(catch ,$3 ,$5))
(Finally (finally Block) \: `(finally ,$2))
;;
;; As promised, expressions. We build up to Expression bottom-up, so
;; as to get operator precedence right.
;;
(PrimaryExpression (this) \: 'this
(null) \: 'null
(true) \: 'true
(false) \: 'false
(Identifier) \: `(ref ,$1)
(StringLiteral) \: `(string ,$1)
(RegexpLiteral) \: `(regexp ,$1)
(NumericLiteral) \: `(number ,$1)
(dot NumericLiteral) \: `(number ,(string->number (string-append "." (number->string $2))))
(ArrayLiteral) \: $1
(ObjectLiteral) \: $1
(lparen Expression rparen) \: $2)
(ArrayLiteral (lbracket rbracket) \: '(array)
(lbracket Elision rbracket) \: '(array ,@$2)
(lbracket ElementList rbracket) \: `(array ,@$2)
(lbracket ElementList comma rbracket) \: `(array ,@$2)
(lbracket ElementList comma Elision rbracket) \: `(array ,@$2))
(ElementList (AssignmentExpression) \: `(,$1)
(Elision AssignmentExpression) \: `(,@$1 ,$2)
(ElementList comma AssignmentExpression) \: `(,@$1 ,$3)
(ElementList comma Elision AssignmentExpression) \: `(,@$1 ,@$3 ,$4))
(Elision (comma) \: '((number 0))
(Elision comma) \: `(,@$1 (number 0)))
(ObjectLiteral (lbrace rbrace) \: `(object)
(lbrace PropertyNameAndValueList rbrace) \: `(object ,@$2))
(PropertyNameAndValueList (PropertyName colon AssignmentExpression) \: `((,$1 ,$3))
(PropertyNameAndValueList comma PropertyName colon AssignmentExpression) \: `(,@$1 (,$3 ,$5)))
(PropertyName (Identifier) \: $1
(StringLiteral) \: (string->symbol $1)
(NumericLiteral) \: $1)
(MemberExpression (PrimaryExpression) \: $1
(FunctionExpression) \: $1
(MemberExpression lbracket Expression rbracket) \: `(aref ,$1 ,$3)
(MemberExpression dot Identifier) \: `(pref ,$1 ,$3)
(new MemberExpression Arguments) \: `(new ,$2 ,$3))
(NewExpression (MemberExpression) \: $1
(new NewExpression) \: `(new ,$2 ()))
(CallExpression (MemberExpression Arguments) \: `(call ,$1 ,$2)
(CallExpression Arguments) \: `(call ,$1 ,$2)
(CallExpression lbracket Expression rbracket) \: `(aref ,$1 ,$3)
(CallExpression dot Identifier) \: `(pref ,$1 ,$3))
(Arguments (lparen rparen) \: '()
(lparen ArgumentList rparen) \: $2)
(ArgumentList (AssignmentExpression) \: `(,$1)
(ArgumentList comma AssignmentExpression) \: `(,@$1 ,$3))
(LeftHandSideExpression (NewExpression) \: $1
(CallExpression) \: $1)
(PostfixExpression (LeftHandSideExpression) \: $1
(LeftHandSideExpression ++) \: `(postinc ,$1)
(LeftHandSideExpression --) \: `(postdec ,$1))
(UnaryExpression (PostfixExpression) \: $1
(delete UnaryExpression) \: `(delete ,$2)
(void UnaryExpression) \: `(void ,$2)
(typeof UnaryExpression) \: `(typeof ,$2)
(++ UnaryExpression) \: `(preinc ,$2)
(-- UnaryExpression) \: `(predec ,$2)
(+ UnaryExpression) \: `(+ ,$2)
(- UnaryExpression) \: `(- ,$2)
(~ UnaryExpression) \: `(~ ,$2)
(! UnaryExpression) \: `(! ,$2))
(MultiplicativeExpression (UnaryExpression) \: $1
(MultiplicativeExpression * UnaryExpression) \: `(* ,$1 ,$3)
(MultiplicativeExpression / UnaryExpression) \: `(/ ,$1 ,$3)
(MultiplicativeExpression % UnaryExpression) \: `(% ,$1 ,$3))
(AdditiveExpression (MultiplicativeExpression) \: $1
(AdditiveExpression + MultiplicativeExpression) \: `(+ ,$1 ,$3)
(AdditiveExpression - MultiplicativeExpression) \: `(- ,$1 ,$3))
(ShiftExpression (AdditiveExpression) \: $1
(ShiftExpression << MultiplicativeExpression) \: `(<< ,$1 ,$3)
(ShiftExpression >> MultiplicativeExpression) \: `(>> ,$1 ,$3)
(ShiftExpression >>> MultiplicativeExpression) \: `(>>> ,$1 ,$3))
(RelationalExpression (ShiftExpression) \: $1
(RelationalExpression < ShiftExpression) \: `(< ,$1 ,$3)
(RelationalExpression > ShiftExpression) \: `(> ,$1 ,$3)
(RelationalExpression <= ShiftExpression) \: `(<= ,$1 ,$3)
(RelationalExpression >= ShiftExpression) \: `(>= ,$1 ,$3)
(RelationalExpression instanceof ShiftExpression) \: `(instanceof ,$1 ,$3)
(RelationalExpression in ShiftExpression) \: `(in ,$1 ,$3))
(RelationalExpressionNoIn (ShiftExpression) \: $1
(RelationalExpressionNoIn < ShiftExpression) \: `(< ,$1 ,$3)
(RelationalExpressionNoIn > ShiftExpression) \: `(> ,$1 ,$3)
(RelationalExpressionNoIn <= ShiftExpression) \: `(<= ,$1 ,$3)
(RelationalExpressionNoIn >= ShiftExpression) \: `(>= ,$1 ,$3)
(RelationalExpressionNoIn instanceof ShiftExpression) \: `(instanceof ,$1 ,$3))
(EqualityExpression (RelationalExpression) \: $1
(EqualityExpression == RelationalExpression) \: `(== ,$1 ,$3)
(EqualityExpression != RelationalExpression) \: `(!= ,$1 ,$3)
(EqualityExpression === RelationalExpression) \: `(=== ,$1 ,$3)
(EqualityExpression !== RelationalExpression) \: `(!== ,$1 ,$3))
(EqualityExpressionNoIn (RelationalExpressionNoIn) \: $1
(EqualityExpressionNoIn == RelationalExpressionNoIn) \: `(== ,$1 ,$3)
(EqualityExpressionNoIn != RelationalExpressionNoIn) \: `(!= ,$1 ,$3)
(EqualityExpressionNoIn === RelationalExpressionNoIn) \: `(=== ,$1 ,$3)
(EqualityExpressionNoIn !== RelationalExpressionNoIn) \: `(!== ,$1 ,$3))
(BitwiseANDExpression (EqualityExpression) \: $1
(BitwiseANDExpression & EqualityExpression) \: `(& ,$1 ,$3))
(BitwiseANDExpressionNoIn (EqualityExpressionNoIn) \: $1
(BitwiseANDExpressionNoIn & EqualityExpressionNoIn) \: `(& ,$1 ,$3))
(BitwiseXORExpression (BitwiseANDExpression) \: $1
(BitwiseXORExpression ^ BitwiseANDExpression) \: `(^ ,$1 ,$3))
(BitwiseXORExpressionNoIn (BitwiseANDExpressionNoIn) \: $1
(BitwiseXORExpressionNoIn ^ BitwiseANDExpressionNoIn) \: `(^ ,$1 ,$3))
(BitwiseORExpression (BitwiseXORExpression) \: $1
(BitwiseORExpression bor BitwiseXORExpression) \: `(bor ,$1 ,$3))
(BitwiseORExpressionNoIn (BitwiseXORExpressionNoIn) \: $1
(BitwiseORExpressionNoIn bor BitwiseXORExpressionNoIn) \: `(bor ,$1 ,$3))
(LogicalANDExpression (BitwiseORExpression) \: $1
(LogicalANDExpression && BitwiseORExpression) \: `(and ,$1 ,$3))
(LogicalANDExpressionNoIn (BitwiseORExpressionNoIn) \: $1
(LogicalANDExpressionNoIn && BitwiseORExpressionNoIn) \: `(and ,$1 ,$3))
(LogicalORExpression (LogicalANDExpression) \: $1
(LogicalORExpression or LogicalANDExpression) \: `(or ,$1 ,$3))
(LogicalORExpressionNoIn (LogicalANDExpressionNoIn) \: $1
(LogicalORExpressionNoIn or LogicalANDExpressionNoIn) \: `(or ,$1 ,$3))
(ConditionalExpression (LogicalORExpression) \: $1
(LogicalORExpression ? AssignmentExpression colon AssignmentExpression) \: `(if ,$1 ,$3 ,$5))
(ConditionalExpressionNoIn (LogicalORExpressionNoIn) \: $1
(LogicalORExpressionNoIn ? AssignmentExpressionNoIn colon AssignmentExpressionNoIn) \: `(if ,$1 ,$3 ,$5))
(AssignmentExpression (ConditionalExpression) \: $1
(LeftHandSideExpression AssignmentOperator AssignmentExpression) \: `(,$2 ,$1 ,$3))
(AssignmentExpressionNoIn (ConditionalExpressionNoIn) \: $1
(LeftHandSideExpression AssignmentOperator AssignmentExpressionNoIn) \: `(,$2 ,$1 ,$3))
(AssignmentOperator (=) \: '=
(*=) \: '*=
(/=) \: '/=
(%=) \: '%=
(+=) \: '+=
(-=) \: '-=
(<<=) \: '<<=
(>>=) \: '>>=
(>>>=) \: '>>>=
(&=) \: '&=
(^=) \: '^=
(bor=) \: 'bor=)
(Expression (AssignmentExpression) \: $1
(Expression comma AssignmentExpression) \: `(begin ,$1 ,$3))
(ExpressionNoIn (AssignmentExpressionNoIn) \: $1
(ExpressionNoIn comma AssignmentExpressionNoIn) \: `(begin ,$1 ,$3))))
;;; ECMAScript specification for Guile
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript spec)
#\use-module (system base language)
#\use-module (language ecmascript parse)
#\use-module (language ecmascript compile-tree-il)
#\export (ecmascript))
;;;
;;; Language definition
;;;
(define-language ecmascript
#\title "ECMAScript"
#\reader (lambda (port env) (read-ecmascript/1 port))
#\compilers `((tree-il . ,compile-tree-il))
;; a pretty-printer would be interesting.
#\printer write
)
;;; ECMAScript for Guile
;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language ecmascript tokenize)
#\use-module (ice-9 rdelim)
#\use-module ((srfi srfi-1) #\select (unfold-right))
#\use-module (system base lalr)
#\export (next-token make-tokenizer make-tokenizer/1 tokenize tokenize/1))
(define (syntax-error what loc form . args)
(throw 'syntax-error #f what
(and=> loc source-location->source-properties)
form #f args))
(define (port-source-location port)
(make-source-location (port-filename port)
(port-line port)
(port-column port)
(false-if-exception (ftell port))
#f))
;; taken from SSAX, sorta
(define (read-until delims port loc)
(if (eof-object? (peek-char port))
(syntax-error "EOF while reading a token" loc #f)
(let ((token (read-delimited delims port 'peek)))
(if (eof-object? (peek-char port))
(syntax-error "EOF while reading a token" loc token)
token))))
(define (char-hex? c)
(and (not (eof-object? c))
(or (char-numeric? c)
(memv c '(#\a #\b #\c #\d #\e #\f))
(memv c '(#\A #\B #\C #\D #\E #\F)))))
(define (digit->number c)
(- (char->integer c) (char->integer #\0)))
(define (hex->number c)
(if (char-numeric? c)
(digit->number c)
(+ 10 (- (char->integer (char-downcase c)) (char->integer #\a)))))
(define (read-slash port loc div?)
(let ((c1 (begin
(read-char port)
(peek-char port))))
(cond
((eof-object? c1)
;; hmm. error if we're not looking for a div? ?
(make-lexical-token '/ loc #f))
((char=? c1 #\/)
(read-line port)
(next-token port div?))
((char=? c1 #\*)
(read-char port)
(let lp ((c (read-char port)))
(cond
((eof-object? c)
(syntax-error "EOF while in multi-line comment" loc #f))
((char=? c #\*)
(if (eqv? (peek-char port) #\/)
(begin
(read-char port)
(next-token port div?))
(lp (read-char port))))
(else
(lp (read-char port))))))
(div?
(case c1
((#\=) (read-char port) (make-lexical-token '/= loc #f))
(else (make-lexical-token '/ loc #f))))
(else
(read-regexp port loc)))))
(define (read-regexp port loc)
;; first slash already read
(let ((terms (string #\/ #\\ #\nl #\cr)))
(let lp ((str (read-until terms port loc)) (head ""))
(let ((terminator (peek-char port)))
(cond
((char=? terminator #\/)
(read-char port)
;; flags
(let lp ((c (peek-char port)) (flags '()))
(if (or (eof-object? c)
(not (or (char-alphabetic? c)
(char-numeric? c)
(char=? c #\$)
(char=? c #\_))))
(make-lexical-token 'RegexpLiteral loc
(cons (string-append head str)
(reverse flags)))
(begin (read-char port)
(lp (peek-char port) (cons c flags))))))
((char=? terminator #\\)
(read-char port)
(let ((echar (read-char port)))
(lp (read-until terms port loc)
(string-append head str (string #\\ echar)))))
(else
(syntax-error "regexp literals may not contain newlines"
loc str)))))))
(define (read-string port loc)
(let ((c (read-char port)))
(let ((terms (string c #\\ #\nl #\cr)))
(define (read-escape port)
(let ((c (read-char port)))
(case c
((#\' #\" #\\) c)
((#\b) #\bs)
((#\f) #\np)
((#\n) #\nl)
((#\r) #\cr)
((#\t) #\tab)
((#\v) #\vt)
((#\0)
(let ((next (peek-char port)))
(cond
((eof-object? next) #\nul)
((char-numeric? next)
(syntax-error "octal escape sequences are not supported"
loc #f))
(else #\nul))))
((#\x)
(let* ((a (read-char port))
(b (read-char port)))
(cond
((and (char-hex? a) (char-hex? b))
(integer->char (+ (* 16 (hex->number a)) (hex->number b))))
(else
(syntax-error "bad hex character escape" loc (string a b))))))
((#\u)
(let* ((a (read-char port))
(b (read-char port))
(c (read-char port))
(d (read-char port)))
(integer->char (string->number (string a b c d) 16))))
(else
c))))
(let lp ((str (read-until terms port loc)))
(let ((terminator (peek-char port)))
(cond
((char=? terminator c)
(read-char port)
(make-lexical-token 'StringLiteral loc str))
((char=? terminator #\\)
(read-char port)
(let ((echar (read-escape port)))
(lp (string-append str (string echar)
(read-until terms port loc)))))
(else
(syntax-error "string literals may not contain newlines"
loc str))))))))
(define *keywords*
'(("break" . break)
("else" . else)
("new" . new)
("var" . var)
("case" . case)
("finally" . finally)
("return" . return)
("void" . void)
("catch" . catch)
("for" . for)
("switch" . switch)
("while" . while)
("continue" . continue)
("function" . function)
("this" . this)
("with" . with)
("default" . default)
("if" . if)
("throw" . throw)
("delete" . delete)
("in" . in)
("try" . try)
("do" . do)
("instanceof" . instanceof)
("typeof" . typeof)
;; these aren't exactly keywords, but hey
("null" . null)
("true" . true)
("false" . false)))
(define *future-reserved-words*
'(("abstract" . abstract)
("enum" . enum)
("int" . int)
("short" . short)
("boolean" . boolean)
("export" . export)
("interface" . interface)
("static" . static)
("byte" . byte)
("extends" . extends)
("long" . long)
("super" . super)
("char" . char)
("final" . final)
("native" . native)
("synchronized" . synchronized)
("class" . class)
("float" . float)
("package" . package)
("throws" . throws)
("const" . const)
("goto" . goto)
("private" . private)
("transient" . transient)
("debugger" . debugger)
("implements" . implements)
("protected" . protected)
("volatile" . volatile)
("double" . double)
("import" . import)
("public" . public)))
(define (read-identifier port loc)
(let lp ((c (peek-char port)) (chars '()))
(if (or (eof-object? c)
(not (or (char-alphabetic? c)
(char-numeric? c)
(char=? c #\$)
(char=? c #\_))))
(let ((word (list->string (reverse chars))))
(cond ((assoc-ref *keywords* word)
=> (lambda (x) (make-lexical-token x loc #f)))
((assoc-ref *future-reserved-words* word)
(syntax-error "word is reserved for the future, dude."
loc word))
(else (make-lexical-token 'Identifier loc
(string->symbol word)))))
(begin (read-char port)
(lp (peek-char port) (cons c chars))))))
(define (read-numeric port loc)
(let* ((c0 (if (char=? (peek-char port) #\.)
#\0
(read-char port)))
(c1 (peek-char port)))
(cond
((eof-object? c1) (digit->number c0))
((and (char=? c0 #\0) (or (char=? c1 #\x) (char=? c1 #\X)))
(read-char port)
(let ((c (peek-char port)))
(if (not (char-hex? c))
(syntax-error "bad digit reading hexadecimal number"
loc c))
(let lp ((c c) (acc 0))
(cond ((char-hex? c)
(read-char port)
(lp (peek-char port)
(+ (* 16 acc) (hex->number c))))
(else
acc)))))
((and (char=? c0 #\0) (char-numeric? c1))
(let lp ((c c1) (acc 0))
(cond ((eof-object? c) acc)
((char-numeric? c)
(if (or (char=? c #\8) (char=? c #\9))
(syntax-error "invalid digit in octal sequence"
loc c))
(read-char port)
(lp (peek-char port)
(+ (* 8 acc) (digit->number c))))
(else
acc))))
(else
(let lp ((c1 c1) (acc (digit->number c0)))
(cond
((eof-object? c1) acc)
((char-numeric? c1)
(read-char port)
(lp (peek-char port)
(+ (* 10 acc) (digit->number c1))))
((or (char=? c1 #\e) (char=? c1 #\E))
(read-char port)
(let ((add (let ((c (peek-char port)))
(cond ((eof-object? c)
(syntax-error "error reading exponent: EOF"
loc #f))
((char=? c #\+) (read-char port) +)
((char=? c #\-) (read-char port) -)
((char-numeric? c) +)
(else
(syntax-error "error reading exponent: non-digit"
loc c))))))
(let lp ((c (peek-char port)) (e 0))
(cond ((and (not (eof-object? c)) (char-numeric? c))
(read-char port)
(lp (peek-char port) (add (* 10 e) (digit->number c))))
(else
(* (if (negative? e) (* acc 1.0) acc) (expt 10 e)))))))
((char=? c1 #\.)
(read-char port)
(let lp2 ((c (peek-char port)) (dec 0.0) (n -1))
(cond ((and (not (eof-object? c)) (char-numeric? c))
(read-char port)
(lp2 (peek-char port)
(+ dec (* (digit->number c) (expt 10 n)))
(1- n)))
(else
;; loop back to catch an exponential part
(lp c (+ acc dec))))))
(else
acc)))))))
(define *punctuation*
'(("{" . lbrace)
("}" . rbrace)
("(" . lparen)
(")" . rparen)
("[" . lbracket)
("]" . rbracket)
("." . dot)
(";" . semicolon)
("," . comma)
("<" . <)
(">" . >)
("<=" . <=)
(">=" . >=)
("==" . ==)
("!=" . !=)
("===" . ===)
("!==" . !==)
("+" . +)
("-" . -)
("*" . *)
("%" . %)
("++" . ++)
("--" . --)
("<<" . <<)
(">>" . >>)
(">>>" . >>>)
("&" . &)
("|" . bor)
("^" . ^)
("!" . !)
("~" . ~)
("&&" . &&)
("||" . or)
("?" . ?)
(":" . colon)
("=" . =)
("+=" . +=)
("-=" . -=)
("*=" . *=)
("%=" . %=)
("<<=" . <<=)
(">>=" . >>=)
(">>>=" . >>>=)
("&=" . &=)
("|=" . bor=)
("^=" . ^=)))
(define *div-punctuation*
'(("/" . /)
("/=" . /=)))
;; node ::= (char (symbol | #f) node*)
(define read-punctuation
(let ((punc-tree (let lp ((nodes '()) (puncs *punctuation*))
(cond ((null? puncs)
nodes)
((assv-ref nodes (string-ref (caar puncs) 0))
=> (lambda (node-tail)
(if (= (string-length (caar puncs)) 1)
(set-car! node-tail (cdar puncs))
(set-cdr! node-tail
(lp (cdr node-tail)
`((,(substring (caar puncs) 1)
. ,(cdar puncs))))))
(lp nodes (cdr puncs))))
(else
(lp (cons (list (string-ref (caar puncs) 0) #f) nodes)
puncs))))))
(lambda (port loc)
(let lp ((c (peek-char port)) (tree punc-tree) (candidate #f))
(cond
((assv-ref tree c)
=> (lambda (node-tail)
(read-char port)
(lp (peek-char port) (cdr node-tail) (car node-tail))))
(candidate
(make-lexical-token candidate loc #f))
(else
(syntax-error "bad syntax: character not allowed" loc c)))))))
(define (next-token port div?)
(let ((c (peek-char port))
(loc (port-source-location port)))
(case c
((#\ht #\vt #\np #\space #\x00A0) ; whitespace
(read-char port)
(next-token port div?))
((#\newline #\cr) ; line break
(read-char port)
(next-token port div?))
((#\/)
;; division, single comment, double comment, or regexp
(read-slash port loc div?))
((#\" #\') ; string literal
(read-string port loc))
(else
(cond
((eof-object? c)
'*eoi*)
((or (char-alphabetic? c)
(char=? c #\$)
(char=? c #\_))
;; reserved word or identifier
(read-identifier port loc))
((char-numeric? c)
;; numeric -- also accept . FIXME, requires lookahead
(make-lexical-token 'NumericLiteral loc (read-numeric port loc)))
(else
;; punctuation
(read-punctuation port loc)))))))
(define (make-tokenizer port)
(let ((div? #f))
(lambda ()
(let ((tok (next-token port div?)))
(set! div? (and (lexical-token? tok)
(let ((cat (lexical-token-category tok)))
(or (eq? cat 'Identifier)
(eq? cat 'NumericLiteral)
(eq? cat 'StringLiteral)))))
tok))))
(define (make-tokenizer/1 port)
(let ((div? #f)
(eoi? #f)
(stack '()))
(lambda ()
(if eoi?
'*eoi*
(let ((tok (next-token port div?)))
(case (if (lexical-token? tok) (lexical-token-category tok) tok)
((lparen)
(set! stack (cons tok stack)))
((rparen)
(if (and (pair? stack)
(eq? (lexical-token-category (car stack)) 'lparen))
(set! stack (cdr stack))
(syntax-error "unexpected right parenthesis"
(lexical-token-source tok)
#f)))
((lbracket)
(set! stack (cons tok stack)))
((rbracket)
(if (and (pair? stack)
(eq? (lexical-token-category (car stack)) 'lbracket))
(set! stack (cdr stack))
(syntax-error "unexpected right bracket"
(lexical-token-source tok)
#f)))
((lbrace)
(set! stack (cons tok stack)))
((rbrace)
(if (and (pair? stack)
(eq? (lexical-token-category (car stack)) 'lbrace))
(set! stack (cdr stack))
(syntax-error "unexpected right brace"
(lexical-token-source tok)
#f)))
((semicolon)
(set! eoi? (null? stack))))
(set! div? (and (lexical-token? tok)
(let ((cat (lexical-token-category tok)))
(or (eq? cat 'Identifier)
(eq? cat 'NumericLiteral)
(eq? cat 'StringLiteral)))))
tok)))))
(define (tokenize port)
(let ((next (make-tokenizer port)))
(let lp ((out '()))
(let ((tok (next)))
(if (eq? tok '*eoi*)
(reverse! out)
(lp (cons tok out)))))))
(define (tokenize/1 port)
(let ((next (make-tokenizer/1 port)))
(let lp ((out '()))
(let ((tok (next)))
(if (eq? tok '*eoi*)
(reverse! out)
(lp (cons tok out)))))))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp bindings)
#\export (make-bindings
mark-global-needed!
map-globals-needed
with-lexical-bindings
with-dynamic-bindings
get-lexical-binding))
;;; This module defines routines to handle analysis of symbol bindings
;;; used during elisp compilation. This data allows to collect the
;;; symbols, for which globals need to be created, or mark certain
;;; symbols as lexically bound.
;;;
;;; Needed globals are stored in an association-list that stores a list
;;; of symbols for each module they are needed in.
;;;
;;; The lexical bindings of symbols are stored in a hash-table that
;;; associates symbols to fluids; those fluids are used in the
;;; with-lexical-binding and with-dynamic-binding routines to associate
;;; symbols to different bindings over a dynamic extent.
;;; Record type used to hold the data necessary.
(define bindings-type
(make-record-type 'bindings '(needed-globals lexical-bindings)))
;;; Construct an 'empty' instance of the bindings data structure to be
;;; used at the start of a fresh compilation.
(define (make-bindings)
((record-constructor bindings-type) '() (make-hash-table)))
;;; Mark that a given symbol is needed as global in the specified
;;; slot-module.
(define (mark-global-needed! bindings sym module)
(let* ((old-needed ((record-accessor bindings-type 'needed-globals)
bindings))
(old-in-module (or (assoc-ref old-needed module) '()))
(new-in-module (if (memq sym old-in-module)
old-in-module
(cons sym old-in-module)))
(new-needed (assoc-set! old-needed module new-in-module)))
((record-modifier bindings-type 'needed-globals)
bindings
new-needed)))
;;; Cycle through all globals needed in order to generate the code for
;;; their creation or some other analysis.
(define (map-globals-needed bindings proc)
(let ((needed ((record-accessor bindings-type 'needed-globals)
bindings)))
(let iterate-modules ((mod-tail needed)
(mod-result '()))
(if (null? mod-tail)
mod-result
(iterate-modules
(cdr mod-tail)
(let* ((aentry (car mod-tail))
(module (car aentry))
(symbols (cdr aentry)))
(let iterate-symbols ((sym-tail symbols)
(sym-result mod-result))
(if (null? sym-tail)
sym-result
(iterate-symbols (cdr sym-tail)
(cons (proc module (car sym-tail))
sym-result))))))))))
;;; Get the current lexical binding (gensym it should refer to in the
;;; current scope) for a symbol or #f if it is dynamically bound.
(define (get-lexical-binding bindings sym)
(let* ((lex ((record-accessor bindings-type 'lexical-bindings)
bindings))
(slot (hash-ref lex sym #f)))
(if slot
(fluid-ref slot)
#f)))
;;; Establish a binding or mark a symbol as dynamically bound for the
;;; extent of calling proc.
(define (with-symbol-bindings bindings syms targets proc)
(if (or (not (list? syms))
(not (and-map symbol? syms)))
(error "can't bind non-symbols" syms))
(let ((lex ((record-accessor bindings-type 'lexical-bindings)
bindings)))
(for-each (lambda (sym)
(if (not (hash-ref lex sym))
(hash-set! lex sym (make-fluid))))
syms)
(with-fluids* (map (lambda (sym) (hash-ref lex sym)) syms)
targets
proc)))
(define (with-lexical-bindings bindings syms targets proc)
(if (or (not (list? targets))
(not (and-map symbol? targets)))
(error "invalid targets for lexical binding" targets)
(with-symbol-bindings bindings syms targets proc)))
(define (with-dynamic-bindings bindings syms proc)
(with-symbol-bindings bindings
syms
(map (lambda (el) #f) syms)
proc))
;;; Guile Emacs Lisp
;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;; 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 3, 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; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
;; Boston, MA 02111-1307, USA.
;;; Code:
(define-module (language elisp compile-tree-il)
#\use-module (language elisp bindings)
#\use-module (language elisp runtime)
#\use-module (language tree-il)
#\use-module (system base pmatch)
#\use-module (system base compile)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-8)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\export (compile-tree-il
compile-progn
compile-if
compile-defconst
compile-defvar
compile-setq
compile-let
compile-lexical-let
compile-flet
compile-let*
compile-lexical-let*
compile-flet*
compile-without-void-checks
compile-with-always-lexical
compile-guile-ref
compile-guile-primitive
compile-while
compile-function
compile-defmacro
compile-defun
#{compile-\`}
compile-quote))
;;; Certain common parameters (like the bindings data structure or
;;; compiler options) are not always passed around but accessed using
;;; fluids to simulate dynamic binding (hey, this is about elisp).
;;; The bindings data structure to keep track of symbol binding related
;;; data.
(define bindings-data (make-fluid))
;;; Store for which symbols (or all/none) void checks are disabled.
(define disable-void-check (make-fluid))
;;; Store which symbols (or all/none) should always be bound lexically,
;;; even with ordinary let and as lambda arguments.
(define always-lexical (make-fluid))
;;; Find the source properties of some parsed expression if there are
;;; any associated with it.
(define (location x)
(and (pair? x)
(let ((props (source-properties x)))
(and (not (null? props))
props))))
;;; Values to use for Elisp's nil and t.
(define (nil-value loc)
(make-const loc (@ (language elisp runtime) nil-value)))
(define (t-value loc)
(make-const loc (@ (language elisp runtime) t-value)))
;;; Modules that contain the value and function slot bindings.
(define runtime '(language elisp runtime))
(define value-slot (@ (language elisp runtime) value-slot-module))
(define function-slot (@ (language elisp runtime) function-slot-module))
;;; The backquoting works the same as quasiquotes in Scheme, but the
;;; forms are named differently; to make easy adaptions, we define these
;;; predicates checking for a symbol being the car of an
;;; unquote/unquote-splicing/backquote form.
(define (unquote? sym)
(and (symbol? sym) (eq? sym '#{\,})))
(define (unquote-splicing? sym)
(and (symbol? sym) (eq? sym '#{\,\@})))
;;; Build a call to a primitive procedure nicely.
(define (call-primitive loc sym . args)
(make-application loc (make-primitive-ref loc sym) args))
;;; Error reporting routine for syntax/compilation problems or build
;;; code for a runtime-error output.
(define (report-error loc . args)
(apply error args))
(define (runtime-error loc msg . args)
(make-application loc
(make-primitive-ref loc 'error)
(cons (make-const loc msg) args)))
;;; Generate code to ensure a global symbol is there for further use of
;;; a given symbol. In general during the compilation, those needed are
;;; only tracked with the bindings data structure. Afterwards, however,
;;; for all those needed symbols the globals are really generated with
;;; this routine.
(define (generate-ensure-global loc sym module)
(make-application loc
(make-module-ref loc runtime 'ensure-fluid! #t)
(list (make-const loc module)
(make-const loc sym))))
(define (ensuring-globals loc bindings body)
(make-sequence
loc
`(,@(map-globals-needed (fluid-ref bindings)
(lambda (mod sym)
(generate-ensure-global loc sym mod)))
,body)))
;;; Build a construct that establishes dynamic bindings for certain
;;; variables. We may want to choose between binding with fluids and
;;; with-fluids* and using just ordinary module symbols and
;;; setting/reverting their values with a dynamic-wind.
(define (let-dynamic loc syms module vals body)
(call-primitive
loc
'with-fluids*
(make-application loc
(make-primitive-ref loc 'list)
(map (lambda (sym)
(make-module-ref loc module sym #t))
syms))
(make-application loc (make-primitive-ref loc 'list) vals)
(make-lambda loc
'()
(make-lambda-case #f '() #f #f #f '() '() body #f))))
;;; Handle access to a variable (reference/setting) correctly depending
;;; on whether it is currently lexically or dynamically bound. lexical
;;; access is done only for references to the value-slot module!
(define (access-variable loc
sym
module
handle-global
handle-lexical
handle-dynamic)
(let ((lexical (get-lexical-binding (fluid-ref bindings-data) sym)))
(cond
(lexical (handle-lexical lexical))
((equal? module function-slot) (handle-global))
(else (handle-dynamic)))))
;;; Generate code to reference a variable. For references in the
;;; value-slot module, we may want to generate a lexical reference
;;; instead if the variable has a lexical binding.
(define (reference-variable loc sym module)
(access-variable
loc
sym
module
(lambda () (make-module-ref loc module sym #t))
(lambda (lexical) (make-lexical-ref loc lexical lexical))
(lambda ()
(mark-global-needed! (fluid-ref bindings-data) sym module)
(call-primitive loc
'fluid-ref
(make-module-ref loc module sym #t)))))
;;; Generate code to set a variable. Just as with reference-variable, in
;;; case of a reference to value-slot, we want to generate a lexical set
;;; when the variable has a lexical binding.
(define (set-variable! loc sym module value)
(access-variable
loc
sym
module
(lambda ()
(make-application
loc
(make-module-ref loc runtime 'set-variable! #t)
(list (make-const loc module) (make-const loc sym) value)))
(lambda (lexical) (make-lexical-set loc lexical lexical value))
(lambda ()
(mark-global-needed! (fluid-ref bindings-data) sym module)
(call-primitive loc
'fluid-set!
(make-module-ref loc module sym #t)
value))))
;;; Process the bindings part of a let or let* expression; that is,
;;; check for correctness and bring it to the form ((sym1 . val1) (sym2
;;; . val2) ...).
(define (process-let-bindings loc bindings)
(map
(lambda (b)
(if (symbol? b)
(cons b 'nil)
(if (or (not (list? b))
(not (= (length b) 2)))
(report-error
loc
"expected symbol or list of 2 elements in let")
(if (not (symbol? (car b)))
(report-error loc "expected symbol in let")
(cons (car b) (cadr b))))))
bindings))
;;; Split the let bindings into a list to be done lexically and one
;;; dynamically. A symbol will be bound lexically if and only if: We're
;;; processing a lexical-let (i.e. module is 'lexical), OR we're
;;; processing a value-slot binding AND the symbol is already lexically
;;; bound or is always lexical, OR we're processing a function-slot
;;; binding.
(define (bind-lexically? sym module)
(or (eq? module 'lexical)
(eq? module function-slot)
(and (equal? module value-slot)
(let ((always (fluid-ref always-lexical)))
(or (eq? always 'all)
(memq sym always)
(get-lexical-binding (fluid-ref bindings-data) sym))))))
(define (split-let-bindings bindings module)
(let iterate ((tail bindings)
(lexical '())
(dynamic '()))
(if (null? tail)
(values (reverse lexical) (reverse dynamic))
(if (bind-lexically? (caar tail) module)
(iterate (cdr tail) (cons (car tail) lexical) dynamic)
(iterate (cdr tail) lexical (cons (car tail) dynamic))))))
;;; Compile let and let* expressions. The code here is used both for
;;; let/let* and flet/flet*, just with a different bindings module.
;;;
;;; A special module value 'lexical means that we're doing a lexical-let
;;; instead and the bindings should not be saved to globals at all but
;;; be done with the lexical framework instead.
;;; Let is done with a single call to let-dynamic binding them locally
;;; to new values all "at once". If there is at least one variable to
;;; bind lexically among the bindings, we first do a let for all of them
;;; to evaluate all values before any bindings take place, and then call
;;; let-dynamic for the variables to bind dynamically.
(define (generate-let loc module bindings body)
(let ((bind (process-let-bindings loc bindings)))
(call-with-values
(lambda () (split-let-bindings bind module))
(lambda (lexical dynamic)
(for-each (lambda (sym)
(mark-global-needed! (fluid-ref bindings-data)
sym
module))
(map car dynamic))
(let ((make-values (lambda (for)
(map (lambda (el) (compile-expr (cdr el)))
for)))
(make-body (lambda ()
(make-sequence loc (map compile-expr body)))))
(if (null? lexical)
(let-dynamic loc (map car dynamic) module
(make-values dynamic) (make-body))
(let* ((lexical-syms (map (lambda (el) (gensym)) lexical))
(dynamic-syms (map (lambda (el) (gensym)) dynamic))
(all-syms (append lexical-syms dynamic-syms))
(vals (append (make-values lexical)
(make-values dynamic))))
(make-let loc
all-syms
all-syms
vals
(with-lexical-bindings
(fluid-ref bindings-data)
(map car lexical) lexical-syms
(lambda ()
(if (null? dynamic)
(make-body)
(let-dynamic loc
(map car dynamic)
module
(map
(lambda (sym)
(make-lexical-ref loc
sym
sym))
dynamic-syms)
(make-body)))))))))))))
;;; Let* is compiled to a cascaded set of "small lets" for each binding
;;; in turn so that each one already sees the preceding bindings.
(define (generate-let* loc module bindings body)
(let ((bind (process-let-bindings loc bindings)))
(begin
(for-each (lambda (sym)
(if (not (bind-lexically? sym module))
(mark-global-needed! (fluid-ref bindings-data)
sym
module)))
(map car bind))
(let iterate ((tail bind))
(if (null? tail)
(make-sequence loc (map compile-expr body))
(let ((sym (caar tail))
(value (compile-expr (cdar tail))))
(if (bind-lexically? sym module)
(let ((target (gensym)))
(make-let loc
`(,target)
`(,target)
`(,value)
(with-lexical-bindings
(fluid-ref bindings-data)
`(,sym)
`(,target)
(lambda () (iterate (cdr tail))))))
(let-dynamic loc
`(,(caar tail))
module
`(,value)
(iterate (cdr tail))))))))))
;;; Split the argument list of a lambda expression into required,
;;; optional and rest arguments and also check it is actually valid.
;;; Additionally, we create a list of all "local variables" (that is,
;;; required, optional and rest arguments together) and also this one
;;; split into those to be bound lexically and dynamically. Returned is
;;; as multiple values: required optional rest lexical dynamic
(define (bind-arg-lexical? arg)
(let ((always (fluid-ref always-lexical)))
(or (eq? always 'all)
(memq arg always))))
(define (split-lambda-arguments loc args)
(let iterate ((tail args)
(mode 'required)
(required '())
(optional '())
(lexical '())
(dynamic '()))
(cond
((null? tail)
(let ((final-required (reverse required))
(final-optional (reverse optional))
(final-lexical (reverse lexical))
(final-dynamic (reverse dynamic)))
(values final-required
final-optional
#f
final-lexical
final-dynamic)))
((and (eq? mode 'required)
(eq? (car tail) '&optional))
(iterate (cdr tail) 'optional required optional lexical dynamic))
((eq? (car tail) '&rest)
(if (or (null? (cdr tail))
(not (null? (cddr tail))))
(report-error loc "expected exactly one symbol after &rest")
(let* ((rest (cadr tail))
(rest-lexical (bind-arg-lexical? rest))
(final-required (reverse required))
(final-optional (reverse optional))
(final-lexical (reverse (if rest-lexical
(cons rest lexical)
lexical)))
(final-dynamic (reverse (if rest-lexical
dynamic
(cons rest dynamic)))))
(values final-required
final-optional
rest
final-lexical
final-dynamic))))
(else
(if (not (symbol? (car tail)))
(report-error loc
"expected symbol in argument list, got"
(car tail))
(let* ((arg (car tail))
(bind-lexical (bind-arg-lexical? arg))
(new-lexical (if bind-lexical
(cons arg lexical)
lexical))
(new-dynamic (if bind-lexical
dynamic
(cons arg dynamic))))
(case mode
((required) (iterate (cdr tail) mode
(cons arg required) optional
new-lexical new-dynamic))
((optional) (iterate (cdr tail) mode
required (cons arg optional)
new-lexical new-dynamic))
(else
(error "invalid mode in split-lambda-arguments"
mode)))))))))
;;; Compile a lambda expression. One thing we have to be aware of is
;;; that lambda arguments are usually dynamically bound, even when a
;;; lexical binding is intact for a symbol. For symbols that are marked
;;; as 'always lexical,' however, we lexically bind here as well, and
;;; thus we get them out of the let-dynamic call and register a lexical
;;; binding for them (the lexical target variable is already there,
;;; namely the real lambda argument from TreeIL).
(define (compile-lambda loc args body)
(if (not (list? args))
(report-error loc "expected list for argument-list" args))
(if (null? body)
(report-error loc "function body must not be empty"))
(receive (required optional rest lexical dynamic)
(split-lambda-arguments loc args)
(define (process-args args)
(define (find-pairs pairs filter)
(lset-intersection (lambda (name+sym x)
(eq? (car name+sym) x))
pairs
filter))
(let* ((syms (map (lambda (x) (gensym)) args))
(pairs (map cons args syms))
(lexical-pairs (find-pairs pairs lexical))
(dynamic-pairs (find-pairs pairs dynamic)))
(values syms pairs lexical-pairs dynamic-pairs)))
(let*-values (((required-syms
required-pairs
required-lex-pairs
required-dyn-pairs)
(process-args required))
((optional-syms
optional-pairs
optional-lex-pairs
optional-dyn-pairs)
(process-args optional))
((rest-syms rest-pairs rest-lex-pairs rest-dyn-pairs)
(process-args (if rest (list rest) '())))
((the-rest-sym) (if rest (car rest-syms) #f))
((all-syms) (append required-syms
optional-syms
rest-syms))
((all-lex-pairs) (append required-lex-pairs
optional-lex-pairs
rest-lex-pairs))
((all-dyn-pairs) (append required-dyn-pairs
optional-dyn-pairs
rest-dyn-pairs)))
(for-each (lambda (sym)
(mark-global-needed! (fluid-ref bindings-data)
sym
value-slot))
dynamic)
(with-dynamic-bindings
(fluid-ref bindings-data)
dynamic
(lambda ()
(with-lexical-bindings
(fluid-ref bindings-data)
(map car all-lex-pairs)
(map cdr all-lex-pairs)
(lambda ()
(make-lambda
loc
'()
(make-lambda-case
#f
required
optional
rest
#f
(map (lambda (x) (nil-value loc)) optional)
all-syms
(let ((compiled-body
(make-sequence loc (map compile-expr body))))
(make-sequence
loc
(list
(if rest
(make-conditional
loc
(call-primitive loc
'null?
(make-lexical-ref loc
rest
the-rest-sym))
(make-lexical-set loc
rest
the-rest-sym
(nil-value loc))
(make-void loc))
(make-void loc))
(if (null? dynamic)
compiled-body
(let-dynamic loc
dynamic
value-slot
(map (lambda (name-sym)
(make-lexical-ref
loc
(car name-sym)
(cdr name-sym)))
all-dyn-pairs)
compiled-body)))))
#f)))))))))
;;; Handle the common part of defconst and defvar, that is, checking for
;;; a correct doc string and arguments as well as maybe in the future
;;; handling the docstring somehow.
(define (handle-var-def loc sym doc)
(cond
((not (symbol? sym)) (report-error loc "expected symbol, got" sym))
((> (length doc) 1) (report-error loc "too many arguments to defvar"))
((and (not (null? doc)) (not (string? (car doc))))
(report-error loc "expected string as third argument of defvar, got"
(car doc)))
;; TODO: Handle doc string if present.
(else #t)))
;;; Handle macro and special operator bindings.
(define (find-operator sym type)
(and
(symbol? sym)
(module-defined? (resolve-interface function-slot) sym)
(let* ((op (module-ref (resolve-module function-slot) sym))
(op (if (fluid? op) (fluid-ref op) op)))
(if (and (pair? op) (eq? (car op) type))
(cdr op)
#f))))
;;; See if a (backquoted) expression contains any unquotes.
(define (contains-unquotes? expr)
(if (pair? expr)
(if (or (unquote? (car expr)) (unquote-splicing? (car expr)))
#t
(or (contains-unquotes? (car expr))
(contains-unquotes? (cdr expr))))
#f))
;;; Process a backquoted expression by building up the needed
;;; cons/append calls. For splicing, it is assumed that the expression
;;; spliced in evaluates to a list. The emacs manual does not really
;;; state either it has to or what to do if it does not, but Scheme
;;; explicitly forbids it and this seems reasonable also for elisp.
(define (unquote-cell? expr)
(and (list? expr) (= (length expr) 2) (unquote? (car expr))))
(define (unquote-splicing-cell? expr)
(and (list? expr) (= (length expr) 2) (unquote-splicing? (car expr))))
(define (process-backquote loc expr)
(if (contains-unquotes? expr)
(if (pair? expr)
(if (or (unquote-cell? expr) (unquote-splicing-cell? expr))
(compile-expr (cadr expr))
(let* ((head (car expr))
(processed-tail (process-backquote loc (cdr expr)))
(head-is-list-2 (and (list? head)
(= (length head) 2)))
(head-unquote (and head-is-list-2
(unquote? (car head))))
(head-unquote-splicing (and head-is-list-2
(unquote-splicing?
(car head)))))
(if head-unquote-splicing
(call-primitive loc
'append
(compile-expr (cadr head))
processed-tail)
(call-primitive loc 'cons
(if head-unquote
(compile-expr (cadr head))
(process-backquote loc head))
processed-tail))))
(report-error loc
"non-pair expression contains unquotes"
expr))
(make-const loc expr)))
;;; Temporarily update a list of symbols that are handled specially
;;; (disabled void check or always lexical) for compiling body. We need
;;; to handle special cases for already all / set to all and the like.
(define (with-added-symbols loc fluid syms body)
(if (null? body)
(report-error loc "symbol-list construct has empty body"))
(if (not (or (eq? syms 'all)
(and (list? syms) (and-map symbol? syms))))
(report-error loc "invalid symbol list" syms))
(let ((old (fluid-ref fluid))
(make-body (lambda ()
(make-sequence loc (map compile-expr body)))))
(if (eq? old 'all)
(make-body)
(let ((new (if (eq? syms 'all)
'all
(append syms old))))
(with-fluids ((fluid new))
(make-body))))))
;;; Special operators
(defspecial progn (loc args)
(make-sequence loc (map compile-expr args)))
(defspecial if (loc args)
(pmatch args
((,cond ,then . ,else)
(make-conditional loc
(compile-expr cond)
(compile-expr then)
(if (null? else)
(nil-value loc)
(make-sequence loc
(map compile-expr else)))))))
(defspecial defconst (loc args)
(pmatch args
((,sym ,value . ,doc)
(if (handle-var-def loc sym doc)
(make-sequence loc
(list (set-variable! loc
sym
value-slot
(compile-expr value))
(make-const loc sym)))))))
(defspecial defvar (loc args)
(pmatch args
((,sym) (make-const loc sym))
((,sym ,value . ,doc)
(if (handle-var-def loc sym doc)
(make-sequence
loc
(list
(make-conditional
loc
(make-conditional
loc
(call-primitive
loc
'module-bound?
(call-primitive loc
'resolve-interface
(make-const loc value-slot))
(make-const loc sym))
(call-primitive loc
'fluid-bound?
(make-module-ref loc value-slot sym #t))
(make-const loc #f))
(make-void loc)
(set-variable! loc sym value-slot (compile-expr value)))
(make-const loc sym)))))))
(defspecial setq (loc args)
(define (car* x) (if (null? x) '() (car x)))
(define (cdr* x) (if (null? x) '() (cdr x)))
(define (cadr* x) (car* (cdr* x)))
(define (cddr* x) (cdr* (cdr* x)))
(make-sequence
loc
(let loop ((args args) (last (nil-value loc)))
(if (null? args)
(list last)
(let ((sym (car args))
(val (compile-expr (cadr* args))))
(if (not (symbol? sym))
(report-error loc "expected symbol in setq")
(cons
(set-variable! loc sym value-slot val)
(loop (cddr* args)
(reference-variable loc sym value-slot)))))))))
(defspecial let (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc value-slot bindings body))))
(defspecial lexical-let (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc 'lexical bindings body))))
(defspecial flet (loc args)
(pmatch args
((,bindings . ,body)
(generate-let loc function-slot bindings body))))
(defspecial let* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc value-slot bindings body))))
(defspecial lexical-let* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc 'lexical bindings body))))
(defspecial flet* (loc args)
(pmatch args
((,bindings . ,body)
(generate-let* loc function-slot bindings body))))
;;; Temporarily set symbols as always lexical only for the lexical scope
;;; of a construct.
(defspecial with-always-lexical (loc args)
(pmatch args
((,syms . ,body)
(with-added-symbols loc always-lexical syms body))))
;;; guile-ref allows building TreeIL's module references from within
;;; elisp as a way to access data within the Guile universe. The module
;;; and symbol referenced are static values, just like (@ module symbol)
;;; does!
(defspecial guile-ref (loc args)
(pmatch args
((,module ,sym) (guard (and (list? module) (symbol? sym)))
(make-module-ref loc module sym #t))))
;;; guile-primitive allows to create primitive references, which are
;;; still a little faster.
(defspecial guile-primitive (loc args)
(pmatch args
((,sym)
(make-primitive-ref loc sym))))
;;; A while construct is transformed into a tail-recursive loop like
;;; this:
;;;
;;; (letrec ((iterate (lambda ()
;;; (if condition
;;; (begin body
;;; (iterate))
;;; #nil))))
;;; (iterate))
;;;
;;; As letrec is not directly accessible from elisp, while is
;;; implemented here instead of with a macro.
(defspecial while (loc args)
(pmatch args
((,condition . ,body)
(let* ((itersym (gensym))
(compiled-body (map compile-expr body))
(iter-call (make-application loc
(make-lexical-ref loc
'iterate
itersym)
(list)))
(full-body (make-sequence loc
`(,@compiled-body ,iter-call)))
(lambda-body (make-conditional loc
(compile-expr condition)
full-body
(nil-value loc)))
(iter-thunk (make-lambda loc
'()
(make-lambda-case #f
'()
#f
#f
#f
'()
'()
lambda-body
#f))))
(make-letrec loc
#f
'(iterate)
(list itersym)
(list iter-thunk)
iter-call)))))
(defspecial function (loc args)
(pmatch args
(((lambda ,args . ,body))
(compile-lambda loc args body))
((,sym) (guard (symbol? sym))
(reference-variable loc sym function-slot))))
(defspecial defmacro (loc args)
(pmatch args
((,name ,args . ,body)
(if (not (symbol? name))
(report-error loc "expected symbol as macro name" name)
(let* ((tree-il
(make-sequence
loc
(list
(set-variable!
loc
name
function-slot
(make-application
loc
(make-module-ref loc '(guile) 'cons #t)
(list (make-const loc 'macro)
(compile-lambda loc args body))))
(make-const loc name)))))
(compile (ensuring-globals loc bindings-data tree-il)
#\from 'tree-il
#\to 'value)
tree-il)))))
(defspecial defun (loc args)
(pmatch args
((,name ,args . ,body)
(if (not (symbol? name))
(report-error loc "expected symbol as function name" name)
(make-sequence loc
(list (set-variable! loc
name
function-slot
(compile-lambda loc
args
body))
(make-const loc name)))))))
(defspecial #{\`} (loc args)
(pmatch args
((,val)
(process-backquote loc val))))
(defspecial quote (loc args)
(pmatch args
((,val)
(make-const loc val))))
;;; Compile a compound expression to Tree-IL.
(define (compile-pair loc expr)
(let ((operator (car expr))
(arguments (cdr expr)))
(cond
((find-operator operator 'special-operator)
=> (lambda (special-operator-function)
(special-operator-function loc arguments)))
((find-operator operator 'macro)
=> (lambda (macro-function)
(compile-expr (apply macro-function arguments))))
(else
(make-application loc
(if (symbol? operator)
(reference-variable loc
operator
function-slot)
(compile-expr operator))
(map compile-expr arguments))))))
;;; Compile a symbol expression. This is a variable reference or maybe
;;; some special value like nil.
(define (compile-symbol loc sym)
(case sym
((nil) (nil-value loc))
((t) (t-value loc))
(else (reference-variable loc sym value-slot))))
;;; Compile a single expression to TreeIL.
(define (compile-expr expr)
(let ((loc (location expr)))
(cond
((symbol? expr)
(compile-symbol loc expr))
((pair? expr)
(compile-pair loc expr))
(else (make-const loc expr)))))
;;; Process the compiler options.
;;; FIXME: Why is '(()) passed as options by the REPL?
(define (valid-symbol-list-arg? value)
(or (eq? value 'all)
(and (list? value) (and-map symbol? value))))
(define (process-options! opt)
(if (and (not (null? opt))
(not (equal? opt '(()))))
(if (null? (cdr opt))
(report-error #f "Invalid compiler options" opt)
(let ((key (car opt))
(value (cadr opt)))
(case key
((#\warnings) ; ignore
#f)
((#\always-lexical)
(if (valid-symbol-list-arg? value)
(fluid-set! always-lexical value)
(report-error #f
"Invalid value for #\always-lexical"
value)))
(else (report-error #f
"Invalid compiler option"
key)))))))
;;; Entry point for compilation to TreeIL. This creates the bindings
;;; data structure, and after compiling the main expression we need to
;;; make sure all globals for symbols used during the compilation are
;;; created using the generate-ensure-global function.
(define (compile-tree-il expr env opts)
(values
(with-fluids ((bindings-data (make-bindings))
(disable-void-check '())
(always-lexical '()))
(process-options! opts)
(let ((compiled (compile-expr expr)))
(ensuring-globals (location expr) bindings-data compiled)))
env
env))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp lexer)
#\use-module (ice-9 regex)
#\export (get-lexer get-lexer/1))
;;; This is the lexical analyzer for the elisp reader. It is
;;; hand-written instead of using some generator. I think this is the
;;; best solution because of all that fancy escape sequence handling and
;;; the like.
;;;
;;; Characters are handled internally as integers representing their
;;; code value. This is necessary because elisp allows a lot of fancy
;;; modifiers that set certain high-range bits and the resulting values
;;; would not fit into a real Scheme character range. Additionally,
;;; elisp wants characters as integers, so we just do the right thing...
;;;
;;; TODO: #@count comments
;;; Report an error from the lexer (that is, invalid input given).
(define (lexer-error port msg . args)
(apply error msg args))
;;; In a character, set a given bit. This is just some bit-wise or'ing
;;; on the characters integer code and converting back to character.
(define (set-char-bit chr bit)
(logior chr (ash 1 bit)))
;;; Check if a character equals some other. This is just like char=?
;;; except that the tested one could be EOF in which case it simply
;;; isn't equal.
(define (is-char? tested should-be)
(and (not (eof-object? tested))
(char=? tested should-be)))
;;; For a character (as integer code), find the real character it
;;; represents or #\nul if out of range. This is used to work with
;;; Scheme character functions like char-numeric?.
(define (real-character chr)
(if (< chr 256)
(integer->char chr)
#\nul))
;;; Return the control modified version of a character. This is not
;;; just setting a modifier bit, because ASCII conrol characters must be
;;; handled as such, and in elisp C-? is the delete character for
;;; historical reasons. Otherwise, we set bit 26.
(define (add-control chr)
(let ((real (real-character chr)))
(if (char-alphabetic? real)
(- (char->integer (char-upcase real)) (char->integer #\@))
(case real
((#\?) 127)
((#\@) 0)
(else (set-char-bit chr 26))))))
;;; Parse a charcode given in some base, basically octal or hexadecimal
;;; are needed. A requested number of digits can be given (#f means it
;;; does not matter and arbitrary many are allowed), and additionally
;;; early return allowed (if fewer valid digits are found). These
;;; options are all we need to handle the \u, \U, \x and \ddd (octal
;;; digits) escape sequences.
(define (charcode-escape port base digits early-return)
(let iterate ((result 0)
(procdigs 0))
(if (and digits (>= procdigs digits))
result
(let* ((cur (read-char port))
(value (cond
((char-numeric? cur)
(- (char->integer cur) (char->integer #\0)))
((char-alphabetic? cur)
(let ((code (- (char->integer (char-upcase cur))
(char->integer #\A))))
(if (< code 0)
#f
(+ code 10))))
(else #f)))
(valid (and value (< value base))))
(if (not valid)
(if (or (not digits) early-return)
(begin
(unread-char cur port)
result)
(lexer-error port
"invalid digit in escape-code"
base
cur))
(iterate (+ (* result base) value) (1+ procdigs)))))))
;;; Read a character and process escape-sequences when necessary. The
;;; special in-string argument defines if this character is part of a
;;; string literal or a single character literal, the difference being
;;; that in strings the meta modifier sets bit 7, while it is bit 27 for
;;; characters.
(define basic-escape-codes
'((#\a . 7)
(#\b . 8)
(#\t . 9)
(#\n . 10)
(#\v . 11)
(#\f . 12)
(#\r . 13)
(#\e . 27)
(#\s . 32)
(#\d . 127)))
(define (get-character port in-string)
(let ((meta-bits `((#\A . 22)
(#\s . 23)
(#\H . 24)
(#\S . 25)
(#\M . ,(if in-string 7 27))))
(cur (read-char port)))
(if (char=? cur #\\)
;; Handle an escape-sequence.
(let* ((escaped (read-char port))
(esc-code (assq-ref basic-escape-codes escaped))
(meta (assq-ref meta-bits escaped)))
(cond
;; Meta-check must be before esc-code check because \s- must
;; be recognized as the super-meta modifier if a - follows.
;; If not, it will be caught as \s -> space escape code.
((and meta (is-char? (peek-char port) #\-))
(if (not (char=? (read-char port) #\-))
(error "expected - after control sequence"))
(set-char-bit (get-character port in-string) meta))
;; One of the basic control character escape names?
(esc-code esc-code)
;; Handle \ddd octal code if it is one.
((and (char>=? escaped #\0) (char<? escaped #\8))
(begin
(unread-char escaped port)
(charcode-escape port 8 3 #t)))
;; Check for some escape-codes directly or otherwise use the
;; escaped character literally.
(else
(case escaped
((#\^) (add-control (get-character port in-string)))
((#\C)
(if (is-char? (peek-char port) #\-)
(begin
(if (not (char=? (read-char port) #\-))
(error "expected - after control sequence"))
(add-control (get-character port in-string)))
escaped))
((#\x) (charcode-escape port 16 #f #t))
((#\u) (charcode-escape port 16 4 #f))
((#\U) (charcode-escape port 16 8 #f))
(else (char->integer escaped))))))
;; No escape-sequence, just the literal character. But remember
;; to get the code instead!
(char->integer cur))))
;;; Read a symbol or number from a port until something follows that
;;; marks the start of a new token (like whitespace or parentheses).
;;; The data read is returned as a string for further conversion to the
;;; correct type, but we also return what this is
;;; (integer/float/symbol). If any escaped character is found, it must
;;; be a symbol. Otherwise we at the end check the result-string
;;; against regular expressions to determine if it is possibly an
;;; integer or a float.
(define integer-regex (make-regexp "^[+-]?[0-9]+\\.?$"))
(define float-regex
(make-regexp
"^[+-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)(e[+-]?[0-9]+)?$"))
;;; A dot is also allowed literally, only a single dort alone is parsed
;;; as the 'dot' terminal for dotted lists.
(define no-escape-punctuation (string->char-set "-+=*/_~!@$%^&:<>{}?."))
(define (get-symbol-or-number port)
(let iterate ((result-chars '())
(had-escape #f))
(let* ((c (read-char port))
(finish (lambda ()
(let ((result (list->string
(reverse result-chars))))
(values
(cond
((and (not had-escape)
(regexp-exec integer-regex result))
'integer)
((and (not had-escape)
(regexp-exec float-regex result))
'float)
(else 'symbol))
result))))
(need-no-escape? (lambda (c)
(or (char-numeric? c)
(char-alphabetic? c)
(char-set-contains?
no-escape-punctuation
c)))))
(cond
((eof-object? c) (finish))
((need-no-escape? c) (iterate (cons c result-chars) had-escape))
((char=? c #\\) (iterate (cons (read-char port) result-chars) #t))
(else
(unread-char c port)
(finish))))))
;;; Parse a circular structure marker without the leading # (which was
;;; already read and recognized), that is, a number as identifier and
;;; then either = or #.
(define (get-circular-marker port)
(call-with-values
(lambda ()
(let iterate ((result 0))
(let ((cur (read-char port)))
(if (char-numeric? cur)
(let ((val (- (char->integer cur) (char->integer #\0))))
(iterate (+ (* result 10) val)))
(values result cur)))))
(lambda (id type)
(case type
((#\#) `(circular-ref . ,id))
((#\=) `(circular-def . ,id))
(else (lexer-error port
"invalid circular marker character"
type))))))
;;; Main lexer routine, which is given a port and does look for the next
;;; token.
(define (lex port)
(let ((return (let ((file (if (file-port? port)
(port-filename port)
#f))
(line (1+ (port-line port)))
(column (1+ (port-column port))))
(lambda (token value)
(let ((obj (cons token value)))
(set-source-property! obj 'filename file)
(set-source-property! obj 'line line)
(set-source-property! obj 'column column)
obj))))
;; Read afterwards so the source-properties are correct above
;; and actually point to the very character to be read.
(c (read-char port)))
(cond
;; End of input must be specially marked to the parser.
((eof-object? c) (return 'eof c))
;; Whitespace, just skip it.
((char-whitespace? c) (lex port))
;; The dot is only the one for dotted lists if followed by
;; whitespace. Otherwise it is considered part of a number of
;; symbol.
((and (char=? c #\.)
(char-whitespace? (peek-char port)))
(return 'dot #f))
;; Continue checking for literal character values.
(else
(case c
;; A line comment, skip until end-of-line is found.
((#\;)
(let iterate ()
(let ((cur (read-char port)))
(if (or (eof-object? cur) (char=? cur #\newline))
(lex port)
(iterate)))))
;; A character literal.
((#\?)
(return 'character (get-character port #f)))
;; A literal string. This is mainly a sequence of characters
;; just as in the character literals, the only difference is
;; that escaped newline and space are to be completely ignored
;; and that meta-escapes set bit 7 rather than bit 27.
((#\")
(let iterate ((result-chars '()))
(let ((cur (read-char port)))
(case cur
((#\")
(return 'string (list->string (reverse result-chars))))
((#\\)
(let ((escaped (read-char port)))
(case escaped
((#\newline #\space)
(iterate result-chars))
(else
(unread-char escaped port)
(unread-char cur port)
(iterate
(cons (integer->char (get-character port #t))
result-chars))))))
(else (iterate (cons cur result-chars)))))))
((#\#)
(let ((c (read-char port)))
(case c
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(unread-char c port)
(let ((mark (get-circular-marker port)))
(return (car mark) (cdr mark))))
((#\')
(return 'function #f)))))
;; Parentheses and other special-meaning single characters.
((#\() (return 'paren-open #f))
((#\)) (return 'paren-close #f))
((#\[) (return 'square-open #f))
((#\]) (return 'square-close #f))
((#\') (return 'quote #f))
((#\`) (return 'backquote #f))
;; Unquote and unquote-splicing.
((#\,)
(if (is-char? (peek-char port) #\@)
(if (not (char=? (read-char port) #\@))
(error "expected @ in unquote-splicing")
(return 'unquote-splicing #f))
(return 'unquote #f)))
;; Remaining are numbers and symbols. Process input until next
;; whitespace is found, and see if it looks like a number
;; (float/integer) or symbol and return accordingly.
(else
(unread-char c port)
(call-with-values
(lambda () (get-symbol-or-number port))
(lambda (type str)
(case type
((symbol)
;; str could be empty if the first character is already
;; something not allowed in a symbol (and not escaped)!
;; Take care about that, it is an error because that
;; character should have been handled elsewhere or is
;; invalid in the input.
(if (zero? (string-length str))
(begin
;; Take it out so the REPL might not get into an
;; infinite loop with further reading attempts.
(read-char port)
(error "invalid character in input" c))
(return 'symbol (string->symbol str))))
((integer)
;; In elisp, something like "1." is an integer, while
;; string->number returns an inexact real. Thus we need
;; a conversion here, but it should always result in an
;; integer!
(return
'integer
(let ((num (inexact->exact (string->number str))))
(if (not (integer? num))
(error "expected integer" str num))
num)))
((float)
(return 'float (let ((num (string->number str)))
(if (exact? num)
(error "expected inexact float"
str
num))
num)))
(else (error "wrong number/symbol type" type)))))))))))
;;; Build a lexer thunk for a port. This is the exported routine which
;;; can be used to create a lexer for the parser to use.
(define (get-lexer port)
(lambda () (lex port)))
;;; Build a special lexer that will only read enough for one expression
;;; and then always return end-of-input. If we find one of the quotation
;;; stuff, one more expression is needed in any case.
(define (get-lexer/1 port)
(let ((lex (get-lexer port))
(finished #f)
(paren-level 0))
(lambda ()
(if finished
(cons 'eof ((@ (ice-9 binary-ports) eof-object)))
(let ((next (lex))
(quotation #f))
(case (car next)
((paren-open square-open)
(set! paren-level (1+ paren-level)))
((paren-close square-close)
(set! paren-level (1- paren-level)))
((quote backquote unquote unquote-splicing circular-def)
(set! quotation #t)))
(if (and (not quotation) (<= paren-level 0))
(set! finished #t))
next)))))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp parser)
#\use-module (language elisp lexer)
#\export (read-elisp))
;;; The parser (reader) for elisp expressions.
;;;
;;; It is hand-written (just as the lexer is) instead of using some
;;; parser generator because this allows easier transfer of source
;;; properties from the lexer ((text parse-lalr) seems not to allow
;;; access to the original lexer token-pair) and is easy enough anyways.
;;; Report a parse error. The first argument is some current lexer
;;; token where source information is available should it be useful.
(define (parse-error token msg . args)
(apply error msg args))
;;; For parsing circular structures, we keep track of definitions in a
;;; hash-map that maps the id's to their values. When defining a new
;;; id, though, we immediatly fill the slot with a promise before
;;; parsing and setting the real value, because it must already be
;;; available at that time in case of a circular reference. The promise
;;; refers to a local variable that will be set when the real value is
;;; available through a closure. After parsing the expression is
;;; completed, we work through it again and force all promises we find.
;;; The definitions themselves are stored in a fluid and their scope is
;;; one call to read-elisp (but not only the currently parsed
;;; expression!).
(define circular-definitions (make-fluid))
(define (make-circular-definitions)
(make-hash-table))
(define (circular-ref token)
(if (not (eq? (car token) 'circular-ref))
(error "invalid token for circular-ref" token))
(let* ((id (cdr token))
(value (hashq-ref (fluid-ref circular-definitions) id)))
(if value
value
(parse-error token "undefined circular reference" id))))
;;; Returned is a closure that, when invoked, will set the final value.
;;; This means both the variable the promise will return and the
;;; hash-table slot so we don't generate promises any longer.
(define (circular-define! token)
(if (not (eq? (car token) 'circular-def))
(error "invalid token for circular-define!" token))
(let ((value #f)
(table (fluid-ref circular-definitions))
(id (cdr token)))
(hashq-set! table id (delay value))
(lambda (real-value)
(set! value real-value)
(hashq-set! table id real-value))))
;;; Work through a parsed data structure and force the promises there.
;;; After a promise is forced, the resulting value must not be recursed
;;; on; this may lead to infinite recursion with a circular structure,
;;; and additionally this value was already processed when it was
;;; defined. All deep data structures that can be parsed must be
;;; handled here!
(define (force-promises! data)
(cond
((pair? data)
(begin
(if (promise? (car data))
(set-car! data (force (car data)))
(force-promises! (car data)))
(if (promise? (cdr data))
(set-cdr! data (force (cdr data)))
(force-promises! (cdr data)))))
((vector? data)
(let ((len (vector-length data)))
(let iterate ((i 0))
(if (< i len)
(let ((el (vector-ref data i)))
(if (promise? el)
(vector-set! data i (force el))
(force-promises! el))
(iterate (1+ i)))))))
;; Else nothing needs to be done.
))
;;; We need peek-functionality for the next lexer token, this is done
;;; with some single token look-ahead storage. This is handled by a
;;; closure which allows getting or peeking the next token. When one
;;; expression is fully parsed, we don't want a look-ahead stored here
;;; because it would miss from future parsing. This is verified by the
;;; finish action.
(define (make-lexer-buffer lex)
(let ((look-ahead #f))
(lambda (action)
(if (eq? action 'finish)
(if look-ahead
(error "lexer-buffer is not empty when finished")
#f)
(begin
(if (not look-ahead)
(set! look-ahead (lex)))
(case action
((peek) look-ahead)
((get)
(let ((result look-ahead))
(set! look-ahead #f)
result))
(else (error "invalid lexer-buffer action" action))))))))
;;; Get the contents of a list, where the opening parentheses has
;;; already been found. The same code is used for vectors and lists,
;;; where lists allow the dotted tail syntax and vectors not;
;;; additionally, the closing parenthesis must of course match. The
;;; implementation here is not tail-recursive, but I think it is clearer
;;; and simpler this way.
(define (get-list lex allow-dot close-square)
(let* ((next (lex 'peek))
(type (car next)))
(cond
((eq? type (if close-square 'square-close 'paren-close))
(begin
(if (not (eq? (car (lex 'get)) type))
(error "got different token than peeked"))
'()))
((and allow-dot (eq? type 'dot))
(begin
(if (not (eq? (car (lex 'get)) type))
(error "got different token than peeked"))
(let ((tail (get-list lex #f close-square)))
(if (not (= (length tail) 1))
(parse-error next
"expected exactly one element after dot"))
(car tail))))
(else
;; Do both parses in exactly this sequence!
(let* ((head (get-expression lex))
(tail (get-list lex allow-dot close-square)))
(cons head tail))))))
;;; Parse a single expression from a lexer-buffer. This is the main
;;; routine in our recursive-descent parser.
(define quotation-symbols '((quote . quote)
(backquote . #\`)
(unquote . #\,)
(unquote-splicing . #\,\@)))
(define (get-expression lex)
(let* ((token (lex 'get))
(type (car token))
(return (lambda (result)
(if (pair? result)
(set-source-properties!
result
(source-properties token)))
result)))
(case type
((eof)
(parse-error token "end of file during parsing"))
((integer float symbol character string)
(return (cdr token)))
((function)
(return `(function ,(get-expression lex))))
((quote backquote unquote unquote-splicing)
(return (list (assq-ref quotation-symbols type)
(get-expression lex))))
((paren-open)
(return (get-list lex #t #f)))
((square-open)
(return (list->vector (get-list lex #f #t))))
((circular-ref)
(circular-ref token))
((circular-def)
;; The order of definitions is important!
(let* ((setter (circular-define! token))
(expr (get-expression lex)))
(setter expr)
(force-promises! expr)
expr))
(else
(parse-error token "expected expression, got" token)))))
;;; Define the reader function based on this; build a lexer, a
;;; lexer-buffer, and then parse a single expression to return. We also
;;; define a circular-definitions data structure to use.
(define (read-elisp port)
(with-fluids ((circular-definitions (make-circular-definitions)))
(let* ((lexer (get-lexer port))
(lexbuf (make-lexer-buffer lexer))
(next (lexbuf 'peek)))
(if (eq? (car next) 'eof)
(cdr next)
(let ((result (get-expression lexbuf)))
(lexbuf 'finish)
result)))))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp runtime)
#\export (nil-value
t-value
value-slot-module
function-slot-module
elisp-bool
ensure-fluid!
reference-variable
set-variable!
runtime-error
macro-error)
#\export-syntax (built-in-func built-in-macro defspecial prim))
;;; This module provides runtime support for the Elisp front-end.
;;; Values for t and nil. (FIXME remove this abstraction)
(define nil-value #nil)
(define t-value #t)
;;; Modules for the binding slots.
;;; Note: Naming those value-slot and/or function-slot clashes with the
;;; submodules of these names!
(define value-slot-module '(language elisp runtime value-slot))
(define function-slot-module '(language elisp runtime function-slot))
;;; Report an error during macro compilation, that means some special
;;; compilation (syntax) error; or report a simple runtime-error from a
;;; built-in function.
(define (macro-error msg . args)
(apply error msg args))
(define runtime-error macro-error)
;;; Convert a scheme boolean to Elisp.
(define (elisp-bool b)
(if b
t-value
nil-value))
;;; Routines for access to elisp dynamically bound symbols. This is
;;; used for runtime access using functions like symbol-value or set,
;;; where the symbol accessed might not be known at compile-time. These
;;; always access the dynamic binding and can not be used for the
;;; lexical!
(define (ensure-fluid! module sym)
(let ((intf (resolve-interface module))
(resolved (resolve-module module)))
(if (not (module-defined? intf sym))
(let ((fluid (make-unbound-fluid)))
(module-define! resolved sym fluid)
(module-export! resolved `(,sym))))))
(define (reference-variable module sym)
(let ((resolved (resolve-module module)))
(cond
((equal? module function-slot-module)
(module-ref resolved sym))
(else
(ensure-fluid! module sym)
(fluid-ref (module-ref resolved sym))))))
(define (set-variable! module sym value)
(let ((intf (resolve-interface module))
(resolved (resolve-module module)))
(cond
((equal? module function-slot-module)
(cond
((module-defined? intf sym)
(module-set! resolved sym value))
(else
(module-define! resolved sym value)
(module-export! resolved `(,sym)))))
(else
(ensure-fluid! module sym)
(fluid-set! (module-ref resolved sym) value))))
value)
;;; Define a predefined function or predefined macro for use in the
;;; function-slot and macro-slot modules, respectively.
(define-syntax built-in-func
(syntax-rules ()
((_ name value)
(begin
(define-public name value)))))
(define (make-id template-id . data)
(let ((append-symbols
(lambda (symbols)
(string->symbol
(apply string-append (map symbol->string symbols))))))
(datum->syntax template-id
(append-symbols
(map (lambda (datum)
((if (identifier? datum)
syntax->datum
identity)
datum))
data)))))
(define-syntax built-in-macro
(lambda (x)
(syntax-case x ()
((_ name value)
(with-syntax ((scheme-name (make-id #'name 'macro- #'name)))
#'(begin
(define-public scheme-name
(make-fluid (cons 'macro value)))))))))
(define-syntax defspecial
(lambda (x)
(syntax-case x ()
((_ name args body ...)
(with-syntax ((scheme-name (make-id #'name 'compile- #'name)))
#'(begin
(define scheme-name
(make-fluid
(cons 'special-operator
(lambda args body ...))))))))))
;;; Call a guile-primitive that may be rebound for elisp and thus needs
;;; absolute addressing.
(define-syntax prim
(syntax-rules ()
((_ sym args ...)
((@ (guile) sym) args ...))))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language elisp runtime function-slot)
#\use-module (language elisp runtime subrs)
#\use-module ((language elisp runtime macros)
#\select
((macro-lambda . lambda)
(macro-prog1 . prog1)
(macro-prog2 . prog2)
(macro-when . when)
(macro-unless . unless)
(macro-cond . cond)
(macro-and . and)
(macro-or . or)
(macro-dotimes . dotimes)
(macro-dolist . dolist)
(macro-catch . catch)
(macro-unwind-protect . unwind-protect)
(macro-pop . pop)
(macro-push . push)))
#\use-module ((language elisp compile-tree-il)
#\select
((compile-progn . progn)
(compile-if . if)
(compile-defconst . defconst)
(compile-defvar . defvar)
(compile-setq . setq)
(compile-let . let)
(compile-lexical-let . lexical-let)
(compile-flet . flet)
(compile-let* . let*)
(compile-lexical-let* . lexical-let*)
(compile-flet* . flet*)
(compile-with-always-lexical . with-always-lexical)
(compile-guile-ref . guile-ref)
(compile-guile-primitive . guile-primitive)
(compile-while . while)
(compile-function . function)
(compile-defun . defun)
(compile-defmacro . defmacro)
(#{compile-\`} . #\`)
(compile-quote . quote)))
#\duplicates (last)
;; special operators
#\re-export (progn
if
defconst
defvar
setq
let
lexical-let
flet
let*
lexical-let*
flet*
with-always-lexical
guile-ref
guile-primitive
while
function
defun
defmacro
#\`
quote)
;; macros
#\re-export (lambda
prog1
prog2
when
unless
cond
and
or
dotimes
dolist
catch
unwind-protect
pop
push)
;; functions
#\re-export (eq
equal
floatp
integerp
numberp
wholenump
zerop
=
/=
<
<=
>
>=
max
min
abs
float
1+
1-
+
-
*
%
ffloor
fceiling
ftruncate
fround
consp
atomp
listp
nlistp
null
car
cdr
car-safe
cdr-safe
nth
nthcdr
length
cons
list
make-list
append
reverse
copy-tree
number-sequence
setcar
setcdr
symbol-value
symbol-function
set
fset
makunbound
fmakunbound
boundp
fboundp
apply
funcall
throw
not
eval
load))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp runtime macros)
#\use-module (language elisp runtime))
;;; This module contains the macro definitions of elisp symbols. In
;;; contrast to the other runtime modules, those are used directly
;;; during compilation, of course, so not really in runtime. But I
;;; think it fits well to the others here.
(built-in-macro lambda
(lambda cdr
`(function (lambda ,@cdr))))
;;; The prog1 and prog2 constructs can easily be defined as macros using
;;; progn and some lexical-let's to save the intermediate value to
;;; return at the end.
(built-in-macro prog1
(lambda (form1 . rest)
(let ((temp (gensym)))
`(lexical-let ((,temp ,form1))
,@rest
,temp))))
(built-in-macro prog2
(lambda (form1 form2 . rest)
`(progn ,form1 (prog1 ,form2 ,@rest))))
;;; Define the conditionals when and unless as macros.
(built-in-macro when
(lambda (condition . thens)
`(if ,condition (progn ,@thens) nil)))
(built-in-macro unless
(lambda (condition . elses)
`(if ,condition nil (progn ,@elses))))
;;; Impement the cond form as nested if's. A special case is a
;;; (condition) subform, in which case we need to return the condition
;;; itself if it is true and thus save it in a local variable before
;;; testing it.
(built-in-macro cond
(lambda (. clauses)
(let iterate ((tail clauses))
(if (null? tail)
'nil
(let ((cur (car tail))
(rest (iterate (cdr tail))))
(prim cond
((prim or (not (list? cur)) (null? cur))
(macro-error "invalid clause in cond" cur))
((null? (cdr cur))
(let ((var (gensym)))
`(lexical-let ((,var ,(car cur)))
(if ,var
,var
,rest))))
(else
`(if ,(car cur)
(progn ,@(cdr cur))
,rest))))))))
;;; The `and' and `or' forms can also be easily defined with macros.
(built-in-macro and
(case-lambda
(() 't)
((x) x)
((x . args)
(let iterate ((x x) (tail args))
(if (null? tail)
x
`(if ,x
,(iterate (car tail) (cdr tail))
nil))))))
(built-in-macro or
(case-lambda
(() 'nil)
((x) x)
((x . args)
(let iterate ((x x) (tail args))
(if (null? tail)
x
(let ((var (gensym)))
`(lexical-let ((,var ,x))
(if ,var
,var
,(iterate (car tail) (cdr tail))))))))))
;;; Define the dotimes and dolist iteration macros.
(built-in-macro dotimes
(lambda (args . body)
(if (prim or
(not (list? args))
(< (length args) 2)
(> (length args) 3))
(macro-error "invalid dotimes arguments" args)
(let ((var (car args))
(count (cadr args)))
(if (not (symbol? var))
(macro-error "expected symbol as dotimes variable"))
`(let ((,var 0))
(while ((guile-primitive <) ,var ,count)
,@body
(setq ,var ((guile-primitive 1+) ,var)))
,@(if (= (length args) 3)
(list (caddr args))
'()))))))
(built-in-macro dolist
(lambda (args . body)
(if (prim or
(not (list? args))
(< (length args) 2)
(> (length args) 3))
(macro-error "invalid dolist arguments" args)
(let ((var (car args))
(iter-list (cadr args))
(tailvar (gensym)))
(if (not (symbol? var))
(macro-error "expected symbol as dolist variable")
`(let (,var)
(lexical-let ((,tailvar ,iter-list))
(while ((guile-primitive not)
((guile-primitive null?) ,tailvar))
(setq ,var ((guile-primitive car) ,tailvar))
,@body
(setq ,tailvar ((guile-primitive cdr) ,tailvar)))
,@(if (= (length args) 3)
(list (caddr args))
'()))))))))
;;; Exception handling. unwind-protect and catch are implemented as
;;; macros (throw is a built-in function).
;;; catch and throw can mainly be implemented directly using Guile's
;;; primitives for exceptions, the only difficulty is that the keys used
;;; within Guile must be symbols, while elisp allows any value and
;;; checks for matches using eq (eq?). We handle this by using always #t
;;; as key for the Guile primitives and check for matches inside the
;;; handler; if the elisp keys are not eq?, we rethrow the exception.
(built-in-macro catch
(lambda (tag . body)
(if (null? body)
(macro-error "catch with empty body"))
(let ((tagsym (gensym)))
`(lexical-let ((,tagsym ,tag))
((guile-primitive catch)
#t
(lambda () ,@body)
,(let* ((dummy-key (gensym))
(elisp-key (gensym))
(value (gensym))
(arglist `(,dummy-key ,elisp-key ,value)))
`(with-always-lexical
,arglist
(lambda ,arglist
(if (eq ,elisp-key ,tagsym)
,value
((guile-primitive throw) ,dummy-key ,elisp-key
,value))))))))))
;;; unwind-protect is just some weaker construct as dynamic-wind, so
;;; straight-forward to implement.
(built-in-macro unwind-protect
(lambda (body . clean-ups)
(if (null? clean-ups)
(macro-error "unwind-protect without cleanup code"))
`((guile-primitive dynamic-wind)
(lambda () nil)
(lambda () ,body)
(lambda () ,@clean-ups))))
;;; Pop off the first element from a list or push one to it.
(built-in-macro pop
(lambda (list-name)
`(prog1 (car ,list-name)
(setq ,list-name (cdr ,list-name)))))
(built-in-macro push
(lambda (new-el list-name)
`(setq ,list-name (cons ,new-el ,list-name))))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License as
;;; published by the Free Software Foundation; either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;;; 02110-1301 USA
;;; Code:
(define-module (language elisp runtime subrs)
#\use-module (language elisp runtime)
#\use-module (system base compile))
;;; This module contains the function-slots of elisp symbols. Elisp
;;; built-in functions are implemented as predefined function bindings
;;; here.
;;; Equivalence and equalness predicates.
(built-in-func eq
(lambda (a b)
(elisp-bool (eq? a b))))
(built-in-func equal
(lambda (a b)
(elisp-bool (equal? a b))))
;;; Number predicates.
(built-in-func floatp
(lambda (num)
(elisp-bool (and (real? num)
(or (inexact? num)
(prim not (integer? num)))))))
(built-in-func integerp
(lambda (num)
(elisp-bool (and (exact? num)
(integer? num)))))
(built-in-func numberp
(lambda (num)
(elisp-bool (real? num))))
(built-in-func wholenump
(lambda (num)
(elisp-bool (and (exact? num)
(integer? num)
(prim >= num 0)))))
(built-in-func zerop
(lambda (num)
(elisp-bool (prim = num 0))))
;;; Number comparisons.
(built-in-func =
(lambda (num1 num2)
(elisp-bool (prim = num1 num2))))
(built-in-func /=
(lambda (num1 num2)
(elisp-bool (prim not (prim = num1 num2)))))
(built-in-func <
(lambda (num1 num2)
(elisp-bool (prim < num1 num2))))
(built-in-func <=
(lambda (num1 num2)
(elisp-bool (prim <= num1 num2))))
(built-in-func >
(lambda (num1 num2)
(elisp-bool (prim > num1 num2))))
(built-in-func >=
(lambda (num1 num2)
(elisp-bool (prim >= num1 num2))))
(built-in-func max
(lambda (. nums)
(prim apply (@ (guile) max) nums)))
(built-in-func min
(lambda (. nums)
(prim apply (@ (guile) min) nums)))
(built-in-func abs
(@ (guile) abs))
;;; Number conversion.
(built-in-func float
(lambda (num)
(if (exact? num)
(exact->inexact num)
num)))
;;; TODO: truncate, floor, ceiling, round.
;;; Arithmetic functions.
(built-in-func 1+ (@ (guile) 1+))
(built-in-func 1- (@ (guile) 1-))
(built-in-func + (@ (guile) +))
(built-in-func - (@ (guile) -))
(built-in-func * (@ (guile) *))
(built-in-func % (@ (guile) modulo))
;;; TODO: / with correct integer/real behaviour, mod (for floating-piont
;;; values).
;;; Floating-point rounding operations.
(built-in-func ffloor (@ (guile) floor))
(built-in-func fceiling (@ (guile) ceiling))
(built-in-func ftruncate (@ (guile) truncate))
(built-in-func fround (@ (guile) round))
;;; List predicates.
(built-in-func consp
(lambda (el)
(elisp-bool (pair? el))))
(built-in-func atomp
(lambda (el)
(elisp-bool (prim not (pair? el)))))
(built-in-func listp
(lambda (el)
(elisp-bool (or (pair? el) (null? el)))))
(built-in-func nlistp
(lambda (el)
(elisp-bool (and (prim not (pair? el))
(prim not (null? el))))))
(built-in-func null
(lambda (el)
(elisp-bool (null? el))))
;;; Accessing list elements.
(built-in-func car
(lambda (el)
(if (null? el)
nil-value
(prim car el))))
(built-in-func cdr
(lambda (el)
(if (null? el)
nil-value
(prim cdr el))))
(built-in-func car-safe
(lambda (el)
(if (pair? el)
(prim car el)
nil-value)))
(built-in-func cdr-safe
(lambda (el)
(if (pair? el)
(prim cdr el)
nil-value)))
(built-in-func nth
(lambda (n lst)
(if (negative? n)
(prim car lst)
(let iterate ((i n)
(tail lst))
(cond
((null? tail) nil-value)
((zero? i) (prim car tail))
(else (iterate (prim 1- i) (prim cdr tail))))))))
(built-in-func nthcdr
(lambda (n lst)
(if (negative? n)
lst
(let iterate ((i n)
(tail lst))
(cond
((null? tail) nil-value)
((zero? i) tail)
(else (iterate (prim 1- i) (prim cdr tail))))))))
(built-in-func length (@ (guile) length))
;;; Building lists.
(built-in-func cons (@ (guile) cons))
(built-in-func list (@ (guile) list))
(built-in-func make-list
(lambda (len obj)
(prim make-list len obj)))
(built-in-func append (@ (guile) append))
(built-in-func reverse (@ (guile) reverse))
(built-in-func copy-tree (@ (guile) copy-tree))
(built-in-func number-sequence
(lambda (from . rest)
(if (prim > (prim length rest) 2)
(runtime-error "too many arguments for number-sequence"
(prim cdddr rest))
(if (null? rest)
`(,from)
(let ((to (prim car rest))
(sep (if (or (null? (prim cdr rest))
(eq? nil-value (prim cadr rest)))
1
(prim cadr rest))))
(cond
((or (eq? nil-value to) (prim = to from)) `(,from))
((and (zero? sep) (prim not (prim = from to)))
(runtime-error "infinite list in number-sequence"))
((prim < (prim * to sep) (prim * from sep)) '())
(else
(let iterate ((i (prim +
from
(prim *
sep
(prim quotient
(prim abs
(prim -
to
from))
(prim abs sep)))))
(result '()))
(if (prim = i from)
(prim cons i result)
(iterate (prim - i sep)
(prim cons i result)))))))))))
;;; Changing lists.
(built-in-func setcar
(lambda (cell val)
(if (and (null? cell) (null? val))
#nil
(prim set-car! cell val))
val))
(built-in-func setcdr
(lambda (cell val)
(if (and (null? cell) (null? val))
#nil
(prim set-cdr! cell val))
val))
;;; Accessing symbol bindings for symbols known only at runtime.
(built-in-func symbol-value
(lambda (sym)
(reference-variable value-slot-module sym)))
(built-in-func symbol-function
(lambda (sym)
(reference-variable function-slot-module sym)))
(built-in-func set
(lambda (sym value)
(set-variable! value-slot-module sym value)))
(built-in-func fset
(lambda (sym value)
(set-variable! function-slot-module sym value)))
(built-in-func makunbound
(lambda (sym)
(if (module-bound? (resolve-interface value-slot-module) sym)
(let ((var (module-variable (resolve-module value-slot-module)
sym)))
(if (and (variable-bound? var) (fluid? (variable-ref var)))
(fluid-unset! (variable-ref var))
(variable-unset! var))))
sym))
(built-in-func fmakunbound
(lambda (sym)
(if (module-bound? (resolve-interface function-slot-module) sym)
(let ((var (module-variable
(resolve-module function-slot-module)
sym)))
(if (and (variable-bound? var) (fluid? (variable-ref var)))
(fluid-unset! (variable-ref var))
(variable-unset! var))))
sym))
(built-in-func boundp
(lambda (sym)
(elisp-bool
(and
(module-bound? (resolve-interface value-slot-module) sym)
(let ((var (module-variable (resolve-module value-slot-module)
sym)))
(and (variable-bound? var)
(if (fluid? (variable-ref var))
(fluid-bound? (variable-ref var))
#t)))))))
(built-in-func fboundp
(lambda (sym)
(elisp-bool
(and
(module-bound? (resolve-interface function-slot-module) sym)
(let* ((var (module-variable (resolve-module function-slot-module)
sym)))
(and (variable-bound? var)
(if (fluid? (variable-ref var))
(fluid-bound? (variable-ref var))
#t)))))))
;;; Function calls. These must take care of special cases, like using
;;; symbols or raw lambda-lists as functions!
(built-in-func apply
(lambda (func . args)
(let ((real-func (cond
((symbol? func)
(reference-variable function-slot-module func))
((list? func)
(if (and (prim not (null? func))
(eq? (prim car func) 'lambda))
(compile func #\from 'elisp #\to 'value)
(runtime-error "list is not a function"
func)))
(else func))))
(prim apply (@ (guile) apply) real-func args))))
(built-in-func funcall
(lambda (func . args)
(apply func args)))
;;; Throw can be implemented as built-in function.
(built-in-func throw
(lambda (tag value)
(prim throw 'elisp-exception tag value)))
;;; Miscellaneous.
(built-in-func not
(lambda (x)
(if x nil-value t-value)))
(built-in-func eval
(lambda (form)
(compile form #\from 'elisp #\to 'value)))
(built-in-func load
(lambda* (file)
(compile-file file #\from 'elisp #\to 'value)
#t))
;;; Guile Emacs Lisp
;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp runtime value-slot))
;;; This module contains the value-slots of elisp symbols.
;;; Guile Emac Lisp
;; Copyright (C) 2001, 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language elisp spec)
#\use-module (language elisp compile-tree-il)
#\use-module (language elisp parser)
#\use-module (system base language)
#\export (elisp))
(define-language elisp
#\title "Emacs Lisp"
#\reader (lambda (port env) (read-elisp port))
#\printer write
#\compilers `((tree-il . ,compile-tree-il)))
;;; Guile Low Intermediate Language
;; Copyright (C) 2001, 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language glil)
#\use-module (system base syntax)
#\use-module (system base pmatch)
#\use-module ((srfi srfi-1) #\select (fold))
#\export
(<glil-program> make-glil-program glil-program?
glil-program-meta glil-program-body
<glil-std-prelude> make-glil-std-prelude glil-std-prelude?
glil-std-prelude-nreq glil-std-prelude-nlocs glil-std-prelude-else-label
<glil-opt-prelude> make-glil-opt-prelude glil-opt-prelude?
glil-opt-prelude-nreq glil-opt-prelude-nopt glil-opt-prelude-rest
glil-opt-prelude-nlocs glil-opt-prelude-else-label
<glil-kw-prelude> make-glil-kw-prelude glil-kw-prelude?
glil-kw-prelude-nreq glil-kw-prelude-nopt glil-kw-prelude-kw
glil-kw-prelude-allow-other-keys? glil-kw-prelude-rest
glil-kw-prelude-nlocs glil-kw-prelude-else-label
<glil-bind> make-glil-bind glil-bind?
glil-bind-vars
<glil-mv-bind> make-glil-mv-bind glil-mv-bind?
glil-mv-bind-vars glil-mv-bind-rest
<glil-unbind> make-glil-unbind glil-unbind?
<glil-source> make-glil-source glil-source?
glil-source-props
<glil-void> make-glil-void glil-void?
<glil-const> make-glil-const glil-const?
glil-const-obj
<glil-lexical> make-glil-lexical glil-lexical?
glil-lexical-local? glil-lexical-boxed? glil-lexical-op glil-lexical-index
<glil-toplevel> make-glil-toplevel glil-toplevel?
glil-toplevel-op glil-toplevel-name
<glil-module> make-glil-module glil-module?
glil-module-op glil-module-mod glil-module-name glil-module-public?
<glil-label> make-glil-label glil-label?
glil-label-label
<glil-branch> make-glil-branch glil-branch?
glil-branch-inst glil-branch-label
<glil-call> make-glil-call glil-call?
glil-call-inst glil-call-nargs
<glil-mv-call> make-glil-mv-call glil-mv-call?
glil-mv-call-nargs glil-mv-call-ra
<glil-prompt> make-glil-prompt glil-prompt? glil-prompt-label glil-prompt-escape-only?
parse-glil unparse-glil))
(define (print-glil x port)
(format port "#<glil ~s>" (unparse-glil x)))
(define-type (<glil> #\printer print-glil)
;; Meta operations
(<glil-program> meta body)
(<glil-std-prelude> nreq nlocs else-label)
(<glil-opt-prelude> nreq nopt rest nlocs else-label)
(<glil-kw-prelude> nreq nopt rest kw allow-other-keys? nlocs else-label)
(<glil-bind> vars)
(<glil-mv-bind> vars rest)
(<glil-unbind>)
(<glil-source> props)
;; Objects
(<glil-void>)
(<glil-const> obj)
;; Variables
(<glil-lexical> local? boxed? op index)
(<glil-toplevel> op name)
(<glil-module> op mod name public?)
;; Controls
(<glil-label> label)
(<glil-branch> inst label)
(<glil-call> inst nargs)
(<glil-mv-call> nargs ra)
(<glil-prompt> label escape-only?))
(define (parse-glil x)
(pmatch x
((program ,meta . ,body)
(make-glil-program meta (map parse-glil body)))
((std-prelude ,nreq ,nlocs ,else-label)
(make-glil-std-prelude nreq nlocs else-label))
((opt-prelude ,nreq ,nopt ,rest ,nlocs ,else-label)
(make-glil-opt-prelude nreq nopt rest nlocs else-label))
((kw-prelude ,nreq ,nopt ,rest ,kw ,allow-other-keys? ,nlocs ,else-label)
(make-glil-kw-prelude nreq nopt rest kw allow-other-keys? nlocs else-label))
((bind . ,vars) (make-glil-bind vars))
((mv-bind ,vars ,rest) (make-glil-mv-bind vars rest))
((unbind) (make-glil-unbind))
((source ,props) (make-glil-source props))
((void) (make-glil-void))
((const ,obj) (make-glil-const obj))
((lexical ,local? ,boxed? ,op ,index) (make-glil-lexical local? boxed? op index))
((toplevel ,op ,name) (make-glil-toplevel op name))
((module public ,op ,mod ,name) (make-glil-module op mod name #t))
((module private ,op ,mod ,name) (make-glil-module op mod name #f))
((label ,label) (make-glil-label label))
((branch ,inst ,label) (make-glil-branch inst label))
((call ,inst ,nargs) (make-glil-call inst nargs))
((mv-call ,nargs ,ra) (make-glil-mv-call nargs ra))
((prompt ,label ,escape-only?)
(make-glil-prompt label escape-only?))
(else (error "invalid glil" x))))
(define (unparse-glil glil)
(record-case glil
;; meta
((<glil-program> meta body)
`(program ,meta ,@(map unparse-glil body)))
((<glil-std-prelude> nreq nlocs else-label)
`(std-prelude ,nreq ,nlocs ,else-label))
((<glil-opt-prelude> nreq nopt rest nlocs else-label)
`(opt-prelude ,nreq ,nopt ,rest ,nlocs ,else-label))
((<glil-kw-prelude> nreq nopt rest kw allow-other-keys? nlocs else-label)
`(kw-prelude ,nreq ,nopt ,rest ,kw ,allow-other-keys? ,nlocs ,else-label))
((<glil-bind> vars) `(bind ,@vars))
((<glil-mv-bind> vars rest) `(mv-bind ,vars ,rest))
((<glil-unbind>) `(unbind))
((<glil-source> props) `(source ,props))
;; constants
((<glil-void>) `(void))
((<glil-const> obj) `(const ,obj))
;; variables
((<glil-lexical> local? boxed? op index)
`(lexical ,local? ,boxed? ,op ,index))
((<glil-toplevel> op name)
`(toplevel ,op ,name))
((<glil-module> op mod name public?)
`(module ,(if public? 'public 'private) ,op ,mod ,name))
;; controls
((<glil-label> label) `(label ,label))
((<glil-branch> inst label) `(branch ,inst ,label))
((<glil-call> inst nargs) `(call ,inst ,nargs))
((<glil-mv-call> nargs ra) `(mv-call ,nargs ,ra))
((<glil-prompt> label escape-only?)
`(prompt ,label escape-only?))))
;;; Guile VM assembler
;; Copyright (C) 2001, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language glil compile-assembly)
#\use-module (system base syntax)
#\use-module (system base pmatch)
#\use-module (language glil)
#\use-module (language assembly)
#\use-module (system vm instruction)
#\use-module ((system vm program) #\select (make-binding))
#\use-module (ice-9 receive)
#\use-module (ice-9 vlist)
#\use-module ((srfi srfi-1) #\select (fold))
#\use-module (rnrs bytevectors)
#\export (compile-assembly))
;; Traversal helpers
;;
(define (vhash-fold-right2 proc vhash s0 s1)
(let lp ((i (vlist-length vhash)) (s0 s0) (s1 s1))
(if (zero? i)
(values s0 s1)
(receive (s0 s1) (let ((pair (vlist-ref vhash (1- i))))
(proc (car pair) (cdr pair) s0 s1))
(lp (1- i) s0 s1)))))
(define (fold2 proc ls s0 s1)
(let lp ((ls ls) (s0 s0) (s1 s1))
(if (null? ls)
(values s0 s1)
(receive (s0 s1) (proc (car ls) s0 s1)
(lp (cdr ls) s0 s1)))))
(define (vector-fold2 proc vect s0 s1)
(let ((len (vector-length vect)))
(let lp ((i 0) (s0 s0) (s1 s1))
(if (< i len)
(receive (s0 s1) (proc (vector-ref vect i) s0 s1)
(lp (1+ i) s0 s1))
(values s0 s1)))))
;; Variable cache cells go in the object table, and serialize as their
;; keys. The reason we wrap the keys in these records is so they don't
;; compare as `equal?' to other objects in the object table.
;;
;; `key' is either a symbol or the list (MODNAME SYM PUBLIC?)
(define-record <variable-cache-cell> key)
(define (limn-sources sources)
(let lp ((in sources) (out '()) (filename #f))
(if (null? in)
(reverse! out)
(let ((addr (caar in))
(new-filename (assq-ref (cdar in ) 'filename))
(line (assq-ref (cdar in) 'line))
(column (assq-ref (cdar in) 'column)))
(cond
((not (equal? new-filename filename))
(lp (cdr in)
`((,addr . (,line . ,column))
(filename . ,new-filename)
. ,out)
new-filename))
((or (null? out) (not (equal? (cdar out) `(,line . ,column))))
(lp (cdr in)
`((,addr . (,line . ,column))
. ,out)
filename))
(else
(lp (cdr in) out filename)))))))
;; Avoid going through the compiler so as to avoid adding to the
;; constant store.
(define (make-meta bindings sources arities tail)
(let ((body `(,@(dump-object `(,bindings ,sources ,arities ,@tail) 0)
(return))))
`(load-program ()
,(addr+ 0 body)
#f
,@body)))
;; If this is true, the object doesn't need to go in a constant table.
;;
(define (immediate? x)
(object->assembly x))
;; This tests for a proper scheme list whose last cdr is '(), not #nil.
;;
(define (scheme-list? x)
(and (list? x)
(or (eq? x '())
(let ((p (last-pair x)))
(and (pair? p)
(eq? (cdr p) '()))))))
;; Note: in all of these procedures that build up constant tables, the
;; first (zeroth) index is reserved. At runtime it is replaced with the
;; procedure's module. Hence all of this 1+ length business.
;; Build up a vhash of constant -> index, allowing us to build up a
;; constant table for a whole compilation unit.
;;
(define (build-constant-store x)
(define (add-to-store store x)
(define (add-to-end store x)
(vhash-cons x (1+ (vlist-length store)) store))
(cond
((vhash-assoc x store)
;; Already in the store.
store)
((immediate? x)
;; Immediates don't need to go in the constant table.
store)
((or (number? x)
(string? x)
(symbol? x)
(keyword? x))
;; Atoms.
(add-to-end store x))
((variable-cache-cell? x)
;; Variable cache cells (see below).
(add-to-end (add-to-store store (variable-cache-cell-key x))
x))
((list? x)
;; Add the elements to the store, then the list itself. We could
;; try hashing the cdrs as well, but that seems a bit overkill, and
;; this way we do compress the bytecode a bit by allowing the use of
;; the `list' opcode.
(let ((store (fold (lambda (x store)
(add-to-store store x))
store
x)))
(add-to-end store x)))
((pair? x)
;; Non-lists get caching on both fields.
(let ((store (add-to-store (add-to-store store (car x))
(cdr x))))
(add-to-end store x)))
((and (vector? x)
(equal? (array-shape x) (list (list 0 (1- (vector-length x))))))
;; Likewise, add the elements to the store, then the vector itself.
;; Important for the vectors produced by the psyntax expansion
;; process.
(let ((store (fold (lambda (x store)
(add-to-store store x))
store
(vector->list x))))
(add-to-end store x)))
((array? x)
;; Naive assumption that if folks are using arrays, that perhaps
;; there's not much more duplication.
(add-to-end store x))
(else
(error "build-constant-store: unrecognized object" x))))
(let walk ((x x) (store vlist-null))
(record-case x
((<glil-program> meta body)
(fold walk store body))
((<glil-const> obj)
(add-to-store store obj))
((<glil-kw-prelude> kw)
(add-to-store store kw))
((<glil-toplevel> op name)
;; We don't add toplevel variable cache cells to the global
;; constant table, because they are sensitive to changes in
;; modules as the toplevel expressions are evaluated. So we just
;; add the name.
(add-to-store store name))
((<glil-module> op mod name public?)
;; However, it is fine add module variable cache cells to the
;; global table, as their bindings are not dependent on the
;; current module.
(add-to-store store
(make-variable-cache-cell (list mod name public?))))
(else store))))
;; Analyze one <glil-program> to determine its object table. Produces a
;; vhash of constant to index.
;;
(define (build-object-table x)
(define (add store x)
(if (vhash-assoc x store)
store
(vhash-cons x (1+ (vlist-length store)) store)))
(record-case x
((<glil-program> meta body)
(fold (lambda (x table)
(record-case x
((<glil-program> meta body)
;; Add the GLIL itself to the table.
(add table x))
((<glil-const> obj)
(if (immediate? obj)
table
(add table obj)))
((<glil-kw-prelude> kw)
(add table kw))
((<glil-toplevel> op name)
(add table (make-variable-cache-cell name)))
((<glil-module> op mod name public?)
(add table (make-variable-cache-cell (list mod name public?))))
(else table)))
vlist-null
body))))
;; A functional stack of names of live variables.
(define (make-open-binding name boxed? index)
(list name boxed? index))
(define (make-closed-binding open-binding start end)
(make-binding (car open-binding) (cadr open-binding)
(caddr open-binding) start end))
(define (open-binding bindings vars start)
(cons
(acons start
(map
(lambda (v)
(pmatch v
((,name ,boxed? ,i)
(make-open-binding name boxed? i))
(else (error "unknown binding type" v))))
vars)
(car bindings))
(cdr bindings)))
(define (close-binding bindings end)
(pmatch bindings
((((,start . ,closing) . ,open) . ,closed)
(cons open
(fold (lambda (o tail)
;; the cons is for dsu sort
(acons start (make-closed-binding o start end)
tail))
closed
closing)))
(else (error "broken bindings" bindings))))
(define (close-all-bindings bindings end)
(if (null? (car bindings))
(map cdr
(stable-sort (reverse (cdr bindings))
(lambda (x y) (< (car x) (car y)))))
(close-all-bindings (close-binding bindings end) end)))
;; A functional arities thingamajiggy.
;; arities := ((ip nreq [[nopt] [[rest] [kw]]]]) ...)
(define (open-arity addr nreq nopt rest kw arities)
(cons
(cond
(kw (list addr nreq nopt rest kw))
(rest (list addr nreq nopt rest))
(nopt (list addr nreq nopt))
(nreq (list addr nreq))
(else (list addr)))
arities))
(define (close-arity addr arities)
(pmatch arities
(() '())
(((,start . ,tail) . ,rest)
`((,start ,addr . ,tail) . ,rest))
(else (error "bad arities" arities))))
(define (begin-arity end start nreq nopt rest kw arities)
(open-arity start nreq nopt rest kw (close-arity end arities)))
(define (compile-assembly glil)
(let* ((all-constants (build-constant-store glil))
(prog (compile-program glil all-constants))
(len (byte-length prog)))
;; The top objcode thunk. We're going to wrap this thunk in
;; a thunk -- yo dawgs -- with the goal being to lift all
;; constants up to the top level. The store forms a DAG, so
;; we can actually build up later elements in terms of
;; earlier ones.
;;
(cond
((vlist-null? all-constants)
;; No constants: just emit the inner thunk.
prog)
(else
;; We have an object store, so write it out, attach it
;; to the inner thunk, and tail call.
(receive (tablecode addr) (dump-constants all-constants)
(let ((prog (align-program prog addr)))
;; Outer thunk.
`(load-program ()
,(+ (addr+ addr prog)
2 ; for (tail-call 0)
)
#f
;; Load the table, build the inner
;; thunk, then tail call.
,@tablecode
,@prog
(tail-call 0))))))))
(define (compile-program glil constants)
(record-case glil
((<glil-program> meta body)
(let lp ((body body) (code '()) (bindings '(())) (source-alist '())
(label-alist '()) (arities '()) (addr 0))
(cond
((null? body)
(let ((code (fold append '() code))
(bindings (close-all-bindings bindings addr))
(sources (limn-sources (reverse! source-alist)))
(labels (reverse label-alist))
(arities (reverse (close-arity addr arities)))
(len addr))
(let* ((meta (make-meta bindings sources arities meta))
(meta-pad (if meta (modulo (- 8 (modulo len 8)) 8) 0)))
`(load-program ,labels
,(+ len meta-pad)
,meta
,@code
,@(if meta
(make-list meta-pad '(nop))
'())))))
(else
(receive (subcode bindings source-alist label-alist arities)
(glil->assembly (car body) bindings
source-alist label-alist
constants arities addr)
(lp (cdr body) (cons subcode code)
bindings source-alist label-alist arities
(addr+ addr subcode)))))))))
(define (compile-objtable constants table addr)
(define (load-constant idx)
(if (< idx 256)
(values `((object-ref ,idx))
2)
(values `((long-object-ref
,(quotient idx 256) ,(modulo idx 256)))
3)))
(cond
((vlist-null? table)
;; Empty table; just return #f.
(values '((make-false))
(1+ addr)))
(else
(call-with-values
(lambda ()
(vhash-fold-right2
(lambda (obj idx codes addr)
(cond
((vhash-assoc obj constants)
=> (lambda (pair)
(receive (load len) (load-constant (cdr pair))
(values (cons load codes)
(+ addr len)))))
((variable-cache-cell? obj)
(cond
((vhash-assoc (variable-cache-cell-key obj) constants)
=> (lambda (pair)
(receive (load len) (load-constant (cdr pair))
(values (cons load codes)
(+ addr len)))))
(else (error "vcache cell key not in table" obj))))
((glil-program? obj)
;; Programs are not cached in the global constants
;; table because when a program is loaded, its module
;; is bound, and we want to do that only after any
;; preceding effectful statements.
(let* ((table (build-object-table obj))
(prog (compile-program obj table)))
(receive (tablecode addr)
(compile-objtable constants table addr)
(let ((prog (align-program prog addr)))
(values (cons `(,@tablecode ,@prog)
codes)
(addr+ addr prog))))))
(else
(error "unrecognized constant" obj))))
table
'(((make-false))) (1+ addr)))
(lambda (elts addr)
(let ((len (1+ (vlist-length table))))
(values
(fold append
`((vector ,(quotient len 256) ,(modulo len 256)))
elts)
(+ addr 3))))))))
(define (glil->assembly glil bindings source-alist label-alist
constants arities addr)
(define (emit-code x)
(values x bindings source-alist label-alist arities))
(define (emit-object-ref i)
(values (if (< i 256)
`((object-ref ,i))
`((long-object-ref ,(quotient i 256) ,(modulo i 256))))
bindings source-alist label-alist arities))
(define (emit-code/arity x nreq nopt rest kw)
(values x bindings source-alist label-alist
(begin-arity addr (addr+ addr x) nreq nopt rest kw arities)))
(record-case glil
((<glil-program> meta body)
(cond
((vhash-assoc glil constants)
;; We are cached in someone's objtable; just emit a load.
=> (lambda (pair)
(emit-object-ref (cdr pair))))
(else
;; Otherwise, build an objtable for the program, compile it, and
;; emit a load-program.
(let* ((table (build-object-table glil))
(prog (compile-program glil table)))
(receive (tablecode addr) (compile-objtable constants table addr)
(emit-code `(,@tablecode ,@(align-program prog addr))))))))
((<glil-std-prelude> nreq nlocs else-label)
(emit-code/arity
(if (and (< nreq 8) (< nlocs (+ nreq 32)) (not else-label))
`((assert-nargs-ee/locals ,(logior nreq (ash (- nlocs nreq) 3))))
`(,(if else-label
`(br-if-nargs-ne ,(quotient nreq 256)
,(modulo nreq 256)
,else-label)
`(assert-nargs-ee ,(quotient nreq 256)
,(modulo nreq 256)))
(reserve-locals ,(quotient nlocs 256)
,(modulo nlocs 256))))
nreq #f #f #f))
((<glil-opt-prelude> nreq nopt rest nlocs else-label)
(let ((bind-required
(if else-label
`((br-if-nargs-lt ,(quotient nreq 256)
,(modulo nreq 256)
,else-label))
`((assert-nargs-ge ,(quotient nreq 256)
,(modulo nreq 256)))))
(bind-optionals
(if (zero? nopt)
'()
`((bind-optionals ,(quotient (+ nopt nreq) 256)
,(modulo (+ nreq nopt) 256)))))
(bind-rest
(cond
(rest
`((push-rest ,(quotient (+ nreq nopt) 256)
,(modulo (+ nreq nopt) 256))))
(else
(if else-label
`((br-if-nargs-gt ,(quotient (+ nreq nopt) 256)
,(modulo (+ nreq nopt) 256)
,else-label))
`((assert-nargs-ee ,(quotient (+ nreq nopt) 256)
,(modulo (+ nreq nopt) 256))))))))
(emit-code/arity
`(,@bind-required
,@bind-optionals
,@bind-rest
(reserve-locals ,(quotient nlocs 256)
,(modulo nlocs 256)))
nreq nopt rest #f)))
((<glil-kw-prelude> nreq nopt rest kw allow-other-keys? nlocs else-label)
(let* ((kw-idx (or (and=> (vhash-assoc kw constants) cdr)
(error "kw not in objtable")))
(bind-required
(if else-label
`((br-if-nargs-lt ,(quotient nreq 256)
,(modulo nreq 256)
,else-label))
`((assert-nargs-ge ,(quotient nreq 256)
,(modulo nreq 256)))))
(ntotal (apply max (+ nreq nopt) (map 1+ (map cdr kw))))
(bind-optionals-and-shuffle
`((,(if (and else-label (not rest))
'bind-optionals/shuffle-or-br
'bind-optionals/shuffle)
,(quotient nreq 256)
,(modulo nreq 256)
,(quotient (+ nreq nopt) 256)
,(modulo (+ nreq nopt) 256)
,(quotient ntotal 256)
,(modulo ntotal 256)
,@(if (and else-label (not rest))
`(,else-label)
'()))))
(bind-kw
;; when this code gets called, all optionals are filled
;; in, space has been made for kwargs, and the kwargs
;; themselves have been shuffled above the slots for all
;; req/opt/kwargs locals.
`((bind-kwargs
,(quotient kw-idx 256)
,(modulo kw-idx 256)
,(quotient ntotal 256)
,(modulo ntotal 256)
,(logior (if rest 2 0)
(if allow-other-keys? 1 0)))))
(bind-rest
(if rest
`((bind-rest ,(quotient ntotal 256)
,(modulo ntotal 256)
,(quotient rest 256)
,(modulo rest 256)))
'())))
(let ((code `(,@bind-required
,@bind-optionals-and-shuffle
,@bind-kw
,@bind-rest
(reserve-locals ,(quotient nlocs 256)
,(modulo nlocs 256)))))
(values code bindings source-alist label-alist
(begin-arity addr (addr+ addr code) nreq nopt rest
(and kw (cons allow-other-keys? kw))
arities)))))
((<glil-bind> vars)
(values '()
(open-binding bindings vars addr)
source-alist
label-alist
arities))
((<glil-mv-bind> vars rest)
(if (integer? vars)
(values `((truncate-values ,vars ,(if rest 1 0)))
bindings
source-alist
label-alist
arities)
(values `((truncate-values ,(length vars) ,(if rest 1 0)))
(open-binding bindings vars addr)
source-alist
label-alist
arities)))
((<glil-unbind>)
(values '()
(close-binding bindings addr)
source-alist
label-alist
arities))
((<glil-source> props)
(values '()
bindings
(acons addr props source-alist)
label-alist
arities))
((<glil-void>)
(emit-code '((void))))
((<glil-const> obj)
(cond
((object->assembly obj)
=> (lambda (code)
(emit-code (list code))))
((vhash-assoc obj constants)
=> (lambda (pair)
(emit-object-ref (cdr pair))))
(else (error "const not in table" obj))))
((<glil-lexical> local? boxed? op index)
(emit-code
(if local?
(if (< index 256)
(case op
((ref) (if boxed?
`((local-boxed-ref ,index))
`((local-ref ,index))))
((set) (if boxed?
`((local-boxed-set ,index))
`((local-set ,index))))
((box) `((box ,index)))
((empty-box) `((empty-box ,index)))
((fix) `((fix-closure 0 ,index)))
((bound?) (if boxed?
`((local-ref ,index)
(variable-bound?))
`((local-bound? ,index))))
(else (error "what" op)))
(let ((a (quotient index 256))
(b (modulo index 256)))
(case op
((ref)
(if boxed?
`((long-local-ref ,a ,b)
(variable-ref))
`((long-local-ref ,a ,b))))
((set)
(if boxed?
`((long-local-ref ,a ,b)
(variable-set))
`((long-local-set ,a ,b))))
((box)
`((make-variable)
(variable-set)
(long-local-set ,a ,b)))
((empty-box)
`((make-variable)
(long-local-set ,a ,b)))
((fix)
`((fix-closure ,a ,b)))
((bound?)
(if boxed?
`((long-local-ref ,a ,b)
(variable-bound?))
`((long-local-bound? ,a ,b))))
(else (error "what" op)))))
`((,(case op
((ref) (if boxed? 'free-boxed-ref 'free-ref))
((set) (if boxed? 'free-boxed-set (error "what." glil)))
(else (error "what" op)))
,index)))))
((<glil-toplevel> op name)
(case op
((ref set)
(cond
((and=> (vhash-assoc (make-variable-cache-cell name) constants)
cdr)
=> (lambda (i)
(emit-code (if (< i 256)
`((,(case op
((ref) 'toplevel-ref)
((set) 'toplevel-set))
,i))
`((,(case op
((ref) 'long-toplevel-ref)
((set) 'long-toplevel-set))
,(quotient i 256)
,(modulo i 256)))))))
(else
(let ((i (or (and=> (vhash-assoc name constants) cdr)
(error "toplevel name not in objtable" name))))
(emit-code `(,(if (< i 256)
`(object-ref ,i)
`(long-object-ref ,(quotient i 256)
,(modulo i 256)))
(link-now)
,(case op
((ref) '(variable-ref))
((set) '(variable-set)))))))))
((define)
(let ((i (or (and=> (vhash-assoc name constants) cdr)
(error "toplevel name not in objtable" name))))
(emit-code `(,(if (< i 256)
`(object-ref ,i)
`(long-object-ref ,(quotient i 256)
,(modulo i 256)))
(define)))))
(else
(error "unknown toplevel var kind" op name))))
((<glil-module> op mod name public?)
(let ((key (list mod name public?)))
(case op
((ref set)
(let ((i (or (and=> (vhash-assoc (make-variable-cache-cell key)
constants) cdr)
(error "module vcache not in objtable" key))))
(emit-code (if (< i 256)
`((,(case op
((ref) 'toplevel-ref)
((set) 'toplevel-set))
,i))
`((,(case op
((ref) 'long-toplevel-ref)
((set) 'long-toplevel-set))
,(quotient i 256)
,(modulo i 256)))))))
(else
(error "unknown module var kind" op key)))))
((<glil-label> label)
(let ((code (align-block addr)))
(values code
bindings
source-alist
(acons label (addr+ addr code) label-alist)
arities)))
((<glil-branch> inst label)
(emit-code `((,inst ,label))))
;; nargs is number of stack args to insn. probably should rename.
((<glil-call> inst nargs)
(if (not (instruction? inst))
(error "Unknown instruction:" inst))
(let ((pops (instruction-pops inst)))
(cond ((< pops 0)
(case (instruction-length inst)
((1) (emit-code `((,inst ,nargs))))
((2) (emit-code `((,inst ,(quotient nargs 256)
,(modulo nargs 256)))))
(else (error "Unknown length for variable-arg instruction:"
inst (instruction-length inst)))))
((= pops nargs)
(emit-code `((,inst))))
(else
(error "Wrong number of stack arguments to instruction:" inst nargs)))))
((<glil-mv-call> nargs ra)
(emit-code `((mv-call ,nargs ,ra))))
((<glil-prompt> label escape-only?)
(emit-code `((prompt ,(if escape-only? 1 0) ,label))))))
(define (dump-object x addr)
(define (too-long x)
(error (string-append x " too long")))
(cond
((object->assembly x) => list)
((variable-cache-cell? x) (dump-object (variable-cache-cell-key x) addr))
((number? x)
`((load-number ,(number->string x))))
((string? x)
(case (string-bytes-per-char x)
((1) `((load-string ,x)))
((4) (align-code `(load-wide-string ,x) addr 4 4))
(else (error "bad string bytes per char" x))))
((symbol? x)
(let ((str (symbol->string x)))
(case (string-bytes-per-char str)
((1) `((load-symbol ,str)))
((4) `(,@(dump-object str addr)
(make-symbol)))
(else (error "bad string bytes per char" str)))))
((keyword? x)
`(,@(dump-object (keyword->symbol x) addr)
(make-keyword)))
((scheme-list? x)
(let ((tail (let ((len (length x)))
(if (>= len 65536) (too-long "list"))
`((list ,(quotient len 256) ,(modulo len 256))))))
(let dump-objects ((objects x) (codes '()) (addr addr))
(if (null? objects)
(fold append tail codes)
(let ((code (dump-object (car objects) addr)))
(dump-objects (cdr objects) (cons code codes)
(addr+ addr code)))))))
((pair? x)
(let ((kar (dump-object (car x) addr)))
`(,@kar
,@(dump-object (cdr x) (addr+ addr kar))
(cons))))
((and (vector? x)
(equal? (array-shape x) (list (list 0 (1- (vector-length x))))))
(let* ((len (vector-length x))
(tail (if (>= len 65536)
(too-long "vector")
`((vector ,(quotient len 256) ,(modulo len 256))))))
(let dump-objects ((i 0) (codes '()) (addr addr))
(if (>= i len)
(fold append tail codes)
(let ((code (dump-object (vector-ref x i) addr)))
(dump-objects (1+ i) (cons code codes)
(addr+ addr code)))))))
((and (array? x) (symbol? (array-type x)))
(let* ((type (dump-object (array-type x) addr))
(shape (dump-object (array-shape x) (addr+ addr type))))
`(,@type
,@shape
,@(align-code
`(load-array ,(uniform-array->bytevector x))
(addr+ (addr+ addr type) shape)
8
4))))
((array? x)
;; an array of generic scheme values
(let* ((contents (array-contents x))
(len (vector-length contents)))
(let dump-objects ((i 0) (codes '()) (addr addr))
(if (< i len)
(let ((code (dump-object (vector-ref contents i) addr)))
(dump-objects (1+ i) (cons code codes)
(addr+ addr code)))
(fold append
`(,@(dump-object (array-shape x) addr)
(make-array ,(quotient (ash len -16) 256)
,(logand #xff (ash len -8))
,(logand #xff len)))
codes)))))
(else
(error "dump-object: unrecognized object" x))))
(define (dump-constants constants)
(define (ref-or-dump x i addr)
(let ((pair (vhash-assoc x constants)))
(if (and pair (< (cdr pair) i))
(let ((idx (cdr pair)))
(if (< idx 256)
(values `((object-ref ,idx))
(+ addr 2))
(values `((long-object-ref ,(quotient idx 256)
,(modulo idx 256)))
(+ addr 3))))
(dump1 x i addr))))
(define (dump1 x i addr)
(cond
((object->assembly x)
=> (lambda (code)
(values (list code)
(+ (byte-length code) addr))))
((or (number? x)
(string? x)
(symbol? x)
(keyword? x))
;; Atoms.
(let ((code (dump-object x addr)))
(values code (addr+ addr code))))
((variable-cache-cell? x)
(dump1 (variable-cache-cell-key x) i addr))
((scheme-list? x)
(receive (codes addr)
(fold2 (lambda (x codes addr)
(receive (subcode addr) (ref-or-dump x i addr)
(values (cons subcode codes) addr)))
x '() addr)
(values (fold append
(let ((len (length x)))
`((list ,(quotient len 256) ,(modulo len 256))))
codes)
(+ addr 3))))
((pair? x)
(receive (car-code addr) (ref-or-dump (car x) i addr)
(receive (cdr-code addr) (ref-or-dump (cdr x) i addr)
(values `(,@car-code ,@cdr-code (cons))
(1+ addr)))))
((and (vector? x)
(<= (vector-length x) #xffff)
(equal? (array-shape x) (list (list 0 (1- (vector-length x))))))
(receive (codes addr)
(vector-fold2 (lambda (x codes addr)
(receive (subcode addr) (ref-or-dump x i addr)
(values (cons subcode codes) addr)))
x '() addr)
(values (fold append
(let ((len (vector-length x)))
`((vector ,(quotient len 256) ,(modulo len 256))))
codes)
(+ addr 3))))
((and (array? x) (symbol? (array-type x)))
(receive (type addr) (ref-or-dump (array-type x) i addr)
(receive (shape addr) (ref-or-dump (array-shape x) i addr)
(let ((bv (align-code `(load-array ,(uniform-array->bytevector x))
addr 8 4)))
(values `(,@type ,@shape ,@bv)
(addr+ addr bv))))))
((array? x)
(let ((contents (array-contents x)))
(receive (codes addr)
(vector-fold2 (lambda (x codes addr)
(receive (subcode addr) (ref-or-dump x i addr)
(values (cons subcode codes) addr)))
contents '() addr)
(receive (shape addr) (ref-or-dump (array-shape x) i addr)
(values (fold append
(let ((len (vector-length contents)))
`(,@shape
(make-array ,(quotient (ash len -16) 256)
,(logand #xff (ash len -8))
,(logand #xff len))))
codes)
(+ addr 4))))))
(else
(error "write-table: unrecognized object" x))))
(receive (codes addr)
(vhash-fold-right2 (lambda (obj idx code addr)
;; The vector is on the stack. Dup it, push
;; the index, push the val, then vector-set.
(let ((pre `((dup)
,(object->assembly idx))))
(receive (valcode addr) (dump1 obj idx
(addr+ addr pre))
(values (cons* '((vector-set))
valcode
pre
code)
(1+ addr)))))
constants
'(((assert-nargs-ee/locals 1)
;; Push the vector.
(local-ref 0)))
4)
(let* ((len (1+ (vlist-length constants)))
(pre-prog-addr (+ 2 ; reserve-locals
len 3 ; empty vector
2 ; local-set
1 ; new-frame
2 ; local-ref
))
(prog (align-program
`(load-program ()
,(+ addr 1)
#f
;; The `return' will be at the tail of the
;; program. The vector is already pushed
;; on the stack.
. ,(fold append '((return)) codes))
pre-prog-addr)))
(values `(;; Reserve storage for the vector.
(assert-nargs-ee/locals ,(logior 0 (ash 1 3)))
;; Push the vector, and store it in slot 0.
,@(make-list len '(make-false))
(vector ,(quotient len 256) ,(modulo len 256))
(local-set 0)
;; Now we open the call frame.
;;
(new-frame)
;; Now build a thunk to init the constants. It will
;; have the unfinished constant table both as its
;; argument and as its objtable. The former allows it
;; to update the objtable, with vector-set!, and the
;; latter allows init code to refer to previously set
;; values.
;;
;; Grab the vector, to be the objtable.
(local-ref 0)
;; Now the load-program, properly aligned. Pops the vector.
,@prog
;; Grab the vector, as an argument this time.
(local-ref 0)
;; Call the init thunk with the vector as an arg.
(call 1)
;; The thunk also returns the vector. Leave it on the
;; stack for compile-assembly to use.
)
;; The byte length of the init code, which we can
;; determine without folding over the code again.
(+ (addr+ pre-prog-addr prog) ; aligned program
2 ; local-ref
2 ; call
)))))
;;; Guile Lowlevel Intermediate Language
;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language glil spec)
#\use-module (system base language)
#\use-module (language glil)
#\use-module (language glil compile-assembly)
#\export (glil))
(define (write-glil exp . port)
(apply write (unparse-glil exp) port))
(define (compile-asm x e opts)
(values (compile-assembly x) e e))
(define-language glil
#\title "Guile Lowlevel Intermediate Language (GLIL)"
#\reader (lambda (port env) (read port))
#\printer write-glil
#\parser parse-glil
#\compilers `((assembly . ,compile-asm))
#\for-humans? #f
)
;;; Guile Virtual Machine Object Code
;; Copyright (C) 2001 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language objcode)
#\export (encode-length decode-length))
;;;
;;; Variable-length interface
;;;
;; NOTE: decoded in vm_fetch_length in vm.c as well.
(define (encode-length len)
(cond ((< len 254) (u8vector len))
((< len (* 256 256))
(u8vector 254 (quotient len 256) (modulo len 256)))
((< len most-positive-fixnum)
(u8vector 255
(quotient len (* 256 256 256))
(modulo (quotient len (* 256 256)) 256)
(modulo (quotient len 256) 256)
(modulo len 256)))
(else (error "Too long code length:" len))))
(define (decode-length pop)
(let ((x (pop)))
(cond ((< x 254) x)
((= x 254) (+ (ash x 8) (pop)))
(else
(let* ((b2 (pop))
(b3 (pop))
(b4 (pop)))
(+ (ash x 24) (ash b2 16) (ash b3 8) b4))))))
;;; Guile Lowlevel Intermediate Language
;; Copyright (C) 2001, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language objcode spec)
#\use-module (system base language)
#\use-module (system vm objcode)
#\use-module (system vm program)
#\export (objcode))
(define (objcode->value x e opts)
(let ((thunk (make-program x #f #f)))
(if (eq? e (current-module))
;; save a cons in this case
(values (thunk) e e)
(save-module-excursion
(lambda ()
(set-current-module e)
(values (thunk) e e))))))
;; since locals are allocated on the stack and can have limited scope,
;; in many cases we use one local for more than one lexical variable. so
;; the returned locals set is a list, where element N of the list is
;; itself a list of bindings for local variable N.
(define (collapse-locals locs)
(let lp ((ret '()) (locs locs))
(if (null? locs)
(map cdr (sort! ret
(lambda (x y) (< (car x) (car y)))))
(let ((b (car locs)))
(cond
((assv-ref ret (binding:index b))
=> (lambda (bindings)
(append! bindings (list b))
(lp ret (cdr locs))))
(else
(lp (acons (binding:index b) (list b) ret)
(cdr locs))))))))
(define (decompile-value x env opts)
(cond
((program? x)
(let ((objs (program-objects x))
(meta (program-meta x))
(free-vars (program-free-variables x))
(binds (program-bindings x))
(srcs (program-sources x)))
(let ((blocs (and binds (collapse-locals binds))))
(values (program-objcode x)
`((objects . ,objs)
(meta . ,(and meta (meta)))
(free-vars . ,free-vars)
(blocs . ,blocs)
(sources . ,srcs))))))
((objcode? x)
(values x #f))
(else
(error "Object for disassembly not a program or objcode" x))))
(define-language objcode
#\title "Guile Object Code"
#\reader #f
#\printer write-objcode
#\compilers `((value . ,objcode->value))
#\decompilers `((value . ,decompile-value))
#\for-humans? #f
)
;;; Guile Scheme specification
;; Copyright (C) 2001, 2009, 2010 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language scheme compile-tree-il)
#\use-module (language tree-il)
#\export (compile-tree-il))
;;; environment := MODULE
(define (compile-tree-il x e opts)
(save-module-excursion
(lambda ()
(set-current-module e)
(let* ((x (macroexpand x 'c '(compile load eval)))
(cenv (current-module)))
(values x cenv cenv)))))
;;; Guile VM code converters
;; Copyright (C) 2001, 2009, 2012, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language scheme decompile-tree-il)
#\use-module (language tree-il)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-26)
#\use-module (ice-9 receive)
#\use-module (ice-9 vlist)
#\use-module (ice-9 match)
#\use-module (system base syntax)
#\export (decompile-tree-il))
(define (decompile-tree-il e env opts)
(apply do-decompile e env opts))
(define* (do-decompile e env
#\key
(use-derived-syntax? #t)
(avoid-lambda? #t)
(use-case? #t)
(strip-numeric-suffixes? #f)
#\allow-other-keys)
(receive (output-name-table occurrence-count-table)
(choose-output-names e use-derived-syntax? strip-numeric-suffixes?)
(define (output-name s) (hashq-ref output-name-table s))
(define (occurrence-count s) (hashq-ref occurrence-count-table s))
(define (const x) (lambda (_) x))
(define (atom? x) (not (or (pair? x) (vector? x))))
(define (build-void) '(if #f #f))
(define (build-begin es)
(match es
(() (build-void))
((e) e)
(_ `(begin ,@es))))
(define (build-lambda-body e)
(match e
(('let () body ...) body)
(('begin es ...) es)
(_ (list e))))
(define (build-begin-body e)
(match e
(('begin es ...) es)
(_ (list e))))
(define (build-define name e)
(match e
((? (const avoid-lambda?)
('lambda formals body ...))
`(define (,name ,@formals) ,@body))
((? (const avoid-lambda?)
('lambda* formals body ...))
`(define* (,name ,@formals) ,@body))
(_ `(define ,name ,e))))
(define (build-let names vals body)
(match `(let ,(map list names vals)
,@(build-lambda-body body))
((_ () e) e)
((_ (b) ('let* (bs ...) body ...))
`(let* (,b ,@bs) ,@body))
((? (const use-derived-syntax?)
(_ (b1) ('let (b2) body ...)))
`(let* (,b1 ,b2) ,@body))
(e e)))
(define (build-letrec in-order? names vals body)
(match `(,(if in-order? 'letrec* 'letrec)
,(map list names vals)
,@(build-lambda-body body))
((_ () e) e)
((_ () body ...) `(let () ,@body))
((_ ((name ('lambda (formals ...) body ...)))
(name args ...))
(=> failure)
(if (= (length formals) (length args))
`(let ,name ,(map list formals args) ,@body)
(failure)))
((? (const avoid-lambda?)
('letrec* _ body ...))
`(let ()
,@(map build-define names vals)
,@body))
(e e)))
(define (build-if test consequent alternate)
(match alternate
(('if #f _) `(if ,test ,consequent))
(_ `(if ,test ,consequent ,alternate))))
(define (build-and xs)
(match xs
(() #t)
((x) x)
(_ `(and ,@xs))))
(define (build-or xs)
(match xs
(() #f)
((x) x)
(_ `(or ,@xs))))
(define (case-test-var test)
(match test
(('memv (? atom? v) ('quote (datums ...)))
v)
(('eqv? (? atom? v) ('quote datum))
v)
(_ #f)))
(define (test->datums v test)
(match (cons v test)
((v 'memv v ('quote (xs ...)))
xs)
((v 'eqv? v ('quote x))
(list x))
(_ #f)))
(define (build-else-tail e)
(match e
(('if #f _) '())
(('and xs ... x) `((,(build-and xs) ,@(build-begin-body x))
(else #f)))
(_ `((else ,@(build-begin-body e))))))
(define (build-cond-else-tail e)
(match e
(('cond clauses ...) clauses)
(_ (build-else-tail e))))
(define (build-case-else-tail v e)
(match (cons v e)
((v 'case v clauses ...)
clauses)
((v 'if ('memv v ('quote (xs ...))) consequent . alternate*)
`((,xs ,@(build-begin-body consequent))
,@(build-case-else-tail v (build-begin alternate*))))
((v 'if ('eqv? v ('quote x)) consequent . alternate*)
`(((,x) ,@(build-begin-body consequent))
,@(build-case-else-tail v (build-begin alternate*))))
(_ (build-else-tail e))))
(define (clauses+tail clauses)
(match clauses
((cs ... (and c ('else . _))) (values cs (list c)))
(_ (values clauses '()))))
(define (build-cond tests consequents alternate)
(case (length tests)
((0) alternate)
((1) (build-if (car tests) (car consequents) alternate))
(else `(cond ,@(map (lambda (test consequent)
`(,test ,@(build-begin-body consequent)))
tests consequents)
,@(build-cond-else-tail alternate)))))
(define (build-cond-or-case tests consequents alternate)
(if (not use-case?)
(build-cond tests consequents alternate)
(let* ((v (and (not (null? tests))
(case-test-var (car tests))))
(datum-lists (take-while identity
(map (cut test->datums v <>)
tests)))
(n (length datum-lists))
(tail (build-case-else-tail v (build-cond
(drop tests n)
(drop consequents n)
alternate))))
(receive (clauses tail) (clauses+tail tail)
(let ((n (+ n (length clauses)))
(datum-lists (append datum-lists
(map car clauses)))
(consequents (append consequents
(map build-begin
(map cdr clauses)))))
(if (< n 2)
(build-cond tests consequents alternate)
`(case ,v
,@(map cons datum-lists (map build-begin-body
(take consequents n)))
,@tail)))))))
(define (recurse e)
(define (recurse-body e)
(build-lambda-body (recurse e)))
(record-case e
((<void>)
(build-void))
((<const> exp)
(if (and (self-evaluating? exp) (not (vector? exp)))
exp
`(quote ,exp)))
((<sequence> exps)
(build-begin (map recurse exps)))
((<application> proc args)
(match `(,(recurse proc) ,@(map recurse args))
((('lambda (formals ...) body ...) args ...)
(=> failure)
(if (= (length formals) (length args))
(build-let formals args (build-begin body))
(failure)))
(e e)))
((<primitive-ref> name)
name)
((<lexical-ref> gensym)
(output-name gensym))
((<lexical-set> gensym exp)
`(set! ,(output-name gensym) ,(recurse exp)))
((<module-ref> mod name public?)
`(,(if public? '@ '@@) ,mod ,name))
((<module-set> mod name public? exp)
`(set! (,(if public? '@ '@@) ,mod ,name) ,(recurse exp)))
((<toplevel-ref> name)
name)
((<toplevel-set> name exp)
`(set! ,name ,(recurse exp)))
((<toplevel-define> name exp)
(build-define name (recurse exp)))
((<lambda> meta body)
(if body
(let ((body (recurse body))
(doc (assq-ref meta 'documentation)))
(if (not doc)
body
(match body
(('lambda formals body ...)
`(lambda ,formals ,doc ,@body))
(('lambda* formals body ...)
`(lambda* ,formals ,doc ,@body))
(('case-lambda (formals body ...) clauses ...)
`(case-lambda (,formals ,doc ,@body) ,@clauses))
(('case-lambda* (formals body ...) clauses ...)
`(case-lambda* (,formals ,doc ,@body) ,@clauses))
(e e))))
'(case-lambda)))
((<lambda-case> req opt rest kw inits gensyms body alternate)
(let ((names (map output-name gensyms)))
(cond
((and (not opt) (not kw) (not alternate))
`(lambda ,(if rest (apply cons* names) names)
,@(recurse-body body)))
((and (not opt) (not kw))
(let ((alt-expansion (recurse alternate))
(formals (if rest (apply cons* names) names)))
(case (car alt-expansion)
((lambda)
`(case-lambda (,formals ,@(recurse-body body))
,(cdr alt-expansion)))
((lambda*)
`(case-lambda* (,formals ,@(recurse-body body))
,(cdr alt-expansion)))
((case-lambda)
`(case-lambda (,formals ,@(recurse-body body))
,@(cdr alt-expansion)))
((case-lambda*)
`(case-lambda* (,formals ,@(recurse-body body))
,@(cdr alt-expansion))))))
(else
(let* ((alt-expansion (and alternate (recurse alternate)))
(nreq (length req))
(nopt (if opt (length opt) 0))
(restargs (if rest (list-ref names (+ nreq nopt)) '()))
(reqargs (list-head names nreq))
(optargs (if opt
`(#\optional
,@(map list
(list-head (list-tail names nreq) nopt)
(map recurse
(list-head inits nopt))))
'()))
(kwargs (if kw
`(#\key
,@(map list
(map output-name (map caddr (cdr kw)))
(map recurse
(list-tail inits nopt))
(map car (cdr kw)))
,@(if (car kw)
'(#\allow-other-keys)
'()))
'()))
(formals `(,@reqargs ,@optargs ,@kwargs . ,restargs)))
(if (not alt-expansion)
`(lambda* ,formals ,@(recurse-body body))
(case (car alt-expansion)
((lambda lambda*)
`(case-lambda* (,formals ,@(recurse-body body))
,(cdr alt-expansion)))
((case-lambda case-lambda*)
`(case-lambda* (,formals ,@(recurse-body body))
,@(cdr alt-expansion))))))))))
((<conditional> test consequent alternate)
(define (simplify-test e)
(match e
(('if ('eqv? (? atom? v) ('quote a)) #t ('eqv? v ('quote b)))
`(memv ,v '(,a ,b)))
(('if ('eqv? (? atom? v) ('quote a)) #t ('memv v ('quote (bs ...))))
`(memv ,v '(,a ,@bs)))
(('case (? atom? v)
((datum) #t) ...
('else ('eqv? v ('quote last-datum))))
`(memv ,v '(,@datum ,last-datum)))
(_ e)))
(match `(if ,(simplify-test (recurse test))
,(recurse consequent)
,@(if (void? alternate) '()
(list (recurse alternate))))
(('if test ('if ('and xs ...) consequent))
(build-if (build-and (cons test xs))
consequent
(build-void)))
((? (const use-derived-syntax?)
('if test1 ('if test2 consequent)))
(build-if (build-and (list test1 test2))
consequent
(build-void)))
(('if (? atom? x) x ('or ys ...))
(build-or (cons x ys)))
((? (const use-derived-syntax?)
('if (? atom? x) x y))
(build-or (list x y)))
(('if test consequent)
`(if ,test ,consequent))
(('if test ('and xs ...) #f)
(build-and (cons test xs)))
((? (const use-derived-syntax?)
('if test consequent #f))
(build-and (list test consequent)))
((? (const use-derived-syntax?)
('if test1 consequent1
('if test2 consequent2 . alternate*)))
(build-cond-or-case (list test1 test2)
(list consequent1 consequent2)
(build-begin alternate*)))
(('if test consequent ('cond clauses ...))
`(cond (,test ,@(build-begin-body consequent))
,@clauses))
(('if ('memv (? atom? v) ('quote (xs ...))) consequent
('case v clauses ...))
`(case ,v (,xs ,@(build-begin-body consequent))
,@clauses))
(('if ('eqv? (? atom? v) ('quote x)) consequent
('case v clauses ...))
`(case ,v ((,x) ,@(build-begin-body consequent))
,@clauses))
(e e)))
((<let> gensyms vals body)
(match (build-let (map output-name gensyms)
(map recurse vals)
(recurse body))
(('let ((v e)) ('or v xs ...))
(=> failure)
(if (and (not (null? gensyms))
(= 3 (occurrence-count (car gensyms))))
`(or ,e ,@xs)
(failure)))
(('let ((v e)) ('case v clauses ...))
(=> failure)
(if (and (not (null? gensyms))
;; FIXME: This fails if any of the 'memv's were
;; optimized into multiple 'eqv?'s, because the
;; occurrence count will be higher than we expect.
(= (occurrence-count (car gensyms))
(1+ (length (clauses+tail clauses)))))
`(case ,e ,@clauses)
(failure)))
(e e)))
((<letrec> in-order? gensyms vals body)
(build-letrec in-order?
(map output-name gensyms)
(map recurse vals)
(recurse body)))
((<fix> gensyms vals body)
;; not a typo, we really do translate back to letrec. use letrec* since it
;; doesn't matter, and the naive letrec* transformation does not require an
;; inner let.
(build-letrec #t
(map output-name gensyms)
(map recurse vals)
(recurse body)))
((<let-values> exp body)
`(call-with-values (lambda () ,@(recurse-body exp))
,(recurse (make-lambda #f '() body))))
((<dynwind> body winder unwinder)
`(dynamic-wind ,(recurse winder)
(lambda () ,@(recurse-body body))
,(recurse unwinder)))
((<dynlet> fluids vals body)
`(with-fluids ,(map list
(map recurse fluids)
(map recurse vals))
,@(recurse-body body)))
((<dynref> fluid)
`(fluid-ref ,(recurse fluid)))
((<dynset> fluid exp)
`(fluid-set! ,(recurse fluid) ,(recurse exp)))
((<prompt> tag body handler)
`(call-with-prompt
,(recurse tag)
(lambda () ,@(recurse-body body))
,(recurse handler)))
((<abort> tag args tail)
`(apply abort ,(recurse tag) ,@(map recurse args)
,(recurse tail)))))
(values (recurse e) env)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Algorithm for choosing better variable names
;; ============================================
;;
;; First we perform an analysis pass, collecting the following
;; information:
;;
;; * For each gensym: how many occurrences will occur in the output?
;;
;; * For each gensym A: which gensyms does A conflict with? Gensym A
;; and gensym B conflict if they have the same base name (usually the
;; same as the source name, but see below), and if giving them the
;; same name would cause a bad variable reference due to unintentional
;; variable capture.
;;
;; The occurrence counter is indexed by gensym and is global (within each
;; invocation of the algorithm), implemented using a hash table. We also
;; keep a global mapping from gensym to source name as provided by the
;; binding construct (we prefer not to trust the source names in the
;; lexical ref or set).
;;
;; As we recurse down into lexical binding forms, we keep track of a
;; mapping from base name to an ordered list of bindings, innermost
;; first. When we encounter a variable occurrence, we increment the
;; counter, look up the base name (preferring not to trust the 'name' in
;; the lexical ref or set), and then look up the bindings currently in
;; effect for that base name. Hopefully our gensym will be the first
;; (innermost) binding. If not, we register a conflict between the
;; referenced gensym and the other bound gensyms with the same base name
;; that shadow the binding we want. These are simply the gensyms on the
;; binding list that come before our gensym.
;;
;; Top-level bindings are treated specially. Whenever top-level
;; references are found, they conflict with every lexical binding
;; currently in effect with the same base name. They are guaranteed to
;; be assigned to their source names. For purposes of recording
;; conflicts (which are normally keyed on gensyms) top-level identifiers
;; are assigned a pseudo-gensym that is an interned pair of the form
;; (top-level . <name>). This allows them to be compared using 'eq?'
;; like other gensyms.
;;
;; The base name is normally just the source name. However, if the
;; source name has a suffix of the form "-N" (where N is a positive
;; integer without leading zeroes), then we strip that suffix (multiple
;; times if necessary) to form the base name. We must do this because
;; we add suffixes of that form in order to resolve conflicts, and we
;; must ensure that only identifiers with the same base name can
;; possibly conflict with each other.
;;
;; XXX FIXME: Currently, primitives are treated exactly like top-level
;; bindings. This handles conflicting lexical bindings properly, but
;; does _not_ handle the case where top-level bindings conflict with the
;; needed primitives.
;;
;; Also note that this requires that 'choose-output-names' be kept in
;; sync with 'tree-il->scheme'. Primitives that are introduced by
;; 'tree-il->scheme' must be anticipated by 'choose-output-name'.
;;
;; We also ensure that lexically-bound identifiers found in operator
;; position will never be assigned one of the standard primitive names.
;; This is needed because 'tree-il->scheme' recognizes primitive names
;; in operator position and assumes that they have the standard
;; bindings.
;;
;;
;; How we assign an output name to each gensym
;; ===========================================
;;
;; We process the gensyms in order of decreasing occurrence count, with
;; each gensym choosing the best output name possible, as long as it
;; isn't the same name as any of the previously-chosen output names of
;; conflicting gensyms.
;;
;;
;; 'choose-output-names' analyzes the top-level form e, chooses good
;; variable names that are as close as possible to the source names,
;; and returns two values:
;;
;; * a hash table mapping gensym to output name
;; * a hash table mapping gensym to number of occurrences
;;
(define choose-output-names
(let ()
(define primitive?
;; This is a list of primitives that 'tree-il->scheme' assumes
;; will have the standard bindings when found in operator
;; position.
(let* ((primitives '(if quote @ @@ set! define define*
begin let let* letrec letrec*
and or cond case
lambda lambda* case-lambda case-lambda*
apply call-with-values dynamic-wind
with-fluids fluid-ref fluid-set!
call-with-prompt abort memv eqv?))
(table (make-hash-table (length primitives))))
(for-each (cut hashq-set! table <> #t) primitives)
(lambda (name) (hashq-ref table name))))
;; Repeatedly strip suffix of the form "-N", where N is a string
;; that could be produced by number->string given a positive
;; integer. In other words, the first digit of N may not be 0.
(define compute-base-name
(let ((digits (string->char-set "0123456789")))
(define (base-name-string str)
(let ((i (string-skip-right str digits)))
(if (and i (< (1+ i) (string-length str))
(eq? #\- (string-ref str i))
(not (eq? #\0 (string-ref str (1+ i)))))
(base-name-string (substring str 0 i))
str)))
(lambda (sym)
(string->symbol (base-name-string (symbol->string sym))))))
;; choose-output-names
(lambda (e use-derived-syntax? strip-numeric-suffixes?)
(define lexical-gensyms '())
(define top-level-intern!
(let ((table (make-hash-table)))
(lambda (name)
(let ((h (hashq-create-handle! table name #f)))
(or (cdr h) (begin (set-cdr! h (cons 'top-level name))
(cdr h)))))))
(define (top-level? s) (pair? s))
(define (top-level-name s) (cdr s))
(define occurrence-count-table (make-hash-table))
(define (occurrence-count s) (or (hashq-ref occurrence-count-table s) 0))
(define (increment-occurrence-count! s)
(let ((h (hashq-create-handle! occurrence-count-table s 0)))
(if (zero? (cdr h))
(set! lexical-gensyms (cons s lexical-gensyms)))
(set-cdr! h (1+ (cdr h)))))
(define base-name
(let ((table (make-hash-table)))
(lambda (name)
(let ((h (hashq-create-handle! table name #f)))
(or (cdr h) (begin (set-cdr! h (compute-base-name name))
(cdr h)))))))
(define source-name-table (make-hash-table))
(define (set-source-name! s name)
(if (not (top-level? s))
(let ((name (if strip-numeric-suffixes?
(base-name name)
name)))
(hashq-set! source-name-table s name))))
(define (source-name s)
(if (top-level? s)
(top-level-name s)
(hashq-ref source-name-table s)))
(define conflict-table (make-hash-table))
(define (conflicts s) (or (hashq-ref conflict-table s) '()))
(define (add-conflict! a b)
(define (add! a b)
(if (not (top-level? a))
(let ((h (hashq-create-handle! conflict-table a '())))
(if (not (memq b (cdr h)))
(set-cdr! h (cons b (cdr h)))))))
(add! a b)
(add! b a))
(let recurse-with-bindings ((e e) (bindings vlist-null))
(let recurse ((e e))
;; We call this whenever we encounter a top-level ref or set
(define (top-level name)
(let ((bname (base-name name)))
(let ((s (top-level-intern! name))
(conflicts (vhash-foldq* cons '() bname bindings)))
(for-each (cut add-conflict! s <>) conflicts))))
;; We call this whenever we encounter a primitive reference.
;; We must also call it for every primitive that might be
;; inserted by 'tree-il->scheme'. It is okay to call this
;; even when 'tree-il->scheme' will not insert the named
;; primitive; the worst that will happen is for a lexical
;; variable of the same name to be renamed unnecessarily.
(define (primitive name) (top-level name))
;; We call this whenever we encounter a lexical ref or set.
(define (lexical s)
(increment-occurrence-count! s)
(let ((conflicts
(take-while
(lambda (s*) (not (eq? s s*)))
(reverse! (vhash-foldq* cons
'()
(base-name (source-name s))
bindings)))))
(for-each (cut add-conflict! s <>) conflicts)))
(record-case e
((<void>) (primitive 'if)) ; (if #f #f)
((<const>) (primitive 'quote))
((<application> proc args)
(if (lexical-ref? proc)
(let* ((gensym (lexical-ref-gensym proc))
(name (source-name gensym)))
;; If the operator position contains a bare variable
;; reference with the same source name as a standard
;; primitive, we must ensure that it will be given a
;; different name, so that 'tree-il->scheme' will not
;; misinterpret the resulting expression.
(if (primitive? name)
(add-conflict! gensym (top-level-intern! name)))))
(recurse proc)
(for-each recurse args))
((<primitive-ref> name) (primitive name))
((<lexical-ref> gensym) (lexical gensym))
((<lexical-set> gensym exp)
(primitive 'set!) (lexical gensym) (recurse exp))
((<module-ref> public?) (primitive (if public? '@ '@@)))
((<module-set> public? exp)
(primitive 'set!) (primitive (if public? '@ '@@)) (recurse exp))
((<toplevel-ref> name) (top-level name))
((<toplevel-set> name exp)
(primitive 'set!) (top-level name) (recurse exp))
((<toplevel-define> name exp) (top-level name) (recurse exp))
((<conditional> test consequent alternate)
(cond (use-derived-syntax?
(primitive 'and) (primitive 'or)
(primitive 'cond) (primitive 'case)
(primitive 'else) (primitive '=>)))
(primitive 'if)
(recurse test) (recurse consequent) (recurse alternate))
((<sequence> exps) (primitive 'begin) (for-each recurse exps))
((<lambda> body)
(if body (recurse body) (primitive 'case-lambda)))
((<lambda-case> req opt rest kw inits gensyms body alternate)
(primitive 'lambda)
(cond ((or opt kw alternate)
(primitive 'lambda*)
(primitive 'case-lambda)
(primitive 'case-lambda*)))
(primitive 'let)
(if use-derived-syntax? (primitive 'let*))
(let* ((names (append req (or opt '()) (if rest (list rest) '())
(map cadr (if kw (cdr kw) '()))))
(base-names (map base-name names))
(body-bindings
(fold vhash-consq bindings base-names gensyms)))
(for-each increment-occurrence-count! gensyms)
(for-each set-source-name! gensyms names)
(for-each recurse inits)
(recurse-with-bindings body body-bindings)
(if alternate (recurse alternate))))
((<let> names gensyms vals body)
(primitive 'let)
(cond (use-derived-syntax? (primitive 'let*) (primitive 'or)))
(for-each increment-occurrence-count! gensyms)
(for-each set-source-name! gensyms names)
(for-each recurse vals)
(recurse-with-bindings
body (fold vhash-consq bindings (map base-name names) gensyms)))
((<letrec> in-order? names gensyms vals body)
(primitive 'let)
(cond (use-derived-syntax? (primitive 'let*) (primitive 'or)))
(primitive (if in-order? 'letrec* 'letrec))
(for-each increment-occurrence-count! gensyms)
(for-each set-source-name! gensyms names)
(let* ((base-names (map base-name names))
(bindings (fold vhash-consq bindings base-names gensyms)))
(for-each (cut recurse-with-bindings <> bindings) vals)
(recurse-with-bindings body bindings)))
((<fix> names gensyms vals body)
(primitive 'let)
(primitive 'letrec*)
(cond (use-derived-syntax? (primitive 'let*) (primitive 'or)))
(for-each increment-occurrence-count! gensyms)
(for-each set-source-name! gensyms names)
(let* ((base-names (map base-name names))
(bindings (fold vhash-consq bindings base-names gensyms)))
(for-each (cut recurse-with-bindings <> bindings) vals)
(recurse-with-bindings body bindings)))
((<let-values> exp body)
(primitive 'call-with-values)
(recurse exp) (recurse body))
((<dynwind> winder body unwinder)
(primitive 'dynamic-wind)
(recurse winder) (recurse body) (recurse unwinder))
((<dynlet> fluids vals body)
(primitive 'with-fluids)
(for-each recurse fluids)
(for-each recurse vals)
(recurse body))
((<dynref> fluid) (primitive 'fluid-ref) (recurse fluid))
((<dynset> fluid exp)
(primitive 'fluid-set!) (recurse fluid) (recurse exp))
((<prompt> tag body handler)
(primitive 'call-with-prompt)
(primitive 'lambda)
(recurse tag) (recurse body) (recurse handler))
((<abort> tag args tail)
(primitive 'apply)
(primitive 'abort)
(recurse tag) (for-each recurse args) (recurse tail)))))
(let ()
(define output-name-table (make-hash-table))
(define (set-output-name! s name)
(hashq-set! output-name-table s name))
(define (output-name s)
(if (top-level? s)
(top-level-name s)
(hashq-ref output-name-table s)))
(define sorted-lexical-gensyms
(sort-list lexical-gensyms
(lambda (a b) (> (occurrence-count a)
(occurrence-count b)))))
(for-each (lambda (s)
(set-output-name!
s
(let ((the-conflicts (conflicts s))
(the-source-name (source-name s)))
(define (not-yet-taken? name)
(not (any (lambda (s*)
(and=> (output-name s*)
(cut eq? name <>)))
the-conflicts)))
(if (not-yet-taken? the-source-name)
the-source-name
(let ((prefix (string-append
(symbol->string the-source-name)
"-")))
(let loop ((i 1) (name the-source-name))
(if (not-yet-taken? name)
name
(loop (+ i 1)
(string->symbol
(string-append
prefix
(number->string i)))))))))))
sorted-lexical-gensyms)
(values output-name-table occurrence-count-table)))))
;;; Guile Scheme specification
;; Copyright (C) 2001, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language scheme spec)
#\use-module (system base compile)
#\use-module (system base language)
#\use-module (language scheme compile-tree-il)
#\use-module (language scheme decompile-tree-il)
#\export (scheme))
;;;
;;; Language definition
;;;
(define-language scheme
#\title "Scheme"
#\reader (lambda (port env)
;; Use the binding of current-reader from the environment.
;; FIXME: Handle `read-options' as well?
((or (and=> (and=> (module-variable env 'current-reader)
variable-ref)
fluid-ref)
read)
port))
#\compilers `((tree-il . ,compile-tree-il))
#\decompilers `((tree-il . ,decompile-tree-il))
#\evaluator (lambda (x module) (primitive-eval x))
#\printer write
#\make-default-environment
(lambda ()
;; Ideally we'd duplicate the whole module hierarchy so that `set!',
;; `fluid-set!', etc. don't have any effect in the current environment.
(let ((m (make-fresh-user-module)))
;; Provide a separate `current-reader' fluid so that
;; compile-time changes to `current-reader' are
;; limited to the current compilation unit.
(module-define! m 'current-reader (make-fluid))
;; Default to `simple-format', as is the case until
;; (ice-9 format) is loaded. This allows
;; compile-time warnings to be emitted when using
;; unsupported options.
(module-set! m 'format simple-format)
m)))
;;;; Copyright (C) 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (language tree-il)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-11)
#\use-module (system base pmatch)
#\use-module (system base syntax)
#\export (tree-il-src
<void> void? make-void void-src
<const> const? make-const const-src const-exp
<primitive-ref> primitive-ref? make-primitive-ref primitive-ref-src primitive-ref-name
<lexical-ref> lexical-ref? make-lexical-ref lexical-ref-src lexical-ref-name lexical-ref-gensym
<lexical-set> lexical-set? make-lexical-set lexical-set-src lexical-set-name lexical-set-gensym lexical-set-exp
<module-ref> module-ref? make-module-ref module-ref-src module-ref-mod module-ref-name module-ref-public?
<module-set> module-set? make-module-set module-set-src module-set-mod module-set-name module-set-public? module-set-exp
<toplevel-ref> toplevel-ref? make-toplevel-ref toplevel-ref-src toplevel-ref-name
<toplevel-set> toplevel-set? make-toplevel-set toplevel-set-src toplevel-set-name toplevel-set-exp
<toplevel-define> toplevel-define? make-toplevel-define toplevel-define-src toplevel-define-name toplevel-define-exp
<conditional> conditional? make-conditional conditional-src conditional-test conditional-consequent conditional-alternate
<application> application? make-application application-src application-proc application-args
<sequence> sequence? make-sequence sequence-src sequence-exps
<lambda> lambda? make-lambda lambda-src lambda-meta lambda-body
<lambda-case> lambda-case? make-lambda-case lambda-case-src
lambda-case-req lambda-case-opt lambda-case-rest lambda-case-kw
lambda-case-inits lambda-case-gensyms
lambda-case-body lambda-case-alternate
<let> let? make-let let-src let-names let-gensyms let-vals let-body
<letrec> letrec? make-letrec letrec-src letrec-in-order? letrec-names letrec-gensyms letrec-vals letrec-body
<fix> fix? make-fix fix-src fix-names fix-gensyms fix-vals fix-body
<let-values> let-values? make-let-values let-values-src let-values-exp let-values-body
<dynwind> dynwind? make-dynwind dynwind-src dynwind-winder dynwind-body dynwind-unwinder
<dynlet> dynlet? make-dynlet dynlet-src dynlet-fluids dynlet-vals dynlet-body
<dynref> dynref? make-dynref dynref-src dynref-fluid
<dynset> dynset? make-dynset dynset-src dynset-fluid dynset-exp
<prompt> prompt? make-prompt prompt-src prompt-tag prompt-body prompt-handler
<abort> abort? make-abort abort-src abort-tag abort-args abort-tail
parse-tree-il
unparse-tree-il
tree-il->scheme
tree-il-fold
make-tree-il-folder
post-order!
pre-order!
tree-il=?
tree-il-hash))
(define (print-tree-il exp port)
(format port "#<tree-il ~S>" (unparse-tree-il exp)))
(define-syntax borrow-core-vtables
(lambda (x)
(syntax-case x ()
((_)
(let lp ((n 0) (out '()))
(if (< n (vector-length %expanded-vtables))
(lp (1+ n)
(let* ((vtable (vector-ref %expanded-vtables n))
(stem (struct-ref vtable (+ vtable-offset-user 0)))
(fields (struct-ref vtable (+ vtable-offset-user 2)))
(sfields (map
(lambda (f) (datum->syntax x f))
fields))
(type (datum->syntax x (symbol-append '< stem '>)))
(ctor (datum->syntax x (symbol-append 'make- stem)))
(pred (datum->syntax x (symbol-append stem '?))))
(let lp ((n 0) (fields fields)
(out (cons*
#`(define (#,ctor #,@sfields)
(make-struct #,type 0 #,@sfields))
#`(define (#,pred x)
(and (struct? x)
(eq? (struct-vtable x) #,type)))
#`(struct-set! #,type vtable-index-printer
print-tree-il)
#`(define #,type
(vector-ref %expanded-vtables #,n))
out)))
(if (null? fields)
out
(lp (1+ n)
(cdr fields)
(let ((acc (datum->syntax
x (symbol-append stem '- (car fields)))))
(cons #`(define #,acc
(make-procedure-with-setter
(lambda (x) (struct-ref x #,n))
(lambda (x v) (struct-set! x #,n v))))
out)))))))
#`(begin #,@(reverse out))))))))
(borrow-core-vtables)
;; (<void>)
;; (<const> exp)
;; (<primitive-ref> name)
;; (<lexical-ref> name gensym)
;; (<lexical-set> name gensym exp)
;; (<module-ref> mod name public?)
;; (<module-set> mod name public? exp)
;; (<toplevel-ref> name)
;; (<toplevel-set> name exp)
;; (<toplevel-define> name exp)
;; (<conditional> test consequent alternate)
;; (<application> proc args)
;; (<sequence> exps)
;; (<lambda> meta body)
;; (<lambda-case> req opt rest kw inits gensyms body alternate)
;; (<let> names gensyms vals body)
;; (<letrec> in-order? names gensyms vals body)
;; (<dynlet> fluids vals body)
(define-type (<tree-il> #\common-slots (src) #\printer print-tree-il)
(<fix> names gensyms vals body)
(<let-values> exp body)
(<dynwind> winder body unwinder)
(<dynref> fluid)
(<dynset> fluid exp)
(<prompt> tag body handler)
(<abort> tag args tail))
(define (location x)
(and (pair? x)
(let ((props (source-properties x)))
(and (pair? props) props))))
(define (parse-tree-il exp)
(let ((loc (location exp))
(retrans (lambda (x) (parse-tree-il x))))
(pmatch exp
((void)
(make-void loc))
((apply ,proc . ,args)
(make-application loc (retrans proc) (map retrans args)))
((if ,test ,consequent ,alternate)
(make-conditional loc (retrans test) (retrans consequent) (retrans alternate)))
((primitive ,name) (guard (symbol? name))
(make-primitive-ref loc name))
((lexical ,name) (guard (symbol? name))
(make-lexical-ref loc name name))
((lexical ,name ,sym) (guard (symbol? name) (symbol? sym))
(make-lexical-ref loc name sym))
((set! (lexical ,name) ,exp) (guard (symbol? name))
(make-lexical-set loc name name (retrans exp)))
((set! (lexical ,name ,sym) ,exp) (guard (symbol? name) (symbol? sym))
(make-lexical-set loc name sym (retrans exp)))
((@ ,mod ,name) (guard (and-map symbol? mod) (symbol? name))
(make-module-ref loc mod name #t))
((set! (@ ,mod ,name) ,exp) (guard (and-map symbol? mod) (symbol? name))
(make-module-set loc mod name #t (retrans exp)))
((@@ ,mod ,name) (guard (and-map symbol? mod) (symbol? name))
(make-module-ref loc mod name #f))
((set! (@@ ,mod ,name) ,exp) (guard (and-map symbol? mod) (symbol? name))
(make-module-set loc mod name #f (retrans exp)))
((toplevel ,name) (guard (symbol? name))
(make-toplevel-ref loc name))
((set! (toplevel ,name) ,exp) (guard (symbol? name))
(make-toplevel-set loc name (retrans exp)))
((define ,name ,exp) (guard (symbol? name))
(make-toplevel-define loc name (retrans exp)))
((lambda ,meta ,body)
(make-lambda loc meta (retrans body)))
((lambda-case ((,req ,opt ,rest ,kw ,inits ,gensyms) ,body) ,alternate)
(make-lambda-case loc req opt rest kw
(map retrans inits) gensyms
(retrans body)
(and=> alternate retrans)))
((lambda-case ((,req ,opt ,rest ,kw ,inits ,gensyms) ,body))
(make-lambda-case loc req opt rest kw
(map retrans inits) gensyms
(retrans body)
#f))
((const ,exp)
(make-const loc exp))
((begin . ,exps)
(make-sequence loc (map retrans exps)))
((let ,names ,gensyms ,vals ,body)
(make-let loc names gensyms (map retrans vals) (retrans body)))
((letrec ,names ,gensyms ,vals ,body)
(make-letrec loc #f names gensyms (map retrans vals) (retrans body)))
((letrec* ,names ,gensyms ,vals ,body)
(make-letrec loc #t names gensyms (map retrans vals) (retrans body)))
((fix ,names ,gensyms ,vals ,body)
(make-fix loc names gensyms (map retrans vals) (retrans body)))
((let-values ,exp ,body)
(make-let-values loc (retrans exp) (retrans body)))
((dynwind ,winder ,body ,unwinder)
(make-dynwind loc (retrans winder) (retrans body) (retrans unwinder)))
((dynlet ,fluids ,vals ,body)
(make-dynlet loc (map retrans fluids) (map retrans vals) (retrans body)))
((dynref ,fluid)
(make-dynref loc (retrans fluid)))
((dynset ,fluid ,exp)
(make-dynset loc (retrans fluid) (retrans exp)))
((prompt ,tag ,body ,handler)
(make-prompt loc (retrans tag) (retrans body) (retrans handler)))
((abort ,tag ,args ,tail)
(make-abort loc (retrans tag) (map retrans args) (retrans tail)))
(else
(error "unrecognized tree-il" exp)))))
(define (unparse-tree-il tree-il)
(record-case tree-il
((<void>)
'(void))
((<application> proc args)
`(apply ,(unparse-tree-il proc) ,@(map unparse-tree-il args)))
((<conditional> test consequent alternate)
`(if ,(unparse-tree-il test) ,(unparse-tree-il consequent) ,(unparse-tree-il alternate)))
((<primitive-ref> name)
`(primitive ,name))
((<lexical-ref> name gensym)
`(lexical ,name ,gensym))
((<lexical-set> name gensym exp)
`(set! (lexical ,name ,gensym) ,(unparse-tree-il exp)))
((<module-ref> mod name public?)
`(,(if public? '@ '@@) ,mod ,name))
((<module-set> mod name public? exp)
`(set! (,(if public? '@ '@@) ,mod ,name) ,(unparse-tree-il exp)))
((<toplevel-ref> name)
`(toplevel ,name))
((<toplevel-set> name exp)
`(set! (toplevel ,name) ,(unparse-tree-il exp)))
((<toplevel-define> name exp)
`(define ,name ,(unparse-tree-il exp)))
((<lambda> meta body)
(if body
`(lambda ,meta ,(unparse-tree-il body))
`(lambda ,meta (lambda-case))))
((<lambda-case> req opt rest kw inits gensyms body alternate)
`(lambda-case ((,req ,opt ,rest ,kw ,(map unparse-tree-il inits) ,gensyms)
,(unparse-tree-il body))
. ,(if alternate (list (unparse-tree-il alternate)) '())))
((<const> exp)
`(const ,exp))
((<sequence> exps)
`(begin ,@(map unparse-tree-il exps)))
((<let> names gensyms vals body)
`(let ,names ,gensyms ,(map unparse-tree-il vals) ,(unparse-tree-il body)))
((<letrec> in-order? names gensyms vals body)
`(,(if in-order? 'letrec* 'letrec) ,names ,gensyms
,(map unparse-tree-il vals) ,(unparse-tree-il body)))
((<fix> names gensyms vals body)
`(fix ,names ,gensyms ,(map unparse-tree-il vals) ,(unparse-tree-il body)))
((<let-values> exp body)
`(let-values ,(unparse-tree-il exp) ,(unparse-tree-il body)))
((<dynwind> winder body unwinder)
`(dynwind ,(unparse-tree-il winder) ,(unparse-tree-il body)
,(unparse-tree-il unwinder)))
((<dynlet> fluids vals body)
`(dynlet ,(map unparse-tree-il fluids) ,(map unparse-tree-il vals)
,(unparse-tree-il body)))
((<dynref> fluid)
`(dynref ,(unparse-tree-il fluid)))
((<dynset> fluid exp)
`(dynset ,(unparse-tree-il fluid) ,(unparse-tree-il exp)))
((<prompt> tag body handler)
`(prompt ,(unparse-tree-il tag) ,(unparse-tree-il body) ,(unparse-tree-il handler)))
((<abort> tag args tail)
`(abort ,(unparse-tree-il tag) ,(map unparse-tree-il args)
,(unparse-tree-il tail)))))
(define* (tree-il->scheme e #\optional (env #f) (opts '()))
(values ((@ (language scheme decompile-tree-il)
decompile-tree-il)
e env opts)))
(define (tree-il-fold leaf down up seed tree)
"Traverse TREE, calling LEAF on each leaf encountered, DOWN upon descent
into a sub-tree, and UP when leaving a sub-tree. Each of these procedures is
invoked as `(PROC TREE SEED)', where TREE is the sub-tree or leaf considered
and SEED is the current result, intially seeded with SEED.
This is an implementation of `foldts' as described by Andy Wingo in
``Applications of fold to XML transformation''."
(let loop ((tree tree)
(result seed))
(if (or (null? tree) (pair? tree))
(fold loop result tree)
(record-case tree
((<lexical-set> exp)
(up tree (loop exp (down tree result))))
((<module-set> exp)
(up tree (loop exp (down tree result))))
((<toplevel-set> exp)
(up tree (loop exp (down tree result))))
((<toplevel-define> exp)
(up tree (loop exp (down tree result))))
((<conditional> test consequent alternate)
(up tree (loop alternate
(loop consequent
(loop test (down tree result))))))
((<application> proc args)
(up tree (loop (cons proc args) (down tree result))))
((<sequence> exps)
(up tree (loop exps (down tree result))))
((<lambda> body)
(let ((result (down tree result)))
(up tree
(if body
(loop body result)
result))))
((<lambda-case> inits body alternate)
(up tree (if alternate
(loop alternate
(loop body (loop inits (down tree result))))
(loop body (loop inits (down tree result))))))
((<let> vals body)
(up tree (loop body
(loop vals
(down tree result)))))
((<letrec> vals body)
(up tree (loop body
(loop vals
(down tree result)))))
((<fix> vals body)
(up tree (loop body
(loop vals
(down tree result)))))
((<let-values> exp body)
(up tree (loop body (loop exp (down tree result)))))
((<dynwind> body winder unwinder)
(up tree (loop unwinder
(loop winder
(loop body (down tree result))))))
((<dynlet> fluids vals body)
(up tree (loop body
(loop vals
(loop fluids (down tree result))))))
((<dynref> fluid)
(up tree (loop fluid (down tree result))))
((<dynset> fluid exp)
(up tree (loop exp (loop fluid (down tree result)))))
((<prompt> tag body handler)
(up tree
(loop tag (loop body (loop handler
(down tree result))))))
((<abort> tag args tail)
(up tree (loop tail (loop args (loop tag (down tree result))))))
(else
(leaf tree result))))))
(define-syntax-rule (make-tree-il-folder seed ...)
(lambda (tree down up seed ...)
(define (fold-values proc exps seed ...)
(if (null? exps)
(values seed ...)
(let-values (((seed ...) (proc (car exps) seed ...)))
(fold-values proc (cdr exps) seed ...))))
(let foldts ((tree tree) (seed seed) ...)
(let*-values
(((seed ...) (down tree seed ...))
((seed ...)
(record-case tree
((<lexical-set> exp)
(foldts exp seed ...))
((<module-set> exp)
(foldts exp seed ...))
((<toplevel-set> exp)
(foldts exp seed ...))
((<toplevel-define> exp)
(foldts exp seed ...))
((<conditional> test consequent alternate)
(let*-values (((seed ...) (foldts test seed ...))
((seed ...) (foldts consequent seed ...)))
(foldts alternate seed ...)))
((<application> proc args)
(let-values (((seed ...) (foldts proc seed ...)))
(fold-values foldts args seed ...)))
((<sequence> exps)
(fold-values foldts exps seed ...))
((<lambda> body)
(if body
(foldts body seed ...)
(values seed ...)))
((<lambda-case> inits body alternate)
(let-values (((seed ...) (fold-values foldts inits seed ...)))
(if alternate
(let-values (((seed ...) (foldts body seed ...)))
(foldts alternate seed ...))
(foldts body seed ...))))
((<let> vals body)
(let*-values (((seed ...) (fold-values foldts vals seed ...)))
(foldts body seed ...)))
((<letrec> vals body)
(let*-values (((seed ...) (fold-values foldts vals seed ...)))
(foldts body seed ...)))
((<fix> vals body)
(let*-values (((seed ...) (fold-values foldts vals seed ...)))
(foldts body seed ...)))
((<let-values> exp body)
(let*-values (((seed ...) (foldts exp seed ...)))
(foldts body seed ...)))
((<dynwind> body winder unwinder)
(let*-values (((seed ...) (foldts body seed ...))
((seed ...) (foldts winder seed ...)))
(foldts unwinder seed ...)))
((<dynlet> fluids vals body)
(let*-values (((seed ...) (fold-values foldts fluids seed ...))
((seed ...) (fold-values foldts vals seed ...)))
(foldts body seed ...)))
((<dynref> fluid)
(foldts fluid seed ...))
((<dynset> fluid exp)
(let*-values (((seed ...) (foldts fluid seed ...)))
(foldts exp seed ...)))
((<prompt> tag body handler)
(let*-values (((seed ...) (foldts tag seed ...))
((seed ...) (foldts body seed ...)))
(foldts handler seed ...)))
((<abort> tag args tail)
(let*-values (((seed ...) (foldts tag seed ...))
((seed ...) (fold-values foldts args seed ...)))
(foldts tail seed ...)))
(else
(values seed ...)))))
(up tree seed ...)))))
(define (post-order! f x)
(let lp ((x x))
(record-case x
((<application> proc args)
(set! (application-proc x) (lp proc))
(set! (application-args x) (map lp args)))
((<conditional> test consequent alternate)
(set! (conditional-test x) (lp test))
(set! (conditional-consequent x) (lp consequent))
(set! (conditional-alternate x) (lp alternate)))
((<lexical-set> name gensym exp)
(set! (lexical-set-exp x) (lp exp)))
((<module-set> mod name public? exp)
(set! (module-set-exp x) (lp exp)))
((<toplevel-set> name exp)
(set! (toplevel-set-exp x) (lp exp)))
((<toplevel-define> name exp)
(set! (toplevel-define-exp x) (lp exp)))
((<lambda> body)
(if body
(set! (lambda-body x) (lp body))))
((<lambda-case> inits body alternate)
(set! inits (map lp inits))
(set! (lambda-case-body x) (lp body))
(if alternate
(set! (lambda-case-alternate x) (lp alternate))))
((<sequence> exps)
(set! (sequence-exps x) (map lp exps)))
((<let> gensyms vals body)
(set! (let-vals x) (map lp vals))
(set! (let-body x) (lp body)))
((<letrec> gensyms vals body)
(set! (letrec-vals x) (map lp vals))
(set! (letrec-body x) (lp body)))
((<fix> gensyms vals body)
(set! (fix-vals x) (map lp vals))
(set! (fix-body x) (lp body)))
((<let-values> exp body)
(set! (let-values-exp x) (lp exp))
(set! (let-values-body x) (lp body)))
((<dynwind> body winder unwinder)
(set! (dynwind-body x) (lp body))
(set! (dynwind-winder x) (lp winder))
(set! (dynwind-unwinder x) (lp unwinder)))
((<dynlet> fluids vals body)
(set! (dynlet-fluids x) (map lp fluids))
(set! (dynlet-vals x) (map lp vals))
(set! (dynlet-body x) (lp body)))
((<dynref> fluid)
(set! (dynref-fluid x) (lp fluid)))
((<dynset> fluid exp)
(set! (dynset-fluid x) (lp fluid))
(set! (dynset-exp x) (lp exp)))
((<prompt> tag body handler)
(set! (prompt-tag x) (lp tag))
(set! (prompt-body x) (lp body))
(set! (prompt-handler x) (lp handler)))
((<abort> tag args tail)
(set! (abort-tag x) (lp tag))
(set! (abort-args x) (map lp args))
(set! (abort-tail x) (lp tail)))
(else #f))
(or (f x) x)))
(define (pre-order! f x)
(let lp ((x x))
(let ((x (or (f x) x)))
(record-case x
((<application> proc args)
(set! (application-proc x) (lp proc))
(set! (application-args x) (map lp args)))
((<conditional> test consequent alternate)
(set! (conditional-test x) (lp test))
(set! (conditional-consequent x) (lp consequent))
(set! (conditional-alternate x) (lp alternate)))
((<lexical-set> exp)
(set! (lexical-set-exp x) (lp exp)))
((<module-set> exp)
(set! (module-set-exp x) (lp exp)))
((<toplevel-set> exp)
(set! (toplevel-set-exp x) (lp exp)))
((<toplevel-define> exp)
(set! (toplevel-define-exp x) (lp exp)))
((<lambda> body)
(if body
(set! (lambda-body x) (lp body))))
((<lambda-case> inits body alternate)
(set! inits (map lp inits))
(set! (lambda-case-body x) (lp body))
(if alternate (set! (lambda-case-alternate x) (lp alternate))))
((<sequence> exps)
(set! (sequence-exps x) (map lp exps)))
((<let> vals body)
(set! (let-vals x) (map lp vals))
(set! (let-body x) (lp body)))
((<letrec> vals body)
(set! (letrec-vals x) (map lp vals))
(set! (letrec-body x) (lp body)))
((<fix> vals body)
(set! (fix-vals x) (map lp vals))
(set! (fix-body x) (lp body)))
((<let-values> exp body)
(set! (let-values-exp x) (lp exp))
(set! (let-values-body x) (lp body)))
((<dynwind> body winder unwinder)
(set! (dynwind-body x) (lp body))
(set! (dynwind-winder x) (lp winder))
(set! (dynwind-unwinder x) (lp unwinder)))
((<dynlet> fluids vals body)
(set! (dynlet-fluids x) (map lp fluids))
(set! (dynlet-vals x) (map lp vals))
(set! (dynlet-body x) (lp body)))
((<dynref> fluid)
(set! (dynref-fluid x) (lp fluid)))
((<dynset> fluid exp)
(set! (dynset-fluid x) (lp fluid))
(set! (dynset-exp x) (lp exp)))
((<prompt> tag body handler)
(set! (prompt-tag x) (lp tag))
(set! (prompt-body x) (lp body))
(set! (prompt-handler x) (lp handler)))
((<abort> tag args tail)
(set! (abort-tag x) (lp tag))
(set! (abort-args x) (map lp args))
(set! (abort-tail x) (lp tail)))
(else #f))
x)))
;; FIXME: We should have a better primitive than this.
(define (struct-nfields x)
(/ (string-length (symbol->string (struct-layout x))) 2))
(define (tree-il=? a b)
(cond
((struct? a)
(and (struct? b)
(eq? (struct-vtable a) (struct-vtable b))
;; Assume that all structs are tree-il, so we skip over the
;; src slot.
(let lp ((n (1- (struct-nfields a))))
(or (zero? n)
(and (tree-il=? (struct-ref a n) (struct-ref b n))
(lp (1- n)))))))
((pair? a)
(and (pair? b)
(tree-il=? (car a) (car b))
(tree-il=? (cdr a) (cdr b))))
(else
(equal? a b))))
(define-syntax hash-bits
(make-variable-transformer
(lambda (x)
(syntax-case x ()
(var
(identifier? #'var)
(logcount most-positive-fixnum))))))
(define (tree-il-hash exp)
(let ((hash-depth 4)
(hash-width 3))
(define (hash-exp exp depth)
(define (rotate x bits)
(logior (ash x (- bits))
(ash (logand x (1- (ash 1 bits))) (- hash-bits bits))))
(define (mix h1 h2)
(logxor h1 (rotate h2 8)))
(define (hash-struct s)
(let ((len (struct-nfields s))
(h (hashq (struct-vtable s) most-positive-fixnum)))
(if (zero? depth)
h
(let lp ((i (max (- len hash-width) 1)) (h h))
(if (< i len)
(lp (1+ i) (mix (hash-exp (struct-ref s i) (1+ depth)) h))
h)))))
(define (hash-list l)
(let ((h (hashq 'list most-positive-fixnum)))
(if (zero? depth)
h
(let lp ((l l) (width 0) (h h))
(if (< width hash-width)
(lp (cdr l) (1+ width)
(mix (hash-exp (car l) (1+ depth)) h))
h)))))
(cond
((struct? exp) (hash-struct exp))
((list? exp) (hash-list exp))
(else (hash exp most-positive-fixnum))))
(hash-exp exp 0)))
;;; TREE-IL -> GLIL compiler
;; Copyright (C) 2001, 2008, 2009, 2010, 2011, 2012,
;; 2014 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il analyze)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\use-module (ice-9 vlist)
#\use-module (ice-9 match)
#\use-module (system base syntax)
#\use-module (system base message)
#\use-module (system vm program)
#\use-module (language tree-il)
#\use-module (system base pmatch)
#\export (analyze-lexicals
analyze-tree
unused-variable-analysis
unused-toplevel-analysis
unbound-variable-analysis
arity-analysis
format-analysis))
;; Allocation is the process of assigning storage locations for lexical
;; variables. A lexical variable has a distinct "address", or storage
;; location, for each procedure in which it is referenced.
;;
;; A variable is "local", i.e., allocated on the stack, if it is
;; referenced from within the procedure that defined it. Otherwise it is
;; a "closure" variable. For example:
;;
;; (lambda (a) a) ; a will be local
;; `a' is local to the procedure.
;;
;; (lambda (a) (lambda () a))
;; `a' is local to the outer procedure, but a closure variable with
;; respect to the inner procedure.
;;
;; If a variable is ever assigned, it needs to be heap-allocated
;; ("boxed"). This is so that closures and continuations capture the
;; variable's identity, not just one of the values it may have over the
;; course of program execution. If the variable is never assigned, there
;; is no distinction between value and identity, so closing over its
;; identity (whether through closures or continuations) can make a copy
;; of its value instead.
;;
;; Local variables are stored on the stack within a procedure's call
;; frame. Their index into the stack is determined from their linear
;; postion within a procedure's binding path:
;; (let (0 1)
;; (let (2 3) ...)
;; (let (2) ...))
;; (let (2 3 4) ...))
;; etc.
;;
;; This algorithm has the problem that variables are only allocated
;; indices at the end of the binding path. If variables bound early in
;; the path are not used in later portions of the path, their indices
;; will not be recycled. This problem is particularly egregious in the
;; expansion of `or':
;;
;; (or x y z)
;; -> (let ((a x)) (if a a (let ((b y)) (if b b z))))
;;
;; As you can see, the `a' binding is only used in the ephemeral
;; `consequent' clause of the first `if', but its index would be
;; reserved for the whole of the `or' expansion. So we have a hack for
;; this specific case. A proper solution would be some sort of liveness
;; analysis, and not our linear allocation algorithm.
;;
;; Closure variables are captured when a closure is created, and stored in a
;; vector inline to the closure object itself. Each closure variable has a
;; unique index into that vector.
;;
;; There is one more complication. Procedures bound by <fix> may, in
;; some cases, be rendered inline to their parent procedure. That is to
;; say,
;;
;; (letrec ((lp (lambda () (lp)))) (lp))
;; => (fix ((lp (lambda () (lp)))) (lp))
;; => goto FIX-BODY; LP: goto LP; FIX-BODY: goto LP;
;; ^ jump over the loop ^ the fixpoint lp ^ starting off the loop
;;
;; The upshot is that we don't have to allocate any space for the `lp'
;; closure at all, as it can be rendered inline as a loop. So there is
;; another kind of allocation, "label allocation", in which the
;; procedure is simply a label, placed at the start of the lambda body.
;; The label is the gensym under which the lambda expression is bound.
;;
;; The analyzer checks to see that the label is called with the correct
;; number of arguments. Calls to labels compile to rename + goto.
;; Lambda, the ultimate goto!
;;
;;
;; The return value of `analyze-lexicals' is a hash table, the
;; "allocation".
;;
;; The allocation maps gensyms -- recall that each lexically bound
;; variable has a unique gensym -- to storage locations ("addresses").
;; Since one gensym may have many storage locations, if it is referenced
;; in many procedures, it is a two-level map.
;;
;; The allocation also stored information on how many local variables
;; need to be allocated for each procedure, lexicals that have been
;; translated into labels, and information on what free variables to
;; capture from its lexical parent procedure.
;;
;; In addition, we have a conflation: while we're traversing the code,
;; recording information to pass to the compiler, we take the
;; opportunity to generate labels for each lambda-case clause, so that
;; generated code can skip argument checks at runtime if they match at
;; compile-time.
;;
;; Also, while we're a-traversing and an-allocating, we check prompt
;; handlers to see if the "continuation" argument is used. If not, we
;; mark the prompt as being "escape-only". This allows us to implement
;; `catch' and `throw' using `prompt' and `control', but without causing
;; a continuation to be reified. Heh heh.
;;
;; That is:
;;
;; sym -> {lambda -> address}
;; lambda -> (labels . free-locs)
;; lambda-case -> (gensym . nlocs)
;; prompt -> escape-only?
;;
;; address ::= (local? boxed? . index)
;; labels ::= ((sym . lambda) ...)
;; free-locs ::= ((sym0 . address0) (sym1 . address1) ...)
;; free variable addresses are relative to parent proc.
(define (make-hashq k v)
(let ((res (make-hash-table)))
(hashq-set! res k v)
res))
(define (analyze-lexicals x)
;; bound-vars: lambda -> (sym ...)
;; all identifiers bound within a lambda
(define bound-vars (make-hash-table))
;; free-vars: lambda -> (sym ...)
;; all identifiers referenced in a lambda, but not bound
;; NB, this includes identifiers referenced by contained lambdas
(define free-vars (make-hash-table))
;; assigned: sym -> #t
;; variables that are assigned
(define assigned (make-hash-table))
;; refcounts: sym -> count
;; allows us to detect the or-expansion in O(1) time
(define refcounts (make-hash-table))
;; labels: sym -> lambda
;; for determining if fixed-point procedures can be rendered as
;; labels.
(define labels (make-hash-table))
;; returns variables referenced in expr
(define (analyze! x proc labels-in-proc tail? tail-call-args)
(define (step y) (analyze! y proc '() #f #f))
(define (step-tail y) (analyze! y proc labels-in-proc tail? #f))
(define (step-tail-call y args) (analyze! y proc labels-in-proc #f
(and tail? args)))
(define (recur/labels x new-proc labels)
(analyze! x new-proc (append labels labels-in-proc) #t #f))
(define (recur x new-proc) (analyze! x new-proc '() tail? #f))
(record-case x
((<application> proc args)
(apply lset-union eq? (step-tail-call proc args)
(map step args)))
((<conditional> test consequent alternate)
(lset-union eq? (step test) (step-tail consequent) (step-tail alternate)))
((<lexical-ref> gensym)
(hashq-set! refcounts gensym (1+ (hashq-ref refcounts gensym 0)))
(if (not (and tail-call-args
(memq gensym labels-in-proc)
(let ((p (hashq-ref labels gensym)))
(and p
(let lp ((c (lambda-body p)))
(and c (lambda-case? c)
(or
;; for now prohibit optional &
;; keyword arguments; can relax this
;; restriction later
(and (= (length (lambda-case-req c))
(length tail-call-args))
(not (lambda-case-opt c))
(not (lambda-case-kw c))
(not (lambda-case-rest c)))
(lp (lambda-case-alternate c)))))))))
(hashq-set! labels gensym #f))
(list gensym))
((<lexical-set> gensym exp)
(hashq-set! assigned gensym #t)
(hashq-set! labels gensym #f)
(lset-adjoin eq? (step exp) gensym))
((<module-set> exp)
(step exp))
((<toplevel-set> exp)
(step exp))
((<toplevel-define> exp)
(step exp))
((<sequence> exps)
(let lp ((exps exps) (ret '()))
(cond ((null? exps) '())
((null? (cdr exps))
(lset-union eq? ret (step-tail (car exps))))
(else
(lp (cdr exps) (lset-union eq? ret (step (car exps))))))))
((<lambda> body)
;; order is important here
(hashq-set! bound-vars x '())
(let ((free (recur body x)))
(hashq-set! bound-vars x (reverse! (hashq-ref bound-vars x)))
(hashq-set! free-vars x free)
free))
((<lambda-case> opt kw inits gensyms body alternate)
(hashq-set! bound-vars proc
(append (reverse gensyms) (hashq-ref bound-vars proc)))
(lset-union
eq?
(lset-difference eq?
(lset-union eq?
(apply lset-union eq? (map step inits))
(step-tail body))
gensyms)
(if alternate (step-tail alternate) '())))
((<let> gensyms vals body)
(hashq-set! bound-vars proc
(append (reverse gensyms) (hashq-ref bound-vars proc)))
(lset-difference eq?
(apply lset-union eq? (step-tail body) (map step vals))
gensyms))
((<letrec> gensyms vals body)
(hashq-set! bound-vars proc
(append (reverse gensyms) (hashq-ref bound-vars proc)))
(for-each (lambda (sym) (hashq-set! assigned sym #t)) gensyms)
(lset-difference eq?
(apply lset-union eq? (step-tail body) (map step vals))
gensyms))
((<fix> gensyms vals body)
;; Try to allocate these procedures as labels.
(for-each (lambda (sym val) (hashq-set! labels sym val))
gensyms vals)
(hashq-set! bound-vars proc
(append (reverse gensyms) (hashq-ref bound-vars proc)))
;; Step into subexpressions.
(let* ((var-refs
(map
;; Since we're trying to label-allocate the lambda,
;; pretend it's not a closure, and just recurse into its
;; body directly. (Otherwise, recursing on a closure
;; that references one of the fix's bound vars would
;; prevent label allocation.)
(lambda (x)
(record-case x
((<lambda> body)
;; just like the closure case, except here we use
;; recur/labels instead of recur
(hashq-set! bound-vars x '())
(let ((free (recur/labels body x gensyms)))
(hashq-set! bound-vars x (reverse! (hashq-ref bound-vars x)))
(hashq-set! free-vars x free)
free))))
vals))
(vars-with-refs (map cons gensyms var-refs))
(body-refs (recur/labels body proc gensyms)))
(define (delabel-dependents! sym)
(let ((refs (assq-ref vars-with-refs sym)))
(if refs
(for-each (lambda (sym)
(if (hashq-ref labels sym)
(begin
(hashq-set! labels sym #f)
(delabel-dependents! sym))))
refs))))
;; Stepping into the lambdas and the body might have made some
;; procedures not label-allocatable -- which might have
;; knock-on effects. For example:
;; (fix ((a (lambda () (b)))
;; (b (lambda () a)))
;; (a))
;; As far as `a' is concerned, both `a' and `b' are
;; label-allocatable. But `b' references `a' not in a proc-tail
;; position, which makes `a' not label-allocatable. The
;; knock-on effect is that, when back-propagating this
;; information to `a', `b' will also become not
;; label-allocatable, as it is referenced within `a', which is
;; allocated as a closure. This is a transitive relationship.
(for-each (lambda (sym)
(if (not (hashq-ref labels sym))
(delabel-dependents! sym)))
gensyms)
;; Now lift bound variables with label-allocated lambdas to the
;; parent procedure.
(for-each
(lambda (sym val)
(if (hashq-ref labels sym)
;; Remove traces of the label-bound lambda. The free
;; vars will propagate up via the return val.
(begin
(hashq-set! bound-vars proc
(append (hashq-ref bound-vars val)
(hashq-ref bound-vars proc)))
(hashq-remove! bound-vars val)
(hashq-remove! free-vars val))))
gensyms vals)
(lset-difference eq?
(apply lset-union eq? body-refs var-refs)
gensyms)))
((<let-values> exp body)
(lset-union eq? (step exp) (step body)))
((<dynwind> body winder unwinder)
(lset-union eq? (step body) (step winder) (step unwinder)))
((<dynlet> fluids vals body)
(apply lset-union eq? (step body) (map step (append fluids vals))))
((<dynref> fluid)
(step fluid))
((<dynset> fluid exp)
(lset-union eq? (step fluid) (step exp)))
((<prompt> tag body handler)
(lset-union eq? (step tag) (step body) (step-tail handler)))
((<abort> tag args tail)
(apply lset-union eq? (step tag) (step tail) (map step args)))
(else '())))
;; allocation: sym -> {lambda -> address}
;; lambda -> (labels . free-locs)
;; lambda-case -> (gensym . nlocs)
(define allocation (make-hash-table))
(define (allocate! x proc n)
(define (recur y) (allocate! y proc n))
(record-case x
((<application> proc args)
(apply max (recur proc) (map recur args)))
((<conditional> test consequent alternate)
(max (recur test) (recur consequent) (recur alternate)))
((<lexical-set> exp)
(recur exp))
((<module-set> exp)
(recur exp))
((<toplevel-set> exp)
(recur exp))
((<toplevel-define> exp)
(recur exp))
((<sequence> exps)
(apply max (map recur exps)))
((<lambda> body)
;; allocate closure vars in order
(let lp ((c (hashq-ref free-vars x)) (n 0))
(if (pair? c)
(begin
(hashq-set! (hashq-ref allocation (car c))
x
`(#f ,(hashq-ref assigned (car c)) . ,n))
(lp (cdr c) (1+ n)))))
(let ((nlocs (allocate! body x 0))
(free-addresses
(map (lambda (v)
(hashq-ref (hashq-ref allocation v) proc))
(hashq-ref free-vars x)))
(labels (filter cdr
(map (lambda (sym)
(cons sym (hashq-ref labels sym)))
(hashq-ref bound-vars x)))))
;; set procedure allocations
(hashq-set! allocation x (cons labels free-addresses)))
n)
((<lambda-case> opt kw inits gensyms body alternate)
(max
(let lp ((gensyms gensyms) (n n))
(if (null? gensyms)
(let ((nlocs (apply
max
(allocate! body proc n)
;; inits not logically at the end, but they
;; are the list...
(map (lambda (x) (allocate! x proc n)) inits))))
;; label and nlocs for the case
(hashq-set! allocation x (cons (gensym ":LCASE") nlocs))
nlocs)
(begin
(hashq-set! allocation (car gensyms)
(make-hashq
proc `(#t ,(hashq-ref assigned (car gensyms)) . ,n)))
(lp (cdr gensyms) (1+ n)))))
(if alternate (allocate! alternate proc n) n)))
((<let> gensyms vals body)
(let ((nmax (apply max (map recur vals))))
(cond
;; the `or' hack
((and (conditional? body)
(= (length gensyms) 1)
(let ((v (car gensyms)))
(and (not (hashq-ref assigned v))
(= (hashq-ref refcounts v 0) 2)
(lexical-ref? (conditional-test body))
(eq? (lexical-ref-gensym (conditional-test body)) v)
(lexical-ref? (conditional-consequent body))
(eq? (lexical-ref-gensym (conditional-consequent body)) v))))
(hashq-set! allocation (car gensyms)
(make-hashq proc `(#t #f . ,n)))
;; the 1+ for this var
(max nmax (1+ n) (allocate! (conditional-alternate body) proc n)))
(else
(let lp ((gensyms gensyms) (n n))
(if (null? gensyms)
(max nmax (allocate! body proc n))
(let ((v (car gensyms)))
(hashq-set!
allocation v
(make-hashq proc
`(#t ,(hashq-ref assigned v) . ,n)))
(lp (cdr gensyms) (1+ n)))))))))
((<letrec> gensyms vals body)
(let lp ((gensyms gensyms) (n n))
(if (null? gensyms)
(let ((nmax (apply max
(map (lambda (x)
(allocate! x proc n))
vals))))
(max nmax (allocate! body proc n)))
(let ((v (car gensyms)))
(hashq-set!
allocation v
(make-hashq proc
`(#t ,(hashq-ref assigned v) . ,n)))
(lp (cdr gensyms) (1+ n))))))
((<fix> gensyms vals body)
(let lp ((in gensyms) (n n))
(if (null? in)
(let lp ((gensyms gensyms) (vals vals) (nmax n))
(cond
((null? gensyms)
(max nmax (allocate! body proc n)))
((hashq-ref labels (car gensyms))
;; allocate lambda body inline to proc
(lp (cdr gensyms)
(cdr vals)
(record-case (car vals)
((<lambda> body)
(max nmax (allocate! body proc n))))))
(else
;; allocate closure
(lp (cdr gensyms)
(cdr vals)
(max nmax (allocate! (car vals) proc n))))))
(let ((v (car in)))
(cond
((hashq-ref assigned v)
(error "fixpoint procedures may not be assigned" x))
((hashq-ref labels v)
;; no binding, it's a label
(lp (cdr in) n))
(else
;; allocate closure binding
(hashq-set! allocation v (make-hashq proc `(#t #f . ,n)))
(lp (cdr in) (1+ n))))))))
((<let-values> exp body)
(max (recur exp) (recur body)))
((<dynwind> body winder unwinder)
(max (recur body) (recur winder) (recur unwinder)))
((<dynlet> fluids vals body)
(apply max (recur body) (map recur (append fluids vals))))
((<dynref> fluid)
(recur fluid))
((<dynset> fluid exp)
(max (recur fluid) (recur exp)))
((<prompt> tag body handler)
(let ((cont-var (and (lambda-case? handler)
(pair? (lambda-case-gensyms handler))
(car (lambda-case-gensyms handler)))))
(hashq-set! allocation x
(and cont-var (zero? (hashq-ref refcounts cont-var 0))))
(max (recur tag) (recur body) (recur handler))))
((<abort> tag args tail)
(apply max (recur tag) (recur tail) (map recur args)))
(else n)))
(analyze! x #f '() #t #f)
(allocate! x #f 0)
allocation)
;;;
;;; Tree analyses for warnings.
;;;
(define-record-type <tree-analysis>
(make-tree-analysis leaf down up post init)
tree-analysis?
(leaf tree-analysis-leaf) ;; (lambda (x result env locs) ...)
(down tree-analysis-down) ;; (lambda (x result env locs) ...)
(up tree-analysis-up) ;; (lambda (x result env locs) ...)
(post tree-analysis-post) ;; (lambda (result env) ...)
(init tree-analysis-init)) ;; arbitrary value
(define (analyze-tree analyses tree env)
"Run all tree analyses listed in ANALYSES on TREE for ENV, using
`tree-il-fold'. Return TREE. The leaf/down/up procedures of each analysis are
passed a ``location stack', which is the stack of `tree-il-src' values for each
parent tree (a list); it can be used to approximate source location when
accurate information is missing from a given `tree-il' element."
(define (traverse proc update-locs)
;; Return a tree traversing procedure that returns a list of analysis
;; results prepended by the location stack.
(lambda (x results)
(let ((locs (update-locs x (car results))))
(cons locs ;; the location stack
(map (lambda (analysis result)
((proc analysis) x result env locs))
analyses
(cdr results))))))
;; Keeping/extending/shrinking the location stack.
(define (keep-locs x locs) locs)
(define (extend-locs x locs) (cons (tree-il-src x) locs))
(define (shrink-locs x locs) (cdr locs))
(let ((results
(tree-il-fold (traverse tree-analysis-leaf keep-locs)
(traverse tree-analysis-down extend-locs)
(traverse tree-analysis-up shrink-locs)
(cons '() ;; empty location stack
(map tree-analysis-init analyses))
tree)))
(for-each (lambda (analysis result)
((tree-analysis-post analysis) result env))
analyses
(cdr results)))
tree)
;;;
;;; Unused variable analysis.
;;;
;; <binding-info> records are used during tree traversals in
;; `unused-variable-analysis'. They contain a list of the local vars
;; currently in scope, and a list of locals vars that have been referenced.
(define-record-type <binding-info>
(make-binding-info vars refs)
binding-info?
(vars binding-info-vars) ;; ((GENSYM NAME LOCATION) ...)
(refs binding-info-refs)) ;; (GENSYM ...)
(define (gensym? sym)
;; Return #t if SYM is (likely) a generated symbol.
(string-any #\space (symbol->string sym)))
(define unused-variable-analysis
;; Report unused variables in the given tree.
(make-tree-analysis
(lambda (x info env locs)
;; X is a leaf: extend INFO's refs accordingly.
(let ((refs (binding-info-refs info))
(vars (binding-info-vars info)))
(record-case x
((<lexical-ref> gensym)
(make-binding-info vars (vhash-consq gensym #t refs)))
(else info))))
(lambda (x info env locs)
;; Going down into X: extend INFO's variable list
;; accordingly.
(let ((refs (binding-info-refs info))
(vars (binding-info-vars info))
(src (tree-il-src x)))
(define (extend inner-vars inner-names)
(fold (lambda (var name vars)
(vhash-consq var (list name src) vars))
vars
inner-vars
inner-names))
(record-case x
((<lexical-set> gensym)
(make-binding-info vars (vhash-consq gensym #t refs)))
((<lambda-case> req opt inits rest kw gensyms)
(let ((names `(,@req
,@(or opt '())
,@(if rest (list rest) '())
,@(if kw (map cadr (cdr kw)) '()))))
(make-binding-info (extend gensyms names) refs)))
((<let> gensyms names)
(make-binding-info (extend gensyms names) refs))
((<letrec> gensyms names)
(make-binding-info (extend gensyms names) refs))
((<fix> gensyms names)
(make-binding-info (extend gensyms names) refs))
(else info))))
(lambda (x info env locs)
;; Leaving X's scope: shrink INFO's variable list
;; accordingly and reported unused nested variables.
(let ((refs (binding-info-refs info))
(vars (binding-info-vars info)))
(define (shrink inner-vars refs)
(vlist-for-each
(lambda (var)
(let ((gensym (car var)))
;; Don't report lambda parameters as unused.
(if (and (memq gensym inner-vars)
(not (vhash-assq gensym refs))
(not (lambda-case? x)))
(let ((name (cadr var))
;; We can get approximate source location by going up
;; the LOCS location stack.
(loc (or (caddr var)
(find pair? locs))))
(if (and (not (gensym? name))
(not (eq? name '_)))
(warning 'unused-variable loc name))))))
vars)
(vlist-drop vars (length inner-vars)))
;; For simplicity, we leave REFS untouched, i.e., with
;; names of variables that are now going out of scope.
;; It doesn't hurt as these are unique names, it just
;; makes REFS unnecessarily fat.
(record-case x
((<lambda-case> gensyms)
(make-binding-info (shrink gensyms refs) refs))
((<let> gensyms)
(make-binding-info (shrink gensyms refs) refs))
((<letrec> gensyms)
(make-binding-info (shrink gensyms refs) refs))
((<fix> gensyms)
(make-binding-info (shrink gensyms refs) refs))
(else info))))
(lambda (result env) #t)
(make-binding-info vlist-null vlist-null)))
;;;
;;; Unused top-level variable analysis.
;;;
;; <reference-graph> record top-level definitions that are made, references to
;; top-level definitions and their context (the top-level definition in which
;; the reference appears), as well as the current context (the top-level
;; definition we're currently in). The second part (`refs' below) is
;; effectively a graph from which we can determine unused top-level definitions.
(define-record-type <reference-graph>
(make-reference-graph refs defs toplevel-context)
reference-graph?
(defs reference-graph-defs) ;; ((NAME . LOC) ...)
(refs reference-graph-refs) ;; ((REF-CONTEXT REF ...) ...)
(toplevel-context reference-graph-toplevel-context)) ;; NAME | #f
(define (graph-reachable-nodes root refs reachable)
;; Add to REACHABLE the nodes reachable from ROOT in graph REFS. REFS is a
;; vhash mapping nodes to the list of their children: for instance,
;; ((A -> (B C)) (B -> (A)) (C -> ())) corresponds to
;;
;; ,-------.
;; v |
;; A ----> B
;; |
;; v
;; C
;;
;; REACHABLE is a vhash of nodes known to be otherwise reachable.
(let loop ((root root)
(path vlist-null)
(result reachable))
(if (or (vhash-assq root path)
(vhash-assq root result))
result
(let* ((children (or (and=> (vhash-assq root refs) cdr) '()))
(path (vhash-consq root #t path))
(result (fold (lambda (kid result)
(loop kid path result))
result
children)))
(fold (lambda (kid result)
(vhash-consq kid #t result))
result
children)))))
(define (graph-reachable-nodes* roots refs)
;; Return the list of nodes in REFS reachable from the nodes listed in ROOTS.
(vlist-fold (lambda (root+true result)
(let* ((root (car root+true))
(reachable (graph-reachable-nodes root refs result)))
(vhash-consq root #t reachable)))
vlist-null
roots))
(define (partition* pred vhash)
;; Partition VHASH according to PRED. Return the two resulting vhashes.
(let ((result
(vlist-fold (lambda (k+v result)
(let ((k (car k+v))
(v (cdr k+v))
(r1 (car result))
(r2 (cdr result)))
(if (pred k)
(cons (vhash-consq k v r1) r2)
(cons r1 (vhash-consq k v r2)))))
(cons vlist-null vlist-null)
vhash)))
(values (car result) (cdr result))))
(define unused-toplevel-analysis
;; Report unused top-level definitions that are not exported.
(let ((add-ref-from-context
(lambda (graph name)
;; Add an edge CTX -> NAME in GRAPH.
(let* ((refs (reference-graph-refs graph))
(defs (reference-graph-defs graph))
(ctx (reference-graph-toplevel-context graph))
(ctx-refs (or (and=> (vhash-assq ctx refs) cdr) '())))
(make-reference-graph (vhash-consq ctx (cons name ctx-refs) refs)
defs ctx)))))
(define (macro-variable? name env)
(and (module? env)
(let ((var (module-variable env name)))
(and var (variable-bound? var)
(macro? (variable-ref var))))))
(make-tree-analysis
(lambda (x graph env locs)
;; X is a leaf.
(let ((ctx (reference-graph-toplevel-context graph)))
(record-case x
((<toplevel-ref> name src)
(add-ref-from-context graph name))
(else graph))))
(lambda (x graph env locs)
;; Going down into X.
(let ((ctx (reference-graph-toplevel-context graph))
(refs (reference-graph-refs graph))
(defs (reference-graph-defs graph)))
(record-case x
((<toplevel-define> name src)
(let ((refs refs)
(defs (vhash-consq name (or src (find pair? locs))
defs)))
(make-reference-graph refs defs name)))
((<toplevel-set> name src)
(add-ref-from-context graph name))
(else graph))))
(lambda (x graph env locs)
;; Leaving X's scope.
(record-case x
((<toplevel-define>)
(let ((refs (reference-graph-refs graph))
(defs (reference-graph-defs graph)))
(make-reference-graph refs defs #f)))
(else graph)))
(lambda (graph env)
;; Process the resulting reference graph: determine all private definitions
;; not reachable from any public definition. Macros
;; (syntax-transformers), which are globally bound, never considered
;; unused since we can't tell whether a macro is actually used; in
;; addition, macros are considered roots of the graph since they may use
;; private bindings. FIXME: The `make-syntax-transformer' calls don't
;; contain any literal `toplevel-ref' of the global bindings they use so
;; this strategy fails.
(define (exported? name)
(if (module? env)
(module-variable (module-public-interface env) name)
#t))
(let-values (((public-defs private-defs)
(partition* (lambda (name)
(or (exported? name)
(macro-variable? name env)))
(reference-graph-defs graph))))
(let* ((roots (vhash-consq #f #t public-defs))
(refs (reference-graph-refs graph))
(reachable (graph-reachable-nodes* roots refs))
(unused (vlist-filter (lambda (name+src)
(not (vhash-assq (car name+src)
reachable)))
private-defs)))
(vlist-for-each (lambda (name+loc)
(let ((name (car name+loc))
(loc (cdr name+loc)))
(if (not (gensym? name))
(warning 'unused-toplevel loc name))))
unused))))
(make-reference-graph vlist-null vlist-null #f))))
;;;
;;; Unbound variable analysis.
;;;
;; <toplevel-info> records are used during tree traversal in search of
;; possibly unbound variable. They contain a list of references to
;; potentially unbound top-level variables, and a list of the top-level
;; defines that have been encountered.
(define-record-type <toplevel-info>
(make-toplevel-info refs defs)
toplevel-info?
(refs toplevel-info-refs) ;; ((VARIABLE-NAME . LOCATION) ...)
(defs toplevel-info-defs)) ;; (VARIABLE-NAME ...)
(define (goops-toplevel-definition proc args env)
;; If application of PROC to ARGS is a GOOPS top-level definition, return
;; the name of the variable being defined; otherwise return #f. This
;; assumes knowledge of the current implementation of `define-class' et al.
(define (toplevel-define-arg args)
(match args
((($ <const> _ (and (? symbol?) exp)) _)
exp)
(_ #f)))
(match proc
(($ <module-ref> _ '(oop goops) 'toplevel-define! #f)
(toplevel-define-arg args))
(($ <toplevel-ref> _ 'toplevel-define!)
;; This may be the result of expanding one of the GOOPS macros within
;; `oop/goops.scm'.
(and (eq? env (resolve-module '(oop goops)))
(toplevel-define-arg args)))
(_ #f)))
(define unbound-variable-analysis
;; Report possibly unbound variables in the given tree.
(make-tree-analysis
(lambda (x info env locs)
;; X is a leaf: extend INFO's refs accordingly.
(let ((refs (toplevel-info-refs info))
(defs (toplevel-info-defs info)))
(define (bound? name)
(or (and (module? env)
(module-variable env name))
(vhash-assq name defs)))
(record-case x
((<toplevel-ref> name src)
(if (bound? name)
info
(let ((src (or src (find pair? locs))))
(make-toplevel-info (vhash-consq name src refs)
defs))))
(else info))))
(lambda (x info env locs)
;; Going down into X.
(let* ((refs (toplevel-info-refs info))
(defs (toplevel-info-defs info))
(src (tree-il-src x)))
(define (bound? name)
(or (and (module? env)
(module-variable env name))
(vhash-assq name defs)))
(record-case x
((<toplevel-set> name src)
(if (bound? name)
(make-toplevel-info refs defs)
(let ((src (find pair? locs)))
(make-toplevel-info (vhash-consq name src refs)
defs))))
((<toplevel-define> name)
(make-toplevel-info (vhash-delq name refs)
(vhash-consq name #t defs)))
((<application> proc args)
;; Check for a dynamic top-level definition, as is
;; done by code expanded from GOOPS macros.
(let ((name (goops-toplevel-definition proc args
env)))
(if (symbol? name)
(make-toplevel-info (vhash-delq name refs)
(vhash-consq name #t defs))
(make-toplevel-info refs defs))))
(else
(make-toplevel-info refs defs)))))
(lambda (x info env locs)
;; Leaving X's scope.
info)
(lambda (toplevel env)
;; Post-process the result.
(vlist-for-each (lambda (name+loc)
(let ((name (car name+loc))
(loc (cdr name+loc)))
(warning 'unbound-variable loc name)))
(vlist-reverse (toplevel-info-refs toplevel))))
(make-toplevel-info vlist-null vlist-null)))
;;;
;;; Arity analysis.
;;;
;; <arity-info> records contain information about lexical definitions of
;; procedures currently in scope, top-level procedure definitions that have
;; been encountered, and calls to top-level procedures that have been
;; encountered.
(define-record-type <arity-info>
(make-arity-info toplevel-calls lexical-lambdas toplevel-lambdas)
arity-info?
(toplevel-calls toplevel-procedure-calls) ;; ((NAME . APPLICATION) ...)
(lexical-lambdas lexical-lambdas) ;; ((GENSYM . DEFINITION) ...)
(toplevel-lambdas toplevel-lambdas)) ;; ((NAME . DEFINITION) ...)
(define (validate-arity proc application lexical?)
;; Validate the argument count of APPLICATION, a tree-il application of
;; PROC, emitting a warning in case of argument count mismatch.
(define (filter-keyword-args keywords allow-other-keys? args)
;; Filter keyword arguments from ARGS and return the resulting list.
;; KEYWORDS is the list of allowed keywords, and ALLOW-OTHER-KEYS?
;; specified whethere keywords not listed in KEYWORDS are allowed.
(let loop ((args args)
(result '()))
(if (null? args)
(reverse result)
(let ((arg (car args)))
(if (and (const? arg)
(or (memq (const-exp arg) keywords)
(and allow-other-keys?
(keyword? (const-exp arg)))))
(loop (if (pair? (cdr args))
(cddr args)
'())
result)
(loop (cdr args)
(cons arg result)))))))
(define (arities proc)
;; Return the arities of PROC, which can be either a tree-il or a
;; procedure.
(define (len x)
(or (and (or (null? x) (pair? x))
(length x))
0))
(cond ((program? proc)
(values (procedure-name proc)
(map (lambda (a)
(list (arity:nreq a) (arity:nopt a) (arity:rest? a)
(map car (arity:kw a))
(arity:allow-other-keys? a)))
(program-arities proc))))
((procedure? proc)
(if (struct? proc)
;; An applicable struct.
(arities (struct-ref proc 0))
;; An applicable smob.
(let ((arity (procedure-minimum-arity proc)))
(values (procedure-name proc)
(list (list (car arity) (cadr arity) (caddr arity)
#f #f))))))
(else
(let loop ((name #f)
(proc proc)
(arities '()))
(if (not proc)
(values name (reverse arities))
(record-case proc
((<lambda-case> req opt rest kw alternate)
(loop name alternate
(cons (list (len req) (len opt) rest
(and (pair? kw) (map car (cdr kw)))
(and (pair? kw) (car kw)))
arities)))
((<lambda> meta body)
(loop (assoc-ref meta 'name) body arities))
(else
(values #f #f))))))))
(let ((args (application-args application))
(src (tree-il-src application)))
(call-with-values (lambda () (arities proc))
(lambda (name arities)
(define matches?
(find (lambda (arity)
(pmatch arity
((,req ,opt ,rest? ,kw ,aok?)
(let ((args (if (pair? kw)
(filter-keyword-args kw aok? args)
args)))
(if (and req opt)
(let ((count (length args)))
(and (>= count req)
(or rest?
(<= count (+ req opt)))))
#t)))
(else #t)))
arities))
(if (not matches?)
(warning 'arity-mismatch src
(or name (with-output-to-string (lambda () (write proc))))
lexical?)))))
#t)
(define arity-analysis
;; Report arity mismatches in the given tree.
(make-tree-analysis
(lambda (x info env locs)
;; X is a leaf.
info)
(lambda (x info env locs)
;; Down into X.
(define (extend lexical-name val info)
;; If VAL is a lambda, add NAME to the lexical-lambdas of INFO.
(let ((toplevel-calls (toplevel-procedure-calls info))
(lexical-lambdas (lexical-lambdas info))
(toplevel-lambdas (toplevel-lambdas info)))
(record-case val
((<lambda> body)
(make-arity-info toplevel-calls
(vhash-consq lexical-name val
lexical-lambdas)
toplevel-lambdas))
((<lexical-ref> gensym)
;; lexical alias
(let ((val* (vhash-assq gensym lexical-lambdas)))
(if (pair? val*)
(extend lexical-name (cdr val*) info)
info)))
((<toplevel-ref> name)
;; top-level alias
(make-arity-info toplevel-calls
(vhash-consq lexical-name val
lexical-lambdas)
toplevel-lambdas))
(else info))))
(let ((toplevel-calls (toplevel-procedure-calls info))
(lexical-lambdas (lexical-lambdas info))
(toplevel-lambdas (toplevel-lambdas info)))
(record-case x
((<toplevel-define> name exp)
(record-case exp
((<lambda> body)
(make-arity-info toplevel-calls
lexical-lambdas
(vhash-consq name exp toplevel-lambdas)))
((<toplevel-ref> name)
;; alias for another toplevel
(let ((proc (vhash-assq name toplevel-lambdas)))
(make-arity-info toplevel-calls
lexical-lambdas
(vhash-consq (toplevel-define-name x)
(if (pair? proc)
(cdr proc)
exp)
toplevel-lambdas))))
(else info)))
((<let> gensyms vals)
(fold extend info gensyms vals))
((<letrec> gensyms vals)
(fold extend info gensyms vals))
((<fix> gensyms vals)
(fold extend info gensyms vals))
((<application> proc args src)
(record-case proc
((<lambda> body)
(validate-arity proc x #t)
info)
((<toplevel-ref> name)
(make-arity-info (vhash-consq name x toplevel-calls)
lexical-lambdas
toplevel-lambdas))
((<lexical-ref> gensym)
(let ((proc (vhash-assq gensym lexical-lambdas)))
(if (pair? proc)
(record-case (cdr proc)
((<toplevel-ref> name)
;; alias to toplevel
(make-arity-info (vhash-consq name x toplevel-calls)
lexical-lambdas
toplevel-lambdas))
(else
(validate-arity (cdr proc) x #t)
info))
;; If GENSYM wasn't found, it may be because it's an
;; argument of the procedure being compiled.
info)))
(else info)))
(else info))))
(lambda (x info env locs)
;; Up from X.
(define (shrink name val info)
;; Remove NAME from the lexical-lambdas of INFO.
(let ((toplevel-calls (toplevel-procedure-calls info))
(lexical-lambdas (lexical-lambdas info))
(toplevel-lambdas (toplevel-lambdas info)))
(make-arity-info toplevel-calls
(if (vhash-assq name lexical-lambdas)
(vlist-tail lexical-lambdas)
lexical-lambdas)
toplevel-lambdas)))
(let ((toplevel-calls (toplevel-procedure-calls info))
(lexical-lambdas (lexical-lambdas info))
(toplevel-lambdas (toplevel-lambdas info)))
(record-case x
((<let> gensyms vals)
(fold shrink info gensyms vals))
((<letrec> gensyms vals)
(fold shrink info gensyms vals))
((<fix> gensyms vals)
(fold shrink info gensyms vals))
(else info))))
(lambda (result env)
;; Post-processing: check all top-level procedure calls that have been
;; encountered.
(let ((toplevel-calls (toplevel-procedure-calls result))
(toplevel-lambdas (toplevel-lambdas result)))
(vlist-for-each
(lambda (name+application)
(let* ((name (car name+application))
(application (cdr name+application))
(proc
(or (and=> (vhash-assq name toplevel-lambdas) cdr)
(and (module? env)
(false-if-exception
(module-ref env name)))))
(proc*
;; handle toplevel aliases
(if (toplevel-ref? proc)
(let ((name (toplevel-ref-name proc)))
(and (module? env)
(false-if-exception
(module-ref env name))))
proc)))
(cond ((lambda? proc*)
(validate-arity proc* application #t))
((procedure? proc*)
(validate-arity proc* application #f)))))
toplevel-calls)))
(make-arity-info vlist-null vlist-null vlist-null)))
;;;
;;; `format' argument analysis.
;;;
(define &syntax-error
;; The `throw' key for syntax errors.
(gensym "format-string-syntax-error"))
(define (format-string-argument-count fmt)
;; Return the minimum and maxium number of arguments that should
;; follow format string FMT (or, ahem, a good estimate thereof) or
;; `any' if the format string can be followed by any number of
;; arguments.
(define (drop-group chars end)
;; Drop characters from CHARS until "~END" is encountered.
(let loop ((chars chars)
(tilde? #f))
(if (null? chars)
(throw &syntax-error 'unterminated-iteration)
(if tilde?
(if (eq? (car chars) end)
(cdr chars)
(loop (cdr chars) #f))
(if (eq? (car chars) #\~)
(loop (cdr chars) #t)
(loop (cdr chars) #f))))))
(define (digit? char)
;; Return true if CHAR is a digit, #f otherwise.
(memq char '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)))
(define (previous-number chars)
;; Return the previous series of digits found in CHARS.
(let ((numbers (take-while digit? chars)))
(and (not (null? numbers))
(string->number (list->string (reverse numbers))))))
(let loop ((chars (string->list fmt))
(state 'literal)
(params '())
(conditions '())
(end-group #f)
(min-count 0)
(max-count 0))
(if (null? chars)
(if end-group
(throw &syntax-error 'unterminated-conditional)
(values min-count max-count))
(case state
((tilde)
(case (car chars)
((#\~ #\% #\& #\t #\T #\_ #\newline #\( #\) #\! #\| #\/ #\q #\Q)
(loop (cdr chars) 'literal '()
conditions end-group
min-count max-count))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 #\, #\: #\@ #\+ #\- #\#)
(loop (cdr chars)
'tilde (cons (car chars) params)
conditions end-group
min-count max-count))
((#\v #\V) (loop (cdr chars)
'tilde (cons (car chars) params)
conditions end-group
(+ 1 min-count)
(+ 1 max-count)))
((#\p #\P) (let* ((colon? (memq #\: params))
(min-count (if colon?
(max 1 min-count)
(+ 1 min-count))))
(loop (cdr chars) 'literal '()
conditions end-group
min-count
(if colon?
(max max-count min-count)
(+ 1 max-count)))))
((#\[)
(loop chars 'literal '() '()
(let ((selector (previous-number params))
(at? (memq #\@ params)))
(lambda (chars conds)
;; end of group
(let ((mins (map car conds))
(maxs (map cdr conds))
(sel? (and selector
(< selector (length conds)))))
(if (and (every number? mins)
(every number? maxs))
(loop chars 'literal '() conditions end-group
(+ min-count
(if sel?
(car (list-ref conds selector))
(+ (if at? 0 1)
(if (null? mins)
0
(apply min mins)))))
(+ max-count
(if sel?
(cdr (list-ref conds selector))
(+ (if at? 0 1)
(if (null? maxs)
0
(apply max maxs))))))
(values 'any 'any))))) ;; XXX: approximation
0 0))
((#\;)
(if end-group
(loop (cdr chars) 'literal '()
(cons (cons min-count max-count) conditions)
end-group
0 0)
(throw &syntax-error 'unexpected-semicolon)))
((#\])
(if end-group
(end-group (cdr chars)
(reverse (cons (cons min-count max-count)
conditions)))
(throw &syntax-error 'unexpected-conditional-termination)))
((#\{) (if (memq #\@ params)
(values min-count 'any)
(loop (drop-group (cdr chars) #\})
'literal '()
conditions end-group
(+ 1 min-count) (+ 1 max-count))))
((#\*) (if (memq #\@ params)
(values 'any 'any) ;; it's unclear what to do here
(loop (cdr chars)
'literal '()
conditions end-group
(+ (or (previous-number params) 1)
min-count)
(+ (or (previous-number params) 1)
max-count))))
((#\? #\k #\K)
;; We don't have enough info to determine the exact number
;; of args, but we could determine a lower bound (TODO).
(values 'any 'any))
((#\^)
(values min-count 'any))
((#\h #\H)
(let ((argc (if (memq #\: params) 2 1)))
(loop (cdr chars) 'literal '()
conditions end-group
(+ argc min-count)
(+ argc max-count))))
((#\')
(if (null? (cdr chars))
(throw &syntax-error 'unexpected-termination)
(loop (cddr chars) 'tilde (cons (cadr chars) params)
conditions end-group min-count max-count)))
(else (loop (cdr chars) 'literal '()
conditions end-group
(+ 1 min-count) (+ 1 max-count)))))
((literal)
(case (car chars)
((#\~) (loop (cdr chars) 'tilde '()
conditions end-group
min-count max-count))
(else (loop (cdr chars) 'literal '()
conditions end-group
min-count max-count))))
(else (error "computer bought the farm" state))))))
(define (proc-ref? exp proc special-name env)
"Return #t when EXP designates procedure PROC in ENV. As a last
resort, return #t when EXP refers to the global variable SPECIAL-NAME."
(define special?
(cut eq? <> special-name))
(match exp
(($ <toplevel-ref> _ (? special?))
;; Allow top-levels like: (define _ (cut gettext <> "my-domain")).
#t)
(($ <toplevel-ref> _ name)
(let ((var (module-variable env name)))
(and var (variable-bound? var)
(eq? (variable-ref var) proc))))
(($ <module-ref> _ _ (? special?))
#t)
(($ <module-ref> _ module name public?)
(let* ((mod (if public?
(false-if-exception (resolve-interface module))
(resolve-module module #\ensure #f)))
(var (and mod (module-variable mod name))))
(and var (variable-bound? var) (eq? (variable-ref var) proc))))
(($ <lexical-ref> _ (? special?))
#t)
(_ #f)))
(define gettext? (cut proc-ref? <> gettext '_ <>))
(define ngettext? (cut proc-ref? <> ngettext 'N_ <>))
(define (const-fmt x env)
;; Return the literal format string for X, or #f.
(match x
(($ <const> _ (? string? exp))
exp)
(($ <application> _ (? (cut gettext? <> env))
(($ <const> _ (? string? fmt))))
;; Gettexted literals, like `(_ "foo")'.
fmt)
(($ <application> _ (? (cut ngettext? <> env))
(($ <const> _ (? string? fmt)) ($ <const> _ (? string?)) _ \.\.1))
;; Plural gettextized literals, like `(N_ "singular" "plural" n)'.
;; TODO: Check whether the singular and plural strings have the
;; same format escapes.
fmt)
(_ #f)))
(define format-analysis
;; Report arity mismatches in the given tree.
(make-tree-analysis
(lambda (x _ env locs)
;; X is a leaf.
#t)
(lambda (x _ env locs)
;; Down into X.
(define (check-format-args args loc)
(pmatch args
((,port ,fmt . ,rest)
(guard (const-fmt fmt env))
(if (and (const? port)
(not (boolean? (const-exp port))))
(warning 'format loc 'wrong-port (const-exp port)))
(let ((fmt (const-fmt fmt env))
(count (length rest)))
(catch &syntax-error
(lambda ()
(let-values (((min max)
(format-string-argument-count fmt)))
(and min max
(or (and (or (eq? min 'any) (>= count min))
(or (eq? max 'any) (<= count max)))
(warning 'format loc 'wrong-format-arg-count
fmt min max count)))))
(lambda (_ key)
(warning 'format loc 'syntax-error key fmt)))))
((,port ,fmt . ,rest)
(if (and (const? port)
(not (boolean? (const-exp port))))
(warning 'format loc 'wrong-port (const-exp port)))
(match fmt
(($ <const> loc* (? (negate string?) fmt))
(warning 'format (or loc* loc) 'wrong-format-string fmt))
;; Warn on non-literal format strings, unless they refer to
;; a lexical variable named "fmt".
(($ <lexical-ref> _ fmt)
#t)
((? (negate const?))
(warning 'format loc 'non-literal-format-string))))
(else
(warning 'format loc 'wrong-num-args (length args)))))
(define (check-simple-format-args args loc)
;; Check the arguments to the `simple-format' procedure, which is
;; less capable than that of (ice-9 format).
(define allowed-chars
'(#\A #\S #\a #\s #\~ #\%))
(define (format-chars fmt)
(let loop ((chars (string->list fmt))
(result '()))
(match chars
(()
(reverse result))
((#\~ opt rest ...)
(loop rest (cons opt result)))
((_ rest ...)
(loop rest result)))))
(match args
((port ($ <const> _ (? string? fmt)) _ ...)
(let ((opts (format-chars fmt)))
(or (every (cut memq <> allowed-chars) opts)
(begin
(warning 'format loc 'simple-format fmt
(find (negate (cut memq <> allowed-chars)) opts))
#f))))
((port (= (cut const-fmt <> env) (? string? fmt)) args ...)
(check-simple-format-args `(,port ,(make-const loc fmt) ,args) loc))
(_ #t)))
(define (resolve-toplevel name)
(and (module? env)
(false-if-exception (module-ref env name))))
(match x
(($ <application> src ($ <toplevel-ref> _ name) args)
(let ((proc (resolve-toplevel name)))
(if (or (and (eq? proc (@ (guile) simple-format))
(check-simple-format-args args
(or src (find pair? locs))))
(eq? proc (@ (ice-9 format) format)))
(check-format-args args (or src (find pair? locs))))))
(($ <application> src ($ <module-ref> _ '(ice-9 format) 'format) args)
(check-format-args args (or src (find pair? locs))))
(($ <application> src ($ <module-ref> _ '(guile)
(or 'format 'simple-format))
args)
(and (check-simple-format-args args
(or src (find pair? locs)))
(check-format-args args (or src (find pair? locs)))))
(_ #t))
#t)
(lambda (x _ env locs)
;; Up from X.
#t)
(lambda (_ env)
;; Post-processing.
#t)
#t))
;;; Tree-il canonicalizer
;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il canonicalize)
#\use-module (language tree-il)
#\use-module (ice-9 match)
#\use-module (srfi srfi-1)
#\export (canonicalize!))
(define (tree-il-any proc exp)
(tree-il-fold (lambda (exp res)
(or res (proc exp)))
(lambda (exp res)
(or res (proc exp)))
(lambda (exp res) res)
#f exp))
(define (canonicalize! x)
(post-order!
(lambda (x)
(match x
(($ <sequence> src (tail))
tail)
(($ <sequence> src exps)
(and (any sequence? exps)
(make-sequence src
(append-map (lambda (x)
(if (sequence? x)
(sequence-exps x)
(list x)))
exps))))
(($ <let> src () () () body)
body)
(($ <letrec> src _ () () () body)
body)
(($ <fix> src () () () body)
body)
(($ <dynlet> src () () body)
body)
(($ <lambda> src meta #f)
;; Give a body to case-lambda with no clauses.
(make-lambda
src meta
(make-lambda-case
#f '() #f #f #f '() '()
(make-application
#f
(make-primitive-ref #f 'throw)
(list (make-const #f 'wrong-number-of-args)
(make-const #f #f)
(make-const #f "Wrong number of arguments")
(make-const #f '())
(make-const #f #f)))
#f)))
(($ <prompt> src tag body handler)
(define (escape-only? handler)
(match handler
(($ <lambda-case> _ (_ . _) _ _ _ _ (cont . _) body #f)
(not (tree-il-any (lambda (x)
(and (lexical-ref? x)
(eq? (lexical-ref-gensym x) cont)))
body)))
(else #f)))
(define (thunk-application? x)
(match x
(($ <application> _
($ <lambda> _ _ ($ <lambda-case> _ () #f #f #f))
()) #t)
(_ #f)))
(define (make-thunk-application body)
(define thunk
(make-lambda #f '()
(make-lambda-case #f '() #f #f #f '() '() body #f)))
(make-application #f thunk '()))
;; This code has a nasty job to do: to ensure that either the
;; handler is escape-only, or the body is the application of a
;; thunk. Sad but true.
(if (or (escape-only? handler)
(thunk-application? body))
#f
(make-prompt src tag (make-thunk-application body) handler)))
(_ #f)))
x))
;;; TREE-IL -> GLIL compiler
;; Copyright (C) 2001,2008,2009,2010,2011,2012,2013,2014 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il compile-glil)
#\use-module (system base syntax)
#\use-module (system base pmatch)
#\use-module (system base message)
#\use-module (ice-9 receive)
#\use-module (language glil)
#\use-module (system vm instruction)
#\use-module (language tree-il)
#\use-module (language tree-il optimize)
#\use-module (language tree-il canonicalize)
#\use-module (language tree-il analyze)
#\use-module ((srfi srfi-1) #\select (filter-map))
#\export (compile-glil))
;; allocation:
;; sym -> {lambda -> address}
;; lambda -> (labels . free-locs)
;; lambda-case -> (gensym . nlocs)
;;
;; address ::= (local? boxed? . index)
;; labels ::= ((sym . lambda) ...)
;; free-locs ::= ((sym0 . address0) (sym1 . address1) ...)
;; free variable addresses are relative to parent proc.
(define *comp-module* (make-fluid))
(define %warning-passes
`((unused-variable . ,unused-variable-analysis)
(unused-toplevel . ,unused-toplevel-analysis)
(unbound-variable . ,unbound-variable-analysis)
(arity-mismatch . ,arity-analysis)
(format . ,format-analysis)))
(define (compile-glil x e opts)
(define warnings
(or (and=> (memq #\warnings opts) cadr)
'()))
;; Go through the warning passes.
(let ((analyses (filter-map (lambda (kind)
(assoc-ref %warning-passes kind))
warnings)))
(analyze-tree analyses x e))
(let* ((x (make-lambda (tree-il-src x) '()
(make-lambda-case #f '() #f #f #f '() '() x #f)))
(x (optimize! x e opts))
(x (canonicalize! x))
(allocation (analyze-lexicals x)))
(with-fluids ((*comp-module* e))
(values (flatten-lambda x #f allocation)
e
e))))
(define *primcall-ops* (make-hash-table))
(for-each
(lambda (x) (hash-set! *primcall-ops* (car x) (cdr x)))
'(((eq? . 2) . eq?)
((eqv? . 2) . eqv?)
((equal? . 2) . equal?)
((= . 2) . ee?)
((< . 2) . lt?)
((> . 2) . gt?)
((<= . 2) . le?)
((>= . 2) . ge?)
((+ . 2) . add)
((- . 2) . sub)
((1+ . 1) . add1)
((1- . 1) . sub1)
((* . 2) . mul)
((/ . 2) . div)
((quotient . 2) . quo)
((remainder . 2) . rem)
((modulo . 2) . mod)
((ash . 2) . ash)
((logand . 2) . logand)
((logior . 2) . logior)
((logxor . 2) . logxor)
((not . 1) . not)
((pair? . 1) . pair?)
((cons . 2) . cons)
((car . 1) . car)
((cdr . 1) . cdr)
((set-car! . 2) . set-car!)
((set-cdr! . 2) . set-cdr!)
((null? . 1) . null?)
((list? . 1) . list?)
((symbol? . 1) . symbol?)
((vector? . 1) . vector?)
(list . list)
(vector . vector)
((class-of . 1) . class-of)
((vector-ref . 2) . vector-ref)
((vector-set! . 3) . vector-set)
((variable-ref . 1) . variable-ref)
;; nb, *not* variable-set! -- the args are switched
((variable-bound? . 1) . variable-bound?)
((struct? . 1) . struct?)
((struct-vtable . 1) . struct-vtable)
((struct-ref . 2) . struct-ref)
((struct-set! . 3) . struct-set)
(make-struct/no-tail . make-struct)
;; hack for javascript
((return . 1) . return)
;; hack for lua
(return/values . return/values)
((bytevector-u8-ref . 2) . bv-u8-ref)
((bytevector-u8-set! . 3) . bv-u8-set)
((bytevector-s8-ref . 2) . bv-s8-ref)
((bytevector-s8-set! . 3) . bv-s8-set)
((bytevector-u16-ref . 3) . bv-u16-ref)
((bytevector-u16-set! . 4) . bv-u16-set)
((bytevector-u16-native-ref . 2) . bv-u16-native-ref)
((bytevector-u16-native-set! . 3) . bv-u16-native-set)
((bytevector-s16-ref . 3) . bv-s16-ref)
((bytevector-s16-set! . 4) . bv-s16-set)
((bytevector-s16-native-ref . 2) . bv-s16-native-ref)
((bytevector-s16-native-set! . 3) . bv-s16-native-set)
((bytevector-u32-ref . 3) . bv-u32-ref)
((bytevector-u32-set! . 4) . bv-u32-set)
((bytevector-u32-native-ref . 2) . bv-u32-native-ref)
((bytevector-u32-native-set! . 3) . bv-u32-native-set)
((bytevector-s32-ref . 3) . bv-s32-ref)
((bytevector-s32-set! . 4) . bv-s32-set)
((bytevector-s32-native-ref . 2) . bv-s32-native-ref)
((bytevector-s32-native-set! . 3) . bv-s32-native-set)
((bytevector-u64-ref . 3) . bv-u64-ref)
((bytevector-u64-set! . 4) . bv-u64-set)
((bytevector-u64-native-ref . 2) . bv-u64-native-ref)
((bytevector-u64-native-set! . 3) . bv-u64-native-set)
((bytevector-s64-ref . 3) . bv-s64-ref)
((bytevector-s64-set! . 4) . bv-s64-set)
((bytevector-s64-native-ref . 2) . bv-s64-native-ref)
((bytevector-s64-native-set! . 3) . bv-s64-native-set)
((bytevector-ieee-single-ref . 3) . bv-f32-ref)
((bytevector-ieee-single-set! . 4) . bv-f32-set)
((bytevector-ieee-single-native-ref . 2) . bv-f32-native-ref)
((bytevector-ieee-single-native-set! . 3) . bv-f32-native-set)
((bytevector-ieee-double-ref . 3) . bv-f64-ref)
((bytevector-ieee-double-set! . 4) . bv-f64-set)
((bytevector-ieee-double-native-ref . 2) . bv-f64-native-ref)
((bytevector-ieee-double-native-set! . 3) . bv-f64-native-set)))
(define (make-label) (gensym ":L"))
(define (vars->bind-list ids vars allocation proc)
(map (lambda (id v)
(pmatch (hashq-ref (hashq-ref allocation v) proc)
((#t ,boxed? . ,n)
(list id boxed? n))
(,x (error "bad var list element" id v x))))
ids
vars))
(define (emit-bindings src ids vars allocation proc emit-code)
(emit-code src (make-glil-bind
(vars->bind-list ids vars allocation proc))))
(define (with-output-to-code proc)
(let ((out '()))
(define (emit-code src x)
(set! out (cons x out))
(if src
(set! out (cons (make-glil-source src) out))))
(proc emit-code)
(reverse out)))
(define (flatten-lambda x self-label allocation)
(record-case x
((<lambda> src meta body)
(make-glil-program
meta
(with-output-to-code
(lambda (emit-code)
;; write source info for proc
(if src (emit-code #f (make-glil-source src)))
;; compile the body, yo
(flatten-lambda-case body allocation x self-label
(car (hashq-ref allocation x))
emit-code)))))))
(define (flatten-lambda-case lcase allocation self self-label fix-labels
emit-code)
(define (emit-label label)
(emit-code #f (make-glil-label label)))
(define (emit-branch src inst label)
(emit-code src (make-glil-branch inst label)))
;; RA: "return address"; #f unless we're in a non-tail fix with labels
;; MVRA: "multiple-values return address"; #f unless we're in a let-values
(let comp ((x lcase) (context 'tail) (RA #f) (MVRA #f))
(define (comp-tail tree) (comp tree context RA MVRA))
(define (comp-push tree) (comp tree 'push #f #f))
(define (comp-drop tree) (comp tree 'drop #f #f))
(define (comp-vals tree MVRA) (comp tree 'vals #f MVRA))
(define (comp-fix tree RA) (comp tree context RA MVRA))
;; A couple of helpers. Note that if we are in tail context, we
;; won't have an RA.
(define (maybe-emit-return)
(if RA
(emit-branch #f 'br RA)
(if (eq? context 'tail)
(emit-code #f (make-glil-call 'return 1)))))
;; After lexical binding forms in non-tail context, call this
;; function to clear stack slots, allowing their previous values to
;; be collected.
(define (clear-stack-slots context syms)
(case context
((push drop)
(for-each (lambda (v)
(and=>
;; Can be #f if the var is labels-allocated.
(hashq-ref allocation v)
(lambda (h)
(pmatch (hashq-ref h self)
((#t _ . ,n)
(emit-code #f (make-glil-void))
(emit-code #f (make-glil-lexical #t #f 'set n)))
(,loc (error "bad let var allocation" x loc))))))
syms))))
(record-case x
((<void>)
(case context
((push vals tail)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
((<const> src exp)
(case context
((push vals tail)
(emit-code src (make-glil-const exp))))
(maybe-emit-return))
;; FIXME: should represent sequence as exps tail
((<sequence> exps)
(let lp ((exps exps))
(if (null? (cdr exps))
(comp-tail (car exps))
(begin
(comp-drop (car exps))
(lp (cdr exps))))))
((<application> src proc args)
;; FIXME: need a better pattern-matcher here
(cond
((and (primitive-ref? proc)
(eq? (primitive-ref-name proc) '@apply)
(>= (length args) 1))
(let ((proc (car args))
(args (cdr args)))
(cond
((and (primitive-ref? proc) (eq? (primitive-ref-name proc) 'values)
(not (eq? context 'push)) (not (eq? context 'vals)))
;; tail: (lambda () (apply values '(1 2)))
;; drop: (lambda () (apply values '(1 2)) 3)
;; push: (lambda () (list (apply values '(10 12)) 1))
(case context
((drop) (for-each comp-drop args) (maybe-emit-return))
((tail)
(for-each comp-push args)
(emit-code src (make-glil-call 'return/values* (length args))))))
(else
(case context
((tail)
(comp-push proc)
(for-each comp-push args)
(emit-code src (make-glil-call 'tail-apply (1+ (length args)))))
((push)
(emit-code src (make-glil-call 'new-frame 0))
(comp-push proc)
(for-each comp-push args)
(emit-code src (make-glil-call 'apply (1+ (length args))))
(maybe-emit-return))
((vals)
(comp-vals
(make-application src (make-primitive-ref #f 'apply)
(cons proc args))
MVRA)
(maybe-emit-return))
((drop)
;; Well, shit. The proc might return any number of
;; values (including 0), since it's in a drop context,
;; yet apply does not create a MV continuation. So we
;; mv-call out to our trampoline instead.
(comp-drop
(make-application src (make-primitive-ref #f 'apply)
(cons proc args)))
(maybe-emit-return)))))))
((and (primitive-ref? proc) (eq? (primitive-ref-name proc) 'values))
;; tail: (lambda () (values '(1 2)))
;; drop: (lambda () (values '(1 2)) 3)
;; push: (lambda () (list (values '(10 12)) 1))
;; vals: (let-values (((a b ...) (values 1 2 ...))) ...)
(case context
((drop) (for-each comp-drop args) (maybe-emit-return))
((push)
(case (length args)
((0)
;; FIXME: This is surely an error. We need to add a
;; values-mismatch warning pass.
(emit-code src (make-glil-call 'new-frame 0))
(comp-push proc)
(emit-code src (make-glil-call 'call 0))
(maybe-emit-return))
(else
;; Taking advantage of unspecified order of evaluation of
;; arguments.
(for-each comp-drop (cdr args))
(comp-push (car args))
(maybe-emit-return))))
((vals)
(for-each comp-push args)
(emit-code #f (make-glil-const (length args)))
(emit-branch src 'br MVRA))
((tail)
(for-each comp-push args)
(emit-code src (let ((len (length args)))
(if (= len 1)
(make-glil-call 'return 1)
(make-glil-call 'return/values len)))))))
((and (primitive-ref? proc)
(eq? (primitive-ref-name proc) '@call-with-values)
(= (length args) 2))
;; CONSUMER
;; PRODUCER
;; (mv-call MV)
;; ([tail]-call 1)
;; goto POST
;; MV: [tail-]call/nargs
;; POST: (maybe-drop)
(case context
((vals)
;; Fall back.
(comp-vals
(make-application src (make-primitive-ref #f 'call-with-values)
args)
MVRA)
(maybe-emit-return))
(else
(let ((MV (make-label)) (POST (make-label))
(producer (car args)) (consumer (cadr args)))
(if (not (eq? context 'tail))
(emit-code src (make-glil-call 'new-frame 0)))
(comp-push consumer)
(emit-code src (make-glil-call 'new-frame 0))
(comp-push producer)
(emit-code src (make-glil-mv-call 0 MV))
(case context
((tail) (emit-code src (make-glil-call 'tail-call 1)))
(else (emit-code src (make-glil-call 'call 1))
(emit-branch #f 'br POST)))
(emit-label MV)
(case context
((tail) (emit-code src (make-glil-call 'tail-call/nargs 0)))
(else (emit-code src (make-glil-call 'call/nargs 0))
(emit-label POST)
(if (eq? context 'drop)
(emit-code #f (make-glil-call 'drop 1)))
(maybe-emit-return)))))))
((and (primitive-ref? proc)
(eq? (primitive-ref-name proc) '@call-with-current-continuation)
(= (length args) 1))
(case context
((tail)
(comp-push (car args))
(emit-code src (make-glil-call 'tail-call/cc 1)))
((vals)
(comp-vals
(make-application
src (make-primitive-ref #f 'call-with-current-continuation)
args)
MVRA)
(maybe-emit-return))
((push)
(comp-push (car args))
(emit-code src (make-glil-call 'call/cc 1))
(maybe-emit-return))
((drop)
;; Crap. Just like `apply' in drop context.
(comp-drop
(make-application
src (make-primitive-ref #f 'call-with-current-continuation)
args))
(maybe-emit-return))))
;; A hack for variable-set, the opcode for which takes its args
;; reversed, relative to the variable-set! function
((and (primitive-ref? proc)
(eq? (primitive-ref-name proc) 'variable-set!)
(= (length args) 2))
(comp-push (cadr args))
(comp-push (car args))
(emit-code src (make-glil-call 'variable-set 2))
(case context
((tail push vals) (emit-code #f (make-glil-void))))
(maybe-emit-return))
((and (primitive-ref? proc)
(or (hash-ref *primcall-ops*
(cons (primitive-ref-name proc) (length args)))
(hash-ref *primcall-ops* (primitive-ref-name proc))))
=> (lambda (op)
(for-each comp-push args)
(emit-code src (make-glil-call op (length args)))
(case (instruction-pushes op)
((0)
(case context
((tail push vals) (emit-code #f (make-glil-void))))
(maybe-emit-return))
((1)
(case context
((drop) (emit-code #f (make-glil-call 'drop 1))))
(maybe-emit-return))
((-1)
;; A control instruction, like return/values. Here we
;; just have to hope that the author of the tree-il
;; knew what they were doing.
*unspecified*)
(else
(error "bad primitive op: too many pushes"
op (instruction-pushes op))))))
;; call to the same lambda-case in tail position
((and (lexical-ref? proc)
self-label (eq? (lexical-ref-gensym proc) self-label)
(eq? context 'tail)
(not (lambda-case-kw lcase))
(not (lambda-case-rest lcase))
(= (length args)
(+ (length (lambda-case-req lcase))
(or (and=> (lambda-case-opt lcase) length) 0))))
(for-each comp-push args)
(for-each (lambda (sym)
(pmatch (hashq-ref (hashq-ref allocation sym) self)
((#t #f . ,index) ; unboxed
(emit-code #f (make-glil-lexical #t #f 'set index)))
((#t #t . ,index) ; boxed
;; new box
(emit-code #f (make-glil-lexical #t #t 'box index)))
(,x (error "bad lambda-case arg allocation" x))))
(reverse (lambda-case-gensyms lcase)))
(emit-branch src 'br (car (hashq-ref allocation lcase))))
;; lambda, the ultimate goto
((and (lexical-ref? proc)
(assq (lexical-ref-gensym proc) fix-labels))
;; like the self-tail-call case, though we can handle "drop"
;; contexts too. first, evaluate new values, pushing them on
;; the stack
(for-each comp-push args)
;; find the specific case, rename args, and goto the case label
(let lp ((lcase (lambda-body
(assq-ref fix-labels (lexical-ref-gensym proc)))))
(cond
((and (lambda-case? lcase)
(not (lambda-case-kw lcase))
(not (lambda-case-opt lcase))
(not (lambda-case-rest lcase))
(= (length args) (length (lambda-case-req lcase))))
;; we have a case that matches the args; rename variables
;; and goto the case label
(for-each (lambda (sym)
(pmatch (hashq-ref (hashq-ref allocation sym) self)
((#t #f . ,index) ; unboxed
(emit-code #f (make-glil-lexical #t #f 'set index)))
((#t #t . ,index) ; boxed
(emit-code #f (make-glil-lexical #t #t 'box index)))
(,x (error "bad lambda-case arg allocation" x))))
(reverse (lambda-case-gensyms lcase)))
(emit-branch src 'br (car (hashq-ref allocation lcase))))
((lambda-case? lcase)
;; no match, try next case
(lp (lambda-case-alternate lcase)))
(else
;; no cases left. we can't really handle this currently.
;; ideally we would push on a new frame, then do a "local
;; call" -- which doesn't require consing up a program
;; object. but for now error, as this sort of case should
;; preclude label allocation.
(error "couldn't find matching case for label call" x)))))
(else
(if (not (eq? context 'tail))
(emit-code src (make-glil-call 'new-frame 0)))
(comp-push proc)
(for-each comp-push args)
(let ((len (length args)))
(case context
((tail) (if (<= len #xff)
(emit-code src (make-glil-call 'tail-call len))
(begin
(comp-push (make-const #f len))
(emit-code src (make-glil-call 'tail-call/nargs 0)))))
((push) (if (<= len #xff)
(emit-code src (make-glil-call 'call len))
(begin
(comp-push (make-const #f len))
(emit-code src (make-glil-call 'call/nargs 0))))
(maybe-emit-return))
;; FIXME: mv-call doesn't have a /nargs variant, so it is
;; limited to 255 args. Can work around it with a
;; trampoline and tail-call/nargs, but it's not so nice.
((vals) (emit-code src (make-glil-mv-call len MVRA))
(maybe-emit-return))
((drop) (let ((MV (make-label)) (POST (make-label)))
(emit-code src (make-glil-mv-call len MV))
(emit-code #f (make-glil-call 'drop 1))
(emit-branch #f 'br (or RA POST))
(emit-label MV)
(emit-code #f (make-glil-mv-bind 0 #f))
(if RA
(emit-branch #f 'br RA)
(emit-label POST)))))))))
((<conditional> src test consequent alternate)
;; TEST
;; (br-if-not L1)
;; consequent
;; (br L2)
;; L1: alternate
;; L2:
(let ((L1 (make-label)) (L2 (make-label)))
;; need a pattern matcher
(record-case test
((<application> proc args)
(record-case proc
((<primitive-ref> name)
(let ((len (length args)))
(cond
((and (eq? name 'eq?) (= len 2))
(comp-push (car args))
(comp-push (cadr args))
(emit-branch src 'br-if-not-eq L1))
((and (eq? name 'null?) (= len 1))
(comp-push (car args))
(emit-branch src 'br-if-not-null L1))
((and (eq? name 'not) (= len 1))
(let ((app (car args)))
(record-case app
((<application> proc args)
(let ((len (length args)))
(record-case proc
((<primitive-ref> name)
(cond
((and (eq? name 'eq?) (= len 2))
(comp-push (car args))
(comp-push (cadr args))
(emit-branch src 'br-if-eq L1))
((and (eq? name 'null?) (= len 1))
(comp-push (car args))
(emit-branch src 'br-if-null L1))
(else
(comp-push app)
(emit-branch src 'br-if L1))))
(else
(comp-push app)
(emit-branch src 'br-if L1)))))
(else
(comp-push app)
(emit-branch src 'br-if L1)))))
(else
(comp-push test)
(emit-branch src 'br-if-not L1)))))
(else
(comp-push test)
(emit-branch src 'br-if-not L1))))
(else
(comp-push test)
(emit-branch src 'br-if-not L1)))
(comp-tail consequent)
;; if there is an RA, comp-tail will cause a jump to it -- just
;; have to clean up here if there is no RA.
(if (and (not RA) (not (eq? context 'tail)))
(emit-branch #f 'br L2))
(emit-label L1)
(comp-tail alternate)
(if (and (not RA) (not (eq? context 'tail)))
(emit-label L2))))
((<primitive-ref> src name)
(cond
((eq? (module-variable (fluid-ref *comp-module*) name)
(module-variable the-root-module name))
(case context
((tail push vals)
(emit-code src (make-glil-toplevel 'ref name))))
(maybe-emit-return))
((module-variable the-root-module name)
(case context
((tail push vals)
(emit-code src (make-glil-module 'ref '(guile) name #f))))
(maybe-emit-return))
(else
(case context
((tail push vals)
(emit-code src (make-glil-module
'ref (module-name (fluid-ref *comp-module*)) name #f))))
(maybe-emit-return))))
((<lexical-ref> src gensym)
(case context
((push vals tail)
(pmatch (hashq-ref (hashq-ref allocation gensym) self)
((,local? ,boxed? . ,index)
(emit-code src (make-glil-lexical local? boxed? 'ref index)))
(,loc
(error "bad lexical allocation" x loc)))))
(maybe-emit-return))
((<lexical-set> src gensym exp)
(comp-push exp)
(pmatch (hashq-ref (hashq-ref allocation gensym) self)
((,local? ,boxed? . ,index)
(emit-code src (make-glil-lexical local? boxed? 'set index)))
(,loc
(error "bad lexical allocation" x loc)))
(case context
((tail push vals)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
((<module-ref> src mod name public?)
(emit-code src (make-glil-module 'ref mod name public?))
(case context
((drop) (emit-code #f (make-glil-call 'drop 1))))
(maybe-emit-return))
((<module-set> src mod name public? exp)
(comp-push exp)
(emit-code src (make-glil-module 'set mod name public?))
(case context
((tail push vals)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
((<toplevel-ref> src name)
(emit-code src (make-glil-toplevel 'ref name))
(case context
((drop) (emit-code #f (make-glil-call 'drop 1))))
(maybe-emit-return))
((<toplevel-set> src name exp)
(comp-push exp)
(emit-code src (make-glil-toplevel 'set name))
(case context
((tail push vals)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
((<toplevel-define> src name exp)
(comp-push exp)
(emit-code src (make-glil-toplevel 'define name))
(case context
((tail push vals)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
((<lambda>)
(let ((free-locs (cdr (hashq-ref allocation x))))
(case context
((push vals tail)
(emit-code #f (flatten-lambda x #f allocation))
(if (not (null? free-locs))
(begin
(for-each
(lambda (loc)
(pmatch loc
((,local? ,boxed? . ,n)
(emit-code #f (make-glil-lexical local? #f 'ref n)))
(else (error "bad lambda free var allocation" x loc))))
free-locs)
(emit-code #f (make-glil-call 'make-closure
(length free-locs))))))))
(maybe-emit-return))
((<lambda-case> src req opt rest kw inits gensyms alternate body)
;; o/~ feature on top of feature o/~
;; req := (name ...)
;; opt := (name ...) | #f
;; rest := name | #f
;; kw: (allow-other-keys? (keyword name var) ...) | #f
;; gensyms: (sym ...)
;; init: tree-il in context of gensyms
;; gensyms map to named arguments in the following order:
;; required, optional (positional), rest, keyword.
(let* ((nreq (length req))
(nopt (if opt (length opt) 0))
(rest-idx (and rest (+ nreq nopt)))
(opt-names (or opt '()))
(allow-other-keys? (if kw (car kw) #f))
(kw-indices (map (lambda (x)
(pmatch x
((,key ,name ,var)
(cons key (list-index gensyms var)))
(else (error "bad kwarg" x))))
(if kw (cdr kw) '())))
(nargs (apply max (+ nreq nopt (if rest 1 0))
(map 1+ (map cdr kw-indices))))
(nlocs (cdr (hashq-ref allocation x)))
(alternate-label (and alternate (make-label))))
(or (= nargs
(length gensyms)
(+ nreq (length inits) (if rest 1 0)))
(error "lambda-case gensyms don't correspond to args"
req opt rest kw inits gensyms nreq nopt kw-indices nargs))
;; the prelude, to check args & reset the stack pointer,
;; allowing room for locals
(emit-code
src
(cond
(kw
(make-glil-kw-prelude nreq nopt rest-idx kw-indices
allow-other-keys? nlocs alternate-label))
((or rest opt)
(make-glil-opt-prelude nreq nopt rest-idx nlocs alternate-label))
(#t
(make-glil-std-prelude nreq nlocs alternate-label))))
;; box args if necessary
(for-each
(lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #t . ,n)
(emit-code #f (make-glil-lexical #t #f 'ref n))
(emit-code #f (make-glil-lexical #t #t 'box n)))))
gensyms)
;; write bindings info
(if (not (null? gensyms))
(emit-bindings
#f
(let lp ((kw (if kw (cdr kw) '()))
(names (append (reverse opt-names) (reverse req)))
(gensyms (list-tail gensyms (+ nreq nopt
(if rest 1 0)))))
(pmatch kw
(()
;; fixme: check that gensyms is empty
(reverse (if rest (cons rest names) names)))
(((,key ,name ,var) . ,kw)
(if (memq var gensyms)
(lp kw (cons name names) (delq var gensyms))
(lp kw names gensyms)))
(,kw (error "bad keywords, yo" kw))))
gensyms allocation self emit-code))
;; init optional/kw args
(let lp ((inits inits) (n nreq) (gensyms (list-tail gensyms nreq)))
(cond
((null? inits)) ; done
((and rest-idx (= n rest-idx))
(lp inits (1+ n) (cdr gensyms)))
(#t
(pmatch (hashq-ref (hashq-ref allocation (car gensyms)) self)
((#t ,boxed? . ,n*) (guard (= n* n))
(let ((L (make-label)))
(emit-code #f (make-glil-lexical #t boxed? 'bound? n))
(emit-code #f (make-glil-branch 'br-if L))
(comp-push (car inits))
(emit-code #f (make-glil-lexical #t boxed? 'set n))
(emit-label L)
(lp (cdr inits) (1+ n) (cdr gensyms))))
(#t (error "bad arg allocation" (car gensyms) inits))))))
;; post-prelude case label for label calls
(emit-label (car (hashq-ref allocation x)))
(comp-tail body)
(if (not (null? gensyms))
(emit-code #f (make-glil-unbind)))
(if alternate-label
(begin
(emit-label alternate-label)
(flatten-lambda-case alternate allocation self self-label
fix-labels emit-code)))))
((<let> src names gensyms vals body)
(for-each comp-push vals)
(emit-bindings src names gensyms allocation self emit-code)
(for-each (lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #f . ,n)
(emit-code src (make-glil-lexical #t #f 'set n)))
((#t #t . ,n)
(emit-code src (make-glil-lexical #t #t 'box n)))
(,loc (error "bad let var allocation" x loc))))
(reverse gensyms))
(comp-tail body)
(clear-stack-slots context gensyms)
(emit-code #f (make-glil-unbind)))
((<letrec> src in-order? names gensyms vals body)
;; First prepare heap storage slots.
(for-each (lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #t . ,n)
(emit-code src (make-glil-lexical #t #t 'empty-box n)))
(,loc (error "bad letrec var allocation" x loc))))
gensyms)
;; Even though the slots are empty, the bindings are valid.
(emit-bindings src names gensyms allocation self emit-code)
(cond
(in-order?
;; For letrec*, bind values in order.
(for-each (lambda (name v val)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #t . ,n)
(comp-push val)
(emit-code src (make-glil-lexical #t #t 'set n)))
(,loc (error "bad letrec var allocation" x loc))))
names gensyms vals))
(else
;; But for letrec, eval all values, then bind.
(for-each comp-push vals)
(for-each (lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #t . ,n)
(emit-code src (make-glil-lexical #t #t 'set n)))
(,loc (error "bad letrec var allocation" x loc))))
(reverse gensyms))))
(comp-tail body)
(clear-stack-slots context gensyms)
(emit-code #f (make-glil-unbind)))
((<fix> src names gensyms vals body)
;; The ideal here is to just render the lambda bodies inline, and
;; wire the code together with gotos. We can do that if
;; analyze-lexicals has determined that a given var has "label"
;; allocation -- which is the case if it is in `fix-labels'.
;;
;; But even for closures that we can't inline, we can do some
;; tricks to avoid heap-allocation for the binding itself. Since
;; we know the vals are lambdas, we can set them to their local
;; var slots first, then capture their bindings, mutating them in
;; place.
(let ((new-RA (if (or (eq? context 'tail) RA) #f (make-label))))
(for-each
(lambda (x v)
(cond
((hashq-ref allocation x)
;; allocating a closure
(emit-code #f (flatten-lambda x v allocation))
(let ((free-locs (cdr (hashq-ref allocation x))))
(if (not (null? free-locs))
;; Need to make-closure first, so we have a fresh closure on
;; the heap, but with a temporary free values.
(begin
(for-each (lambda (loc)
(emit-code #f (make-glil-const #f)))
free-locs)
(emit-code #f (make-glil-call 'make-closure
(length free-locs))))))
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #f . ,n)
(emit-code src (make-glil-lexical #t #f 'set n)))
(,loc (error "bad fix var allocation" x loc))))
(else
;; labels allocation: emit label & body, but jump over it
(let ((POST (make-label)))
(emit-branch #f 'br POST)
(let lp ((lcase (lambda-body x)))
(if lcase
(record-case lcase
((<lambda-case> src req gensyms body alternate)
(emit-label (car (hashq-ref allocation lcase)))
;; FIXME: opt & kw args in the bindings
(emit-bindings #f req gensyms allocation self emit-code)
(if src
(emit-code #f (make-glil-source src)))
(comp-fix body (or RA new-RA))
(emit-code #f (make-glil-unbind))
(lp alternate)))
(emit-label POST)))))))
vals
gensyms)
;; Emit bindings metadata for closures
(let ((binds (let lp ((out '()) (gensyms gensyms) (names names))
(cond ((null? gensyms) (reverse! out))
((assq (car gensyms) fix-labels)
(lp out (cdr gensyms) (cdr names)))
(else
(lp (acons (car gensyms) (car names) out)
(cdr gensyms) (cdr names)))))))
(emit-bindings src (map cdr binds) (map car binds)
allocation self emit-code))
;; Now go back and fix up the bindings for closures.
(for-each
(lambda (x v)
(let ((free-locs (if (hashq-ref allocation x)
(cdr (hashq-ref allocation x))
;; can hit this latter case for labels allocation
'())))
(if (not (null? free-locs))
(begin
(for-each
(lambda (loc)
(pmatch loc
((,local? ,boxed? . ,n)
(emit-code #f (make-glil-lexical local? #f 'ref n)))
(else (error "bad free var allocation" x loc))))
free-locs)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #f . ,n)
(emit-code #f (make-glil-lexical #t #f 'fix n)))
(,loc (error "bad fix var allocation" x loc)))))))
vals
gensyms)
(comp-tail body)
(if new-RA
(emit-label new-RA))
(clear-stack-slots context gensyms)
(emit-code #f (make-glil-unbind))))
((<let-values> src exp body)
(record-case body
((<lambda-case> req opt kw rest gensyms body alternate)
(if (or opt kw alternate)
(error "unexpected lambda-case in let-values" x))
(let ((MV (make-label)))
(comp-vals exp MV)
(emit-code #f (make-glil-const 1))
(emit-label MV)
(emit-code src (make-glil-mv-bind
(vars->bind-list
(append req (if rest (list rest) '()))
gensyms allocation self)
(and rest #t)))
(for-each (lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #f . ,n)
(emit-code src (make-glil-lexical #t #f 'set n)))
((#t #t . ,n)
(emit-code src (make-glil-lexical #t #t 'box n)))
(,loc (error "bad let-values var allocation" x loc))))
(reverse gensyms))
(comp-tail body)
(clear-stack-slots context gensyms)
(emit-code #f (make-glil-unbind))))))
;; much trickier than i thought this would be, at first, due to the need
;; to have body's return value(s) on the stack while the unwinder runs,
;; then proceed with returning or dropping or what-have-you, interacting
;; with RA and MVRA. What have you, I say.
((<dynwind> src body winder unwinder)
(comp-push winder)
(comp-push unwinder)
(comp-drop (make-application src winder '()))
(emit-code #f (make-glil-call 'wind 2))
(case context
((tail)
(let ((MV (make-label)))
(comp-vals body MV)
;; one value: unwind...
(emit-code #f (make-glil-call 'unwind 0))
(comp-drop (make-application src unwinder '()))
;; ...and return the val
(emit-code #f (make-glil-call 'return 1))
(emit-label MV)
;; multiple values: unwind...
(emit-code #f (make-glil-call 'unwind 0))
(comp-drop (make-application src unwinder '()))
;; and return the values.
(emit-code #f (make-glil-call 'return/nvalues 1))))
((push)
;; we only want one value. so ask for one value
(comp-push body)
;; and unwind, leaving the val on the stack
(emit-code #f (make-glil-call 'unwind 0))
(comp-drop (make-application src unwinder '())))
((vals)
(let ((MV (make-label)))
(comp-vals body MV)
;; one value: push 1 and fall through to MV case
(emit-code #f (make-glil-const 1))
(emit-label MV)
;; multiple values: unwind...
(emit-code #f (make-glil-call 'unwind 0))
(comp-drop (make-application src unwinder '()))
;; and goto the MVRA.
(emit-branch #f 'br MVRA)))
((drop)
;; compile body, discarding values. then unwind...
(comp-drop body)
(emit-code #f (make-glil-call 'unwind 0))
(comp-drop (make-application src unwinder '()))
;; and fall through, or goto RA if there is one.
(if RA
(emit-branch #f 'br RA)))))
((<dynlet> src fluids vals body)
(for-each comp-push fluids)
(for-each comp-push vals)
(emit-code #f (make-glil-call 'wind-fluids (length fluids)))
(case context
((tail)
(let ((MV (make-label)))
;; NB: in tail case, it is possible to preserve asymptotic tail
;; recursion, via merging unwind-fluids structures -- but we'd need
;; to compile in the body twice (once in tail context, assuming the
;; caller unwinds, and once with this trampoline thing, unwinding
;; ourselves).
(comp-vals body MV)
;; one value: unwind and return
(emit-code #f (make-glil-call 'unwind-fluids 0))
(emit-code #f (make-glil-call 'return 1))
(emit-label MV)
;; multiple values: unwind and return values
(emit-code #f (make-glil-call 'unwind-fluids 0))
(emit-code #f (make-glil-call 'return/nvalues 1))))
((push)
(comp-push body)
(emit-code #f (make-glil-call 'unwind-fluids 0)))
((vals)
(let ((MV (make-label)))
(comp-vals body MV)
;; one value: push 1 and fall through to MV case
(emit-code #f (make-glil-const 1))
(emit-label MV)
;; multiple values: unwind and goto MVRA
(emit-code #f (make-glil-call 'unwind-fluids 0))
(emit-branch #f 'br MVRA)))
((drop)
;; compile body, discarding values. then unwind...
(comp-drop body)
(emit-code #f (make-glil-call 'unwind-fluids 0))
;; and fall through, or goto RA if there is one.
(if RA
(emit-branch #f 'br RA)))))
((<dynref> src fluid)
(case context
((drop)
(comp-drop fluid))
((push vals tail)
(comp-push fluid)
(emit-code #f (make-glil-call 'fluid-ref 1))))
(maybe-emit-return))
((<dynset> src fluid exp)
(comp-push fluid)
(comp-push exp)
(emit-code #f (make-glil-call 'fluid-set 2))
(case context
((push vals tail)
(emit-code #f (make-glil-void))))
(maybe-emit-return))
;; What's the deal here? The deal is that we are compiling the start of a
;; delimited continuation. We try to avoid heap allocation in the normal
;; case; so the body is an expression, not a thunk, and we try to render
;; the handler inline. Also we did some analysis, in analyze.scm, so that
;; if the continuation isn't referenced, we don't reify it. This makes it
;; possible to implement catch and throw with delimited continuations,
;; without any overhead.
((<prompt> src tag body handler)
(let ((H (make-label))
(POST (make-label))
(escape-only? (hashq-ref allocation x)))
;; First, set up the prompt.
(comp-push tag)
(emit-code src (make-glil-prompt H escape-only?))
;; Then we compile the body, with its normal return path, unwinding
;; before proceeding.
(case context
((tail)
(let ((MV (make-label)))
(comp-vals body MV)
;; one value: unwind and return
(emit-code #f (make-glil-call 'unwind 0))
(emit-code #f (make-glil-call 'return 1))
;; multiple values: unwind and return
(emit-label MV)
(emit-code #f (make-glil-call 'unwind 0))
(emit-code #f (make-glil-call 'return/nvalues 1))))
((push)
;; we only want one value. so ask for one value, unwind, and jump to
;; post
(comp-push body)
(emit-code #f (make-glil-call 'unwind 0))
(emit-branch #f 'br (or RA POST)))
((vals)
(let ((MV (make-label)))
(comp-vals body MV)
;; one value: push 1 and fall through to MV case
(emit-code #f (make-glil-const 1))
;; multiple values: unwind and goto MVRA
(emit-label MV)
(emit-code #f (make-glil-call 'unwind 0))
(emit-branch #f 'br MVRA)))
((drop)
;; compile body, discarding values, then unwind & fall through.
(comp-drop body)
(emit-code #f (make-glil-call 'unwind 0))
(emit-branch #f 'br (or RA POST))))
(emit-label H)
;; Now the handler. The stack is now made up of the continuation, and
;; then the args to the continuation (pushed separately), and then the
;; number of args, including the continuation.
(record-case handler
((<lambda-case> req opt kw rest gensyms body alternate)
(if (or opt kw alternate)
(error "unexpected lambda-case in prompt" x))
(emit-code src (make-glil-mv-bind
(vars->bind-list
(append req (if rest (list rest) '()))
gensyms allocation self)
(and rest #t)))
(for-each (lambda (v)
(pmatch (hashq-ref (hashq-ref allocation v) self)
((#t #f . ,n)
(emit-code src (make-glil-lexical #t #f 'set n)))
((#t #t . ,n)
(emit-code src (make-glil-lexical #t #t 'box n)))
(,loc
(error "bad prompt handler arg allocation" x loc))))
(reverse gensyms))
(comp-tail body)
(emit-code #f (make-glil-unbind))))
(if (and (not RA)
(or (eq? context 'push) (eq? context 'drop)))
(emit-label POST))))
((<abort> src tag args tail)
(comp-push tag)
(for-each comp-push args)
(comp-push tail)
(emit-code src (make-glil-call 'abort (length args)))
;; so, the abort can actually return. if it does, the values will be on
;; the stack, then the MV marker, just as in an MV context.
(case context
((tail)
;; Return values.
(emit-code #f (make-glil-call 'return/nvalues 1)))
((drop)
;; Drop all values and goto RA, or otherwise fall through.
(emit-code #f (make-glil-mv-bind 0 #f))
(if RA (emit-branch #f 'br RA)))
((push)
;; Truncate to one value.
(emit-code #f (make-glil-mv-bind 1 #f)))
((vals)
;; Go to MVRA.
(emit-branch #f 'br MVRA)))))))
;;; Common Subexpression Elimination (CSE) on Tree-IL
;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il cse)
#\use-module (language tree-il)
#\use-module (language tree-il primitives)
#\use-module (language tree-il effects)
#\use-module (ice-9 vlist)
#\use-module (ice-9 match)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\export (cse))
;;;
;;; This pass eliminates common subexpressions in Tree-IL. It works
;;; best locally -- within a function -- so it is meant to be run after
;;; partial evaluation, which usually inlines functions and so opens up
;;; a bigger space for CSE to work.
;;;
;;; The algorithm traverses the tree of expressions, returning two
;;; values: the newly rebuilt tree, and a "database". The database is
;;; the set of expressions that will have been evaluated as part of
;;; evaluating an expression. For example, in:
;;;
;;; (1- (+ (if a b c) (* x y)))
;;;
;;; We can say that when it comes time to evaluate (1- <>), that the
;;; subexpressions +, x, y, and (* x y) must have been evaluated in
;;; values context. We know that a was evaluated in test context, but
;;; we don't know if it was true or false.
;;;
;;; The expressions in the database /dominate/ any subsequent
;;; expression: FOO dominates BAR if evaluation of BAR implies that any
;;; effects associated with FOO have already occured.
;;;
;;; When adding expressions to the database, we record the context in
;;; which they are evaluated. We treat expressions in test context
;;; specially: the presence of such an expression indicates that the
;;; expression is true. In this way we can elide duplicate predicates.
;;;
;;; Duplicate predicates are not common in code that users write, but
;;; can occur quite frequently in macro-generated code.
;;;
;;; For example:
;;;
;;; (and (foo? x) (foo-bar x))
;;; => (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (struct-ref x 1)
;;; (throw 'not-a-foo))
;;; #f))
;;; => (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (struct-ref x 1)
;;; #f)
;;;
;;; A conditional bailout in effect context also has the effect of
;;; adding predicates to the database:
;;;
;;; (begin (foo-bar x) (foo-baz x))
;;; => (begin
;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (struct-ref x 1)
;;; (throw 'not-a-foo))
;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (struct-ref x 2)
;;; (throw 'not-a-foo)))
;;; => (begin
;;; (if (and (struct? x) (eq? (struct-vtable x) <foo>))
;;; (struct-ref x 1)
;;; (throw 'not-a-foo))
;;; (struct-ref x 2))
;;;
;;; When removing code, we have to ensure that the semantics of the
;;; source program and the residual program are the same. It's easy to
;;; ensure that they have the same value, because those manipulations
;;; are just algebraic, but the tricky thing is to ensure that the
;;; expressions exhibit the same ordering of effects. For that, we use
;;; the effects analysis of (language tree-il effects). We only
;;; eliminate code if the duplicate code commutes with all of the
;;; dominators on the path from the duplicate to the original.
;;;
;;; The implementation uses vhashes as the fundamental data structure.
;;; This can be seen as a form of global value numbering. This
;;; algorithm currently spends most of its time in vhash-assoc. I'm not
;;; sure whether that is due to our bad hash function in Guile 2.0, an
;;; inefficiency in vhashes, or what. Overall though the complexity
;;; should be linear, or N log N -- whatever vhash-assoc's complexity
;;; is. Walking the dominators is nonlinear, but that only happens when
;;; we've actually found a common subexpression so that should be OK.
;;;
;; Logging helpers, as in peval.
;;
(define-syntax *logging* (identifier-syntax #f))
;; (define %logging #f)
;; (define-syntax *logging* (identifier-syntax %logging))
(define-syntax log
(syntax-rules (quote)
((log 'event arg ...)
(if (and *logging*
(or (eq? *logging* #t)
(memq 'event *logging*)))
(log* 'event arg ...)))))
(define (log* event . args)
(let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
'pretty-print)))
(pp `(log ,event . ,args))
(newline)
(values)))
;; A pre-pass on the source program to determine the set of assigned
;; lexicals.
;;
(define* (build-assigned-var-table exp #\optional (table vlist-null))
(tree-il-fold
(lambda (exp res)
res)
(lambda (exp res)
(match exp
(($ <lexical-set> src name gensym exp)
(vhash-consq gensym #t res))
(_ res)))
(lambda (exp res) res)
table exp))
(define (boolean-valued-primitive? primitive)
(or (negate-primitive primitive)
(eq? primitive 'not)
(let ((chars (symbol->string primitive)))
(eqv? (string-ref chars (1- (string-length chars)))
#\?))))
(define (boolean-valued-expression? x ctx)
(match x
(($ <application> _
($ <primitive-ref> _ (? boolean-valued-primitive?))) #t)
(($ <const> _ (? boolean?)) #t)
(_ (eq? ctx 'test))))
(define (singly-valued-expression? x ctx)
(match x
(($ <const>) #t)
(($ <lexical-ref>) #t)
(($ <void>) #t)
(($ <lexical-ref>) #t)
(($ <primitive-ref>) #t)
(($ <module-ref>) #t)
(($ <toplevel-ref>) #t)
(($ <application> _
($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
(($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
(($ <lambda>) #t)
(_ (eq? ctx 'value))))
(define* (cse exp)
"Eliminate common subexpressions in EXP."
(define assigned-lexical?
(let ((table (build-assigned-var-table exp)))
(lambda (sym)
(vhash-assq sym table))))
(define %compute-effects
(make-effects-analyzer assigned-lexical?))
(define (negate exp ctx)
(match exp
(($ <const> src x)
(make-const src (not x)))
(($ <void> src)
(make-const src #f))
(($ <conditional> src test consequent alternate)
(make-conditional src test (negate consequent ctx) (negate alternate ctx)))
(($ <application> _ ($ <primitive-ref> _ 'not)
((and x (? (cut boolean-valued-expression? <> ctx)))))
x)
(($ <application> src
($ <primitive-ref> _ (and pred (? negate-primitive)))
args)
(make-application src
(make-primitive-ref #f (negate-primitive pred))
args))
(_
(make-application #f (make-primitive-ref #f 'not) (list exp)))))
(define (hasher n)
(lambda (x size) (modulo n size)))
(define (add-to-db exp effects ctx db)
(let ((v (vector exp effects ctx))
(h (tree-il-hash exp)))
(vhash-cons v h db (hasher h))))
(define (control-flow-boundary db)
(let ((h (hashq 'lambda most-positive-fixnum)))
(vhash-cons 'lambda h db (hasher h))))
(define (find-dominating-expression exp effects ctx db)
(define (entry-matches? v1 v2)
(match (if (vector? v1) v1 v2)
(#(exp* effects* ctx*)
(and (tree-il=? exp exp*)
(or (not ctx) (eq? ctx* ctx))))
(_ #f)))
(let ((len (vlist-length db))
(h (tree-il-hash exp)))
(and (vhash-assoc #t db entry-matches? (hasher h))
(let lp ((n 0))
(and (< n len)
(match (vlist-ref db n)
(('lambda . h*)
;; We assume that lambdas can escape and thus be
;; called from anywhere. Thus code inside a lambda
;; only has a dominating expression if it does not
;; depend on any effects.
(and (not (depends-on-effects? effects &all-effects))
(lp (1+ n))))
((#(exp* effects* ctx*) . h*)
(log 'walk (unparse-tree-il exp) effects
(unparse-tree-il exp*) effects* ctx*)
(or (and (= h h*)
(or (not ctx) (eq? ctx ctx*))
(tree-il=? exp exp*))
(and (effects-commute? effects effects*)
(lp (1+ n)))))))))))
;; Return #t if EXP is dominated by an instance of itself. In that
;; case, we can exclude *type-check* effects, because the first
;; expression already caused them if needed.
(define (has-dominating-effect? exp effects db)
(or (constant? effects)
(and
(effect-free?
(exclude-effects effects
(logior &zero-values
&allocation
&type-check)))
(find-dominating-expression exp effects #f db))))
(define (find-dominating-test exp effects db)
(and
(effect-free?
(exclude-effects effects (logior &allocation
&type-check)))
(match exp
(($ <const> src val)
(if (boolean? val)
exp
(make-const src (not (not val)))))
;; For (not FOO), try to prove FOO, then negate the result.
(($ <application> src ($ <primitive-ref> _ 'not) (exp*))
(match (find-dominating-test exp* effects db)
(($ <const> _ val)
(log 'inferring exp (not val))
(make-const src (not val)))
(_
#f)))
(_
(cond
((find-dominating-expression exp effects 'test db)
;; We have an EXP fact, so we infer #t.
(log 'inferring exp #t)
(make-const (tree-il-src exp) #t))
((find-dominating-expression (negate exp 'test) effects 'test db)
;; We have a (not EXP) fact, so we infer #f.
(log 'inferring exp #f)
(make-const (tree-il-src exp) #f))
(else
;; Otherwise we don't know.
#f))))))
(define (add-to-env exp name sym db env)
(let* ((v (vector exp name sym (vlist-length db)))
(h (tree-il-hash exp)))
(vhash-cons v h env (hasher h))))
(define (augment-env env names syms exps db)
(if (null? names)
env
(let ((name (car names)) (sym (car syms)) (exp (car exps)))
(augment-env (if (or (assigned-lexical? sym)
(lexical-ref? exp))
env
(add-to-env exp name sym db env))
(cdr names) (cdr syms) (cdr exps) db))))
(define (find-dominating-lexical exp effects env db)
(define (entry-matches? v1 v2)
(match (if (vector? v1) v1 v2)
(#(exp* name sym db)
(tree-il=? exp exp*))
(_ #f)))
(define (unroll db base n)
(or (zero? n)
(match (vlist-ref db base)
(('lambda . h*)
;; See note in find-dominating-expression.
(and (not (depends-on-effects? effects &all-effects))
(unroll db (1+ base) (1- n))))
((#(exp* effects* ctx*) . h*)
(and (effects-commute? effects effects*)
(unroll db (1+ base) (1- n)))))))
(let ((h (tree-il-hash exp)))
(and (effect-free? (exclude-effects effects &type-check))
(vhash-assoc exp env entry-matches? (hasher h))
(let ((env-len (vlist-length env))
(db-len (vlist-length db)))
(let lp ((n 0) (m 0))
(and (< n env-len)
(match (vlist-ref env n)
((#(exp* name sym db-len*) . h*)
(let ((niter (- (- db-len db-len*) m)))
(and (unroll db m niter)
(if (and (= h h*) (tree-il=? exp* exp))
(make-lexical-ref (tree-il-src exp) name sym)
(lp (1+ n) (- db-len db-len*)))))))))))))
(define (lookup-lexical sym env)
(let ((env-len (vlist-length env)))
(let lp ((n 0))
(and (< n env-len)
(match (vlist-ref env n)
((#(exp _ sym* _) . _)
(if (eq? sym sym*)
exp
(lp (1+ n)))))))))
(define (intersection db+ db-)
(vhash-fold-right
(lambda (k h out)
(if (vhash-assoc k db- equal? (hasher h))
(vhash-cons k h out (hasher h))
out))
vlist-null
db+))
(define (concat db1 db2)
(vhash-fold-right (lambda (k h tail)
(vhash-cons k h tail (hasher h)))
db2 db1))
(let visit ((exp exp)
(db vlist-null) ; dominating expressions: #(exp effects ctx) -> hash
(env vlist-null) ; named expressions: #(exp name sym db) -> hash
(ctx 'values)) ; test, effect, value, or values
(define (parallel-visit exps db env ctx)
(let lp ((in exps) (out '()) (db* vlist-null))
(if (pair? in)
(call-with-values (lambda () (visit (car in) db env ctx))
(lambda (x db**)
(lp (cdr in) (cons x out) (concat db** db*))))
(values (reverse out) db*))))
(define (compute-effects exp)
(%compute-effects exp (lambda (sym) (lookup-lexical sym env))))
(define (bailout? exp)
(causes-effects? (compute-effects exp) &definite-bailout))
(define (return exp db*)
(let ((effects (compute-effects exp)))
(cond
((and (eq? ctx 'effect)
(not (lambda-case? exp))
(or (effect-free?
(exclude-effects effects
(logior &zero-values
&allocation)))
(has-dominating-effect? exp effects db)))
(cond
((void? exp)
(values exp db*))
(else
(log 'elide ctx (unparse-tree-il exp))
(values (make-void #f) db*))))
((and (boolean-valued-expression? exp ctx)
(find-dominating-test exp effects db))
=> (lambda (exp)
(log 'propagate-test ctx (unparse-tree-il exp))
(values exp db*)))
((and (singly-valued-expression? exp ctx)
(find-dominating-lexical exp effects env db))
=> (lambda (exp)
(log 'propagate-value ctx (unparse-tree-il exp))
(values exp db*)))
((and (constant? effects) (memq ctx '(value values)))
;; Adds nothing to the db.
(values exp db*))
(else
(log 'return ctx effects (unparse-tree-il exp) db*)
(values exp
(add-to-db exp effects ctx db*))))))
(log 'visit ctx (unparse-tree-il exp) db env)
(match exp
(($ <const>)
(return exp vlist-null))
(($ <void>)
(return exp vlist-null))
(($ <lexical-ref> _ _ gensym)
(return exp vlist-null))
(($ <lexical-set> src name gensym exp)
(let*-values (((exp db*) (visit exp db env 'value)))
(return (make-lexical-set src name gensym exp)
db*)))
(($ <let> src names gensyms vals body)
(let*-values (((vals db*) (parallel-visit vals db env 'value))
((body db**) (visit body (concat db* db)
(augment-env env names gensyms vals db)
ctx)))
(return (make-let src names gensyms vals body)
(concat db** db*))))
(($ <letrec> src in-order? names gensyms vals body)
(let*-values (((vals db*) (parallel-visit vals db env 'value))
((body db**) (visit body (concat db* db)
(augment-env env names gensyms vals db)
ctx)))
(return (make-letrec src in-order? names gensyms vals body)
(concat db** db*))))
(($ <fix> src names gensyms vals body)
(let*-values (((vals db*) (parallel-visit vals db env 'value))
((body db**) (visit body (concat db* db) env ctx)))
(return (make-fix src names gensyms vals body)
(concat db** db*))))
(($ <let-values> src producer consumer)
(let*-values (((producer db*) (visit producer db env 'values))
((consumer db**) (visit consumer (concat db* db) env ctx)))
(return (make-let-values src producer consumer)
(concat db** db*))))
(($ <dynwind> src winder body unwinder)
(let*-values (((pre db*) (visit winder db env 'value))
((body db**) (visit body (concat db* db) env ctx))
((post db***) (visit unwinder db env 'value)))
(return (make-dynwind src pre body post)
(concat db* (concat db** db***)))))
(($ <dynlet> src fluids vals body)
(let*-values (((fluids db*) (parallel-visit fluids db env 'value))
((vals db**) (parallel-visit vals db env 'value))
((body db***) (visit body (concat db** (concat db* db))
env ctx)))
(return (make-dynlet src fluids vals body)
(concat db*** (concat db** db*)))))
(($ <dynref> src fluid)
(let*-values (((fluid db*) (visit fluid db env 'value)))
(return (make-dynref src fluid)
db*)))
(($ <dynset> src fluid exp)
(let*-values (((fluid db*) (visit fluid db env 'value))
((exp db**) (visit exp db env 'value)))
(return (make-dynset src fluid exp)
(concat db** db*))))
(($ <toplevel-ref>)
(return exp vlist-null))
(($ <module-ref>)
(return exp vlist-null))
(($ <module-set> src mod name public? exp)
(let*-values (((exp db*) (visit exp db env 'value)))
(return (make-module-set src mod name public? exp)
db*)))
(($ <toplevel-define> src name exp)
(let*-values (((exp db*) (visit exp db env 'value)))
(return (make-toplevel-define src name exp)
db*)))
(($ <toplevel-set> src name exp)
(let*-values (((exp db*) (visit exp db env 'value)))
(return (make-toplevel-set src name exp)
db*)))
(($ <primitive-ref>)
(return exp vlist-null))
(($ <conditional> src test consequent alternate)
(let*-values
(((test db+) (visit test db env 'test))
((converse db-) (visit (negate test 'test) db env 'test))
((consequent db++) (visit consequent (concat db+ db) env ctx))
((alternate db--) (visit alternate (concat db- db) env ctx)))
(match (make-conditional src test consequent alternate)
(($ <conditional> _ ($ <const> _ exp))
(if exp
(return consequent (concat db++ db+))
(return alternate (concat db-- db-))))
;; (if FOO A A) => (begin FOO A)
(($ <conditional> src _
($ <const> _ a) ($ <const> _ (? (cut equal? a <>))))
(visit (make-sequence #f (list test (make-const #f a)))
db env ctx))
;; (if FOO #t #f) => FOO for boolean-valued FOO.
(($ <conditional> src
(? (cut boolean-valued-expression? <> ctx))
($ <const> _ #t) ($ <const> _ #f))
(return test db+))
;; (if FOO #f #t) => (not FOO)
(($ <conditional> src _ ($ <const> _ #f) ($ <const> _ #t))
(visit (negate test ctx) db env ctx))
;; Allow "and"-like conditions to accumulate in test context.
((and c ($ <conditional> _ _ _ ($ <const> _ #f)))
(return c (if (eq? ctx 'test) (concat db++ db+) vlist-null)))
((and c ($ <conditional> _ _ ($ <const> _ #f) _))
(return c (if (eq? ctx 'test) (concat db-- db-) vlist-null)))
;; Conditional bailouts turn expressions into predicates.
((and c ($ <conditional> _ _ _ (? bailout?)))
(return c (concat db++ db+)))
((and c ($ <conditional> _ _ (? bailout?) _))
(return c (concat db-- db-)))
(c
(return c (intersection (concat db++ db+) (concat db-- db-)))))))
(($ <application> src proc args)
(let*-values (((proc db*) (visit proc db env 'value))
((args db**) (parallel-visit args db env 'value)))
(return (make-application src proc args)
(concat db** db*))))
(($ <lambda> src meta body)
(let*-values (((body _) (if body
(visit body (control-flow-boundary db)
env 'values)
(values #f #f))))
(return (make-lambda src meta body)
vlist-null)))
(($ <lambda-case> src req opt rest kw inits gensyms body alt)
(let*-values (((inits _) (parallel-visit inits db env 'value))
((body db*) (visit body db env ctx))
((alt _) (if alt
(visit alt db env ctx)
(values #f #f))))
(return (make-lambda-case src req opt rest kw inits gensyms body alt)
(if alt vlist-null db*))))
(($ <sequence> src exps)
(let lp ((in exps) (out '()) (db* vlist-null))
(match in
((last)
(let*-values (((last db**) (visit last (concat db* db) env ctx)))
(if (null? out)
(return last (concat db** db*))
(return (make-sequence src (reverse (cons last out)))
(concat db** db*)))))
((head . rest)
(let*-values (((head db**) (visit head (concat db* db) env 'effect)))
(cond
((sequence? head)
(lp (append (sequence-exps head) rest) out db*))
((void? head)
(lp rest out db*))
(else
(lp rest (cons head out) (concat db** db*)))))))))
(($ <prompt> src tag body handler)
(let*-values (((tag db*) (visit tag db env 'value))
((body _) (visit body (concat db* db) env 'values))
((handler _) (visit handler (concat db* db) env ctx)))
(return (make-prompt src tag body handler)
db*)))
(($ <abort> src tag args tail)
(let*-values (((tag db*) (visit tag db env 'value))
((args db**) (parallel-visit args db env 'value))
((tail db***) (visit tail db env 'value)))
(return (make-abort src tag args tail)
(concat db* (concat db** db***))))))))
;;; Tree-IL verifier
;; Copyright (C) 2011, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il debug)
#\use-module (language tree-il)
#\use-module (ice-9 match)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-26)
#\export (verify-tree-il))
(define (verify-tree-il exp)
(define seen-gensyms (make-hash-table))
(define (add sym env)
(if (hashq-ref seen-gensyms sym)
(error "duplicate gensym" sym)
(begin
(hashq-set! seen-gensyms sym #t)
(cons sym env))))
(define (add-env new env)
(if (null? new)
env
(add-env (cdr new) (add (car new) env))))
(let visit ((exp exp)
(env '()))
(match exp
(($ <lambda-case> src req opt rest kw inits gensyms body alt)
(cond
((not (and (list? req) (and-map symbol? req)))
(error "bad required args (should be list of symbols)" exp))
((and opt (not (and (list? opt) (and-map symbol? opt))))
(error "bad optionals (should be #f or list of symbols)" exp))
((and rest (not (symbol? rest)))
(error "bad required args (should be #f or symbol)" exp))
((and kw (not (match kw
((aok . kwlist)
(and (list? kwlist)
(and-map
(lambda (x)
(match x
(((? keyword?) (? symbol?) (? symbol? sym))
(memq sym gensyms))
(_ #f)))
kwlist)))
(_ #f))))
(error "bad keywords (should be #f or (aok (kw name sym) ...))" exp))
((not (and (list? gensyms) (and-map symbol? gensyms)))
(error "bad gensyms (should be list of symbols)" exp))
((not (and (list? gensyms) (and-map symbol? gensyms)))
(error "bad gensyms (should be list of symbols)" exp))
((not (= (length gensyms)
(+ (length req)
(if opt (length opt) 0)
;; FIXME: technically possible for kw gensyms to
;; alias other gensyms
(if rest 1 0)
(if kw (1- (length kw)) 0))))
(error "unexpected gensyms length" exp))
(else
(let lp ((env (add-env (take gensyms (length req)) env))
(nopt (if opt (length opt) 0))
(inits inits)
(tail (drop gensyms (length req))))
(if (zero? nopt)
(let lp ((env (if rest (add (car tail) env) env))
(inits inits)
(tail (if rest (cdr tail) tail)))
(if (pair? inits)
(begin
(visit (car inits) env)
(lp (add (car tail) env) (cdr inits)
(cdr tail)))
(visit body env)))
(begin
(visit (car inits) env)
(lp (add (car tail) env)
(1- nopt)
(cdr inits)
(cdr tail)))))
(if alt (visit alt env)))))
(($ <lexical-ref> src name gensym)
(cond
((not (symbol? name))
(error "name should be a symbol" name))
((not (hashq-ref seen-gensyms gensym))
(error "unbound lexical" exp))
((not (memq gensym env))
(error "displaced lexical" exp))))
(($ <lexical-set> src name gensym exp)
(cond
((not (symbol? name))
(error "name should be a symbol" name))
((not (hashq-ref seen-gensyms gensym))
(error "unbound lexical" exp))
((not (memq gensym env))
(error "displaced lexical" exp))
(else
(visit exp env))))
(($ <lambda> src meta body)
(cond
((and meta (not (and (list? meta) (and-map pair? meta))))
(error "meta should be alist" meta))
((and body (not (lambda-case? body)))
(error "lambda body should be lambda-case" exp))
(else
(if body
(visit body env)))))
(($ <let> src names gensyms vals body)
(cond
((not (and (list? names) (and-map symbol? names)))
(error "names should be list of syms" exp))
((not (and (list? gensyms) (and-map symbol? gensyms)))
(error "gensyms should be list of syms" exp))
((not (list? vals))
(error "vals should be list" exp))
((not (= (length names) (length gensyms) (length vals)))
(error "names, syms, vals should be same length" exp))
(else
(for-each (cut visit <> env) vals)
(visit body (add-env gensyms env)))))
(($ <letrec> src in-order? names gensyms vals body)
(cond
((not (and (list? names) (and-map symbol? names)))
(error "names should be list of syms" exp))
((not (and (list? gensyms) (and-map symbol? gensyms)))
(error "gensyms should be list of syms" exp))
((not (list? vals))
(error "vals should be list" exp))
((not (= (length names) (length gensyms) (length vals)))
(error "names, syms, vals should be same length" exp))
(else
(let ((env (add-env gensyms env)))
(for-each (cut visit <> env) vals)
(visit body env)))))
(($ <fix> src names gensyms vals body)
(cond
((not (and (list? names) (and-map symbol? names)))
(error "names should be list of syms" exp))
((not (and (list? gensyms) (and-map symbol? gensyms)))
(error "gensyms should be list of syms" exp))
((not (list? vals))
(error "vals should be list" exp))
((not (= (length names) (length gensyms) (length vals)))
(error "names, syms, vals should be same length" exp))
(else
(let ((env (add-env gensyms env)))
(for-each (cut visit <> env) vals)
(visit body env)))))
(($ <let-values> src exp body)
(cond
((not (lambda-case? body))
(error "let-values body should be lambda-case" exp))
(else
(visit exp env)
(visit body env))))
(($ <const> src val) #t)
(($ <void> src) #t)
(($ <toplevel-ref> src name)
(cond
((not (symbol? name))
(error "name should be a symbol" name))))
(($ <module-ref> src mod name public?)
(cond
((not (and (list? mod) (and-map symbol? mod)))
(error "module name should be list of symbols" exp))
((not (symbol? name))
(error "name should be symbol" exp))))
(($ <primitive-ref> src name)
(cond
((not (symbol? name))
(error "name should be symbol" exp))))
(($ <toplevel-set> src name exp)
(cond
((not (symbol? name))
(error "name should be a symbol" name))
(else
(visit exp env))))
(($ <toplevel-define> src name exp)
(cond
((not (symbol? name))
(error "name should be a symbol" name))
(else
(visit exp env))))
(($ <module-set> src mod name public? exp)
(cond
((not (and (list? mod) (and-map symbol? mod)))
(error "module name should be list of symbols" exp))
((not (symbol? name))
(error "name should be symbol" exp))
(else
(visit exp env))))
(($ <dynlet> src fluids vals body)
(cond
((not (list? fluids))
(error "fluids should be list" exp))
((not (list? vals))
(error "vals should be list" exp))
((not (= (length fluids) (length vals)))
(error "mismatch in fluids/vals" exp))
(else
(for-each (cut visit <> env) fluids)
(for-each (cut visit <> env) vals)
(visit body env))))
(($ <dynwind> src winder body unwinder)
(visit winder env)
(visit body env)
(visit unwinder env))
(($ <dynref> src fluid)
(visit fluid env))
(($ <dynset> src fluid exp)
(visit fluid env)
(visit exp env))
(($ <conditional> src condition subsequent alternate)
(visit condition env)
(visit subsequent env)
(visit alternate env))
(($ <application> src proc args)
(cond
((not (list? args))
(error "expected list of args" args))
(else
(visit proc env)
(for-each (cut visit <> env) args))))
(($ <sequence> src exps)
(cond
((not (list? exps))
(error "expected list of exps" exp))
((null? exps)
(error "expected more than one exp" exp))
(else
(for-each (cut visit <> env) exps))))
(($ <prompt> src tag body handler)
(visit tag env)
(visit body env)
(visit handler env))
(($ <abort> src tag args tail)
(visit tag env)
(for-each (cut visit <> env) args)
(visit tail env))
(_
(error "unexpected tree-il" exp)))
(let ((src (tree-il-src exp)))
(if (and src (not (and (list? src) (and-map pair? src)
(and-map symbol? (map car src)))))
(error "bad src"))
;; Return it, why not.
exp)))
;;; Effects analysis on Tree-IL
;; Copyright (C) 2011, 2012, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il effects)
#\use-module (language tree-il)
#\use-module (language tree-il primitives)
#\use-module (ice-9 match)
#\export (make-effects-analyzer
&mutable-lexical
&toplevel
&fluid
&definite-bailout
&possible-bailout
&zero-values
&allocation
&mutable-data
&type-check
&all-effects
effects-commute?
exclude-effects
effect-free?
constant?
depends-on-effects?
causes-effects?))
;;;
;;; Hey, it's some effects analysis! If you invoke
;;; `make-effects-analyzer', you get a procedure that computes the set
;;; of effects that an expression depends on and causes. This
;;; information is useful when writing algorithms that move code around,
;;; while preserving the semantics of an input program.
;;;
;;; The effects set is represented by a bitfield, as a fixnum. The set
;;; of possible effects is modelled rather coarsely. For example, a
;;; toplevel reference to FOO is modelled as depending on the &toplevel
;;; effect, and causing a &type-check effect. If any intervening code
;;; sets any toplevel variable, that will block motion of FOO.
;;;
;;; For each effect, two bits are reserved: one to indicate that an
;;; expression depends on the effect, and the other to indicate that an
;;; expression causes the effect.
;;;
(define-syntax define-effects
(lambda (x)
(syntax-case x ()
((_ all name ...)
(with-syntax (((n ...) (iota (length #'(name ...)))))
#'(begin
(define-syntax name (identifier-syntax (ash 1 (* n 2))))
...
(define-syntax all (identifier-syntax (logior name ...)))))))))
;; Here we define the effects, indicating the meaning of the effect.
;;
;; Effects that are described in a "depends on" sense can also be used
;; in the "causes" sense.
;;
;; Effects that are described as causing an effect are not usually used
;; in a "depends-on" sense. Although the "depends-on" sense is used
;; when checking for the existence of the "causes" effect, the effects
;; analyzer will not associate the "depends-on" sense of these effects
;; with any expression.
;;
(define-effects &all-effects
;; Indicates that an expression depends on the value of a mutable
;; lexical variable.
&mutable-lexical
;; Indicates that an expression depends on the value of a toplevel
;; variable.
&toplevel
;; Indicates that an expression depends on the value of a fluid
;; variable.
&fluid
;; Indicates that an expression definitely causes a non-local,
;; non-resumable exit -- a bailout. Only used in the "changes" sense.
&definite-bailout
;; Indicates that an expression may cause a bailout.
&possible-bailout
;; Indicates than an expression may return zero values -- a "causes"
;; effect.
&zero-values
;; Indicates that an expression may return a fresh object -- a
;; "causes" effect.
&allocation
;; Indicates that an expression depends on the value of a mutable data
;; structure.
&mutable-data
;; Indicates that an expression may cause a type check. A type check,
;; for the purposes of this analysis, is the possibility of throwing
;; an exception the first time an expression is evaluated. If the
;; expression did not cause an exception to be thrown, users can
;; assume that evaluating the expression again will not cause an
;; exception to be thrown.
;;
;; For example, (+ x y) might throw if X or Y are not numbers. But if
;; it doesn't throw, it should be safe to elide a dominated, common
;; subexpression (+ x y).
&type-check)
(define-syntax &no-effects (identifier-syntax 0))
;; Definite bailout is an oddball effect. Since it indicates that an
;; expression definitely causes bailout, it's not in the set of effects
;; of a call to an unknown procedure. At the same time, it's also
;; special in that a definite bailout in a subexpression doesn't always
;; cause an outer expression to include &definite-bailout in its
;; effects. For that reason we have to treat it specially.
;;
(define-syntax &all-effects-but-bailout
(identifier-syntax
(logand &all-effects (lognot &definite-bailout))))
(define-inlinable (cause effect)
(ash effect 1))
(define-inlinable (&depends-on a)
(logand a &all-effects))
(define-inlinable (&causes a)
(logand a (cause &all-effects)))
(define (exclude-effects effects exclude)
(logand effects (lognot (cause exclude))))
(define (effect-free? effects)
(zero? (&causes effects)))
(define (constant? effects)
(zero? effects))
(define-inlinable (depends-on-effects? x effects)
(not (zero? (logand (&depends-on x) effects))))
(define-inlinable (causes-effects? x effects)
(not (zero? (logand (&causes x) (cause effects)))))
(define-inlinable (effects-commute? a b)
(and (not (causes-effects? a (&depends-on b)))
(not (causes-effects? b (&depends-on a)))))
(define (make-effects-analyzer assigned-lexical?)
"Returns a procedure of type EXP -> EFFECTS that analyzes the effects
of an expression."
(let ((cache (make-hash-table)))
(define* (compute-effects exp #\optional (lookup (lambda (x) #f)))
(define (compute-effects exp)
(or (hashq-ref cache exp)
(let ((effects (visit exp)))
(hashq-set! cache exp effects)
effects)))
(define (accumulate-effects exps)
(let lp ((exps exps) (out &no-effects))
(if (null? exps)
out
(lp (cdr exps) (logior out (compute-effects (car exps)))))))
(define (visit exp)
(match exp
(($ <const>)
&no-effects)
(($ <void>)
&no-effects)
(($ <lexical-ref> _ _ gensym)
(if (assigned-lexical? gensym)
&mutable-lexical
&no-effects))
(($ <lexical-set> _ name gensym exp)
(logior (cause &mutable-lexical)
(compute-effects exp)))
(($ <let> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <letrec> _ in-order? names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <fix> _ names gensyms vals body)
(logior (if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(accumulate-effects vals)
(compute-effects body)))
(($ <let-values> _ producer consumer)
(logior (compute-effects producer)
(compute-effects consumer)
(cause &type-check)))
(($ <dynwind> _ winder body unwinder)
(logior (compute-effects winder)
(compute-effects body)
(compute-effects unwinder)))
(($ <dynlet> _ fluids vals body)
(logior (accumulate-effects fluids)
(accumulate-effects vals)
(cause &type-check)
(cause &fluid)
(compute-effects body)))
(($ <dynref> _ fluid)
(logior (compute-effects fluid)
(cause &type-check)
&fluid))
(($ <dynset> _ fluid exp)
(logior (compute-effects fluid)
(compute-effects exp)
(cause &type-check)
(cause &fluid)))
(($ <toplevel-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-ref>)
(logior &toplevel
(cause &type-check)))
(($ <module-set> _ mod name public? exp)
(logior (cause &toplevel)
(cause &type-check)
(compute-effects exp)))
(($ <toplevel-define> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <toplevel-set> _ name exp)
(logior (cause &toplevel)
(compute-effects exp)))
(($ <primitive-ref>)
&no-effects)
(($ <conditional> _ test consequent alternate)
(let ((tfx (compute-effects test))
(cfx (compute-effects consequent))
(afx (compute-effects alternate)))
(if (causes-effects? (logior tfx (logand afx cfx))
&definite-bailout)
(logior tfx cfx afx)
(exclude-effects (logior tfx cfx afx)
&definite-bailout))))
;; Zero values.
(($ <application> _ ($ <primitive-ref> _ 'values) ())
(cause &zero-values))
;; Effect-free primitives.
(($ <application> _
($ <primitive-ref> _ (or 'values 'eq? 'eqv? 'equal?))
args)
(accumulate-effects args))
(($ <application> _
($ <primitive-ref> _ (or 'not 'pair? 'null? 'list? 'symbol?
'vector? 'struct? 'string? 'number?
'char?))
(arg))
(compute-effects arg))
;; Primitives that allocate memory.
(($ <application> _ ($ <primitive-ref> _ 'cons) (x y))
(logior (compute-effects x) (compute-effects y)
(cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ (or 'list 'vector)) args)
(logior (accumulate-effects args) (cause &allocation)))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) ())
(cause &allocation))
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag) (arg))
(logior (compute-effects arg) (cause &allocation)))
;; Primitives that are normally effect-free, but which might
;; cause type checks, allocate memory, or access mutable
;; memory. FIXME: expand, to be more precise.
(($ <application> _
($ <primitive-ref> _ (and name
(? effect-free-primitive?)))
args)
(logior (accumulate-effects args)
(cause &type-check)
(if (constructor-primitive? name)
(cause &allocation)
(if (accessor-primitive? name)
&mutable-data
&no-effects))))
;; Lambda applications might throw wrong-number-of-args.
(($ <application> _ ($ <lambda> _ _ body) args)
(logior (accumulate-effects args)
(match body
(($ <lambda-case> _ req #f #f #f () syms body #f)
(logior (compute-effects body)
(if (= (length req) (length args))
0
(cause &type-check))))
(($ <lambda-case>)
(logior (compute-effects body)
(cause &type-check)))
(#f
;; Calling a case-lambda with no clauses
;; definitely causes bailout.
(logior (cause &definite-bailout)
(cause &possible-bailout))))))
;; Bailout primitives.
(($ <application> src ($ <primitive-ref> _ (? bailout-primitive? name))
args)
(logior (accumulate-effects args)
(cause &definite-bailout)
(cause &possible-bailout)))
;; A call to a lexically bound procedure, perhaps labels
;; allocated.
(($ <application> _ (and proc ($ <lexical-ref> _ _ sym)) args)
(cond
((lookup sym)
=> (lambda (proc)
(compute-effects (make-application #f proc args))))
(else
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
;; A call to an unknown procedure can do anything.
(($ <application> _ proc args)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))
(($ <lambda> _ meta body)
&no-effects)
(($ <lambda-case> _ req opt rest kw inits gensyms body alt)
(logior (exclude-effects (accumulate-effects inits)
&definite-bailout)
(if (or-map assigned-lexical? gensyms)
(cause &allocation)
&no-effects)
(compute-effects body)
(if alt (compute-effects alt) &no-effects)))
(($ <sequence> _ exps)
(let lp ((exps exps) (effects &no-effects))
(match exps
((tail)
(logior (compute-effects tail)
;; Returning zero values to a for-effect continuation is
;; not observable.
(exclude-effects effects (cause &zero-values))))
((head . tail)
(lp tail (logior (compute-effects head) effects))))))
(($ <prompt> _ tag body handler)
(logior (compute-effects tag)
(compute-effects body)
(compute-effects handler)))
(($ <abort> _ tag args tail)
(logior &all-effects-but-bailout
(cause &all-effects-but-bailout)))))
(compute-effects exp))
compute-effects))
;;; transformation of letrec into simpler forms
;; Copyright (C) 2009, 2010, 2011, 2012, 2016 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il fix-letrec)
#\use-module (system base syntax)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-11)
#\use-module (language tree-il)
#\use-module (language tree-il effects)
#\export (fix-letrec!))
;; For a detailed discussion, see "Fixing Letrec: A Faithful Yet
;; Efficient Implementation of Scheme's Recursive Binding Construct", by
;; Oscar Waddell, Dipanwita Sarkar, and R. Kent Dybvig.
(define fix-fold
(make-tree-il-folder unref ref set simple lambda complex))
(define (simple-expression? x bound-vars simple-primcall?)
(record-case x
((<void>) #t)
((<const>) #t)
((<lexical-ref> gensym)
(not (memq gensym bound-vars)))
((<conditional> test consequent alternate)
(and (simple-expression? test bound-vars simple-primcall?)
(simple-expression? consequent bound-vars simple-primcall?)
(simple-expression? alternate bound-vars simple-primcall?)))
((<sequence> exps)
(and-map (lambda (x) (simple-expression? x bound-vars simple-primcall?))
exps))
((<application> proc args)
(and (primitive-ref? proc)
(simple-primcall? x)
(and-map (lambda (x)
(simple-expression? x bound-vars simple-primcall?))
args)))
(else #f)))
(define (partition-vars x)
(let-values
(((unref ref set simple lambda* complex)
(fix-fold x
(lambda (x unref ref set simple lambda* complex)
(record-case x
((<lexical-ref> gensym)
(values (delq gensym unref)
(lset-adjoin eq? ref gensym)
set
simple
lambda*
complex))
((<lexical-set> gensym)
(values unref
ref
(lset-adjoin eq? set gensym)
simple
lambda*
complex))
((<letrec> gensyms)
(values (append gensyms unref)
ref
set
simple
lambda*
complex))
((<let> gensyms)
(values (append gensyms unref)
ref
set
simple
lambda*
complex))
(else
(values unref ref set simple lambda* complex))))
(lambda (x unref ref set simple lambda* complex)
(record-case x
((<letrec> in-order? (orig-gensyms gensyms) vals)
(define compute-effects
(make-effects-analyzer (lambda (x) (memq x set))))
(define (effect-free-primcall? x)
(let ((effects (compute-effects x)))
(effect-free?
(exclude-effects effects (logior &allocation
&type-check)))))
(define (effect+exception-free-primcall? x)
(let ((effects (compute-effects x)))
(effect-free?
(exclude-effects effects &allocation))))
(let lp ((gensyms orig-gensyms) (vals vals)
(s '()) (l '()) (c '()))
(cond
((null? gensyms)
;; Unreferenced complex vars are still
;; complex for letrec*. We need to update
;; our algorithm to "Fixing letrec reloaded"
;; to fix this.
(values (if in-order?
(lset-difference eq? unref c)
unref)
ref
set
(append s simple)
(append l lambda*)
(append c complex)))
((memq (car gensyms) unref)
;; See above note about unref and letrec*.
(if (and in-order?
(not (lambda? (car vals)))
(not (simple-expression?
(car vals) orig-gensyms
effect+exception-free-primcall?)))
(lp (cdr gensyms) (cdr vals)
s l (cons (car gensyms) c))
(lp (cdr gensyms) (cdr vals)
s l c)))
((memq (car gensyms) set)
(lp (cdr gensyms) (cdr vals)
s l (cons (car gensyms) c)))
((lambda? (car vals))
(lp (cdr gensyms) (cdr vals)
s (cons (car gensyms) l) c))
((simple-expression?
(car vals) orig-gensyms
(if in-order?
effect+exception-free-primcall?
effect-free-primcall?))
;; For letrec*, we can't consider e.g. `car' to be
;; "simple", as it could raise an exception. Hence
;; effect+exception-free-primitive? above.
(lp (cdr gensyms) (cdr vals)
(cons (car gensyms) s) l c))
(else
(lp (cdr gensyms) (cdr vals)
s l (cons (car gensyms) c))))))
((<let> (orig-gensyms gensyms) vals)
;; The point is to compile let-bound lambdas as
;; efficiently as we do letrec-bound lambdas, so
;; we use the same algorithm for analyzing the
;; gensyms. There is no problem recursing into the
;; bindings after the let, because all variables
;; have been renamed.
(let lp ((gensyms orig-gensyms) (vals vals)
(s '()) (l '()) (c '()))
(cond
((null? gensyms)
(values unref
ref
set
(append s simple)
(append l lambda*)
(append c complex)))
((memq (car gensyms) unref)
(lp (cdr gensyms) (cdr vals)
s l c))
((memq (car gensyms) set)
(lp (cdr gensyms) (cdr vals)
s l (cons (car gensyms) c)))
((and (lambda? (car vals))
(not (memq (car gensyms) set)))
(lp (cdr gensyms) (cdr vals)
s (cons (car gensyms) l) c))
;; There is no difference between simple and
;; complex, for the purposes of let. Just lump
;; them all into complex.
(else
(lp (cdr gensyms) (cdr vals)
s l (cons (car gensyms) c))))))
(else
(values unref ref set simple lambda* complex))))
'()
'()
'()
'()
'()
'())))
(values unref simple lambda* complex)))
(define (make-sequence* src exps)
(let lp ((in exps) (out '()))
(if (null? (cdr in))
(if (null? out)
(car in)
(make-sequence src (reverse (cons (car in) out))))
(let ((head (car in)))
(record-case head
((<lambda>) (lp (cdr in) out))
((<const>) (lp (cdr in) out))
((<lexical-ref>) (lp (cdr in) out))
((<void>) (lp (cdr in) out))
(else (lp (cdr in) (cons head out))))))))
(define (fix-letrec! x)
(let-values (((unref simple lambda* complex) (partition-vars x)))
(post-order!
(lambda (x)
(record-case x
;; Sets to unreferenced variables may be replaced by their
;; expression, called for effect.
((<lexical-set> gensym exp)
(if (memq gensym unref)
(make-sequence* #f (list exp (make-void #f)))
x))
((<letrec> src in-order? names gensyms vals body)
(let ((binds (map list gensyms names vals)))
;; The bindings returned by this function need to appear in the same
;; order that they appear in the letrec.
(define (lookup set)
(let lp ((binds binds))
(cond
((null? binds) '())
((memq (caar binds) set)
(cons (car binds) (lp (cdr binds))))
(else (lp (cdr binds))))))
(let ((u (lookup unref))
(s (lookup simple))
(l (lookup lambda*))
(c (lookup complex)))
;; Bind "simple" bindings, and locations for complex
;; bindings.
(make-let
src
(append (map cadr s) (map cadr c))
(append (map car s) (map car c))
(append (map caddr s) (map (lambda (x) (make-void #f)) c))
;; Bind lambdas using the fixpoint operator.
(make-fix
src (map cadr l) (map car l) (map caddr l)
(make-sequence*
src
(append
;; The right-hand-sides of the unreferenced
;; bindings, for effect.
(map caddr u)
(cond
((null? c)
;; No complex bindings, just emit the body.
(list body))
(in-order?
;; For letrec*, assign complex bindings in order, then the
;; body.
(append
(map (lambda (c)
(make-lexical-set #f (cadr c) (car c)
(caddr c)))
c)
(list body)))
(else
;; Otherwise for plain letrec, evaluate the "complex"
;; bindings, in a `let' to indicate that order doesn't
;; matter, and bind to their variables.
(list
(let ((tmps (map (lambda (x)
(module-gensym "fixlr"))
c)))
(make-let
#f (map cadr c) tmps (map caddr c)
(make-sequence
#f
(map (lambda (x tmp)
(make-lexical-set
#f (cadr x) (car x)
(make-lexical-ref #f (cadr x) tmp)))
c tmps))))
body))))))))))
((<let> src names gensyms vals body)
(let ((binds (map list gensyms names vals)))
(define (lookup set)
(map (lambda (v) (assq v binds))
(lset-intersection eq? gensyms set)))
(let ((u (lookup unref))
(l (lookup lambda*))
(c (lookup complex)))
(make-sequence*
src
(append
;; unreferenced bindings, called for effect.
(map caddr u)
(list
;; unassigned lambdas use fix.
(make-fix src (map cadr l) (map car l) (map caddr l)
;; and the "complex" bindings.
(make-let src (map cadr c) (map car c) (map caddr c)
body))))))))
(else x)))
x)))
;;; Local Variables:
;;; eval: (put 'record-case 'scheme-indent-function 1)
;;; End:
;;; a simple inliner
;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il inline)
#\export (inline!))
(define (inline! x)
(issue-deprecation-warning
"`inline!' is deprecated. Use (language tree-il peval) instead.")
x)
;;; Tree-il optimizer
;; Copyright (C) 2009, 2011, 2012 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il optimize)
#\use-module (language tree-il)
#\use-module (language tree-il primitives)
#\use-module (language tree-il peval)
#\use-module (language tree-il cse)
#\use-module (language tree-il fix-letrec)
#\use-module (language tree-il debug)
#\use-module (ice-9 match)
#\export (optimize!))
(define (optimize! x env opts)
(let ((peval (match (memq #\partial-eval? opts)
((#\partial-eval? #f _ ...)
;; Disable partial evaluation.
(lambda (x e) x))
(_ peval)))
(cse (match (memq #\cse? opts)
((#\cse? #f _ ...)
;; Disable CSE.
(lambda (x) x))
(_ cse))))
(fix-letrec!
(verify-tree-il
(cse
(verify-tree-il
(peval (expand-primitives! (resolve-primitives! x env))
env)))))))
;;; Tree-IL partial evaluator
;; Copyright (C) 2011-2014 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (language tree-il peval)
#\use-module (language tree-il)
#\use-module (language tree-il primitives)
#\use-module (language tree-il effects)
#\use-module (ice-9 vlist)
#\use-module (ice-9 match)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\use-module (ice-9 control)
#\export (peval))
;;;
;;; Partial evaluation is Guile's most important source-to-source
;;; optimization pass. It performs copy propagation, dead code
;;; elimination, inlining, and constant folding, all while preserving
;;; the order of effects in the residual program.
;;;
;;; For more on partial evaluation, see William Cook’s excellent
;;; tutorial on partial evaluation at DSL 2011, called “Build your own
;;; partial evaluator in 90 minutes”[0].
;;;
;;; Our implementation of this algorithm was heavily influenced by
;;; Waddell and Dybvig's paper, "Fast and Effective Procedure Inlining",
;;; IU CS Dept. TR 484.
;;;
;;; [0] http://www.cs.utexas.edu/~wcook/tutorial/.
;;;
;; First, some helpers.
;;
(define-syntax *logging* (identifier-syntax #f))
;; For efficiency we define *logging* to inline to #f, so that the call
;; to log* gets optimized out. If you want to log, uncomment these
;; lines:
;;
;; (define %logging #f)
;; (define-syntax *logging* (identifier-syntax %logging))
;;
;; Then you can change %logging at runtime.
(define-syntax log
(syntax-rules (quote)
((log 'event arg ...)
(if (and *logging*
(or (eq? *logging* #t)
(memq 'event *logging*)))
(log* 'event arg ...)))))
(define (log* event . args)
(let ((pp (module-ref (resolve-interface '(ice-9 pretty-print))
'pretty-print)))
(pp `(log ,event . ,args))
(newline)
(values)))
(define (tree-il-any proc exp)
(let/ec k
(tree-il-fold (lambda (exp res)
(let ((res (proc exp)))
(if res (k res) #f)))
(lambda (exp res)
(let ((res (proc exp)))
(if res (k res) #f)))
(lambda (exp res) #f)
#f exp)))
(define (vlist-any proc vlist)
(let ((len (vlist-length vlist)))
(let lp ((i 0))
(and (< i len)
(or (proc (vlist-ref vlist i))
(lp (1+ i)))))))
(define (singly-valued-expression? exp)
(match exp
(($ <const>) #t)
(($ <lexical-ref>) #t)
(($ <void>) #t)
(($ <lexical-ref>) #t)
(($ <primitive-ref>) #t)
(($ <module-ref>) #t)
(($ <toplevel-ref>) #t)
(($ <application> _
($ <primitive-ref> _ (? singly-valued-primitive?))) #t)
(($ <application> _ ($ <primitive-ref> _ 'values) (val)) #t)
(($ <lambda>) #t)
(else #f)))
(define (truncate-values x)
"Discard all but the first value of X."
(if (singly-valued-expression? x)
x
(make-application (tree-il-src x)
(make-primitive-ref #f 'values)
(list x))))
;; Peval will do a one-pass analysis on the source program to determine
;; the set of assigned lexicals, and to identify unreferenced and
;; singly-referenced lexicals.
;;
(define-record-type <var>
(make-var name gensym refcount set?)
var?
(name var-name)
(gensym var-gensym)
(refcount var-refcount set-var-refcount!)
(set? var-set? set-var-set?!))
(define* (build-var-table exp #\optional (table vlist-null))
(tree-il-fold
(lambda (exp res)
(match exp
(($ <lexical-ref> src name gensym)
(let ((var (cdr (vhash-assq gensym res))))
(set-var-refcount! var (1+ (var-refcount var)))
res))
(_ res)))
(lambda (exp res)
(match exp
(($ <lambda-case> src req opt rest kw init gensyms body alt)
(fold (lambda (name sym res)
(vhash-consq sym (make-var name sym 0 #f) res))
res
(append req (or opt '()) (if rest (list rest) '())
(match kw
((aok? (kw name sym) ...) name)
(_ '())))
gensyms))
(($ <let> src names gensyms vals body)
(fold (lambda (name sym res)
(vhash-consq sym (make-var name sym 0 #f) res))
res names gensyms))
(($ <letrec> src in-order? names gensyms vals body)
(fold (lambda (name sym res)
(vhash-consq sym (make-var name sym 0 #f) res))
res names gensyms))
(($ <fix> src names gensyms vals body)
(fold (lambda (name sym res)
(vhash-consq sym (make-var name sym 0 #f) res))
res names gensyms))
(($ <lexical-set> src name gensym exp)
(set-var-set?! (cdr (vhash-assq gensym res)) #t)
res)
(_ res)))
(lambda (exp res) res)
table exp))
;; Counters are data structures used to limit the effort that peval
;; spends on particular inlining attempts. Each call site in the source
;; program is allocated some amount of effort. If peval exceeds the
;; effort counter while attempting to inline a call site, it aborts the
;; inlining attempt and residualizes a call instead.
;;
;; As there is a fixed number of call sites, that makes `peval' O(N) in
;; the number of call sites in the source program.
;;
;; Counters should limit the size of the residual program as well, but
;; currently this is not implemented.
;;
;; At the top level, before seeing any peval call, there is no counter,
;; because inlining will terminate as there is no recursion. When peval
;; sees a call at the top level, it will make a new counter, allocating
;; it some amount of effort and size.
;;
;; This top-level effort counter effectively "prints money". Within a
;; toplevel counter, no more effort is printed ex nihilo; for a nested
;; inlining attempt to proceed, effort must be transferred from the
;; toplevel counter to the nested counter.
;;
;; Via `data' and `prev', counters form a linked list, terminating in a
;; toplevel counter. In practice `data' will be the a pointer to the
;; source expression of the procedure being inlined.
;;
;; In this way peval can detect a recursive inlining attempt, by walking
;; back on the `prev' links looking for matching `data'. Recursive
;; counters receive a more limited effort allocation, as we don't want
;; to spend all of the effort for a toplevel inlining site on loops.
;; Also, recursive counters don't need a prompt at each inlining site:
;; either the call chain folds entirely, or it will be residualized at
;; its original call.
;;
(define-record-type <counter>
(%make-counter effort size continuation recursive? data prev)
counter?
(effort effort-counter)
(size size-counter)
(continuation counter-continuation)
(recursive? counter-recursive? set-counter-recursive?!)
(data counter-data)
(prev counter-prev))
(define (abort-counter c)
((counter-continuation c)))
(define (record-effort! c)
(let ((e (effort-counter c)))
(if (zero? (variable-ref e))
(abort-counter c)
(variable-set! e (1- (variable-ref e))))))
(define (record-size! c)
(let ((s (size-counter c)))
(if (zero? (variable-ref s))
(abort-counter c)
(variable-set! s (1- (variable-ref s))))))
(define (find-counter data counter)
(and counter
(if (eq? data (counter-data counter))
counter
(find-counter data (counter-prev counter)))))
(define* (transfer! from to #\optional
(effort (variable-ref (effort-counter from)))
(size (variable-ref (size-counter from))))
(define (transfer-counter! from-v to-v amount)
(let* ((from-balance (variable-ref from-v))
(to-balance (variable-ref to-v))
(amount (min amount from-balance)))
(variable-set! from-v (- from-balance amount))
(variable-set! to-v (+ to-balance amount))))
(transfer-counter! (effort-counter from) (effort-counter to) effort)
(transfer-counter! (size-counter from) (size-counter to) size))
(define (make-top-counter effort-limit size-limit continuation data)
(%make-counter (make-variable effort-limit)
(make-variable size-limit)
continuation
#t
data
#f))
(define (make-nested-counter continuation data current)
(let ((c (%make-counter (make-variable 0)
(make-variable 0)
continuation
#f
data
current)))
(transfer! current c)
c))
(define (make-recursive-counter effort-limit size-limit orig current)
(let ((c (%make-counter (make-variable 0)
(make-variable 0)
(counter-continuation orig)
#t
(counter-data orig)
current)))
(transfer! current c effort-limit size-limit)
c))
;; Operand structures allow bindings to be processed lazily instead of
;; eagerly. By doing so, hopefully we can get process them in a way
;; appropriate to their use contexts. Operands also prevent values from
;; being visited multiple times, wasting effort.
;;
;; TODO: Record value size in operand structure?
;;
(define-record-type <operand>
(%make-operand var sym visit source visit-count use-count
copyable? residual-value constant-value alias)
operand?
(var operand-var)
(sym operand-sym)
(visit %operand-visit)
(source operand-source)
(visit-count operand-visit-count set-operand-visit-count!)
(use-count operand-use-count set-operand-use-count!)
(copyable? operand-copyable? set-operand-copyable?!)
(residual-value operand-residual-value %set-operand-residual-value!)
(constant-value operand-constant-value set-operand-constant-value!)
(alias operand-alias set-operand-alias!))
(define* (make-operand var sym #\optional source visit alias)
;; Bind SYM to VAR, with value SOURCE. Unassigned bound operands are
;; considered copyable until we prove otherwise. If we have a source
;; expression, truncate it to one value. Copy propagation does not
;; work on multiply-valued expressions.
(let ((source (and=> source truncate-values)))
(%make-operand var sym visit source 0 0
(and source (not (var-set? var))) #f #f
(and (not (var-set? var)) alias))))
(define* (make-bound-operands vars syms sources visit #\optional aliases)
(if aliases
(map (lambda (name sym source alias)
(make-operand name sym source visit alias))
vars syms sources aliases)
(map (lambda (name sym source)
(make-operand name sym source visit #f))
vars syms sources)))
(define (make-unbound-operands vars syms)
(map make-operand vars syms))
(define (set-operand-residual-value! op val)
(%set-operand-residual-value!
op
(match val
(($ <application> src ($ <primitive-ref> _ 'values) (first))
;; The continuation of a residualized binding does not need the
;; introduced `values' node, so undo the effects of truncation.
first)
(else
val))))
(define* (visit-operand op counter ctx #\optional effort-limit size-limit)
;; Peval is O(N) in call sites of the source program. However,
;; visiting an operand can introduce new call sites. If we visit an
;; operand outside a counter -- i.e., outside an inlining attempt --
;; this can lead to divergence. So, if we are visiting an operand to
;; try to copy it, and there is no counter, make a new one.
;;
;; This will only happen at most as many times as there are lexical
;; references in the source program.
(and (zero? (operand-visit-count op))
(dynamic-wind
(lambda ()
(set-operand-visit-count! op (1+ (operand-visit-count op))))
(lambda ()
(and (operand-source op)
(if (or counter (and (not effort-limit) (not size-limit)))
((%operand-visit op) (operand-source op) counter ctx)
(let/ec k
(define (abort)
;; If we abort when visiting the value in a
;; fresh context, we won't succeed in any future
;; attempt, so don't try to copy it again.
(set-operand-copyable?! op #f)
(k #f))
((%operand-visit op)
(operand-source op)
(make-top-counter effort-limit size-limit abort op)
ctx)))))
(lambda ()
(set-operand-visit-count! op (1- (operand-visit-count op)))))))
;; A helper for constant folding.
;;
(define (types-check? primitive-name args)
(case primitive-name
((values) #t)
((not pair? null? list? symbol? vector? struct?)
(= (length args) 1))
((eq? eqv? equal?)
(= (length args) 2))
;; FIXME: add more cases?
(else #f)))
(define* (peval exp #\optional (cenv (current-module)) (env vlist-null)
#\key
(operator-size-limit 40)
(operand-size-limit 20)
(value-size-limit 10)
(effort-limit 500)
(recursive-effort-limit 100))
"Partially evaluate EXP in compilation environment CENV, with
top-level bindings from ENV and return the resulting expression."
;; This is a simple partial evaluator. It effectively performs
;; constant folding, copy propagation, dead code elimination, and
;; inlining.
;; TODO:
;;
;; Propagate copies across toplevel bindings, if we can prove the
;; bindings to be immutable.
;;
;; Specialize lambda expressions with invariant arguments.
(define local-toplevel-env
;; The top-level environment of the module being compiled.
(match exp
(($ <toplevel-define> _ name)
(vhash-consq name #t env))
(($ <sequence> _ exps)
(fold (lambda (x r)
(match x
(($ <toplevel-define> _ name)
(vhash-consq name #t r))
(_ r)))
env
exps))
(_ env)))
(define (local-toplevel? name)
(vhash-assq name local-toplevel-env))
;; gensym -> <var>
;; renamed-term -> original-term
;;
(define store (build-var-table exp))
(define (record-new-temporary! name sym refcount)
(set! store (vhash-consq sym (make-var name sym refcount #f) store)))
(define (lookup-var sym)
(let ((v (vhash-assq sym store)))
(if v (cdr v) (error "unbound var" sym (vlist->list store)))))
(define (fresh-gensyms vars)
(map (lambda (var)
(let ((new (gensym (string-append (symbol->string (var-name var))
" "))))
(set! store (vhash-consq new var store))
new))
vars))
(define (fresh-temporaries ls)
(map (lambda (elt)
(let ((new (gensym "tmp ")))
(record-new-temporary! 'tmp new 1)
new))
ls))
(define (assigned-lexical? sym)
(var-set? (lookup-var sym)))
(define (lexical-refcount sym)
(var-refcount (lookup-var sym)))
;; ORIG has been alpha-renamed to NEW. Analyze NEW and record a link
;; from it to ORIG.
;;
(define (record-source-expression! orig new)
(set! store (vhash-consq new (source-expression orig) store))
new)
;; Find the source expression corresponding to NEW. Used to detect
;; recursive inlining attempts.
;;
(define (source-expression new)
(let ((x (vhash-assq new store)))
(if x (cdr x) new)))
(define (record-operand-use op)
(set-operand-use-count! op (1+ (operand-use-count op))))
(define (unrecord-operand-uses op n)
(let ((count (- (operand-use-count op) n)))
(when (zero? count)
(set-operand-residual-value! op #f))
(set-operand-use-count! op count)))
(define* (residualize-lexical op #\optional ctx val)
(log 'residualize op)
(record-operand-use op)
(if (memq ctx '(value values))
(set-operand-residual-value! op val))
(make-lexical-ref #f (var-name (operand-var op)) (operand-sym op)))
(define (fold-constants src name args ctx)
(define (apply-primitive name args)
;; todo: further optimize commutative primitives
(catch #t
(lambda ()
(call-with-values
(lambda ()
(case name
((eq? eqv?)
;; Constants will be deduplicated later, but eq?
;; folding can happen now. Anticipate the
;; deduplication by using equal? instead of eq?.
;; Same for eqv?.
(apply equal? args))
(else
(apply (module-ref the-scm-module name) args))))
(lambda results
(values #t results))))
(lambda _
(values #f '()))))
(define (make-values src values)
(match values
((single) single) ; 1 value
((_ ...) ; 0, or 2 or more values
(make-application src (make-primitive-ref src 'values)
values))))
(define (residualize-call)
(make-application src (make-primitive-ref #f name) args))
(cond
((every const? args)
(let-values (((success? values)
(apply-primitive name (map const-exp args))))
(log 'fold success? values name args)
(if success?
(case ctx
((effect) (make-void src))
((test)
;; Values truncation: only take the first
;; value.
(if (pair? values)
(make-const src (car values))
(make-values src '())))
(else
(make-values src (map (cut make-const src <>) values))))
(residualize-call))))
((and (eq? ctx 'effect) (types-check? name args))
(make-void #f))
(else
(residualize-call))))
(define (inline-values src exp nmin nmax consumer)
(let loop ((exp exp))
(match exp
;; Some expression types are always singly-valued.
((or ($ <const>)
($ <void>)
($ <lambda>)
($ <lexical-ref>)
($ <toplevel-ref>)
($ <module-ref>)
($ <primitive-ref>)
($ <dynref>)
($ <lexical-set>) ; FIXME: these set! expressions
($ <toplevel-set>) ; could return zero values in
($ <toplevel-define>) ; the future
($ <module-set>) ;
($ <dynset>) ;
($ <application> src
($ <primitive-ref> _ (? singly-valued-primitive?))))
(and (<= nmin 1) (or (not nmax) (>= nmax 1))
(make-application src (make-lambda #f '() consumer) (list exp))))
;; Statically-known number of values.
(($ <application> src ($ <primitive-ref> _ 'values) vals)
(and (<= nmin (length vals)) (or (not nmax) (>= nmax (length vals)))
(make-application src (make-lambda #f '() consumer) vals)))
;; Not going to copy code into both branches.
(($ <conditional>) #f)
;; Bail on other applications.
(($ <application>) #f)
;; Bail on prompt and abort.
(($ <prompt>) #f)
(($ <abort>) #f)
;; Propagate to tail positions.
(($ <let> src names gensyms vals body)
(let ((body (loop body)))
(and body
(make-let src names gensyms vals body))))
(($ <letrec> src in-order? names gensyms vals body)
(let ((body (loop body)))
(and body
(make-letrec src in-order? names gensyms vals body))))
(($ <fix> src names gensyms vals body)
(let ((body (loop body)))
(and body
(make-fix src names gensyms vals body))))
(($ <let-values> src exp
($ <lambda-case> src2 req opt rest kw inits gensyms body #f))
(let ((body (loop body)))
(and body
(make-let-values src exp
(make-lambda-case src2 req opt rest kw
inits gensyms body #f)))))
(($ <dynwind> src winder body unwinder)
(let ((body (loop body)))
(and body
(make-dynwind src winder body unwinder))))
(($ <dynlet> src fluids vals body)
(let ((body (loop body)))
(and body
(make-dynlet src fluids vals body))))
(($ <sequence> src exps)
(match exps
((head ... tail)
(let ((tail (loop tail)))
(and tail
(make-sequence src (append head (list tail)))))))))))
(define compute-effects
(make-effects-analyzer assigned-lexical?))
(define (constant-expression? x)
;; Return true if X is constant, for the purposes of copying or
;; elision---i.e., if it is known to have no effects, does not
;; allocate storage for a mutable object, and does not access
;; mutable data (like `car' or toplevel references).
(constant? (compute-effects x)))
(define (prune-bindings ops in-order? body counter ctx build-result)
;; This helper handles both `let' and `letrec'/`fix'. In the latter
;; cases we need to make sure that if referenced binding A needs
;; as-yet-unreferenced binding B, that B is processed for value.
;; Likewise if C, when processed for effect, needs otherwise
;; unreferenced D, then D needs to be processed for value too.
;;
(define (referenced? op)
;; When we visit lambdas in operator context, we just copy them,
;; as we will process their body later. However this does have
;; the problem that any free var referenced by the lambda is not
;; marked as needing residualization. Here we hack around this
;; and treat all bindings as referenced if we are in operator
;; context.
(or (eq? ctx 'operator)
(not (zero? (operand-use-count op)))))
;; values := (op ...)
;; effects := (op ...)
(define (residualize values effects)
;; Note, values and effects are reversed.
(cond
(in-order?
(let ((values (filter operand-residual-value ops)))
(if (null? values)
body
(build-result (map (compose var-name operand-var) values)
(map operand-sym values)
(map operand-residual-value values)
body))))
(else
(let ((body
(if (null? effects)
body
(let ((effect-vals (map operand-residual-value effects)))
(make-sequence #f (reverse (cons body effect-vals)))))))
(if (null? values)
body
(let ((values (reverse values)))
(build-result (map (compose var-name operand-var) values)
(map operand-sym values)
(map operand-residual-value values)
body)))))))
;; old := (bool ...)
;; values := (op ...)
;; effects := ((op . value) ...)
(let prune ((old (map referenced? ops)) (values '()) (effects '()))
(let lp ((ops* ops) (values values) (effects effects))
(cond
((null? ops*)
(let ((new (map referenced? ops)))
(if (not (equal? new old))
(prune new values '())
(residualize values
(map (lambda (op val)
(set-operand-residual-value! op val)
op)
(map car effects) (map cdr effects))))))
(else
(let ((op (car ops*)))
(cond
((memq op values)
(lp (cdr ops*) values effects))
((operand-residual-value op)
(lp (cdr ops*) (cons op values) effects))
((referenced? op)
(set-operand-residual-value! op (visit-operand op counter 'value))
(lp (cdr ops*) (cons op values) effects))
(else
(lp (cdr ops*)
values
(let ((effect (visit-operand op counter 'effect)))
(if (void? effect)
effects
(acons op effect effects))))))))))))
(define (small-expression? x limit)
(let/ec k
(tree-il-fold
(lambda (x res) ; leaf
(1+ res))
(lambda (x res) ; down
(1+ res))
(lambda (x res) ; up
(if (< res limit)
res
(k #f)))
0 x)
#t))
(define (extend-env sym op env)
(vhash-consq (operand-sym op) op (vhash-consq sym op env)))
(let loop ((exp exp)
(env vlist-null) ; vhash of gensym -> <operand>
(counter #f) ; inlined call stack
(ctx 'values)) ; effect, value, values, test, operator, or call
(define (lookup var)
(cond
((vhash-assq var env) => cdr)
(else (error "unbound var" var))))
;; Find a value referenced a specific number of times. This is a hack
;; that's used for propagating fresh data structures like rest lists and
;; prompt tags. Usually we wouldn't copy consed data, but we can do so in
;; some special cases like `apply' or prompts if we can account
;; for all of its uses.
;;
;; You don't want to use this in general because it introduces a slight
;; nonlinearity by running peval again (though with a small effort and size
;; counter).
;;
(define (find-definition x n-aliases)
(cond
((lexical-ref? x)
(cond
((lookup (lexical-ref-gensym x))
=> (lambda (op)
(if (var-set? (operand-var op))
(values #f #f)
(let ((y (or (operand-residual-value op)
(visit-operand op counter 'value 10 10)
(operand-source op))))
(cond
((and (lexical-ref? y)
(= (lexical-refcount (lexical-ref-gensym x)) 1))
;; X is a simple alias for Y. Recurse, regardless of
;; the number of aliases we were expecting.
(find-definition y n-aliases))
((= (lexical-refcount (lexical-ref-gensym x)) n-aliases)
;; We found a definition that is aliased the right
;; number of times. We still recurse in case it is a
;; lexical.
(values (find-definition y 1)
op))
(else
;; We can't account for our aliases.
(values #f #f)))))))
(else
;; A formal parameter. Can't say anything about that.
(values #f #f))))
((= n-aliases 1)
;; Not a lexical: success, but only if we are looking for an
;; unaliased value.
(values x #f))
(else (values #f #f))))
(define (visit exp ctx)
(loop exp env counter ctx))
(define (for-value exp) (visit exp 'value))
(define (for-values exp) (visit exp 'values))
(define (for-test exp) (visit exp 'test))
(define (for-effect exp) (visit exp 'effect))
(define (for-call exp) (visit exp 'call))
(define (for-tail exp) (visit exp ctx))
(if counter
(record-effort! counter))
(log 'visit ctx (and=> counter effort-counter)
(unparse-tree-il exp))
(match exp
(($ <const>)
(case ctx
((effect) (make-void #f))
(else exp)))
(($ <void>)
(case ctx
((test) (make-const #f #t))
(else exp)))
(($ <lexical-ref> _ _ gensym)
(log 'begin-copy gensym)
(let lp ((op (lookup gensym)))
(cond
((eq? ctx 'effect)
(log 'lexical-for-effect gensym)
(make-void #f))
((operand-alias op)
;; This is an unassigned operand that simply aliases some
;; other operand. Recurse to avoid residualizing the leaf
;; binding.
=> lp)
((eq? ctx 'call)
;; Don't propagate copies if we are residualizing a call.
(log 'residualize-lexical-call gensym op)
(residualize-lexical op))
((var-set? (operand-var op))
;; Assigned lexicals don't copy-propagate.
(log 'assigned-var gensym op)
(residualize-lexical op))
((not (operand-copyable? op))
;; We already know that this operand is not copyable.
(log 'not-copyable gensym op)
(residualize-lexical op))
((and=> (operand-constant-value op)
(lambda (x) (or (const? x) (void? x) (primitive-ref? x))))
;; A cache hit.
(let ((val (operand-constant-value op)))
(log 'memoized-constant gensym val)
(for-tail val)))
((visit-operand op counter (if (eq? ctx 'values) 'value ctx)
recursive-effort-limit operand-size-limit)
=>
;; If we end up deciding to residualize this value instead of
;; copying it, save that residualized value.
(lambda (val)
(cond
((not (constant-expression? val))
(log 'not-constant gensym op)
;; At this point, ctx is operator, test, or value. A
;; value that is non-constant in one context will be
;; non-constant in the others, so it's safe to record
;; that here, and avoid future visits.
(set-operand-copyable?! op #f)
(residualize-lexical op ctx val))
((or (const? val)
(void? val)
(primitive-ref? val))
;; Always propagate simple values that cannot lead to
;; code bloat.
(log 'copy-simple gensym val)
;; It could be this constant is the result of folding.
;; If that is the case, cache it. This helps loop
;; unrolling get farther.
(if (or (eq? ctx 'value) (eq? ctx 'values))
(begin
(log 'memoize-constant gensym val)
(set-operand-constant-value! op val)))
val)
((= 1 (var-refcount (operand-var op)))
;; Always propagate values referenced only once.
(log 'copy-single gensym val)
val)
;; FIXME: do demand-driven size accounting rather than
;; these heuristics.
((eq? ctx 'operator)
;; A pure expression in the operator position. Inline
;; if it's a lambda that's small enough.
(if (and (lambda? val)
(small-expression? val operator-size-limit))
(begin
(log 'copy-operator gensym val)
val)
(begin
(log 'too-big-for-operator gensym val)
(residualize-lexical op ctx val))))
(else
;; A pure expression, processed for call or for value.
;; Don't inline lambdas, because they will probably won't
;; fold because we don't know the operator.
(if (and (small-expression? val value-size-limit)
(not (tree-il-any lambda? val)))
(begin
(log 'copy-value gensym val)
val)
(begin
(log 'too-big-or-has-lambda gensym val)
(residualize-lexical op ctx val)))))))
(else
;; Visit failed. Either the operand isn't bound, as in
;; lambda formal parameters, or the copy was aborted.
(log 'unbound-or-aborted gensym op)
(residualize-lexical op)))))
(($ <lexical-set> src name gensym exp)
(let ((op (lookup gensym)))
(if (zero? (var-refcount (operand-var op)))
(let ((exp (for-effect exp)))
(if (void? exp)
exp
(make-sequence src (list exp (make-void #f)))))
(begin
(record-operand-use op)
(make-lexical-set src name (operand-sym op) (for-value exp))))))
(($ <let> src
(names ... rest)
(gensyms ... rest-sym)
(vals ... ($ <application> _ ($ <primitive-ref> _ 'list) rest-args))
($ <application> asrc
($ <primitive-ref> _ (or 'apply '@apply))
(proc args ...
($ <lexical-ref> _
(? (cut eq? <> rest))
(? (lambda (sym)
(and (eq? sym rest-sym)
(= (lexical-refcount sym) 1))))))))
(let* ((tmps (make-list (length rest-args) 'tmp))
(tmp-syms (fresh-temporaries tmps)))
(for-tail
(make-let src
(append names tmps)
(append gensyms tmp-syms)
(append vals rest-args)
(make-application
asrc
proc
(append args
(map (cut make-lexical-ref #f <> <>)
tmps tmp-syms)))))))
(($ <let> src names gensyms vals body)
(define (lookup-alias exp)
;; It's very common for macros to introduce something like:
;;
;; ((lambda (x y) ...) x-exp y-exp)
;;
;; In that case you might end up trying to inline something like:
;;
;; (let ((x x-exp) (y y-exp)) ...)
;;
;; But if x-exp is itself a lexical-ref that aliases some much
;; larger expression, perhaps it will fail to inline due to
;; size. However we don't want to introduce a useless alias
;; (in this case, x). So if the RHS of a let expression is a
;; lexical-ref, we record that expression. If we end up having
;; to residualize X, then instead we residualize X-EXP, as long
;; as it isn't assigned.
;;
(match exp
(($ <lexical-ref> _ _ sym)
(let ((op (lookup sym)))
(and (not (var-set? (operand-var op))) op)))
(_ #f)))
(let* ((vars (map lookup-var gensyms))
(new (fresh-gensyms vars))
(ops (make-bound-operands vars new vals
(lambda (exp counter ctx)
(loop exp env counter ctx))
(map lookup-alias vals)))
(env (fold extend-env env gensyms ops))
(body (loop body env counter ctx)))
(cond
((const? body)
(for-tail (make-sequence src (append vals (list body)))))
((and (lexical-ref? body)
(memq (lexical-ref-gensym body) new))
(let ((sym (lexical-ref-gensym body))
(pairs (map cons new vals)))
;; (let ((x foo) (y bar) ...) x) => (begin bar ... foo)
(for-tail
(make-sequence
src
(append (map cdr (alist-delete sym pairs eq?))
(list (assq-ref pairs sym)))))))
(else
;; Only include bindings for which lexical references
;; have been residualized.
(prune-bindings ops #f body counter ctx
(lambda (names gensyms vals body)
(if (null? names) (error "what!" names))
(make-let src names gensyms vals body)))))))
(($ <letrec> src in-order? names gensyms vals body)
;; Note the difference from the `let' case: here we use letrec*
;; so that the `visit' procedure for the new operands closes over
;; an environment that includes the operands. Also we don't try
;; to elide aliases, because we can't sensibly reduce something
;; like (letrec ((a b) (b a)) a).
(letrec* ((visit (lambda (exp counter ctx)
(loop exp env* counter ctx)))
(vars (map lookup-var gensyms))
(new (fresh-gensyms vars))
(ops (make-bound-operands vars new vals visit))
(env* (fold extend-env env gensyms ops))
(body* (visit body counter ctx)))
(if (and (const? body*) (every constant-expression? vals))
;; We may have folded a loop completely, even though there
;; might be cyclical references between the bound values.
;; Handle this degenerate case specially.
body*
(prune-bindings ops in-order? body* counter ctx
(lambda (names gensyms vals body)
(make-letrec src in-order?
names gensyms vals body))))))
(($ <fix> src names gensyms vals body)
(letrec* ((visit (lambda (exp counter ctx)
(loop exp env* counter ctx)))
(vars (map lookup-var gensyms))
(new (fresh-gensyms vars))
(ops (make-bound-operands vars new vals visit))
(env* (fold extend-env env gensyms ops))
(body* (visit body counter ctx)))
(if (const? body*)
body*
(prune-bindings ops #f body* counter ctx
(lambda (names gensyms vals body)
(make-fix src names gensyms vals body))))))
(($ <let-values> lv-src producer consumer)
;; Peval the producer, then try to inline the consumer into
;; the producer. If that succeeds, peval again. Otherwise
;; reconstruct the let-values, pevaling the consumer.
(let ((producer (for-values producer)))
(or (match consumer
(($ <lambda-case> src req opt rest #f inits gensyms body #f)
(let* ((nmin (length req))
(nmax (and (not rest) (+ nmin (if opt (length opt) 0)))))
(cond
((inline-values lv-src producer nmin nmax consumer)
=> for-tail)
(else #f))))
(_ #f))
(make-let-values lv-src producer (for-tail consumer)))))
(($ <dynwind> src winder body unwinder)
(let ((pre (for-value winder))
(body (for-tail body))
(post (for-value unwinder)))
(cond
((not (constant-expression? pre))
(cond
((not (constant-expression? post))
(let ((pre-sym (gensym "pre-")) (post-sym (gensym "post-")))
(record-new-temporary! 'pre pre-sym 1)
(record-new-temporary! 'post post-sym 1)
(make-let src '(pre post) (list pre-sym post-sym) (list pre post)
(make-dynwind src
(make-lexical-ref #f 'pre pre-sym)
body
(make-lexical-ref #f 'post post-sym)))))
(else
(let ((pre-sym (gensym "pre-")))
(record-new-temporary! 'pre pre-sym 1)
(make-let src '(pre) (list pre-sym) (list pre)
(make-dynwind src
(make-lexical-ref #f 'pre pre-sym)
body
post))))))
((not (constant-expression? post))
(let ((post-sym (gensym "post-")))
(record-new-temporary! 'post post-sym 1)
(make-let src '(post) (list post-sym) (list post)
(make-dynwind src
pre
body
(make-lexical-ref #f 'post post-sym)))))
(else
(make-dynwind src pre body post)))))
(($ <dynlet> src fluids vals body)
(make-dynlet src (map for-value fluids) (map for-value vals)
(for-tail body)))
(($ <dynref> src fluid)
(make-dynref src (for-value fluid)))
(($ <dynset> src fluid exp)
(make-dynset src (for-value fluid) (for-value exp)))
(($ <toplevel-ref> src (? effect-free-primitive? name))
(if (local-toplevel? name)
exp
(let ((exp (resolve-primitives! exp cenv)))
(if (primitive-ref? exp)
(for-tail exp)
exp))))
(($ <toplevel-ref>)
;; todo: open private local bindings.
exp)
(($ <module-ref> src module (? effect-free-primitive? name) #f)
(let ((module (false-if-exception
(resolve-module module #\ensure #f))))
(if (module? module)
(let ((var (module-variable module name)))
(if (eq? var (module-variable the-scm-module name))
(make-primitive-ref src name)
exp))
exp)))
(($ <module-ref>)
exp)
(($ <module-set> src mod name public? exp)
(make-module-set src mod name public? (for-value exp)))
(($ <toplevel-define> src name exp)
(make-toplevel-define src name (for-value exp)))
(($ <toplevel-set> src name exp)
(make-toplevel-set src name (for-value exp)))
(($ <primitive-ref>)
(case ctx
((effect) (make-void #f))
((test) (make-const #f #t))
(else exp)))
(($ <conditional> src condition subsequent alternate)
(define (call-with-failure-thunk exp proc)
(match exp
(($ <application> _ _ ()) (proc exp))
(($ <const>) (proc exp))
(($ <void>) (proc exp))
(($ <lexical-ref>) (proc exp))
(_
(let ((t (gensym "failure-")))
(record-new-temporary! 'failure t 2)
(make-let
src (list 'failure) (list t)
(list
(make-lambda
#f '()
(make-lambda-case #f '() #f #f #f '() '() exp #f)))
(proc (make-application #f (make-lexical-ref #f 'failure t)
'())))))))
(define (simplify-conditional c)
(match c
;; Swap the arms of (if (not FOO) A B), to simplify.
(($ <conditional> src
($ <application> _ ($ <primitive-ref> _ 'not) (pred))
subsequent alternate)
(simplify-conditional
(make-conditional src pred alternate subsequent)))
;; Special cases for common tests in the predicates of chains
;; of if expressions.
(($ <conditional> src
($ <conditional> src* outer-test inner-test ($ <const> _ #f))
inner-subsequent
alternate)
(let lp ((alternate alternate))
(match alternate
;; Lift a common repeated test out of a chain of if
;; expressions.
(($ <conditional> _ (? (cut tree-il=? outer-test <>))
other-subsequent alternate)
(make-conditional
src outer-test
(simplify-conditional
(make-conditional src* inner-test inner-subsequent
other-subsequent))
alternate))
;; Likewise, but punching through any surrounding
;; failure continuations.
(($ <let> let-src (name) (sym) ((and thunk ($ <lambda>))) body)
(make-let
let-src (list name) (list sym) (list thunk)
(lp body)))
;; Otherwise, rotate AND tests to expose a simple
;; condition in the front. Although this may result in
;; lexically binding failure thunks, the thunks will be
;; compiled to labels allocation, so there's no actual
;; code growth.
(_
(call-with-failure-thunk
alternate
(lambda (failure)
(make-conditional
src outer-test
(simplify-conditional
(make-conditional src* inner-test inner-subsequent failure))
failure)))))))
(_ c)))
(match (for-test condition)
(($ <const> _ val)
(if val
(for-tail subsequent)
(for-tail alternate)))
(c
(simplify-conditional
(make-conditional src c (for-tail subsequent)
(for-tail alternate))))))
(($ <application> src
($ <primitive-ref> _ '@call-with-values)
(producer
($ <lambda> _ _
(and consumer
;; No optional or kwargs.
($ <lambda-case>
_ req #f rest #f () gensyms body #f)))))
(for-tail (make-let-values src (make-application src producer '())
consumer)))
(($ <application> src ($ <primitive-ref> _ 'values) exps)
(cond
((null? exps)
(if (eq? ctx 'effect)
(make-void #f)
exp))
(else
(let ((vals (map for-value exps)))
(if (and (case ctx
((value test effect) #t)
(else (null? (cdr vals))))
(every singly-valued-expression? vals))
(for-tail (make-sequence src (append (cdr vals) (list (car vals)))))
(make-application src (make-primitive-ref #f 'values) vals))))))
(($ <application> src (and apply ($ <primitive-ref> _ (or 'apply '@apply)))
(proc args ... tail))
(let lp ((tail* (find-definition tail 1)) (speculative? #t))
(define (copyable? x)
;; Inlining a result from find-definition effectively copies it,
;; relying on the let-pruning to remove its original binding. We
;; shouldn't copy non-constant expressions.
(or (not speculative?) (constant-expression? x)))
(match tail*
(($ <const> _ (args* ...))
(let ((args* (map (cut make-const #f <>) args*)))
(for-tail (make-application src proc (append args args*)))))
(($ <application> _ ($ <primitive-ref> _ 'cons)
((and head (? copyable?)) (and tail (? copyable?))))
(for-tail (make-application src apply
(cons proc
(append args (list head tail))))))
(($ <application> _ ($ <primitive-ref> _ 'list)
(and args* ((? copyable?) ...)))
(for-tail (make-application src proc (append args args*))))
(tail*
(if speculative?
(lp (for-value tail) #f)
(let ((args (append (map for-value args) (list tail*))))
(make-application src apply
(cons (for-value proc) args))))))))
(($ <application> src orig-proc orig-args)
;; todo: augment the global env with specialized functions
(let revisit-proc ((proc (visit orig-proc 'operator)))
(match proc
(($ <primitive-ref> _ (? constructor-primitive? name))
(cond
((and (memq ctx '(effect test))
(match (cons name orig-args)
((or ('cons _ _)
('list . _)
('vector . _)
('make-prompt-tag)
('make-prompt-tag ($ <const> _ (? string?))))
#t)
(_ #f)))
;; Some expressions can be folded without visiting the
;; arguments for value.
(let ((res (if (eq? ctx 'effect)
(make-void #f)
(make-const #f #t))))
(for-tail (make-sequence src (append orig-args (list res))))))
(else
(match (cons name (map for-value orig-args))
(('cons head tail)
(match tail
(($ <const> src (? (cut eq? <> '())))
(make-application src (make-primitive-ref #f 'list)
(list head)))
(($ <application> src ($ <primitive-ref> _ 'list) elts)
(make-application src (make-primitive-ref #f 'list)
(cons head elts)))
(_ (make-application src proc (list head tail)))))
((_ . args)
(make-application src proc args))))))
(($ <primitive-ref> _ (? accessor-primitive? name))
(match (cons name (map for-value orig-args))
;; FIXME: these for-tail recursions could take place outside
;; an effort counter.
(('car ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
(for-tail (make-sequence src (list tail head))))
(('cdr ($ <application> src ($ <primitive-ref> _ 'cons) (head tail)))
(for-tail (make-sequence src (list head tail))))
(('car ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
(for-tail (make-sequence src (append tail (list head)))))
(('cdr ($ <application> src ($ <primitive-ref> _ 'list) (head . tail)))
(for-tail (make-sequence
src
(list head
(make-application
src (make-primitive-ref #f 'list) tail)))))
(('car ($ <const> src (head . tail)))
(for-tail (make-const src head)))
(('cdr ($ <const> src (head . tail)))
(for-tail (make-const src tail)))
(((or 'memq 'memv) k ($ <const> _ (elts ...)))
;; FIXME: factor
(case ctx
((effect)
(for-tail
(make-sequence src (list k (make-void #f)))))
((test)
(cond
((const? k)
;; A shortcut. The `else' case would handle it, but
;; this way is faster.
(let ((member (case name ((memq) memq) ((memv) memv))))
(make-const #f (and (member (const-exp k) elts) #t))))
((null? elts)
(for-tail
(make-sequence src (list k (make-const #f #f)))))
(else
(let ((t (gensym "t-"))
(eq (if (eq? name 'memq) 'eq? 'eqv?)))
(record-new-temporary! 't t (length elts))
(for-tail
(make-let
src (list 't) (list t) (list k)
(let lp ((elts elts))
(define test
(make-application
#f (make-primitive-ref #f eq)
(list (make-lexical-ref #f 't t)
(make-const #f (car elts)))))
(if (null? (cdr elts))
test
(make-conditional src test
(make-const #f #t)
(lp (cdr elts)))))))))))
(else
(cond
((const? k)
(let ((member (case name ((memq) memq) ((memv) memv))))
(make-const #f (member (const-exp k) elts))))
((null? elts)
(for-tail (make-sequence src (list k (make-const #f #f)))))
(else
(make-application src proc (list k (make-const #f elts))))))))
((_ . args)
(or (fold-constants src name args ctx)
(make-application src proc args)))))
(($ <primitive-ref> _ (? effect-free-primitive? name))
(let ((args (map for-value orig-args)))
(or (fold-constants src name args ctx)
(make-application src proc args))))
(($ <lambda> _ _
($ <lambda-case> _ req opt rest #f inits gensyms body #f))
;; Simple case: no keyword arguments.
;; todo: handle the more complex cases
(let* ((nargs (length orig-args))
(nreq (length req))
(nopt (if opt (length opt) 0))
(key (source-expression proc)))
(define (inlined-application)
(cond
((= nargs (+ nreq nopt))
(make-let src
(append req
(or opt '())
(if rest (list rest) '()))
gensyms
(append orig-args
(if rest
(list (make-const #f '()))
'()))
body))
((> nargs (+ nreq nopt))
(make-let src
(append req
(or opt '())
(list rest))
gensyms
(append (take orig-args (+ nreq nopt))
(list (make-application
#f
(make-primitive-ref #f 'list)
(drop orig-args (+ nreq nopt)))))
body))
(else
;; Here we handle the case where nargs < nreq + nopt,
;; so the rest argument (if any) will be empty, and
;; there will be optional arguments that rely on their
;; default initializers.
;;
;; The default initializers of optional arguments
;; may refer to earlier arguments, so in the general
;; case we must expand into a series of nested let
;; expressions.
;;
;; In the generated code, the outermost let
;; expression will bind all arguments provided by
;; the application's argument list, as well as the
;; empty rest argument, if any. Each remaining
;; optional argument that relies on its default
;; initializer will be bound within an inner let.
;;
;; rest-gensyms, rest-vars and rest-inits will have
;; either 0 or 1 elements. They are oddly named, but
;; allow simpler code below.
(let*-values
(((non-rest-gensyms rest-gensyms)
(split-at gensyms (+ nreq nopt)))
((provided-gensyms default-gensyms)
(split-at non-rest-gensyms nargs))
((provided-vars default-vars)
(split-at (append req opt) nargs))
((rest-vars)
(if rest (list rest) '()))
((rest-inits)
(if rest
(list (make-const #f '()))
'()))
((default-inits)
(drop inits (- nargs nreq))))
(make-let src
(append provided-vars rest-vars)
(append provided-gensyms rest-gensyms)
(append orig-args rest-inits)
(fold-right (lambda (var gensym init body)
(make-let src
(list var)
(list gensym)
(list init)
body))
body
default-vars
default-gensyms
default-inits))))))
(cond
((or (< nargs nreq) (and (not rest) (> nargs (+ nreq nopt))))
;; An error, or effecting arguments.
(make-application src (for-call orig-proc)
(map for-value orig-args)))
((or (and=> (find-counter key counter) counter-recursive?)
(lambda? orig-proc))
;; A recursive call, or a lambda in the operator
;; position of the source expression. Process again in
;; tail context.
;;
;; In the recursive case, mark intervening counters as
;; recursive, so we can handle a toplevel counter that
;; recurses mutually with some other procedure.
;; Otherwise, the next time we see the other procedure,
;; the effort limit would be clamped to 100.
;;
(let ((found (find-counter key counter)))
(if (and found (counter-recursive? found))
(let lp ((counter counter))
(if (not (eq? counter found))
(begin
(set-counter-recursive?! counter #t)
(lp (counter-prev counter)))))))
(log 'inline-recurse key)
(loop (inlined-application) env counter ctx))
(else
;; An integration at the top-level, the first
;; recursion of a recursive procedure, or a nested
;; integration of a procedure that hasn't been seen
;; yet.
(log 'inline-begin exp)
(let/ec k
(define (abort)
(log 'inline-abort exp)
(k (make-application src (for-call orig-proc)
(map for-value orig-args))))
(define new-counter
(cond
;; These first two cases will transfer effort
;; from the current counter into the new
;; counter.
((find-counter key counter)
=> (lambda (prev)
(make-recursive-counter recursive-effort-limit
operand-size-limit
prev counter)))
(counter
(make-nested-counter abort key counter))
;; This case opens a new account, effectively
;; printing money. It should only do so once
;; for each call site in the source program.
(else
(make-top-counter effort-limit operand-size-limit
abort key))))
(define result
(loop (inlined-application) env new-counter ctx))
(if counter
;; The nested inlining attempt succeeded.
;; Deposit the unspent effort and size back
;; into the current counter.
(transfer! new-counter counter))
(log 'inline-end result exp)
result)))))
(($ <let> _ _ _ vals _)
;; Attempt to inline `let' in the operator position.
;;
;; We have to re-visit the proc in value mode, since the
;; `let' bindings might have been introduced or renamed,
;; whereas the lambda (if any) in operator position has not
;; been renamed.
(if (or (and-map constant-expression? vals)
(and-map constant-expression? orig-args))
;; The arguments and the let-bound values commute.
(match (for-value orig-proc)
(($ <let> lsrc names syms vals body)
(log 'inline-let orig-proc)
(for-tail
(make-let lsrc names syms vals
(make-application src body orig-args))))
;; It's possible for a `let' to go away after the
;; visit due to the fact that visiting a procedure in
;; value context will prune unused bindings, whereas
;; visiting in operator mode can't because it doesn't
;; traverse through lambdas. In that case re-visit
;; the procedure.
(proc (revisit-proc proc)))
(make-application src (for-call orig-proc)
(map for-value orig-args))))
(_
(make-application src (for-call orig-proc)
(map for-value orig-args))))))
(($ <lambda> src meta body)
(case ctx
((effect) (make-void #f))
((test) (make-const #f #t))
((operator) exp)
(else (record-source-expression!
exp
(make-lambda src meta (and body (for-values body)))))))
(($ <lambda-case> src req opt rest kw inits gensyms body alt)
(define (lift-applied-lambda body gensyms)
(and (not opt) rest (not kw)
(match body
(($ <application> _
($ <primitive-ref> _ '@apply)
(($ <lambda> _ _ (and lcase ($ <lambda-case>)))
($ <lexical-ref> _ _ sym)
...))
(and (equal? sym gensyms)
(not (lambda-case-alternate lcase))
lcase))
(_ #f))))
(let* ((vars (map lookup-var gensyms))
(new (fresh-gensyms vars))
(env (fold extend-env env gensyms
(make-unbound-operands vars new)))
(new-sym (lambda (old)
(operand-sym (cdr (vhash-assq old env)))))
(body (loop body env counter ctx)))
(or
;; (lambda args (apply (lambda ...) args)) => (lambda ...)
(lift-applied-lambda body new)
(make-lambda-case src req opt rest
(match kw
((aok? (kw name old) ...)
(cons aok? (map list kw name (map new-sym old))))
(_ #f))
(map (cut loop <> env counter 'value) inits)
new
body
(and alt (for-tail alt))))))
(($ <sequence> src exps)
(let lp ((exps exps) (effects '()))
(match exps
((last)
(if (null? effects)
(for-tail last)
(make-sequence
src
(reverse (cons (for-tail last) effects)))))
((head . rest)
(let ((head (for-effect head)))
(cond
((sequence? head)
(lp (append (sequence-exps head) rest) effects))
((void? head)
(lp rest effects))
(else
(lp rest (cons head effects)))))))))
(($ <prompt> src tag body handler)
(define (make-prompt-tag? x)
(match x
(($ <application> _ ($ <primitive-ref> _ 'make-prompt-tag)
(or () ((? constant-expression?))))
#t)
(_ #f)))
(let ((tag (for-value tag))
(body (for-values body)))
(cond
((find-definition tag 1)
(lambda (val op)
(make-prompt-tag? val))
=> (lambda (val op)
;; There is no way that an <abort> could know the tag
;; for this <prompt>, so we can elide the <prompt>
;; entirely.
(unrecord-operand-uses op 1)
body))
((find-definition tag 2)
(lambda (val op)
(and (make-prompt-tag? val)
(abort? body)
(tree-il=? (abort-tag body) tag)))
=> (lambda (val op)
;; (let ((t (make-prompt-tag)))
;; (call-with-prompt t
;; (lambda () (abort-to-prompt t val ...))
;; (lambda (k arg ...) e ...)))
;; => (let-values (((k arg ...) (values values val ...)))
;; e ...)
(unrecord-operand-uses op 2)
(for-tail
(make-let-values
src
(make-application #f (make-primitive-ref #f 'apply)
`(,(make-primitive-ref #f 'values)
,(make-primitive-ref #f 'values)
,@(abort-args body)
,(abort-tail body)))
(for-tail handler)))))
(else
(make-prompt src tag body (for-tail handler))))))
(($ <abort> src tag args tail)
(make-abort src (for-value tag) (map for-value args)
(for-value tail))))))
;;; open-coding primitive procedures
;; Copyright (C) 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il primitives)
#\use-module (system base pmatch)
#\use-module (ice-9 match)
#\use-module (rnrs bytevectors)
#\use-module (system base syntax)
#\use-module (language tree-il)
#\use-module (srfi srfi-4)
#\use-module (srfi srfi-16)
#\export (resolve-primitives! add-interesting-primitive!
expand-primitives!
effect-free-primitive? effect+exception-free-primitive?
constructor-primitive? accessor-primitive?
singly-valued-primitive? bailout-primitive?
negate-primitive))
;; When adding to this, be sure to update *multiply-valued-primitives*
;; if appropriate.
(define *interesting-primitive-names*
'(apply @apply
call-with-values @call-with-values
call-with-current-continuation @call-with-current-continuation
call/cc
dynamic-wind
@dynamic-wind
values
eq? eqv? equal?
memq memv
= < > <= >= zero? positive? negative?
+ * - / 1- 1+ quotient remainder modulo
ash logand logior logxor lognot
not
pair? null? list? symbol? vector? string? struct? number? char?
complex? real? rational? inf? nan? integer? exact? inexact? even? odd?
char<? char<=? char>=? char>?
integer->char char->integer number->string string->number
acons cons cons*
list vector
car cdr
set-car! set-cdr!
caar cadr cdar cddr
caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
vector-ref vector-set!
variable-ref variable-set!
variable-bound?
fluid-ref fluid-set!
@prompt call-with-prompt @abort abort-to-prompt
make-prompt-tag
throw error scm-error
string-length string-ref string-set!
struct-vtable make-struct struct-ref struct-set!
bytevector-u8-ref bytevector-u8-set!
bytevector-s8-ref bytevector-s8-set!
u8vector-ref u8vector-set! s8vector-ref s8vector-set!
bytevector-u16-ref bytevector-u16-set!
bytevector-u16-native-ref bytevector-u16-native-set!
bytevector-s16-ref bytevector-s16-set!
bytevector-s16-native-ref bytevector-s16-native-set!
u16vector-ref u16vector-set! s16vector-ref s16vector-set!
bytevector-u32-ref bytevector-u32-set!
bytevector-u32-native-ref bytevector-u32-native-set!
bytevector-s32-ref bytevector-s32-set!
bytevector-s32-native-ref bytevector-s32-native-set!
u32vector-ref u32vector-set! s32vector-ref s32vector-set!
bytevector-u64-ref bytevector-u64-set!
bytevector-u64-native-ref bytevector-u64-native-set!
bytevector-s64-ref bytevector-s64-set!
bytevector-s64-native-ref bytevector-s64-native-set!
u64vector-ref u64vector-set! s64vector-ref s64vector-set!
bytevector-ieee-single-ref bytevector-ieee-single-set!
bytevector-ieee-single-native-ref bytevector-ieee-single-native-set!
bytevector-ieee-double-ref bytevector-ieee-double-set!
bytevector-ieee-double-native-ref bytevector-ieee-double-native-set!
f32vector-ref f32vector-set! f64vector-ref f64vector-set!))
(define (add-interesting-primitive! name)
(hashq-set! *interesting-primitive-vars*
(or (module-variable (current-module) name)
(error "unbound interesting primitive" name))
name))
(define *interesting-primitive-vars* (make-hash-table))
(for-each add-interesting-primitive! *interesting-primitive-names*)
(define *primitive-constructors*
;; Primitives that return a fresh object.
'(acons cons cons* list vector make-struct make-struct/no-tail
make-prompt-tag))
(define *primitive-accessors*
;; Primitives that are pure, but whose result depends on the mutable
;; memory pointed to by their operands.
'(vector-ref
car cdr
memq memv
struct-ref
string-ref
bytevector-u8-ref bytevector-s8-ref
bytevector-u16-ref bytevector-u16-native-ref
bytevector-s16-ref bytevector-s16-native-ref
bytevector-u32-ref bytevector-u32-native-ref
bytevector-s32-ref bytevector-s32-native-ref
bytevector-u64-ref bytevector-u64-native-ref
bytevector-s64-ref bytevector-s64-native-ref
bytevector-ieee-single-ref bytevector-ieee-single-native-ref
bytevector-ieee-double-ref bytevector-ieee-double-native-ref))
(define *effect-free-primitives*
`(values
eq? eqv? equal?
= < > <= >= zero? positive? negative?
ash logand logior logxor lognot
+ * - / 1- 1+ quotient remainder modulo
not
pair? null? list? symbol? vector? struct? string? number? char?
complex? real? rational? inf? nan? integer? exact? inexact? even? odd?
char<? char<=? char>=? char>?
integer->char char->integer number->string string->number
struct-vtable
string-length
;; These all should get expanded out by expand-primitives!.
caar cadr cdar cddr
caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
,@*primitive-constructors*
,@*primitive-accessors*))
;; Like *effect-free-primitives* above, but further restricted in that they
;; cannot raise exceptions.
(define *effect+exception-free-primitives*
'(values
eq? eqv? equal?
not
pair? null? list? symbol? vector? struct? string? number? char?
acons cons cons* list vector))
;; Primitives that don't always return one value.
(define *multiply-valued-primitives*
'(apply @apply
call-with-values @call-with-values
call-with-current-continuation @call-with-current-continuation
call/cc
dynamic-wind
@dynamic-wind
values
@prompt call-with-prompt @abort abort-to-prompt))
;; Procedures that cause a nonlocal, non-resumable abort.
(define *bailout-primitives*
'(throw error scm-error))
;; Negatable predicates.
(define *negatable-primitives*
'((even? . odd?)
(exact? . inexact?)
;; (< <= > >=) are not negatable because of NaNs.
(char<? . char>=?)
(char>? . char<=?)))
(define *effect-free-primitive-table* (make-hash-table))
(define *effect+exceptions-free-primitive-table* (make-hash-table))
(define *multiply-valued-primitive-table* (make-hash-table))
(define *bailout-primitive-table* (make-hash-table))
(define *negatable-primitive-table* (make-hash-table))
(for-each (lambda (x)
(hashq-set! *effect-free-primitive-table* x #t))
*effect-free-primitives*)
(for-each (lambda (x)
(hashq-set! *effect+exceptions-free-primitive-table* x #t))
*effect+exception-free-primitives*)
(for-each (lambda (x)
(hashq-set! *multiply-valued-primitive-table* x #t))
*multiply-valued-primitives*)
(for-each (lambda (x)
(hashq-set! *bailout-primitive-table* x #t))
*bailout-primitives*)
(for-each (lambda (x)
(hashq-set! *negatable-primitive-table* (car x) (cdr x))
(hashq-set! *negatable-primitive-table* (cdr x) (car x)))
*negatable-primitives*)
(define (constructor-primitive? prim)
(memq prim *primitive-constructors*))
(define (accessor-primitive? prim)
(memq prim *primitive-accessors*))
(define (effect-free-primitive? prim)
(hashq-ref *effect-free-primitive-table* prim))
(define (effect+exception-free-primitive? prim)
(hashq-ref *effect+exceptions-free-primitive-table* prim))
(define (singly-valued-primitive? prim)
(not (hashq-ref *multiply-valued-primitive-table* prim)))
(define (bailout-primitive? prim)
(hashq-ref *bailout-primitive-table* prim))
(define (negate-primitive prim)
(hashq-ref *negatable-primitive-table* prim))
(define (resolve-primitives! x mod)
(post-order!
(lambda (x)
(record-case x
((<toplevel-ref> src name)
(and=> (hashq-ref *interesting-primitive-vars*
(module-variable mod name))
(lambda (name) (make-primitive-ref src name))))
((<module-ref> src mod name public?)
(and=> (and=> (resolve-module mod)
(if public?
module-public-interface
identity))
(lambda (m)
(and=> (hashq-ref *interesting-primitive-vars*
(module-variable m name))
(lambda (name)
(make-primitive-ref src name))))))
(else #f)))
x))
(define *primitive-expand-table* (make-hash-table))
(define (expand-primitives! x)
(pre-order!
(lambda (x)
(record-case x
((<application> src proc args)
(and (primitive-ref? proc)
(let ((expand (hashq-ref *primitive-expand-table*
(primitive-ref-name proc))))
(and expand (apply expand src args)))))
(else #f)))
x))
;;; I actually did spend about 10 minutes trying to redo this with
;;; syntax-rules. Patches appreciated.
;;;
(define-macro (define-primitive-expander sym . clauses)
(define (inline-args args)
(let lp ((in args) (out '()))
(cond ((null? in) `(list ,@(reverse out)))
((symbol? in) `(cons* ,@(reverse out) ,in))
((pair? (car in))
(lp (cdr in)
(cons (if (eq? (caar in) 'quote)
`(make-const src ,@(cdar in))
`(make-application src (make-primitive-ref src ',(caar in))
,(inline-args (cdar in))))
out)))
((symbol? (car in))
;; assume it's locally bound
(lp (cdr in) (cons (car in) out)))
((self-evaluating? (car in))
(lp (cdr in) (cons `(make-const src ,(car in)) out)))
(else
(error "what what" (car in))))))
(define (consequent exp)
(cond
((pair? exp)
(pmatch exp
((if ,test ,then ,else)
`(if ,test
,(consequent then)
,(consequent else)))
(else
`(make-application src (make-primitive-ref src ',(car exp))
,(inline-args (cdr exp))))))
((symbol? exp)
;; assume locally bound
exp)
((number? exp)
`(make-const src ,exp))
((not exp)
;; failed match
#f)
(else (error "bad consequent yall" exp))))
`(hashq-set! *primitive-expand-table*
',sym
(match-lambda*
,@(let lp ((in clauses) (out '()))
(if (null? in)
(reverse (cons '(_ #f) out))
(lp (cddr in)
(cons `((src . ,(car in))
,(consequent (cadr in)))
out)))))))
(define-primitive-expander zero? (x)
(= x 0))
(define-primitive-expander positive? (x)
(> x 0))
(define-primitive-expander negative? (x)
(< x 0))
;; FIXME: All the code that uses `const?' is redundant with `peval'.
(define-primitive-expander +
() 0
(x) (values x)
(x y) (if (and (const? y) (eqv? (const-exp y) 1))
(1+ x)
(if (and (const? y) (eqv? (const-exp y) -1))
(1- x)
(if (and (const? x) (eqv? (const-exp x) 1))
(1+ y)
(if (and (const? x) (eqv? (const-exp x) -1))
(1- y)
(+ x y)))))
(x y z ... last) (+ (+ x y . z) last))
(define-primitive-expander *
() 1
(x) (values x)
(x y z ... last) (* (* x y . z) last))
(define-primitive-expander -
(x) (- 0 x)
(x y) (if (and (const? y) (eqv? (const-exp y) 1))
(1- x)
(- x y))
(x y z ... last) (- (- x y . z) last))
(define-primitive-expander /
(x) (/ 1 x)
(x y z ... last) (/ (/ x y . z) last))
(define-primitive-expander logior
() 0
(x) (logior x 0)
(x y) (logior x y)
(x y z ... last) (logior (logior x y . z) last))
(define-primitive-expander logand
() -1
(x) (logand x -1)
(x y) (logand x y)
(x y z ... last) (logand (logand x y . z) last))
(define-primitive-expander caar (x) (car (car x)))
(define-primitive-expander cadr (x) (car (cdr x)))
(define-primitive-expander cdar (x) (cdr (car x)))
(define-primitive-expander cddr (x) (cdr (cdr x)))
(define-primitive-expander caaar (x) (car (car (car x))))
(define-primitive-expander caadr (x) (car (car (cdr x))))
(define-primitive-expander cadar (x) (car (cdr (car x))))
(define-primitive-expander caddr (x) (car (cdr (cdr x))))
(define-primitive-expander cdaar (x) (cdr (car (car x))))
(define-primitive-expander cdadr (x) (cdr (car (cdr x))))
(define-primitive-expander cddar (x) (cdr (cdr (car x))))
(define-primitive-expander cdddr (x) (cdr (cdr (cdr x))))
(define-primitive-expander caaaar (x) (car (car (car (car x)))))
(define-primitive-expander caaadr (x) (car (car (car (cdr x)))))
(define-primitive-expander caadar (x) (car (car (cdr (car x)))))
(define-primitive-expander caaddr (x) (car (car (cdr (cdr x)))))
(define-primitive-expander cadaar (x) (car (cdr (car (car x)))))
(define-primitive-expander cadadr (x) (car (cdr (car (cdr x)))))
(define-primitive-expander caddar (x) (car (cdr (cdr (car x)))))
(define-primitive-expander cadddr (x) (car (cdr (cdr (cdr x)))))
(define-primitive-expander cdaaar (x) (cdr (car (car (car x)))))
(define-primitive-expander cdaadr (x) (cdr (car (car (cdr x)))))
(define-primitive-expander cdadar (x) (cdr (car (cdr (car x)))))
(define-primitive-expander cdaddr (x) (cdr (car (cdr (cdr x)))))
(define-primitive-expander cddaar (x) (cdr (cdr (car (car x)))))
(define-primitive-expander cddadr (x) (cdr (cdr (car (cdr x)))))
(define-primitive-expander cdddar (x) (cdr (cdr (cdr (car x)))))
(define-primitive-expander cddddr (x) (cdr (cdr (cdr (cdr x)))))
(define-primitive-expander cons*
(x) (values x)
(x y) (cons x y)
(x y . rest) (cons x (cons* y . rest)))
(define-primitive-expander acons (x y z)
(cons (cons x y) z))
(define-primitive-expander apply (f a0 . args)
(@apply f a0 . args))
(define-primitive-expander call-with-values (producer consumer)
(@call-with-values producer consumer))
(define-primitive-expander call-with-current-continuation (proc)
(@call-with-current-continuation proc))
(define-primitive-expander call/cc (proc)
(@call-with-current-continuation proc))
(define-primitive-expander make-struct (vtable tail-size . args)
(if (and (const? tail-size)
(let ((n (const-exp tail-size)))
(and (number? n) (exact? n) (zero? n))))
(make-struct/no-tail vtable . args)
#f))
(define-primitive-expander u8vector-ref (vec i)
(bytevector-u8-ref vec i))
(define-primitive-expander u8vector-set! (vec i x)
(bytevector-u8-set! vec i x))
(define-primitive-expander s8vector-ref (vec i)
(bytevector-s8-ref vec i))
(define-primitive-expander s8vector-set! (vec i x)
(bytevector-s8-set! vec i x))
(define-primitive-expander u16vector-ref (vec i)
(bytevector-u16-native-ref vec (* i 2)))
(define-primitive-expander u16vector-set! (vec i x)
(bytevector-u16-native-set! vec (* i 2) x))
(define-primitive-expander s16vector-ref (vec i)
(bytevector-s16-native-ref vec (* i 2)))
(define-primitive-expander s16vector-set! (vec i x)
(bytevector-s16-native-set! vec (* i 2) x))
(define-primitive-expander u32vector-ref (vec i)
(bytevector-u32-native-ref vec (* i 4)))
(define-primitive-expander u32vector-set! (vec i x)
(bytevector-u32-native-set! vec (* i 4) x))
(define-primitive-expander s32vector-ref (vec i)
(bytevector-s32-native-ref vec (* i 4)))
(define-primitive-expander s32vector-set! (vec i x)
(bytevector-s32-native-set! vec (* i 4) x))
(define-primitive-expander u64vector-ref (vec i)
(bytevector-u64-native-ref vec (* i 8)))
(define-primitive-expander u64vector-set! (vec i x)
(bytevector-u64-native-set! vec (* i 8) x))
(define-primitive-expander s64vector-ref (vec i)
(bytevector-s64-native-ref vec (* i 8)))
(define-primitive-expander s64vector-set! (vec i x)
(bytevector-s64-native-set! vec (* i 8) x))
(define-primitive-expander f32vector-ref (vec i)
(bytevector-ieee-single-native-ref vec (* i 4)))
(define-primitive-expander f32vector-set! (vec i x)
(bytevector-ieee-single-native-set! vec (* i 4) x))
(define-primitive-expander f32vector-ref (vec i)
(bytevector-ieee-single-native-ref vec (* i 4)))
(define-primitive-expander f32vector-set! (vec i x)
(bytevector-ieee-single-native-set! vec (* i 4) x))
(define-primitive-expander f64vector-ref (vec i)
(bytevector-ieee-double-native-ref vec (* i 8)))
(define-primitive-expander f64vector-set! (vec i x)
(bytevector-ieee-double-native-set! vec (* i 8) x))
(define-primitive-expander f64vector-ref (vec i)
(bytevector-ieee-double-native-ref vec (* i 8)))
(define-primitive-expander f64vector-set! (vec i x)
(bytevector-ieee-double-native-set! vec (* i 8) x))
(define (chained-comparison-expander prim-name)
(case-lambda
((src) (make-const src #t))
((src a) #f)
((src a b) #f)
((src a b . rest)
(let* ((prim (make-primitive-ref src prim-name))
(b-sym (gensym "b"))
(b* (make-lexical-ref src 'b b-sym)))
(make-let src
'(b)
(list b-sym)
(list b)
(make-conditional src
(make-application src prim (list a b*))
(make-application src prim (cons b* rest))
(make-const src #f)))))))
(for-each (lambda (prim-name)
(hashq-set! *primitive-expand-table* prim-name
(chained-comparison-expander prim-name)))
'(< > <= >= =))
;; Appropriate for use with either 'eqv?' or 'equal?'.
(define maybe-simplify-to-eq
(case-lambda
((src a b)
;; Simplify cases where either A or B is constant.
(define (maybe-simplify a b)
(and (const? a)
(let ((v (const-exp a)))
(and (or (memq v '(#f #t () #nil))
(symbol? v)
(and (integer? v)
(exact? v)
(<= most-negative-fixnum v most-positive-fixnum)))
(make-application src (make-primitive-ref #f 'eq?)
(list a b))))))
(or (maybe-simplify a b) (maybe-simplify b a)))
(else #f)))
(hashq-set! *primitive-expand-table* 'eqv? maybe-simplify-to-eq)
(hashq-set! *primitive-expand-table* 'equal? maybe-simplify-to-eq)
(hashq-set! *primitive-expand-table*
'dynamic-wind
(case-lambda
((src pre thunk post)
(let ((PRE (gensym "pre-"))
(THUNK (gensym "thunk-"))
(POST (gensym "post-")))
(make-let
src
'(pre thunk post)
(list PRE THUNK POST)
(list pre thunk post)
(make-dynwind
src
(make-lexical-ref #f 'pre PRE)
(make-application #f (make-lexical-ref #f 'thunk THUNK) '())
(make-lexical-ref #f 'post POST)))))
(else #f)))
(hashq-set! *primitive-expand-table*
'@dynamic-wind
(case-lambda
((src pre expr post)
(let ((PRE (gensym "pre-"))
(POST (gensym "post-")))
(make-let
src
'(pre post)
(list PRE POST)
(list pre post)
(make-dynwind
src
(make-lexical-ref #f 'pre PRE)
expr
(make-lexical-ref #f 'post POST)))))))
(hashq-set! *primitive-expand-table*
'fluid-ref
(case-lambda
((src fluid) (make-dynref src fluid))
(else #f)))
(hashq-set! *primitive-expand-table*
'fluid-set!
(case-lambda
((src fluid exp) (make-dynset src fluid exp))
(else #f)))
(hashq-set! *primitive-expand-table*
'@prompt
(case-lambda
((src tag exp handler)
(let ((args-sym (gensym)))
(make-prompt
src tag exp
;; If handler itself is a lambda, the inliner can do some
;; trickery here.
(make-lambda-case
(tree-il-src handler) '() #f 'args #f '() (list args-sym)
(make-application #f (make-primitive-ref #f 'apply)
(list handler
(make-lexical-ref #f 'args args-sym)))
#f))))
(else #f)))
(hashq-set! *primitive-expand-table*
'call-with-prompt
(case-lambda
((src tag thunk handler)
(let ((handler-sym (gensym))
(args-sym (gensym)))
(make-let
src '(handler) (list handler-sym) (list handler)
(make-prompt
src tag (make-application #f thunk '())
;; If handler itself is a lambda, the inliner can do some
;; trickery here.
(make-lambda-case
(tree-il-src handler) '() #f 'args #f '() (list args-sym)
(make-application
#f (make-primitive-ref #f 'apply)
(list (make-lexical-ref #f 'handler handler-sym)
(make-lexical-ref #f 'args args-sym)))
#f)))))
(else #f)))
(hashq-set! *primitive-expand-table*
'@abort
(case-lambda
((src tag tail-args)
(make-abort src tag '() tail-args))
(else #f)))
(hashq-set! *primitive-expand-table*
'abort-to-prompt
(case-lambda
((src tag . args)
(make-abort src tag args (make-const #f '())))
(else #f)))
;;; Tree Intermediate Language
;; Copyright (C) 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language tree-il spec)
#\use-module (system base language)
#\use-module (system base pmatch)
#\use-module (language glil)
#\use-module (language tree-il)
#\use-module (language tree-il compile-glil)
#\export (tree-il))
(define (write-tree-il exp . port)
(apply write (unparse-tree-il exp) port))
(define (join exps env)
(pmatch exps
(() (make-void #f))
((,x) x)
(else (make-sequence #f exps))))
(define-language tree-il
#\title "Tree Intermediate Language"
#\reader (lambda (port env) (read port))
#\printer write-tree-il
#\parser parse-tree-il
#\joiner join
#\compilers `((glil . ,compile-glil))
#\for-humans? #f
)
;;; Guile Lowlevel Intermediate Language
;; Copyright (C) 2001, 2010, 2013 Free Software Foundation, Inc.
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (language value spec)
#\use-module (system base language)
#\export (value))
(define-language value
#\title "Values"
#\reader #f
#\printer write
#\for-humans? #f
)
;;; installed-scm-file
;;;; Copyright (C) 1998,1999,2000,2001,2002, 2003, 2006, 2009, 2010, 2011, 2014, 2015 Free Software Foundation, Inc.
;;;; Copyright (C) 1993-1998 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;;
;;;; This file was based upon stklos.stk from the STk distribution
;;;; version 4.0.1 by Erick Gallesio <eg@unice.fr>.
;;;;
(define-module (oop goops)
#\use-module (srfi srfi-1)
#\use-module (ice-9 match)
#\use-module (oop goops util)
#\export-syntax (define-class class standard-define-class
define-generic define-accessor define-method
define-extended-generic define-extended-generics
method)
#\export (is-a? class-of
ensure-metaclass ensure-metaclass-with-supers
make-class
make-generic ensure-generic
make-extended-generic
make-accessor ensure-accessor
add-method!
class-slot-ref class-slot-set! slot-unbound slot-missing
slot-definition-name slot-definition-options
slot-definition-allocation
slot-definition-getter slot-definition-setter
slot-definition-accessor
slot-definition-init-value slot-definition-init-form
slot-definition-init-thunk slot-definition-init-keyword
slot-init-function class-slot-definition
method-source
compute-cpl compute-std-cpl compute-get-n-set compute-slots
compute-getter-method compute-setter-method
allocate-instance initialize make-instance make
no-next-method no-applicable-method no-method
change-class update-instance-for-different-class
shallow-clone deep-clone
class-redefinition
apply-generic apply-method apply-methods
compute-applicable-methods %compute-applicable-methods
method-more-specific? sort-applicable-methods
class-subclasses class-methods
goops-error
min-fixnum max-fixnum
;;; *fixme* Should go into goops.c
instance? slot-ref-using-class
slot-set-using-class! slot-bound-using-class?
slot-exists-using-class? slot-ref slot-set! slot-bound?
class-name class-direct-supers class-direct-subclasses
class-direct-methods class-direct-slots class-precedence-list
class-slots
generic-function-name
generic-function-methods method-generic-function
method-specializers method-formals
primitive-generic-generic enable-primitive-generic!
method-procedure accessor-method-slot-definition
slot-exists? make find-method get-keyword))
(define *goops-module* (current-module))
;; First initialize the builtin part of GOOPS
(eval-when (expand load eval)
(%init-goops-builtins))
(eval-when (expand load eval)
(use-modules ((language tree-il primitives) \:select (add-interesting-primitive!)))
(add-interesting-primitive! 'class-of))
;; Then load the rest of GOOPS
(use-modules (oop goops dispatch))
;;;
;;; Compiling next methods into method bodies
;;;
;;; So, for the reader: there basic idea is that, given that the
;;; semantics of `next-method' depend on the concrete types being
;;; dispatched, why not compile a specific procedure to handle each type
;;; combination that we see at runtime.
;;;
;;; In theory we can do much better than a bytecode compilation, because
;;; we know the *exact* types of the arguments. It's ideal for native
;;; compilation. A task for the future.
;;;
;;; I think this whole generic application mess would benefit from a
;;; strict MOP.
(define (compute-cmethod methods types)
(match methods
((method . methods)
(let ((make-procedure (slot-ref method 'make-procedure)))
(if make-procedure
(make-procedure
(if (null? methods)
(lambda args
(no-next-method (method-generic-function method) args))
(compute-cmethod methods types)))
(method-procedure method))))))
(eval-when (expand load eval)
(define min-fixnum (- (expt 2 29)))
(define max-fixnum (- (expt 2 29) 1)))
;;
;; goops-error
;;
(define (goops-error format-string . args)
(scm-error 'goops-error #f format-string args '()))
;;
;; is-a?
;;
(define (is-a? obj class)
(and (memq class (class-precedence-list (class-of obj))) #t))
;;;
;;; {Meta classes}
;;;
(define ensure-metaclass-with-supers
(let ((table-of-metas '()))
(lambda (meta-supers)
(let ((entry (assoc meta-supers table-of-metas)))
(if entry
;; Found a previously created metaclass
(cdr entry)
;; Create a new meta-class which inherit from "meta-supers"
(let ((new (make <class> #\dsupers meta-supers
#\slots '()
#\name (gensym "metaclass"))))
(set! table-of-metas (cons (cons meta-supers new) table-of-metas))
new))))))
(define (ensure-metaclass supers)
(if (null? supers)
<class>
(let* ((all-metas (map (lambda (x) (class-of x)) supers))
(all-cpls (append-map (lambda (m)
(cdr (class-precedence-list m)))
all-metas))
(needed-metas '()))
;; Find the most specific metaclasses. The new metaclass will be
;; a subclass of these.
(for-each
(lambda (meta)
(if (and (not (member meta all-cpls))
(not (member meta needed-metas)))
(set! needed-metas (append needed-metas (list meta)))))
all-metas)
;; Now return a subclass of the metaclasses we found.
(if (null? (cdr needed-metas))
(car needed-metas) ; If there's only one, just use it.
(ensure-metaclass-with-supers needed-metas)))))
;;;
;;; {Classes}
;;;
;;; (define-class NAME (SUPER ...) SLOT-DEFINITION ... OPTION ...)
;;;
;;; SLOT-DEFINITION ::= SLOT-NAME | (SLOT-NAME OPTION ...)
;;; OPTION ::= KEYWORD VALUE
;;;
(define (kw-do-map mapper f kwargs)
(define (keywords l)
(cond
((null? l) '())
((or (null? (cdr l)) (not (keyword? (car l))))
(goops-error "malformed keyword arguments: ~a" kwargs))
(else (cons (car l) (keywords (cddr l))))))
(define (args l)
(if (null? l) '() (cons (cadr l) (args (cddr l)))))
;; let* to check keywords first
(let* ((k (keywords kwargs))
(a (args kwargs)))
(mapper f k a)))
(define (make-class supers slots . options)
(let* ((name (get-keyword #\name options (make-unbound)))
(supers (if (not (or-map (lambda (class)
(memq <object>
(class-precedence-list class)))
supers))
(append supers (list <object>))
supers))
(metaclass (or (get-keyword #\metaclass options #f)
(ensure-metaclass supers))))
;; Verify that all direct slots are different and that we don't inherit
;; several time from the same class
(let ((tmp1 (find-duplicate supers))
(tmp2 (find-duplicate (map slot-definition-name slots))))
(if tmp1
(goops-error "make-class: super class ~S is duplicate in class ~S"
tmp1 name))
(if tmp2
(goops-error "make-class: slot ~S is duplicate in class ~S"
tmp2 name)))
;; Everything seems correct, build the class
(apply make metaclass
#\dsupers supers
#\slots slots
#\name name
options)))
;;; (class (SUPER ...) SLOT-DEFINITION ... OPTION ...)
;;;
;;; SLOT-DEFINITION ::= SLOT-NAME | (SLOT-NAME OPTION ...)
;;; OPTION ::= KEYWORD VALUE
;;;
(define-macro (class supers . slots)
(define (make-slot-definition-forms slots)
(map
(lambda (def)
(cond
((pair? def)
`(list ',(car def)
,@(kw-do-map append-map
(lambda (kw arg)
(case kw
((#\init-form)
`(#\init-form ',arg
#\init-thunk (lambda () ,arg)))
(else (list kw arg))))
(cdr def))))
(else
`(list ',def))))
slots))
(if (not (list? supers))
(goops-error "malformed superclass list: ~S" supers))
(let ((slots (take-while (lambda (x) (not (keyword? x))) slots))
(options (or (find-tail keyword? slots) '())))
`(make-class
;; evaluate super class variables
(list ,@supers)
;; evaluate slot definitions, except the slot name!
(list ,@(make-slot-definition-forms slots))
;; evaluate class options
,@options)))
(define-syntax define-class-pre-definition
(lambda (x)
(syntax-case x ()
((_ (k arg rest ...) out ...)
(keyword? (syntax->datum #'k))
(case (syntax->datum #'k)
((#\getter #\setter)
#'(define-class-pre-definition (rest ...)
out ...
(if (or (not (defined? 'arg))
(not (is-a? arg <generic>)))
(toplevel-define!
'arg
(ensure-generic (if (defined? 'arg) arg #f) 'arg)))))
((#\accessor)
#'(define-class-pre-definition (rest ...)
out ...
(if (or (not (defined? 'arg))
(not (is-a? arg <accessor>)))
(toplevel-define!
'arg
(ensure-accessor (if (defined? 'arg) arg #f) 'arg)))))
(else
#'(define-class-pre-definition (rest ...) out ...))))
((_ () out ...)
#'(begin out ...)))))
;; Some slot options require extra definitions to be made. In
;; particular, we want to make sure that the generic function objects
;; which represent accessors exist before `make-class' tries to add
;; methods to them.
(define-syntax define-class-pre-definitions
(lambda (x)
(syntax-case x ()
((_ () out ...)
#'(begin out ...))
((_ (slot rest ...) out ...)
(keyword? (syntax->datum #'slot))
#'(begin out ...))
((_ (slot rest ...) out ...)
(identifier? #'slot)
#'(define-class-pre-definitions (rest ...)
out ...))
((_ ((slotname slotopt ...) rest ...) out ...)
#'(define-class-pre-definitions (rest ...)
out ... (define-class-pre-definition (slotopt ...)))))))
(define-syntax-rule (define-class name supers slot ...)
(begin
(define-class-pre-definitions (slot ...))
(if (and (defined? 'name)
(is-a? name <class>)
(memq <object> (class-precedence-list name)))
(class-redefinition name
(class supers slot ... #\name 'name))
(toplevel-define! 'name (class supers slot ... #\name 'name)))))
(define-syntax-rule (standard-define-class arg ...)
(define-class arg ...))
;;;
;;; {Generic functions and accessors}
;;;
;; Apparently the desired semantics are that we extend previous
;; procedural definitions, but that if `name' was already a generic, we
;; overwrite its definition.
(define-macro (define-generic name)
(if (not (symbol? name))
(goops-error "bad generic function name: ~S" name))
`(define ,name
(if (and (defined? ',name) (is-a? ,name <generic>))
(make <generic> #\name ',name)
(ensure-generic (if (defined? ',name) ,name #f) ',name))))
(define-macro (define-extended-generic name val)
(if (not (symbol? name))
(goops-error "bad generic function name: ~S" name))
`(define ,name (make-extended-generic ,val ',name)))
(define-macro (define-extended-generics names . args)
(let ((prefixes (get-keyword #\prefix args #f)))
(if prefixes
`(begin
,@(map (lambda (name)
`(define-extended-generic ,name
(list ,@(map (lambda (prefix)
(symbol-append prefix name))
prefixes))))
names))
(goops-error "no prefixes supplied"))))
(define* (make-generic #\optional name)
(make <generic> #\name name))
(define* (make-extended-generic gfs #\optional name)
(let* ((gfs (if (list? gfs) gfs (list gfs)))
(gws? (any (lambda (gf) (is-a? gf <generic-with-setter>)) gfs)))
(let ((ans (if gws?
(let* ((sname (and name (make-setter-name name)))
(setters
(append-map (lambda (gf)
(if (is-a? gf <generic-with-setter>)
(list (ensure-generic (setter gf)
sname))
'()))
gfs))
(es (make <extended-generic-with-setter>
#\name name
#\extends gfs
#\setter (make <extended-generic>
#\name sname
#\extends setters))))
(extended-by! setters (setter es))
es)
(make <extended-generic>
#\name name
#\extends gfs))))
(extended-by! gfs ans)
ans)))
(define (extended-by! gfs eg)
(for-each (lambda (gf)
(slot-set! gf 'extended-by
(cons eg (slot-ref gf 'extended-by))))
gfs)
(invalidate-method-cache! eg))
(define (not-extended-by! gfs eg)
(for-each (lambda (gf)
(slot-set! gf 'extended-by
(delq! eg (slot-ref gf 'extended-by))))
gfs)
(invalidate-method-cache! eg))
(define* (ensure-generic old-definition #\optional name)
(cond ((is-a? old-definition <generic>) old-definition)
((procedure-with-setter? old-definition)
(make <generic-with-setter>
#\name name
#\default (procedure old-definition)
#\setter (setter old-definition)))
((procedure? old-definition)
(if (generic-capability? old-definition) old-definition
(make <generic> #\name name #\default old-definition)))
(else (make <generic> #\name name))))
;; same semantics as <generic>
(define-syntax-rule (define-accessor name)
(define name
(cond ((not (defined? 'name)) (ensure-accessor #f 'name))
((is-a? name <accessor>) (make <accessor> #\name 'name))
(else (ensure-accessor name 'name)))))
(define (make-setter-name name)
(string->symbol (string-append "setter:" (symbol->string name))))
(define* (make-accessor #\optional name)
(make <accessor>
#\name name
#\setter (make <generic>
#\name (and name (make-setter-name name)))))
(define* (ensure-accessor proc #\optional name)
(cond ((and (is-a? proc <accessor>)
(is-a? (setter proc) <generic>))
proc)
((is-a? proc <generic-with-setter>)
(upgrade-accessor proc (setter proc)))
((is-a? proc <generic>)
(upgrade-accessor proc (make-generic name)))
((procedure-with-setter? proc)
(make <accessor>
#\name name
#\default (procedure proc)
#\setter (ensure-generic (setter proc) name)))
((procedure? proc)
(ensure-accessor (if (generic-capability? proc)
(make <generic> #\name name #\default proc)
(ensure-generic proc name))
name))
(else
(make-accessor name))))
(define (upgrade-accessor generic setter)
(let ((methods (slot-ref generic 'methods))
(gws (make (if (is-a? generic <extended-generic>)
<extended-generic-with-setter>
<accessor>)
#\name (generic-function-name generic)
#\extended-by (slot-ref generic 'extended-by)
#\setter setter)))
(if (is-a? generic <extended-generic>)
(let ((gfs (slot-ref generic 'extends)))
(not-extended-by! gfs generic)
(slot-set! gws 'extends gfs)
(extended-by! gfs gws)))
;; Steal old methods
(for-each (lambda (method)
(slot-set! method 'generic-function gws))
methods)
(slot-set! gws 'methods methods)
(invalidate-method-cache! gws)
gws))
;;;
;;; {Methods}
;;;
(define (toplevel-define! name val)
(module-define! (current-module) name val))
(define-syntax define-method
(syntax-rules (setter)
((_ ((setter name) . args) body ...)
(begin
(if (or (not (defined? 'name))
(not (is-a? name <accessor>)))
(toplevel-define! 'name
(ensure-accessor
(if (defined? 'name) name #f) 'name)))
(add-method! (setter name) (method args body ...))))
((_ (name . args) body ...)
(begin
;; FIXME: this code is how it always was, but it's quite cracky:
;; it will only define the generic function if it was undefined
;; before (ok), or *was defined to #f*. The latter is crack. But
;; there are bootstrap issues about fixing this -- change it to
;; (is-a? name <generic>) and see.
(if (or (not (defined? 'name))
(not name))
(toplevel-define! 'name (make <generic> #\name 'name)))
(add-method! name (method args body ...))))))
(define-syntax method
(lambda (x)
(define (parse-args args)
(let lp ((ls args) (formals '()) (specializers '()))
(syntax-case ls ()
(((f s) . rest)
(and (identifier? #'f) (identifier? #'s))
(lp #'rest
(cons #'f formals)
(cons #'s specializers)))
((f . rest)
(identifier? #'f)
(lp #'rest
(cons #'f formals)
(cons #'<top> specializers)))
(()
(list (reverse formals)
(reverse (cons #''() specializers))))
(tail
(identifier? #'tail)
(list (append (reverse formals) #'tail)
(reverse (cons #'<top> specializers)))))))
(define (find-free-id exp referent)
(syntax-case exp ()
((x . y)
(or (find-free-id #'x referent)
(find-free-id #'y referent)))
(x
(identifier? #'x)
(let ((id (datum->syntax #'x referent)))
(and (free-identifier=? #'x id) id)))
(_ #f)))
(define (compute-procedure formals body)
(syntax-case body ()
((body0 ...)
(with-syntax ((formals formals))
#'(lambda formals body0 ...)))))
(define (->proper args)
(let lp ((ls args) (out '()))
(syntax-case ls ()
((x . xs) (lp #'xs (cons #'x out)))
(() (reverse out))
(tail (reverse (cons #'tail out))))))
(define (compute-make-procedure formals body next-method)
(syntax-case body ()
((body ...)
(with-syntax ((next-method next-method))
(syntax-case formals ()
((formal ...)
#'(lambda (real-next-method)
(lambda (formal ...)
(let ((next-method (lambda args
(if (null? args)
(real-next-method formal ...)
(apply real-next-method args)))))
body ...))))
(formals
(with-syntax (((formal ...) (->proper #'formals)))
#'(lambda (real-next-method)
(lambda formals
(let ((next-method (lambda args
(if (null? args)
(apply real-next-method formal ...)
(apply real-next-method args)))))
body ...))))))))))
(define (compute-procedures formals body)
;; So, our use of this is broken, because it operates on the
;; pre-expansion source code. It's equivalent to just searching
;; for referent in the datums. Ah well.
(let ((id (find-free-id body 'next-method)))
(if id
;; return a make-procedure
(values #'#f
(compute-make-procedure formals body id))
(values (compute-procedure formals body)
#'#f))))
(syntax-case x ()
((_ args) #'(method args (if #f #f)))
((_ args body0 body1 ...)
(with-syntax (((formals (specializer ...)) (parse-args #'args)))
(call-with-values
(lambda ()
(compute-procedures #'formals #'(body0 body1 ...)))
(lambda (procedure make-procedure)
(with-syntax ((procedure procedure)
(make-procedure make-procedure))
#'(make <method>
#\specializers (cons* specializer ...)
#\formals 'formals
#\body '(body0 body1 ...)
#\make-procedure make-procedure
#\procedure procedure)))))))))
;;;
;;; {add-method!}
;;;
(define (add-method-in-classes! m)
;; Add method in all the classes which appears in its specializers list
(for-each* (lambda (x)
(let ((dm (class-direct-methods x)))
(if (not (memq m dm))
(slot-set! x 'direct-methods (cons m dm)))))
(method-specializers m)))
(define (remove-method-in-classes! m)
;; Remove method in all the classes which appears in its specializers list
(for-each* (lambda (x)
(slot-set! x
'direct-methods
(delv! m (class-direct-methods x))))
(method-specializers m)))
(define (compute-new-list-of-methods gf new)
(let ((new-spec (method-specializers new))
(methods (slot-ref gf 'methods)))
(let loop ((l methods))
(if (null? l)
(cons new methods)
(if (equal? (method-specializers (car l)) new-spec)
(begin
;; This spec. list already exists. Remove old method from dependents
(remove-method-in-classes! (car l))
(set-car! l new)
methods)
(loop (cdr l)))))))
(define (method-n-specializers m)
(length* (slot-ref m 'specializers)))
(define (calculate-n-specialized gf)
(fold (lambda (m n) (max n (method-n-specializers m)))
0
(generic-function-methods gf)))
(define (invalidate-method-cache! gf)
(%invalidate-method-cache! gf)
(slot-set! gf 'n-specialized (calculate-n-specialized gf))
(for-each (lambda (gf) (invalidate-method-cache! gf))
(slot-ref gf 'extended-by)))
(define internal-add-method!
(method ((gf <generic>) (m <method>))
(slot-set! m 'generic-function gf)
(slot-set! gf 'methods (compute-new-list-of-methods gf m))
(invalidate-method-cache! gf)
(add-method-in-classes! m)
*unspecified*))
(define-generic add-method!)
((method-procedure internal-add-method!) add-method! internal-add-method!)
(define-method (add-method! (proc <procedure>) (m <method>))
(if (generic-capability? proc)
(begin
(enable-primitive-generic! proc)
(add-method! proc m))
(next-method)))
(define-method (add-method! (pg <primitive-generic>) (m <method>))
(add-method! (primitive-generic-generic pg) m))
(define-method (add-method! obj (m <method>))
(goops-error "~S is not a valid generic function" obj))
;;;
;;; {Access to meta objects}
;;;
;;;
;;; Methods
;;;
(define-method (method-source (m <method>))
(let* ((spec (map* class-name (slot-ref m 'specializers)))
(src (procedure-source (slot-ref m 'procedure))))
(and src
(let ((args (cadr src))
(body (cddr src)))
(cons 'method
(cons (map* list args spec)
body))))))
(define-method (method-formals (m <method>))
(slot-ref m 'formals))
;;;
;;; Slots
;;;
(define slot-definition-name car)
(define slot-definition-options cdr)
(define (slot-definition-allocation s)
(get-keyword #\allocation (cdr s) #\instance))
(define (slot-definition-getter s)
(get-keyword #\getter (cdr s) #f))
(define (slot-definition-setter s)
(get-keyword #\setter (cdr s) #f))
(define (slot-definition-accessor s)
(get-keyword #\accessor (cdr s) #f))
(define (slot-definition-init-value s)
;; can be #f, so we can't use #f as non-value
(get-keyword #\init-value (cdr s) (make-unbound)))
(define (slot-definition-init-form s)
(get-keyword #\init-form (cdr s) (make-unbound)))
(define (slot-definition-init-thunk s)
(get-keyword #\init-thunk (cdr s) #f))
(define (slot-definition-init-keyword s)
(get-keyword #\init-keyword (cdr s) #f))
(define (class-slot-definition class slot-name)
(assq slot-name (class-slots class)))
(define (slot-init-function class slot-name)
(cadr (assq slot-name (slot-ref class 'getters-n-setters))))
(define (accessor-method-slot-definition obj)
"Return the slot definition of the accessor @var{obj}."
(slot-ref obj 'slot-definition))
;;;
;;; {Standard methods used by the C runtime}
;;;
;;; Methods to compare objects
;;;
;; Have to do this in a strange order because equal? is used in the
;; add-method! implementation; we need to make sure that when the
;; primitive is extended, that the generic has a method. =
(define g-equal? (make-generic 'equal?))
;; When this generic gets called, we will have already checked eq? and
;; eqv? -- the purpose of this generic is to extend equality. So by
;; default, there is no extension, thus the #f return.
(add-method! g-equal? (method (x y) #f))
(set-primitive-generic! equal? g-equal?)
;;;
;;; methods to display/write an object
;;;
; Code for writing objects must test that the slots they use are
; bound. Otherwise a slot-unbound method will be called and will
; conduct to an infinite loop.
;; Write
(define (display-address o file)
(display (number->string (object-address o) 16) file))
(define-method (write o file)
(display "#<instance " file)
(display-address o file)
(display #\> file))
(define write-object (primitive-generic-generic write))
(define-method (write (o <object>) file)
(let ((class (class-of o)))
(if (slot-bound? class 'name)
(begin
(display "#<" file)
(display (class-name class) file)
(display #\space file)
(display-address o file)
(display #\> file))
(next-method))))
(define-method (write (class <class>) file)
(let ((meta (class-of class)))
(if (and (slot-bound? class 'name)
(slot-bound? meta 'name))
(begin
(display "#<" file)
(display (class-name meta) file)
(display #\space file)
(display (class-name class) file)
(display #\space file)
(display-address class file)
(display #\> file))
(next-method))))
(define-method (write (gf <generic>) file)
(let ((meta (class-of gf)))
(if (and (slot-bound? meta 'name)
(slot-bound? gf 'methods))
(begin
(display "#<" file)
(display (class-name meta) file)
(let ((name (generic-function-name gf)))
(if name
(begin
(display #\space file)
(display name file))))
(display " (" file)
(display (length (generic-function-methods gf)) file)
(display ")>" file))
(next-method))))
(define-method (write (o <method>) file)
(let ((meta (class-of o)))
(if (and (slot-bound? meta 'name)
(slot-bound? o 'specializers))
(begin
(display "#<" file)
(display (class-name meta) file)
(display #\space file)
(display (map* (lambda (spec)
(if (slot-bound? spec 'name)
(slot-ref spec 'name)
spec))
(method-specializers o))
file)
(display #\space file)
(display-address o file)
(display #\> file))
(next-method))))
;; Display (do the same thing as write by default)
(define-method (display o file)
(write-object o file))
;;;
;;; Handling of duplicate bindings in the module system
;;;
(define-method (merge-generics (module <module>)
(name <symbol>)
(int1 <module>)
(val1 <top>)
(int2 <module>)
(val2 <top>)
(var <top>)
(val <top>))
#f)
(define-method (merge-generics (module <module>)
(name <symbol>)
(int1 <module>)
(val1 <generic>)
(int2 <module>)
(val2 <generic>)
(var <top>)
(val <boolean>))
(and (not (eq? val1 val2))
(make-variable (make-extended-generic (list val2 val1) name))))
(define-method (merge-generics (module <module>)
(name <symbol>)
(int1 <module>)
(val1 <generic>)
(int2 <module>)
(val2 <generic>)
(var <top>)
(gf <extended-generic>))
(and (not (memq val2 (slot-ref gf 'extends)))
(begin
(slot-set! gf
'extends
(cons val2 (delq! val2 (slot-ref gf 'extends))))
(slot-set! val2
'extended-by
(cons gf (delq! gf (slot-ref val2 'extended-by))))
(invalidate-method-cache! gf)
var)))
(module-define! duplicate-handlers 'merge-generics merge-generics)
(define-method (merge-accessors (module <module>)
(name <symbol>)
(int1 <module>)
(val1 <top>)
(int2 <module>)
(val2 <top>)
(var <top>)
(val <top>))
#f)
(define-method (merge-accessors (module <module>)
(name <symbol>)
(int1 <module>)
(val1 <accessor>)
(int2 <module>)
(val2 <accessor>)
(var <top>)
(val <top>))
(merge-generics module name int1 val1 int2 val2 var val))
(module-define! duplicate-handlers 'merge-accessors merge-accessors)
;;;
;;; slot access
;;;
(define (class-slot-g-n-s class slot-name)
(let* ((this-slot (assq slot-name (slot-ref class 'slots)))
(g-n-s (cddr (or (assq slot-name (slot-ref class 'getters-n-setters))
(slot-missing class slot-name)))))
(if (not (memq (slot-definition-allocation this-slot)
'(#\class #\each-subclass)))
(slot-missing class slot-name))
g-n-s))
(define (class-slot-ref class slot)
(let ((x ((car (class-slot-g-n-s class slot)) #f)))
(if (unbound? x)
(slot-unbound class slot)
x)))
(define (class-slot-set! class slot value)
((cadr (class-slot-g-n-s class slot)) #f value))
(define-method (slot-unbound (c <class>) (o <object>) s)
(goops-error "Slot `~S' is unbound in object ~S" s o))
(define-method (slot-unbound (c <class>) s)
(goops-error "Slot `~S' is unbound in class ~S" s c))
(define-method (slot-unbound (o <object>))
(goops-error "Unbound slot in object ~S" o))
(define-method (slot-missing (c <class>) (o <object>) s)
(goops-error "No slot with name `~S' in object ~S" s o))
(define-method (slot-missing (c <class>) s)
(goops-error "No class slot with name `~S' in class ~S" s c))
(define-method (slot-missing (c <class>) (o <object>) s value)
(slot-missing c o s))
;;; Methods for the possible error we can encounter when calling a gf
(define-method (no-next-method (gf <generic>) args)
(goops-error "No next method when calling ~S\nwith arguments ~S" gf args))
(define-method (no-applicable-method (gf <generic>) args)
(goops-error "No applicable method for ~S in call ~S"
gf (cons (generic-function-name gf) args)))
(define-method (no-method (gf <generic>) args)
(goops-error "No method defined for ~S" gf))
;;;
;;; {Cloning functions (from rdeline@CS.CMU.EDU)}
;;;
(define-method (shallow-clone (self <object>))
(let ((clone (%allocate-instance (class-of self) '()))
(slots (map slot-definition-name
(class-slots (class-of self)))))
(for-each (lambda (slot)
(if (slot-bound? self slot)
(slot-set! clone slot (slot-ref self slot))))
slots)
clone))
(define-method (deep-clone (self <object>))
(let ((clone (%allocate-instance (class-of self) '()))
(slots (map slot-definition-name
(class-slots (class-of self)))))
(for-each (lambda (slot)
(if (slot-bound? self slot)
(slot-set! clone slot
(let ((value (slot-ref self slot)))
(if (instance? value)
(deep-clone value)
value)))))
slots)
clone))
;;;
;;; {Class redefinition utilities}
;;;
;;; (class-redefinition OLD NEW)
;;;
;;; Has correct the following conditions:
;;; Methods
;;;
;;; 1. New accessor specializers refer to new header
;;;
;;; Classes
;;;
;;; 1. New class cpl refers to the new class header
;;; 2. Old class header exists on old super classes direct-subclass lists
;;; 3. New class header exists on new super classes direct-subclass lists
(define-method (class-redefinition (old <class>) (new <class>))
;; Work on direct methods:
;; 1. Remove accessor methods from the old class
;; 2. Patch the occurences of new in the specializers by old
;; 3. Displace the methods from old to new
(remove-class-accessors! old) ;; -1-
(let ((methods (class-direct-methods new)))
(for-each (lambda (m)
(update-direct-method! m new old)) ;; -2-
methods)
(slot-set! new
'direct-methods
(append methods (class-direct-methods old))))
;; Substitute old for new in new cpl
(set-car! (slot-ref new 'cpl) old)
;; Remove the old class from the direct-subclasses list of its super classes
(for-each (lambda (c) (slot-set! c 'direct-subclasses
(delv! old (class-direct-subclasses c))))
(class-direct-supers old))
;; Replace the new class with the old in the direct-subclasses of the supers
(for-each (lambda (c)
(slot-set! c 'direct-subclasses
(cons old (delv! new (class-direct-subclasses c)))))
(class-direct-supers new))
;; Swap object headers
(%modify-class old new)
;; Now old is NEW!
;; Redefine all the subclasses of old to take into account modification
(for-each
(lambda (c)
(update-direct-subclass! c new old))
(class-direct-subclasses new))
;; Invalidate class so that subsequent instances slot accesses invoke
;; change-object-class
(slot-set! new 'redefined old)
(%invalidate-class new) ;must come after slot-set!
old)
;;;
;;; remove-class-accessors!
;;;
(define-method (remove-class-accessors! (c <class>))
(for-each (lambda (m)
(if (is-a? m <accessor-method>)
(let ((gf (slot-ref m 'generic-function)))
;; remove the method from its GF
(slot-set! gf 'methods
(delq1! m (slot-ref gf 'methods)))
(invalidate-method-cache! gf)
;; remove the method from its specializers
(remove-method-in-classes! m))))
(class-direct-methods c)))
;;;
;;; update-direct-method!
;;;
(define-method (update-direct-method! (m <method>)
(old <class>)
(new <class>))
(let loop ((l (method-specializers m)))
;; Note: the <top> in dotted list is never used.
;; So we can work as if we had only proper lists.
(if (pair? l)
(begin
(if (eqv? (car l) old)
(set-car! l new))
(loop (cdr l))))))
;;;
;;; update-direct-subclass!
;;;
(define-method (update-direct-subclass! (c <class>)
(old <class>)
(new <class>))
(class-redefinition c
(make-class (class-direct-supers c)
(class-direct-slots c)
#\name (class-name c)
#\metaclass (class-of c))))
;;;
;;; {Utilities for INITIALIZE methods}
;;;
;;; compute-slot-accessors
;;;
(define (compute-slot-accessors class slots)
(for-each
(lambda (s g-n-s)
(let ((getter-function (slot-definition-getter s))
(setter-function (slot-definition-setter s))
(accessor (slot-definition-accessor s)))
(if getter-function
(add-method! getter-function
(compute-getter-method class g-n-s)))
(if setter-function
(add-method! setter-function
(compute-setter-method class g-n-s)))
(if accessor
(begin
(add-method! accessor
(compute-getter-method class g-n-s))
(add-method! (setter accessor)
(compute-setter-method class g-n-s))))))
slots (slot-ref class 'getters-n-setters)))
(define-method (compute-getter-method (class <class>) g-n-s)
(let ((init-thunk (cadr g-n-s))
(g-n-s (cddr g-n-s)))
(make <accessor-method>
#\specializers (list class)
#\procedure (cond ((pair? g-n-s)
(make-generic-bound-check-getter (car g-n-s)))
(init-thunk
(standard-get g-n-s))
(else
(bound-check-get g-n-s)))
#\slot-definition g-n-s)))
(define-method (compute-setter-method (class <class>) g-n-s)
(let ((init-thunk (cadr g-n-s))
(g-n-s (cddr g-n-s)))
(make <accessor-method>
#\specializers (list class <top>)
#\procedure (if (pair? g-n-s)
(cadr g-n-s)
(standard-set g-n-s))
#\slot-definition g-n-s)))
(define (make-generic-bound-check-getter proc)
(lambda (o) (assert-bound (proc o) o)))
;; the idea is to compile the index into the procedure, for fastest
;; lookup.
(eval-when (expand load eval)
(define num-standard-pre-cache 20))
(define-macro (define-standard-accessor-method form . body)
(let ((name (caar form))
(n-var (cadar form))
(args (cdr form)))
(define (make-one x)
(define (body-trans form)
(cond ((not (pair? form)) form)
((eq? (car form) 'struct-ref)
`(,(car form) ,(cadr form) ,x))
((eq? (car form) 'struct-set!)
`(,(car form) ,(cadr form) ,x ,(cadddr form)))
(else
(map body-trans form))))
`(lambda ,args ,@(map body-trans body)))
`(define ,name
(let ((cache (vector ,@(map make-one (iota num-standard-pre-cache)))))
(lambda (n)
(if (< n ,num-standard-pre-cache)
(vector-ref cache n)
((lambda (,n-var) (lambda ,args ,@body)) n)))))))
(define-standard-accessor-method ((bound-check-get n) o)
(let ((x (struct-ref o n)))
(if (unbound? x)
(slot-unbound o)
x)))
(define-standard-accessor-method ((standard-get n) o)
(struct-ref o n))
(define-standard-accessor-method ((standard-set n) o v)
(struct-set! o n v))
;;; compute-getters-n-setters
;;;
(define (compute-getters-n-setters class slots)
(define (compute-slot-init-function name s)
(or (let ((thunk (slot-definition-init-thunk s)))
(and thunk
(if (thunk? thunk)
thunk
(goops-error "Bad init-thunk for slot `~S' in ~S: ~S"
name class thunk))))
(let ((init (slot-definition-init-value s)))
(and (not (unbound? init))
(lambda () init)))))
(define (verify-accessors slot l)
(cond ((integer? l))
((not (and (list? l) (= (length l) 2)))
(goops-error "Bad getter and setter for slot `~S' in ~S: ~S"
slot class l))
(else
(let ((get (car l))
(set (cadr l)))
(if (not (procedure? get))
(goops-error "Bad getter closure for slot `~S' in ~S: ~S"
slot class get))
(if (not (procedure? set))
(goops-error "Bad setter closure for slot `~S' in ~S: ~S"
slot class set))))))
(map (lambda (s)
;; The strange treatment of nfields is due to backward compatibility.
(let* ((index (slot-ref class 'nfields))
(g-n-s (compute-get-n-set class s))
(size (- (slot-ref class 'nfields) index))
(name (slot-definition-name s)))
;; NOTE: The following is interdependent with C macros
;; defined above goops.c:scm_sys_prep_layout_x.
;;
;; For simple instance slots, we have the simplest form
;; '(name init-function . index)
;; For other slots we have
;; '(name init-function getter setter . alloc)
;; where alloc is:
;; '(index size) for instance allocated slots
;; '() for other slots
(verify-accessors name g-n-s)
(case (slot-definition-allocation s)
((#\each-subclass #\class)
(unless (and (zero? size) (pair? g-n-s))
(error "Class-allocated slots should not reserve fields"))
;; Don't initialize the slot; that's handled when the slot
;; is allocated, in compute-get-n-set.
(cons name (cons #f g-n-s)))
(else
(cons name
(cons (compute-slot-init-function name s)
(if (or (integer? g-n-s)
(zero? size))
g-n-s
(append g-n-s (list index size)))))))))
slots))
;;; compute-cpl
;;;
;;; Correct behaviour:
;;;
;;; (define-class food ())
;;; (define-class fruit (food))
;;; (define-class spice (food))
;;; (define-class apple (fruit))
;;; (define-class cinnamon (spice))
;;; (define-class pie (apple cinnamon))
;;; => cpl (pie) = pie apple fruit cinnamon spice food object top
;;;
;;; (define-class d ())
;;; (define-class e ())
;;; (define-class f ())
;;; (define-class b (d e))
;;; (define-class c (e f))
;;; (define-class a (b c))
;;; => cpl (a) = a b d c e f object top
;;;
(define-method (compute-cpl (class <class>))
(compute-std-cpl class class-direct-supers))
;; Support
(define (only-non-null lst)
(filter (lambda (l) (not (null? l))) lst))
(define (compute-std-cpl c get-direct-supers)
(let ((c-direct-supers (get-direct-supers c)))
(merge-lists (list c)
(only-non-null (append (map class-precedence-list
c-direct-supers)
(list c-direct-supers))))))
(define (merge-lists reversed-partial-result inputs)
(cond
((every null? inputs)
(reverse! reversed-partial-result))
(else
(let* ((candidate (lambda (c)
(and (not (any (lambda (l)
(memq c (cdr l)))
inputs))
c)))
(candidate-car (lambda (l)
(and (not (null? l))
(candidate (car l)))))
(next (any candidate-car inputs)))
(if (not next)
(goops-error "merge-lists: Inconsistent precedence graph"))
(let ((remove-next (lambda (l)
(if (eq? (car l) next)
(cdr l)
l))))
(merge-lists (cons next reversed-partial-result)
(only-non-null (map remove-next inputs))))))))
;; Modified from TinyClos:
;;
;; A simple topological sort.
;;
;; It's in this file so that both TinyClos and Objects can use it.
;;
;; This is a fairly modified version of code I originally got from Anurag
;; Mendhekar <anurag@moose.cs.indiana.edu>.
;;
(define (compute-clos-cpl c get-direct-supers)
(top-sort ((build-transitive-closure get-direct-supers) c)
((build-constraints get-direct-supers) c)
(std-tie-breaker get-direct-supers)))
(define (top-sort elements constraints tie-breaker)
(let loop ((elements elements)
(constraints constraints)
(result '()))
(if (null? elements)
result
(let ((can-go-in-now
(filter
(lambda (x)
(every (lambda (constraint)
(or (not (eq? (cadr constraint) x))
(memq (car constraint) result)))
constraints))
elements)))
(if (null? can-go-in-now)
(goops-error "top-sort: Invalid constraints")
(let ((choice (if (null? (cdr can-go-in-now))
(car can-go-in-now)
(tie-breaker result
can-go-in-now))))
(loop
(filter (lambda (x) (not (eq? x choice)))
elements)
constraints
(append result (list choice)))))))))
(define (std-tie-breaker get-supers)
(lambda (partial-cpl min-elts)
(let loop ((pcpl (reverse partial-cpl)))
(let ((current-elt (car pcpl)))
(let ((ds-of-ce (get-supers current-elt)))
(let ((common (filter (lambda (x)
(memq x ds-of-ce))
min-elts)))
(if (null? common)
(if (null? (cdr pcpl))
(goops-error "std-tie-breaker: Nothing valid")
(loop (cdr pcpl)))
(car common))))))))
(define (build-transitive-closure get-follow-ons)
(lambda (x)
(let track ((result '())
(pending (list x)))
(if (null? pending)
result
(let ((next (car pending)))
(if (memq next result)
(track result (cdr pending))
(track (cons next result)
(append (get-follow-ons next)
(cdr pending)))))))))
(define (build-constraints get-follow-ons)
(lambda (x)
(let loop ((elements ((build-transitive-closure get-follow-ons) x))
(this-one '())
(result '()))
(if (or (null? this-one) (null? (cdr this-one)))
(if (null? elements)
result
(loop (cdr elements)
(cons (car elements)
(get-follow-ons (car elements)))
result))
(loop elements
(cdr this-one)
(cons (list (car this-one) (cadr this-one))
result))))))
;;; compute-get-n-set
;;;
(define-method (compute-get-n-set (class <class>) s)
(define (class-slot-init-value)
(let ((thunk (slot-definition-init-thunk s)))
(if thunk
(thunk)
(slot-definition-init-value s))))
(case (slot-definition-allocation s)
((#\instance) ;; Instance slot
;; get-n-set is just its offset
(let ((already-allocated (slot-ref class 'nfields)))
(slot-set! class 'nfields (+ already-allocated 1))
already-allocated))
((#\class) ;; Class slot
;; Class-slots accessors are implemented as 2 closures around
;; a Scheme variable. As instance slots, class slots must be
;; unbound at init time.
(let ((name (slot-definition-name s)))
(if (memq name (map slot-definition-name (class-direct-slots class)))
;; This slot is direct; create a new shared variable
(make-closure-variable class (class-slot-init-value))
;; Slot is inherited. Find its definition in superclass
(let loop ((l (cdr (class-precedence-list class))))
(let ((r (assoc name (slot-ref (car l) 'getters-n-setters))))
(if r
(cddr r)
(loop (cdr l))))))))
((#\each-subclass) ;; slot shared by instances of direct subclass.
;; (Thomas Buerger, April 1998)
(make-closure-variable class (class-slot-init-value)))
((#\virtual) ;; No allocation
;; slot-ref and slot-set! function must be given by the user
(let ((get (get-keyword #\slot-ref (slot-definition-options s) #f))
(set (get-keyword #\slot-set! (slot-definition-options s) #f)))
(if (not (and get set))
(goops-error "You must supply a #:slot-ref and a #:slot-set! in ~S"
s))
(list get set)))
(else (next-method))))
(define (make-closure-variable class value)
(list (lambda (o) value)
(lambda (o v) (set! value v))))
(define-method (compute-get-n-set (o <object>) s)
(goops-error "Allocation \"~S\" is unknown" (slot-definition-allocation s)))
(define-method (compute-slots (class <class>))
(%compute-slots class))
;;;
;;; {Initialize}
;;;
(define-method (initialize (object <object>) initargs)
(%initialize-object object initargs))
(define-method (initialize (class <class>) initargs)
(next-method)
(let ((dslots (get-keyword #\slots initargs '()))
(supers (get-keyword #\dsupers initargs '())))
(slot-set! class 'name (get-keyword #\name initargs '???))
(slot-set! class 'direct-supers supers)
(slot-set! class 'direct-slots dslots)
(slot-set! class 'direct-subclasses '())
(slot-set! class 'direct-methods '())
(slot-set! class 'cpl (compute-cpl class))
(slot-set! class 'redefined #f)
(let ((slots (compute-slots class)))
(slot-set! class 'slots slots)
(slot-set! class 'nfields 0)
(slot-set! class 'getters-n-setters (compute-getters-n-setters class
slots))
;; Build getters - setters - accessors
(compute-slot-accessors class slots))
;; Update the "direct-subclasses" of each inherited classes
(for-each (lambda (x)
(slot-set! x
'direct-subclasses
(cons class (slot-ref x 'direct-subclasses))))
supers)
;; Support for the underlying structs:
;; Set the layout slot
(%prep-layout! class)
;; Inherit class flags (invisible on scheme level) from supers
(%inherit-magic! class supers)))
(define (initialize-object-procedure object initargs)
(let ((proc (get-keyword #\procedure initargs #f)))
(cond ((not proc))
((pair? proc)
(apply slot-set! object 'procedure proc))
(else
(slot-set! object 'procedure proc)))))
(define-method (initialize (applicable-struct <applicable-struct>) initargs)
(next-method)
(initialize-object-procedure applicable-struct initargs))
(define-method (initialize (generic <generic>) initargs)
(let ((previous-definition (get-keyword #\default initargs #f))
(name (get-keyword #\name initargs #f)))
(next-method)
(slot-set! generic 'methods (if (is-a? previous-definition <procedure>)
(list (method args
(apply previous-definition args)))
'()))
(if name
(set-procedure-property! generic 'name name))
))
(define-method (initialize (gws <generic-with-setter>) initargs)
(next-method)
(%set-object-setter! gws (get-keyword #\setter initargs #f)))
(define-method (initialize (eg <extended-generic>) initargs)
(next-method)
(slot-set! eg 'extends (get-keyword #\extends initargs '())))
(define dummy-procedure (lambda args *unspecified*))
(define-method (initialize (method <method>) initargs)
(next-method)
(slot-set! method 'generic-function (get-keyword #\generic-function initargs #f))
(slot-set! method 'specializers (get-keyword #\specializers initargs '()))
(slot-set! method 'procedure
(get-keyword #\procedure initargs #f))
(slot-set! method 'formals (get-keyword #\formals initargs '()))
(slot-set! method 'body (get-keyword #\body initargs '()))
(slot-set! method 'make-procedure (get-keyword #\make-procedure initargs #f)))
;;;
;;; {Change-class}
;;;
(define (change-object-class old-instance old-class new-class)
(let ((new-instance (allocate-instance new-class '())))
;; Initialize the slots of the new instance
(for-each (lambda (slot)
(if (and (slot-exists-using-class? old-class old-instance slot)
(eq? (slot-definition-allocation
(class-slot-definition old-class slot))
#\instance)
(slot-bound-using-class? old-class old-instance slot))
;; Slot was present and allocated in old instance; copy it
(slot-set-using-class!
new-class
new-instance
slot
(slot-ref-using-class old-class old-instance slot))
;; slot was absent; initialize it with its default value
(let ((init (slot-init-function new-class slot)))
(if init
(slot-set-using-class!
new-class
new-instance
slot
(apply init '()))))))
(map slot-definition-name (class-slots new-class)))
;; Exchange old and new instance in place to keep pointers valid
(%modify-instance old-instance new-instance)
;; Allow class specific updates of instances (which now are swapped)
(update-instance-for-different-class new-instance old-instance)
old-instance))
(define-method (update-instance-for-different-class (old-instance <object>)
(new-instance
<object>))
;;not really important what we do, we just need a default method
new-instance)
(define-method (change-class (old-instance <object>) (new-class <class>))
(change-object-class old-instance (class-of old-instance) new-class))
;;;
;;; {make}
;;;
;;; A new definition which overwrites the previous one which was built-in
;;;
(define-method (allocate-instance (class <class>) initargs)
(%allocate-instance class initargs))
(define-method (make-instance (class <class>) . initargs)
(let ((instance (allocate-instance class initargs)))
(initialize instance initargs)
instance))
(define make make-instance)
;;;
;;; {apply-generic}
;;;
;;; Protocol for calling standard generic functions. This protocol is
;;; not used for real <generic> functions (in this case we use a
;;; completely C hard-coded protocol). Apply-generic is used by
;;; goops for calls to subclasses of <generic> and <generic-with-setter>.
;;; The code below is similar to the first MOP described in AMOP. In
;;; particular, it doesn't used the currified approach to gf
;;; call. There are 2 reasons for that:
;;; - the protocol below is exposed to mimic completely the one written in C
;;; - the currified protocol would be imho inefficient in C.
;;;
(define-method (apply-generic (gf <generic>) args)
(if (null? (slot-ref gf 'methods))
(no-method gf args))
(let ((methods (compute-applicable-methods gf args)))
(if methods
(apply-methods gf (sort-applicable-methods gf methods args) args)
(no-applicable-method gf args))))
;; compute-applicable-methods is bound to %compute-applicable-methods.
;; *fixme* use let
(define %%compute-applicable-methods
(make <generic> #\name 'compute-applicable-methods))
(define-method (%%compute-applicable-methods (gf <generic>) args)
(%compute-applicable-methods gf args))
(set! compute-applicable-methods %%compute-applicable-methods)
(define-method (sort-applicable-methods (gf <generic>) methods args)
(let ((targs (map class-of args)))
(sort methods (lambda (m1 m2) (method-more-specific? m1 m2 targs)))))
(define-method (method-more-specific? (m1 <method>) (m2 <method>) targs)
(%method-more-specific? m1 m2 targs))
(define-method (apply-method (gf <generic>) methods build-next args)
(apply (method-procedure (car methods))
(build-next (cdr methods) args)
args))
(define-method (apply-methods (gf <generic>) (l <list>) args)
(letrec ((next (lambda (procs args)
(lambda new-args
(let ((a (if (null? new-args) args new-args)))
(if (null? procs)
(no-next-method gf a)
(apply-method gf procs next a)))))))
(apply-method gf l next args)))
;; We don't want the following procedure to turn up in backtraces:
(for-each (lambda (proc)
(set-procedure-property! proc 'system-procedure #t))
(list slot-unbound
slot-missing
no-next-method
no-applicable-method
no-method
))
;;;
;;; {<composite-metaclass> and <active-metaclass>}
;;;
;(autoload "active-slot" <active-metaclass>)
;(autoload "composite-slot" <composite-metaclass>)
;(export <composite-metaclass> <active-metaclass>)
;;;
;;; {Tools}
;;;
;; list2set
;;
;; duplicate the standard list->set function but using eq instead of
;; eqv which really sucks a lot, uselessly here
;;
(define (list2set l)
(let loop ((l l)
(res '()))
(cond
((null? l) res)
((memq (car l) res) (loop (cdr l) res))
(else (loop (cdr l) (cons (car l) res))))))
(define (class-subclasses c)
(letrec ((allsubs (lambda (c)
(cons c (mapappend allsubs
(class-direct-subclasses c))))))
(list2set (cdr (allsubs c)))))
(define (class-methods c)
(list2set (mapappend class-direct-methods
(cons c (class-subclasses c)))))
;;;
;;; {Final initialization}
;;;
;; Tell C code that the main bulk of Goops has been loaded
(%goops-loaded)
;;;; Copyright (C) 1999, 2000, 2005, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops accessors)
\:use-module (oop goops)
\:re-export (standard-define-class)
\:export (define-class-with-accessors
define-class-with-accessors-keywords))
(define-macro (define-class-with-accessors name supers . slots)
(let ((eat? #f))
`(standard-define-class
,name ,supers
,@(map-in-order
(lambda (slot)
(cond (eat?
(set! eat? #f)
slot)
((keyword? slot)
(set! eat? #t)
slot)
((pair? slot)
(if (get-keyword #\accessor (cdr slot) #f)
slot
(let ((name (car slot)))
`(,name #\accessor ,name ,@(cdr slot)))))
(else
`(,slot #\accessor ,slot))))
slots))))
(define-macro (define-class-with-accessors-keywords name supers . slots)
(let ((eat? #f))
`(standard-define-class
,name ,supers
,@(map-in-order
(lambda (slot)
(cond (eat?
(set! eat? #f)
slot)
((keyword? slot)
(set! eat? #t)
slot)
((pair? slot)
(let ((slot
(if (get-keyword #\accessor (cdr slot) #f)
slot
(let ((name (car slot)))
`(,name #\accessor ,name ,@(cdr slot))))))
(if (get-keyword #\init-keyword (cdr slot) #f)
slot
(let* ((name (car slot))
(keyword (symbol->keyword name)))
`(,name #\init-keyword ,keyword ,@(cdr slot))))))
(else
`(,slot #\accessor ,slot
#\init-keyword ,(symbol->keyword slot)))))
slots))))
;;; installed-scm-file
;;;; Copyright (C) 1999, 2001, 2006, 2009 Free Software Foundation, Inc.
;;;; Copyright (C) 1993-1998 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;;
;;;; This file was based upon active-slot.stklos from the STk distribution
;;;; version 4.0.1 by Erick Gallesio <eg@unice.fr>.
;;;;
(define-module (oop goops active-slot)
\:use-module (oop goops internal)
\:export (<active-class>))
(define-class <active-class> (<class>))
(define-method (compute-get-n-set (class <active-class>) slot)
(if (eq? (slot-definition-allocation slot) #\active)
(let* ((index (slot-ref class 'nfields))
(s (cdr slot))
(before-ref (get-keyword #\before-slot-ref s #f))
(after-ref (get-keyword #\after-slot-ref s #f))
(before-set! (get-keyword #\before-slot-set! s #f))
(after-set! (get-keyword #\after-slot-set! s #f))
(unbound (make-unbound)))
(slot-set! class 'nfields (+ index 1))
(list (lambda (o)
(if before-ref
(if (before-ref o)
(let ((res (%fast-slot-ref o index)))
(and after-ref (not (eqv? res unbound)) (after-ref o))
res)
(make-unbound))
(let ((res (%fast-slot-ref o index)))
(and after-ref (not (eqv? res unbound)) (after-ref o))
res)))
(lambda (o v)
(if before-set!
(if (before-set! o v)
(begin
(%fast-slot-set! o index v)
(and after-set! (after-set! o v))))
(begin
(%fast-slot-set! o index v)
(and after-set! (after-set! o v)))))))
(next-method)))
;;;; Copyright (C) 1999, 2001, 2006, 2009, 2015 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops compile)
#\use-module (oop goops internal)
#\re-export (compute-cmethod))
;;; installed-scm-file
;;;; Copyright (C) 1999, 2000, 2001, 2006 Free Software Foundation, Inc.
;;;; Copyright (C) 1993-1998 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;;
;;;; This file was based upon composite-slot.stklos from the STk distribution
;;;; version 4.0.1 by Erick Gallesio <eg@unice.fr>.
;;;;
(define-module (oop goops composite-slot)
\:use-module (oop goops)
\:export (<composite-class>))
;;;
;;; (define-class CLASS SUPERS
;;; ...
;;; (OBJECT ...)
;;; ...
;;; (SLOT #\allocation #\propagated
;;; #\propagate-to '(PROPAGATION ...))
;;; ...
;;; #\metaclass <composite-class>)
;;;
;;; PROPAGATION ::= OBJECT | (OBJECT TARGETSLOT)
;;;
;;; The slot SLOT will be propagated to the slot TARGETSLOT in the object
;;; stored in slot OBJECT. If TARGETSLOT is omitted, assume that the target
;;; slot is named SLOT.
;;;
(define-class <composite-class> (<class>))
(define-method (compute-get-n-set (class <composite-class>) slot)
(if (eq? (slot-definition-allocation slot) #\propagated)
(compute-propagated-get-n-set slot)
(next-method)))
(define (compute-propagated-get-n-set s)
(let ((prop (get-keyword #\propagate-to (cdr s) #f))
(s-name (slot-definition-name s)))
(if (not prop)
(goops-error "Propagation not specified for slot ~S" s-name))
(if (not (pair? prop))
(goops-error "Bad propagation list for slot ~S" s-name))
(let ((objects (map (lambda (p) (if (pair? p) (car p) p)) prop))
(slots (map (lambda (p) (if (pair? p) (cadr p) s-name)) prop)))
(let ((first-object (car objects))
(first-slot (car slots)))
(list
;; The getter
(lambda (o)
(slot-ref (slot-ref o first-object) first-slot))
;; The setter
(if (null? (cdr objects))
(lambda (o v)
(slot-set! (slot-ref o first-object) first-slot v))
(lambda (o v)
(for-each (lambda (object slot)
(slot-set! (slot-ref o object) slot v))
objects
slots))))))))
;;; installed-scm-file
;;;; Copyright (C) 1998, 1999, 2001, 2006, 2008, 2009 Free Software Foundation, Inc.
;;;; Copyright (C) 1993-1998 Erick Gallesio - I3S-CNRS/ESSI <eg@unice.fr>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;;;
;;;; This file was based upon describe.stklos from the STk distribution
;;;; version 4.0.1 by Erick Gallesio <eg@unice.fr>.
;;;;
(define-module (oop goops describe)
\:use-module (oop goops)
\:use-module (ice-9 session)
\:use-module (ice-9 format)
\:export (describe)) ; Export the describe generic function
;;;
;;; describe for simple objects
;;;
(define-method (describe (x <top>))
(format #t "~s is " x)
(cond
((integer? x) (format #t "an integer"))
((real? x) (format #t "a real"))
((complex? x) (format #t "a complex number"))
((null? x) (format #t "an empty list"))
((boolean? x) (format #t "a boolean value (~s)" (if x 'true 'false)))
((char? x) (format #t "a character, ascii value is ~s"
(char->integer x)))
((symbol? x) (format #t "a symbol"))
((list? x) (format #t "a list"))
((pair? x) (if (pair? (cdr x))
(format #t "an improper list")
(format #t "a pair")))
((string? x) (if (eqv? x "")
(format #t "an empty string")
(format #t "a string of length ~s" (string-length x))))
((vector? x) (if (eqv? x '#())
(format #t "an empty vector")
(format #t "a vector of length ~s" (vector-length x))))
((eof-object? x) (format #t "the end-of-file object"))
(else (format #t "an unknown object (~s)" x)))
(format #t ".~%")
*unspecified*)
(define-method (describe (x <procedure>))
(let ((name (procedure-name x)))
(if name
(format #t "`~s'" name)
(display x))
(display " is ")
(display (if name #\a "an anonymous"))
(display " procedure")
(display " with ")
(arity x)))
;;;
;;; describe for GOOPS instances
;;;
(define (safe-class-name class)
(if (slot-bound? class 'name)
(class-name class)
class))
(define-method (describe (x <object>))
(format #t "~S is an instance of class ~A~%"
x (safe-class-name (class-of x)))
;; print all the instance slots
(format #t "Slots are: ~%")
(for-each (lambda (slot)
(let ((name (slot-definition-name slot)))
(format #t " ~S = ~A~%"
name
(if (slot-bound? x name)
(format #f "~S" (slot-ref x name))
"#<unbound>"))))
(class-slots (class-of x)))
*unspecified*)
;;;
;;; Describe for classes
;;;
(define-method (describe (x <class>))
(format #t "~S is a class. It's an instance of ~A~%"
(safe-class-name x) (safe-class-name (class-of x)))
;; Super classes
(format #t "Superclasses are:~%")
(for-each (lambda (class) (format #t " ~A~%" (safe-class-name class)))
(class-direct-supers x))
;; Direct slots
(let ((slots (class-direct-slots x)))
(if (null? slots)
(format #t "(No direct slot)~%")
(begin
(format #t "Directs slots are:~%")
(for-each (lambda (s)
(format #t " ~A~%" (slot-definition-name s)))
slots))))
;; Direct subclasses
(let ((classes (class-direct-subclasses x)))
(if (null? classes)
(format #t "(No direct subclass)~%")
(begin
(format #t "Directs subclasses are:~%")
(for-each (lambda (s)
(format #t " ~A~%" (safe-class-name s)))
classes))))
;; CPL
(format #t "Class Precedence List is:~%")
(for-each (lambda (s) (format #t " ~A~%" (safe-class-name s)))
(class-precedence-list x))
;; Direct Methods
(let ((methods (class-direct-methods x)))
(if (null? methods)
(format #t "(No direct method)~%")
(begin
(format #t "Class direct methods are:~%")
(for-each describe methods))))
; (format #t "~%Field Initializers ~% ")
; (write (slot-ref x 'initializers)) (newline)
; (format #t "~%Getters and Setters~% ")
; (write (slot-ref x 'getters-n-setters)) (newline)
)
;;;
;;; Describe for generic functions
;;;
(define-method (describe (x <generic>))
(let ((name (generic-function-name x))
(methods (generic-function-methods x)))
;; Title
(format #t "~S is a generic function. It's an instance of ~A.~%"
name (safe-class-name (class-of x)))
;; Methods
(if (null? methods)
(format #t "(No method defined for ~S)~%" name)
(begin
(format #t "Methods defined for ~S~%" name)
(for-each (lambda (x) (describe x #t)) methods)))))
;;;
;;; Describe for methods
;;;
(define-method (describe (x <method>) . omit-generic)
(letrec ((print-args (lambda (args)
;; take care of dotted arg lists
(cond ((null? args) (newline))
((pair? args)
(display #\space)
(display (safe-class-name (car args)))
(print-args (cdr args)))
(else
(display #\space)
(display (safe-class-name args))
(newline))))))
;; Title
(format #t " Method ~A~%" x)
;; Associated generic
(if (null? omit-generic)
(let ((gf (method-generic-function x)))
(if gf
(format #t "\t Generic: ~A~%" (generic-function-name gf))
(format #t "\t(No generic)~%"))))
;; GF specializers
(format #t "\tSpecializers:")
(print-args (method-specializers x))))
(provide 'describe)
;;;; Copyright (C) 1999, 2000, 2001, 2003, 2006, 2009, 2012, 2015 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;; There are circularities here; you can't import (oop goops compile)
;; before (oop goops). So when compiling, make sure that things are
;; kosher.
(eval-when (expand) (resolve-module '(oop goops)))
(define-module (oop goops dispatch)
#\use-module (oop goops)
#\use-module (oop goops util)
#\use-module (system base target)
#\export (memoize-method!)
#\no-backtrace)
(define *dispatch-module* (current-module))
;;;
;;; Generic functions have an applicable-methods cache associated with
;;; them. Every distinct set of types that is dispatched through a
;;; generic adds an entry to the cache. This cache gets compiled out to
;;; a dispatch procedure. In steady-state, this dispatch procedure is
;;; never recompiled; but during warm-up there is some churn, both to
;;; the cache and to the dispatch procedure.
;;;
;;; So what is the deal if warm-up happens in a multithreaded context?
;;; There is indeed a window between missing the cache for a certain set
;;; of arguments, and then updating the cache with the newly computed
;;; applicable methods. One of the updaters is liable to lose their new
;;; entry.
;;;
;;; This is actually OK though, because a subsequent cache miss for the
;;; race loser will just cause memoization to try again. The cache will
;;; eventually be consistent. We're not mutating the old part of the
;;; cache, just consing on the new entry.
;;;
;;; It doesn't even matter if the dispatch procedure and the cache are
;;; inconsistent -- most likely the type-set that lost the dispatch
;;; procedure race will simply re-trigger a memoization, but since the
;;; winner isn't in the effective-methods cache, it will likely also
;;; re-trigger a memoization, and the cache will finally be consistent.
;;; As you can see there is a possibility for ping-pong effects, but
;;; it's unlikely given the shortness of the window between slot-set!
;;; invocations. We could add a mutex, but it is strictly unnecessary,
;;; and would add runtime cost and complexity.
;;;
(define (emit-linear-dispatch gf-sym nargs methods free rest?)
(define (gen-syms n stem)
(let lp ((n (1- n)) (syms '()))
(if (< n 0)
syms
(lp (1- n) (cons (gensym stem) syms)))))
(let* ((args (gen-syms nargs "a"))
(types (gen-syms nargs "t")))
(let lp ((methods methods)
(free free)
(exp `(cache-miss ,gf-sym
,(if rest?
`(cons* ,@args rest)
`(list ,@args)))))
(cond
((null? methods)
(values `(,(if rest? `(,@args . rest) args)
(let ,(map (lambda (t a)
`(,t (class-of ,a)))
types args)
,exp))
free))
(else
;; jeez
(let preddy ((free free)
(types types)
(specs (vector-ref (car methods) 1))
(checks '()))
(if (null? types)
(let ((m-sym (gensym "p")))
(lp (cdr methods)
(acons (vector-ref (car methods) 3)
m-sym
free)
`(if (and . ,checks)
,(if rest?
`(apply ,m-sym ,@args rest)
`(,m-sym . ,args))
,exp)))
(let ((var (assq-ref free (car specs))))
(if var
(preddy free
(cdr types)
(cdr specs)
(cons `(eq? ,(car types) ,var)
checks))
(let ((var (gensym "c")))
(preddy (acons (car specs) var free)
(cdr types)
(cdr specs)
(cons `(eq? ,(car types) ,var)
checks))))))))))))
(define (compute-dispatch-procedure gf cache)
(define (scan)
(let lp ((ls cache) (nreq -1) (nrest -1))
(cond
((null? ls)
(collate (make-vector (1+ nreq) '())
(make-vector (1+ nrest) '())))
((vector-ref (car ls) 2) ; rest
(lp (cdr ls) nreq (max nrest (vector-ref (car ls) 0))))
(else ; req
(lp (cdr ls) (max nreq (vector-ref (car ls) 0)) nrest)))))
(define (collate req rest)
(let lp ((ls cache))
(cond
((null? ls)
(emit req rest))
((vector-ref (car ls) 2) ; rest
(let ((n (vector-ref (car ls) 0)))
(vector-set! rest n (cons (car ls) (vector-ref rest n)))
(lp (cdr ls))))
(else ; req
(let ((n (vector-ref (car ls) 0)))
(vector-set! req n (cons (car ls) (vector-ref req n)))
(lp (cdr ls)))))))
(define (emit req rest)
(let ((gf-sym (gensym "g")))
(define (emit-rest n clauses free)
(if (< n (vector-length rest))
(let ((methods (vector-ref rest n)))
(cond
((null? methods)
(emit-rest (1+ n) clauses free))
;; FIXME: hash dispatch
(else
(call-with-values
(lambda ()
(emit-linear-dispatch gf-sym n methods free #t))
(lambda (clause free)
(emit-rest (1+ n) (cons clause clauses) free))))))
(emit-req (1- (vector-length req)) clauses free)))
(define (emit-req n clauses free)
(if (< n 0)
(comp `(lambda ,(map cdr free)
(case-lambda ,@clauses))
(map car free))
(let ((methods (vector-ref req n)))
(cond
((null? methods)
(emit-req (1- n) clauses free))
;; FIXME: hash dispatch
(else
(call-with-values
(lambda ()
(emit-linear-dispatch gf-sym n methods free #f))
(lambda (clause free)
(emit-req (1- n) (cons clause clauses) free))))))))
(emit-rest 0
(if (or (zero? (vector-length rest))
(null? (vector-ref rest 0)))
(list `(args (cache-miss ,gf-sym args)))
'())
(acons gf gf-sym '()))))
(define (comp exp vals)
;; When cross-compiling Guile itself, the native Guile must generate
;; code for the host.
(with-target %host-type
(lambda ()
(let ((p ((@ (system base compile) compile) exp
#\env *dispatch-module*
#\from 'scheme
#\opts '(#\partial-eval? #f #\cse? #f))))
(apply p vals)))))
;; kick it.
(scan))
;; o/~ ten, nine, eight
;; sometimes that's just how it goes
;; three, two, one
;;
;; get out before it blows o/~
;;
(define timer-init 30)
(define (delayed-compile gf)
(let ((timer timer-init))
(lambda args
(set! timer (1- timer))
(cond
((zero? timer)
(let ((dispatch (compute-dispatch-procedure
gf (slot-ref gf 'effective-methods))))
(slot-set! gf 'procedure dispatch)
(apply dispatch args)))
(else
;; interestingly, this catches recursive compilation attempts as
;; well; in that case, timer is negative
(cache-dispatch gf args))))))
(define (cache-dispatch gf args)
(define (map-until n f ls)
(if (or (zero? n) (null? ls))
'()
(cons (f (car ls)) (map-until (1- n) f (cdr ls)))))
(define (equal? x y) ; can't use the stock equal? because it's a generic...
(cond ((pair? x) (and (pair? y)
(eq? (car x) (car y))
(equal? (cdr x) (cdr y))))
((null? x) (null? y))
(else #f)))
(if (slot-ref gf 'n-specialized)
(let ((types (map-until (slot-ref gf 'n-specialized) class-of args)))
(let lp ((cache (slot-ref gf 'effective-methods)))
(cond ((null? cache)
(cache-miss gf args))
((equal? (vector-ref (car cache) 1) types)
(apply (vector-ref (car cache) 3) args))
(else (lp (cdr cache))))))
(cache-miss gf args)))
(define (cache-miss gf args)
(apply (memoize-method! gf args) args))
(define (memoize-effective-method! gf args applicable)
(define (first-n ls n)
(if (or (zero? n) (null? ls))
'()
(cons (car ls) (first-n (cdr ls) (- n 1)))))
(define (parse n ls)
(cond ((null? ls)
(memoize n #f (map class-of args)))
((= n (slot-ref gf 'n-specialized))
(memoize n #t (map class-of (first-n args n))))
(else
(parse (1+ n) (cdr ls)))))
(define (memoize len rest? types)
(let* ((cmethod ((@@ (oop goops) compute-cmethod) applicable types))
(cache (cons (vector len types rest? cmethod)
(slot-ref gf 'effective-methods))))
(slot-set! gf 'effective-methods cache)
(slot-set! gf 'procedure (delayed-compile gf))
cmethod))
(parse 0 args))
;;;
;;; Memoization
;;;
(define (memoize-method! gf args)
(let ((applicable ((if (eq? gf compute-applicable-methods)
%compute-applicable-methods
compute-applicable-methods)
gf args)))
(cond (applicable
(memoize-effective-method! gf args applicable))
(else
(no-applicable-method gf args)))))
(set-procedure-property! memoize-method! 'system-procedure #t)
;;; installed-scm-file
;;;; Copyright (C) 1999, 2001, 2006 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops internal)
\:use-module (oop goops))
;; Export all the bindings that are internal to `(oop goops)'.
(let ((public-i (module-public-interface (current-module))))
(module-for-each (lambda (name var)
(if (eq? name '%module-public-interface)
#t
(module-add! public-i name var)))
(resolve-module '(oop goops))))
;;; installed-scm-file
;;;; Copyright (C) 2000,2001,2002, 2006, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops save)
\:use-module (oop goops internal)
\:use-module (oop goops util)
\:re-export (make-unbound)
\:export (save-objects load-objects restore
enumerate! enumerate-component!
write-readably write-component write-component-procedure
literal? readable make-readable))
;;;
;;; save-objects ALIST PORT [EXCLUDED] [USES]
;;;
;;; ALIST ::= ((NAME . OBJECT) ...)
;;;
;;; Save OBJECT ... to PORT so that when the data is read and evaluated
;;; OBJECT ... are re-created under names NAME ... .
;;; Exclude any references to objects in the list EXCLUDED.
;;; Add a (use-modules . USES) line to the top of the saved text.
;;;
;;; In some instances, when `save-object' doesn't know how to produce
;;; readable syntax for an object, you can explicitly register read
;;; syntax for an object using the special form `readable'.
;;;
;;; Example:
;;;
;;; The function `foo' produces an object of obscure structure.
;;; Only `foo' can construct such objects. Because of this, an
;;; object such as
;;;
;;; (define x (vector 1 (foo)))
;;;
;;; cannot be saved by `save-objects'. But if you instead write
;;;
;;; (define x (vector 1 (readable (foo))))
;;;
;;; `save-objects' will happily produce the necessary read syntax.
;;;
;;; To add new read syntax, hang methods on `enumerate!' and
;;; `write-readably'.
;;;
;;; enumerate! OBJECT ENV
;;; Should call `enumerate-component!' (which takes same args) on
;;; each component object. Should return #t if the composite object
;;; can be written as a literal. (`enumerate-component!' returns #t
;;; if the component is a literal.
;;;
;;; write-readably OBJECT PORT ENV
;;; Should write a readable representation of OBJECT to PORT.
;;; Should use `write-component' to print each component object.
;;; Use `literal?' to decide if a component is a literal.
;;;
;;; Utilities:
;;;
;;; enumerate-component! OBJECT ENV
;;;
;;; write-component OBJECT PATCHER PORT ENV
;;; PATCHER is an expression which, when evaluated, stores OBJECT
;;; into its current location.
;;;
;;; Example:
;;;
;;; (write-component (car ls) `(set-car! ,ls ,(car ls)) file env)
;;;
;;; write-component is a macro.
;;;
;;; literal? COMPONENT ENV
;;;
(define-method (immediate? (o <top>)) #f)
(define-method (immediate? (o <null>)) #t)
(define-method (immediate? (o <number>)) #t)
(define-method (immediate? (o <boolean>)) #t)
(define-method (immediate? (o <symbol>)) #t)
(define-method (immediate? (o <char>)) #t)
(define-method (immediate? (o <keyword>)) #t)
;;; enumerate! OBJECT ENVIRONMENT
;;;
;;; Return #t if object is a literal.
;;;
(define-method (enumerate! (o <top>) env) #t)
(define-method (write-readably (o <top>) file env)
;;(goops-error "No read-syntax defined for object `~S'" o)
(write o file) ;doesn't catch bugs, but is much more flexible
)
;;;
;;; Readables
;;;
(define readables (make-weak-key-hash-table 61))
(define-macro (readable exp)
`(make-readable ,exp ',(copy-tree exp)))
(define (make-readable obj expr)
(hashq-set! readables obj expr)
obj)
(define (readable-expression obj)
`(readable ,(hashq-ref readables obj)))
;; FIXME: if obj is nil or false, this can return a false value. OTOH
;; usually this is only for non-immediates.
(define (readable? obj)
(hashq-ref readables obj))
;;;
;;; Writer helpers
;;;
(define (write-component-procedure o file env)
"Return #f if circular reference"
(cond ((immediate? o) (write o file) #t)
((readable? o) (write (readable-expression o) file) #t)
((excluded? o env) (display #f file) #t)
(else
(let ((info (object-info o env)))
(cond ((not (binding? info)) (write-readably o file env) #t)
((not (eq? (visiting info) #\defined)) #f) ;forward reference
(else (display (binding info) file) #t))))))
;;; write-component OBJECT PATCHER FILE ENV
;;;
(define-macro (write-component object patcher file env)
`(or (write-component-procedure ,object ,file ,env)
(begin
(display #f ,file)
(add-patcher! ,patcher ,env))))
;;;
;;; Strings
;;;
(define-method (enumerate! (o <string>) env) #f)
;;;
;;; Vectors
;;;
(define-method (enumerate! (o <vector>) env)
(or (not (vector? o))
(let ((literal? #t))
(array-for-each (lambda (o)
(if (not (enumerate-component! o env))
(set! literal? #f)))
o)
literal?)))
(define-method (write-readably (o <vector>) file env)
(if (not (vector? o))
(write o file)
(let ((n (vector-length o)))
(if (zero? n)
(display "#()" file)
(let ((not-literal? (not (literal? o env))))
(display (if not-literal?
"(vector "
"#(")
file)
(if (and not-literal?
(literal? (vector-ref o 0) env))
(display #\' file))
(write-component (vector-ref o 0)
`(vector-set! ,o 0 ,(vector-ref o 0))
file
env)
(do ((i 1 (+ 1 i)))
((= i n))
(display #\space file)
(if (and not-literal?
(literal? (vector-ref o i) env))
(display #\' file))
(write-component (vector-ref o i)
`(vector-set! ,o ,i ,(vector-ref o i))
file
env))
(display #\) file))))))
;;;
;;; Arrays
;;;
(define-method (enumerate! (o <array>) env)
(enumerate-component! (shared-array-root o) env))
(define (make-mapper array)
(let* ((n (array-rank array))
(indices (reverse (if (<= n 11)
(list-tail '(t s r q p n m l k j i) (- 11 n))
(let loop ((n n)
(ls '()))
(if (zero? n)
ls
(loop (- n 1)
(cons (gensym "i") ls))))))))
`(lambda ,indices
(+ ,(shared-array-offset array)
,@(map (lambda (ind dim inc)
`(* ,inc ,(if (pair? dim) `(- ,ind ,(car dim)) ind)))
indices
(array-dimensions array)
(shared-array-increments array))))))
(define (write-array prefix o not-literal? file env)
(letrec ((inner (lambda (n indices)
(if (not (zero? n))
(let ((el (apply array-ref o
(reverse (cons 0 indices)))))
(if (and not-literal?
(literal? el env))
(display #\' file))
(write-component
el
`(array-set! ,o ,el ,@indices)
file
env)))
(do ((i 1 (+ 1 i)))
((= i n))
(display #\space file)
(let ((el (apply array-ref o
(reverse (cons i indices)))))
(if (and not-literal?
(literal? el env))
(display #\' file))
(write-component
el
`(array-set! ,o ,el ,@indices)
file
env))))))
(display prefix file)
(let loop ((dims (array-dimensions o))
(indices '()))
(cond ((null? (cdr dims))
(inner (car dims) indices))
(else
(let ((n (car dims)))
(do ((i 0 (+ 1 i)))
((= i n))
(if (> i 0)
(display #\space file))
(display prefix file)
(loop (cdr dims) (cons i indices))
(display #\) file))))))
(display #\) file)))
(define-method (write-readably (o <array>) file env)
(let ((root (shared-array-root o)))
(cond ((literal? o env)
(if (not (vector? root))
(write o file)
(begin
(display #\# file)
(display (array-rank o) file)
(write-array #\( o #f file env))))
((binding? root env)
(display "(make-shared-array " file)
(if (literal? root env)
(display #\' file))
(write-component root
(goops-error "write-readably(<array>): internal error")
file
env)
(display #\space file)
(display (make-mapper o) file)
(for-each (lambda (dim)
(display #\space file)
(display dim file))
(array-dimensions o))
(display #\) file))
(else
(display "(list->uniform-array " file)
(display (array-rank o) file)
(display " '() " file)
(write-array "(list " o #f file env)))))
;;;
;;; Pairs
;;;
;;; These methods have more complex structure than is required for
;;; most objects, since they take over some of the logic of
;;; `write-component'.
;;;
(define-method (enumerate! (o <pair>) env)
(let ((literal? (enumerate-component! (car o) env)))
(and (enumerate-component! (cdr o) env)
literal?)))
(define-method (write-readably (o <pair>) file env)
(let ((proper? (let loop ((ls o))
(or (null? ls)
(and (pair? ls)
(not (binding? (cdr ls) env))
(loop (cdr ls))))))
(1? (or (not (pair? (cdr o)))
(binding? (cdr o) env)))
(not-literal? (not (literal? o env)))
(infos '())
(refs (ref-stack env)))
(display (cond ((not not-literal?) #\()
(proper? "(list ")
(1? "(cons ")
(else "(cons* "))
file)
(if (and not-literal?
(literal? (car o) env))
(display #\' file))
(write-component (car o) `(set-car! ,o ,(car o)) file env)
(do ((ls (cdr o) (cdr ls))
(prev o ls))
((or (not (pair? ls))
(binding? ls env))
(if (not (null? ls))
(begin
(if (not not-literal?)
(display " ." file))
(display #\space file)
(if (and not-literal?
(literal? ls env))
(display #\' file))
(write-component ls `(set-cdr! ,prev ,ls) file env)))
(display #\) file))
(display #\space file)
(set! infos (cons (object-info ls env) infos))
(push-ref! ls env) ;*fixme* optimize
(set! (visiting? (car infos)) #t)
(if (and not-literal?
(literal? (car ls) env))
(display #\' file))
(write-component (car ls) `(set-car! ,ls ,(car ls)) file env)
)
(for-each (lambda (info)
(set! (visiting? info) #f))
infos)
(set! (ref-stack env) refs)
))
;;;
;;; Objects
;;;
;;; Doesn't yet handle unbound slots
;; Don't export this function! This is all very temporary.
;;
(define (get-set-for-each proc class)
(for-each (lambda (slotdef g-n-s)
(let ((g-n-s (cddr g-n-s)))
(cond ((integer? g-n-s)
(proc (standard-get g-n-s) (standard-set g-n-s)))
((not (memq (slot-definition-allocation slotdef)
'(#\class #\each-subclass)))
(proc (car g-n-s) (cadr g-n-s))))))
(class-slots class)
(slot-ref class 'getters-n-setters)))
(define (access-for-each proc class)
(for-each (lambda (slotdef g-n-s)
(let ((g-n-s (cddr g-n-s))
(a (slot-definition-accessor slotdef)))
(cond ((integer? g-n-s)
(proc (slot-definition-name slotdef)
(and a (generic-function-name a))
(standard-get g-n-s)
(standard-set g-n-s)))
((not (memq (slot-definition-allocation slotdef)
'(#\class #\each-subclass)))
(proc (slot-definition-name slotdef)
(and a (generic-function-name a))
(car g-n-s)
(cadr g-n-s))))))
(class-slots class)
(slot-ref class 'getters-n-setters)))
(define-macro (restore class slots . exps)
"(restore CLASS (SLOT-NAME1 ...) EXP1 ...)"
`(let ((o ((@@ (oop goops) %allocate-instance) ,class '())))
(for-each (lambda (name val)
(slot-set! o name val))
',slots
(list ,@exps))
o))
(define-method (enumerate! (o <object>) env)
(get-set-for-each (lambda (get set)
(let ((val (get o)))
(if (not (unbound? val))
(enumerate-component! val env))))
(class-of o))
#f)
(define-method (write-readably (o <object>) file env)
(let ((class (class-of o)))
(display "(restore " file)
(display (class-name class) file)
(display " (" file)
(let ((slotdefs
(filter (lambda (slotdef)
(not (or (memq (slot-definition-allocation slotdef)
'(#\class #\each-subclass))
(and (slot-bound? o (slot-definition-name slotdef))
(excluded?
(slot-ref o (slot-definition-name slotdef))
env)))))
(class-slots class))))
(if (not (null? slotdefs))
(begin
(display (slot-definition-name (car slotdefs)) file)
(for-each (lambda (slotdef)
(display #\space file)
(display (slot-definition-name slotdef) file))
(cdr slotdefs)))))
(display #\) file)
(access-for-each (lambda (name aname get set)
(display #\space file)
(let ((val (get o)))
(cond ((unbound? val)
(display '(make-unbound) file))
((excluded? val env))
(else
(if (literal? val env)
(display #\' file))
(write-component val
(if aname
`(set! (,aname ,o) ,val)
`(slot-set! ,o ',name ,val))
file env)))))
class)
(display #\) file)))
;;;
;;; Classes
;;;
;;; Currently, we don't support reading in class objects
;;;
(define-method (enumerate! (o <class>) env) #f)
(define-method (write-readably (o <class>) file env)
(display (class-name o) file))
;;;
;;; Generics
;;;
;;; Currently, we don't support reading in generic functions
;;;
(define-method (enumerate! (o <generic>) env) #f)
(define-method (write-readably (o <generic>) file env)
(display (generic-function-name o) file))
;;;
;;; Method
;;;
;;; Currently, we don't support reading in methods
;;;
(define-method (enumerate! (o <method>) env) #f)
(define-method (write-readably (o <method>) file env)
(goops-error "No read-syntax for <method> defined"))
;;;
;;; Environments
;;;
(define-class <environment> ()
(object-info #\accessor object-info
#\init-form (make-hash-table 61))
(excluded #\accessor excluded
#\init-form (make-hash-table 61))
(pass-2? #\accessor pass-2?
#\init-value #f)
(ref-stack #\accessor ref-stack
#\init-value '())
(objects #\accessor objects
#\init-value '())
(pre-defines #\accessor pre-defines
#\init-value '())
(locals #\accessor locals
#\init-value '())
(stand-ins #\accessor stand-ins
#\init-value '())
(post-defines #\accessor post-defines
#\init-value '())
(patchers #\accessor patchers
#\init-value '())
(multiple-bound #\accessor multiple-bound
#\init-value '())
)
(define-method (initialize (env <environment>) initargs)
(next-method)
(cond ((get-keyword #\excluded initargs #f)
=> (lambda (excludees)
(for-each (lambda (e)
(hashq-create-handle! (excluded env) e #f))
excludees)))))
(define-method (object-info o env)
(hashq-ref (object-info env) o))
(define-method ((setter object-info) o env x)
(hashq-set! (object-info env) o x))
(define (excluded? o env)
(hashq-get-handle (excluded env) o))
(define (add-patcher! patcher env)
(set! (patchers env) (cons patcher (patchers env))))
(define (push-ref! o env)
(set! (ref-stack env) (cons o (ref-stack env))))
(define (pop-ref! env)
(set! (ref-stack env) (cdr (ref-stack env))))
(define (container env)
(car (ref-stack env)))
(define-class <object-info> ()
(visiting #\accessor visiting
#\init-value #f)
(binding #\accessor binding
#\init-value #f)
(literal? #\accessor literal?
#\init-value #f)
)
(define visiting? visiting)
(define-method (binding (info <boolean>))
#f)
(define-method (binding o env)
(binding (object-info o env)))
(define binding? binding)
(define-method (literal? (info <boolean>))
#t)
;;; Note that this method is intended to be used only during the
;;; writing pass
;;;
(define-method (literal? o env)
(or (immediate? o)
(excluded? o env)
(let ((info (object-info o env)))
;; write-component sets all bindings first to #\defining,
;; then to #\defined
(and (or (not (binding? info))
;; we might be using `literal?' in a write-readably method
;; to query about the object being defined
(and (eq? (visiting info) #\defining)
(null? (cdr (ref-stack env)))))
(literal? info)))))
;;;
;;; Enumeration
;;;
;;; Enumeration has two passes.
;;;
;;; Pass 1: Detect common substructure, circular references and order
;;;
;;; Pass 2: Detect literals
(define (enumerate-component! o env)
(cond ((immediate? o) #t)
((readable? o) #f)
((excluded? o env) #t)
((pass-2? env)
(let ((info (object-info o env)))
(if (binding? info)
;; if circular reference, we print as a literal
;; (note that during pass-2, circular references are
;; forward references, i.e. *not* yet marked with #\pass-2
(not (eq? (visiting? info) #\pass-2))
(and (enumerate! o env)
(begin
(set! (literal? info) #t)
#t)))))
((object-info o env)
=> (lambda (info)
(set! (binding info) #t)
(if (visiting? info)
;; circular reference--mark container
(set! (binding (object-info (container env) env)) #t))))
(else
(let ((info (make <object-info>)))
(set! (object-info o env) info)
(push-ref! o env)
(set! (visiting? info) #t)
(enumerate! o env)
(set! (visiting? info) #f)
(pop-ref! env)
(set! (objects env) (cons o (objects env)))))))
;;;
;;; Main engine
;;;
(define binding-name car)
(define binding-object cdr)
(define (pass-1! alist env)
;; Determine object order and necessary bindings
(for-each (lambda (binding)
(enumerate-component! (binding-object binding) env))
alist))
(define (make-local i)
(string->symbol (string-append "%o" (number->string i))))
(define (name-bindings! alist env)
;; Name top-level bindings
(for-each (lambda (b)
(let ((o (binding-object b)))
(if (not (or (immediate? o)
(readable? o)
(excluded? o env)))
(let ((info (object-info o env)))
(if (symbol? (binding info))
;; already bound to a variable
(set! (multiple-bound env)
(acons (binding info)
(binding-name b)
(multiple-bound env)))
(set! (binding info)
(binding-name b)))))))
alist)
;; Name rest of bindings and create stand-in and definition lists
(let post-loop ((ls (objects env))
(post-defs '()))
(cond ((or (null? ls)
(eq? (binding (car ls) env) #t))
(set! (post-defines env) post-defs)
(set! (objects env) ls))
((not (binding (car ls) env))
(post-loop (cdr ls) post-defs))
(else
(post-loop (cdr ls) (cons (car ls) post-defs)))))
(let pre-loop ((ls (reverse (objects env)))
(i 0)
(pre-defs '())
(locs '())
(sins '()))
(if (null? ls)
(begin
(set! (pre-defines env) (reverse pre-defs))
(set! (locals env) (reverse locs))
(set! (stand-ins env) (reverse sins)))
(let ((info (object-info (car ls) env)))
(cond ((not (binding? info))
(pre-loop (cdr ls) i pre-defs locs sins))
((boolean? (binding info))
;; local
(set! (binding info) (make-local i))
(pre-loop (cdr ls)
(+ 1 i)
pre-defs
(cons (car ls) locs)
sins))
((null? locs)
(pre-loop (cdr ls)
i
(cons (car ls) pre-defs)
locs
sins))
(else
(let ((real-name (binding info)))
(set! (binding info) (make-local i))
(pre-loop (cdr ls)
(+ 1 i)
pre-defs
(cons (car ls) locs)
(acons (binding info) real-name sins)))))))))
(define (pass-2! env)
(set! (pass-2? env) #t)
(for-each (lambda (o)
(let ((info (object-info o env)))
(set! (literal? info) (enumerate! o env))
(set! (visiting info) #\pass-2)))
(append (pre-defines env)
(locals env)
(post-defines env))))
(define (write-define! name val literal? file)
(display "(define " file)
(display name file)
(display #\space file)
(if literal? (display #\' file))
(write val file)
(display ")\n" file))
(define (write-empty-defines! file env)
(for-each (lambda (stand-in)
(write-define! (cdr stand-in) #f #f file))
(stand-ins env))
(for-each (lambda (o)
(write-define! (binding o env) #f #f file))
(post-defines env)))
(define (write-definition! prefix o file env)
(display prefix file)
(let ((info (object-info o env)))
(display (binding info) file)
(display #\space file)
(if (literal? info)
(display #\' file))
(push-ref! o env)
(set! (visiting info) #\defining)
(write-readably o file env)
(set! (visiting info) #\defined)
(pop-ref! env)
(display #\) file)))
(define (write-let*-head! file env)
(display "(let* (" file)
(write-definition! "(" (car (locals env)) file env)
(for-each (lambda (o)
(write-definition! "\n (" o file env))
(cdr (locals env)))
(display ")\n" file))
(define (write-rebindings! prefix bindings file env)
(for-each (lambda (patch)
(display prefix file)
(display (cdr patch) file)
(display #\space file)
(display (car patch) file)
(display ")\n" file))
bindings))
(define (write-definitions! selector prefix file env)
(for-each (lambda (o)
(write-definition! prefix o file env)
(newline file))
(selector env)))
(define (write-patches! prefix file env)
(for-each (lambda (patch)
(display prefix file)
(display (let name-objects ((patcher patch))
(cond ((binding patcher env)
=> (lambda (name)
(cond ((assq name (stand-ins env))
=> cdr)
(else name))))
((pair? patcher)
(cons (name-objects (car patcher))
(name-objects (cdr patcher))))
(else patcher)))
file)
(newline file))
(reverse (patchers env))))
(define (write-immediates! alist file)
(for-each (lambda (b)
(if (immediate? (binding-object b))
(write-define! (binding-name b)
(binding-object b)
#t
file)))
alist))
(define (write-readables! alist file env)
(let ((written '()))
(for-each (lambda (b)
(cond ((not (readable? (binding-object b))))
((assq (binding-object b) written)
=> (lambda (p)
(set! (multiple-bound env)
(acons (cdr p)
(binding-name b)
(multiple-bound env)))))
(else
(write-define! (binding-name b)
(readable-expression (binding-object b))
#f
file)
(set! written (acons (binding-object b)
(binding-name b)
written)))))
alist)))
(define-method (save-objects (alist <pair>) (file <string>) . rest)
(let ((port (open-output-file file)))
(apply save-objects alist port rest)
(close-port port)
*unspecified*))
(define-method (save-objects (alist <pair>) (file <output-port>) . rest)
(let ((excluded (if (>= (length rest) 1) (car rest) '()))
(uses (if (>= (length rest) 2) (cadr rest) '())))
(let ((env (make <environment> #\excluded excluded)))
(pass-1! alist env)
(name-bindings! alist env)
(pass-2! env)
(if (not (null? uses))
(begin
(write `(use-modules ,@uses) file)
(newline file)))
(write-immediates! alist file)
(if (null? (locals env))
(begin
(write-definitions! post-defines "(define " file env)
(write-patches! "" file env))
(begin
(write-definitions! pre-defines "(define " file env)
(write-empty-defines! file env)
(write-let*-head! file env)
(write-rebindings! " (set! " (stand-ins env) file env)
(write-definitions! post-defines " (set! " file env)
(write-patches! " " file env)
(display " )\n" file)))
(write-readables! alist file env)
(write-rebindings! "(define " (reverse (multiple-bound env)) file env))))
(define-method (load-objects (file <string>))
(let* ((port (open-input-file file))
(objects (load-objects port)))
(close-port port)
objects))
(define iface (module-public-interface (current-module)))
(define-method (load-objects (file <input-port>))
(let ((m (make-module)))
(module-use! m the-scm-module)
(module-use! m iface)
(save-module-excursion
(lambda ()
(set-current-module m)
(let loop ((sexp (read file)))
(if (not (eof-object? sexp))
(begin
(eval sexp m)
(loop (read file)))))))
(module-map (lambda (name var)
(cons name (variable-ref var)))
m)))
;;; installed-scm-file
;;;; Copyright (C) 2005, 2006, 2010, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops simple)
\:use-module (oop goops accessors)
\:export (define-class)
\:no-backtrace)
(define-syntax-rule (define-class arg ...)
(define-class-with-accessors-keywords arg ...))
(module-use! (module-public-interface (current-module))
(resolve-interface '(oop goops)))
;;;; Copyright (C) 1999,2002, 2006, 2010, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops stklos)
\:use-module (oop goops internal)
\:no-backtrace
)
;;;
;;; This is the stklos compatibility module.
;;;
;;; WARNING: This module is under construction. While we expect to be able
;;; to run most stklos code without problems in the future, this is not the
;;; case now. The current compatibility is only superficial.
;;;
;;; Any comments/complaints/patches are welcome. Tell us about
;;; your incompatibility problems (bug-guile@gnu.org).
;;;
;; Export all bindings that are exported from (oop goops)...
(module-for-each (lambda (sym var)
(module-add! (module-public-interface (current-module))
sym var))
(resolve-interface '(oop goops)))
;; ...but replace the following bindings:
(export define-class define-method)
;; Also export the following
(export write-object)
;;; Enable keyword support (*fixme*---currently this has global effect)
(read-set! keywords 'prefix)
(define-syntax-rule (define-class name supers (slot ...) rest ...)
(standard-define-class name supers slot ... rest ...))
(define (toplevel-define! name val)
(module-define! (current-module) name val))
(define-syntax define-method
(syntax-rules (setter)
((_ (setter name) rest ...)
(begin
(if (or (not (defined? 'name))
(not (is-a? name <generic-with-setter>)))
(toplevel-define! 'name
(ensure-accessor
(if (defined? 'name) name #f) 'name)))
(add-method! (setter name) (method rest ...))))
((_ name rest ...)
(begin
(if (or (not (defined? 'name))
(not (or (is-a? name <generic>)
(is-a? name <primitive-generic>))))
(toplevel-define! 'name
(ensure-generic
(if (defined? 'name) name #f) 'name)))
(add-method! name (method rest ...))))))
;;;; Copyright (C) 1999, 2000, 2001, 2003, 2006, 2008 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (oop goops util)
\:export (mapappend find-duplicate
map* for-each* length* improper->proper)
\:use-module (srfi srfi-1)
\:re-export (any every)
\:no-backtrace
)
;;;
;;; {Utilities}
;;;
(define mapappend append-map)
(define (find-duplicate l) ; find a duplicate in a list; #f otherwise
(cond
((null? l) #f)
((memv (car l) (cdr l)) (car l))
(else (find-duplicate (cdr l)))))
(begin-deprecated
(define (top-level-env)
(let ((mod (current-module)))
(if mod
(module-eval-closure mod)
'())))
(define (top-level-env? env)
(or (null? env)
(procedure? (car env))))
(export top-level-env? top-level-env))
(define (map* fn . l) ; A map which accepts dotted lists (arg lists
(cond ; must be "isomorph"
((null? (car l)) '())
((pair? (car l)) (cons (apply fn (map car l))
(apply map* fn (map cdr l))))
(else (apply fn l))))
(define (for-each* fn . l) ; A for-each which accepts dotted lists (arg lists
(cond ; must be "isomorph"
((null? (car l)) '())
((pair? (car l)) (apply fn (map car l)) (apply for-each* fn (map cdr l)))
(else (apply fn l))))
(define (length* ls)
(do ((n 0 (+ 1 n))
(ls ls (cdr ls)))
((not (pair? ls)) n)))
(define (improper->proper ls)
(if (pair? ls)
(cons (car ls) (improper->proper (cdr ls)))
(list ls)))
;;; rnrs.scm --- The R6RS composite library
;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs (6))
(export ;; (rnrs arithmetic bitwise)
bitwise-not bitwise-and bitwise-ior bitwise-xor bitwise-if
bitwise-bit-count bitwise-length bitwise-first-bit-set
bitwise-bit-set? bitwise-copy-bit bitwise-bit-field
bitwise-copy-bit-field bitwise-arithmetic-shift
bitwise-arithmetic-shift-left bitwise-arithmetic-shift-right
bitwise-rotate-bit-field bitwise-reverse-bit-field
;; (rnrs arithmetic fixnums)
fixnum? fixnum-width least-fixnum greatest-fixnum fx=? fx>? fx<? fx>=?
fx<=? fxzero? fxpositive? fxnegative? fxodd? fxeven? fxmax fxmin fx+
fx* fx- fxdiv-and-mod fxdiv fxmod fxdiv0-and-mod0 fxdiv0 fxmod0
fx+/carry fx-/carry fx*/carry fxnot fxand fxior fxxor fxif fxbit-count
fxlength fxfirst-bit-set fxbit-set? fxcopy-bit fxbit-field
fxcopy-bit-field fxarithmetic-shift fxarithmetic-shift-left
fxarithmetic-shift-right fxrotate-bit-field fxreverse-bit-field
;; (rnrs arithmetic flonums)
flonum? real->flonum fl=? fl<? fl<=? fl>? fl>=? flinteger? flzero?
flpositive? flnegative? flodd? fleven? flfinite? flinfinite? flnan?
flmax flmin fl+ fl* fl- fl/ flabs fldiv-and-mod fldiv flmod
fldiv0-and-mod0 fldiv0 flmod0 flnumerator fldenominator flfloor
flceiling fltruncate flround flexp fllog flsin flcos fltan flacos
flasin flatan flsqrt flexpt &no-infinities
make-no-infinities-violation no-infinities-violation? &no-nans
make-no-nans-violation no-nans-violation? fixnum->flonum
;; (rnrs base)
boolean? symbol? char? vector? null? pair? number? string? procedure?
define define-syntax syntax-rules lambda let let* let-values
let*-values letrec letrec* begin quote lambda if set! cond case or
and not eqv? equal? eq? + - * / max min abs numerator denominator gcd
lcm floor ceiling truncate round rationalize real-part imag-part
make-rectangular angle div mod div-and-mod div0 mod0 div0-and-mod0
expt exact-integer-sqrt sqrt exp log sin cos tan asin acos atan
make-polar magnitude angle complex? real? rational? integer? exact?
inexact? real-valued? rational-valued? integer-valued? zero?
positive? negative? odd? even? nan? finite? infinite? exact inexact =
< > <= >= number->string string->number boolean=? cons car cdr caar
cadr cdar cddr caaar caadr cadar cdaar caddr cdadr cddar cdddr caaaar
caaadr caadar cadaar cdaaar cddaar cdadar cdaadr cadadr caaddr caddar
cadddr cdaddr cddadr cdddar cddddr list? list length append reverse
list-tail list-ref map for-each symbol->string string->symbol symbol=?
char->integer integer->char char=? char<? char>? char<=? char>=?
make-string string string-length string-ref string=? string<? string>?
string<=? string>=? substring string-append string->list list->string
string-for-each string-copy vector? make-vector vector vector-length
vector-ref vector-set! vector->list list->vector vector-fill!
vector-map vector-for-each error assertion-violation assert
call-with-current-continuation call/cc call-with-values dynamic-wind
values apply quasiquote unquote unquote-splicing let-syntax
letrec-syntax syntax-rules identifier-syntax
;; (rnrs bytevectors)
endianness native-endianness bytevector? make-bytevector
bytevector-length bytevector=? bytevector-fill! bytevector-copy!
bytevector-copy uniform-array->bytevector bytevector-u8-ref
bytevector-s8-ref bytevector-u8-set! bytevector-s8-set!
bytevector->u8-list u8-list->bytevector bytevector-uint-ref
bytevector-uint-set! bytevector-sint-ref bytevector-sint-set!
bytevector->sint-list bytevector->uint-list uint-list->bytevector
sint-list->bytevector bytevector-u16-ref bytevector-s16-ref
bytevector-u16-set! bytevector-s16-set! bytevector-u16-native-ref
bytevector-s16-native-ref bytevector-u16-native-set!
bytevector-s16-native-set! bytevector-u32-ref bytevector-s32-ref
bytevector-u32-set! bytevector-s32-set! bytevector-u32-native-ref
bytevector-s32-native-ref bytevector-u32-native-set!
bytevector-s32-native-set! bytevector-u64-ref bytevector-s64-ref
bytevector-u64-set! bytevector-s64-set! bytevector-u64-native-ref
bytevector-s64-native-ref bytevector-u64-native-set!
bytevector-s64-native-set! bytevector-ieee-single-ref
bytevector-ieee-single-set! bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set! bytevector-ieee-double-ref
bytevector-ieee-double-set! bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set! string->utf8 string->utf16
string->utf32 utf8->string utf16->string utf32->string
;; (rnrs conditions)
&condition condition simple-conditions condition? condition-predicate
condition-accessor define-condition-type &message
make-message-condition message-condition? condition-message &warning
make-warning warning? &serious make-serious-condition
serious-condition? &error make-error error? &violation make-violation
violation? &assertion make-assertion-violation assertion-violation?
&irritants make-irritants-condition irritants-condition?
condition-irritants &who make-who-condition who-condition?
condition-who &non-continuable make-non-continuable-violation
non-continuable-violation? &implementation-restriction
make-implementation-restriction-violation
implementation-restriction-violation? &lexical make-lexical-violation
lexical-violation? &syntax make-syntax-violation syntax-violation?
syntax-violation-form syntax-violation-subform &undefined
make-undefined-violation undefined-violation?
;; (rnrs control)
when unless do case-lambda
;; (rnrs enums)
make-enumeration enum-set-universe enum-set-indexer
enum-set-constructor enum-set->list enum-set-member? enum-set-subset?
enum-set=? enum-set-union enum-set-intersection enum-set-difference
enum-set-complement enum-set-projection define-enumeration
;; (rnrs exceptions)
guard with-exception-handler raise raise-continuable
;; (rnrs files)
file-exists? delete-file &i/o make-i/o-error i/o-error? &i/o-read
make-i/o-read-error i/o-read-error? &i/o-write make-i/o-write-error
i/o-write-error? &i/o-invalid-position
make-i/o-invalid-position-error i/o-invalid-position-error?
i/o-error-position &i/o-filename make-i/o-filename-error
i/o-filename-error? i/o-error-filename &i/o-file-protection
make-i/o-file-protection-error i/o-file-protection-error?
&i/o-file-is-read-only make-i/o-file-is-read-only-error
i/o-file-is-read-only-error? &i/o-file-already-exists
make-i/o-file-already-exists-error i/o-file-already-exists-error?
&i/o-file-does-not-exist make-i/o-file-does-not-exist-error
i/o-file-does-not-exist-error? &i/o-port make-i/o-port-error
i/o-port-error? i/o-error-port
;; (rnrs hashtables)
make-eq-hashtable make-eqv-hashtable make-hashtable hashtable?
hashtable-size hashtable-ref hashtable-set! hashtable-delete!
hashtable-contains? hashtable-update! hashtable-copy hashtable-clear!
hashtable-keys hashtable-entries hashtable-equivalence-function
hashtable-hash-function hashtable-mutable? equal-hash string-hash
string-ci-hash symbol-hash
;; (rnrs io ports)
file-options buffer-mode buffer-mode?
eol-style native-eol-style error-handling-mode
make-transcoder transcoder-codec transcoder-eol-style
transcoder-error-handling-mode native-transcoder
latin-1-codec utf-8-codec utf-16-codec
eof-object? port? input-port? output-port? eof-object port-eof?
port-transcoder
binary-port? textual-port? transcoded-port
port-position set-port-position!
port-has-port-position? port-has-set-port-position!?
close-port call-with-port
open-bytevector-input-port make-custom-binary-input-port get-u8
lookahead-u8 get-bytevector-n get-bytevector-n! get-bytevector-some
get-bytevector-all open-bytevector-output-port
make-custom-binary-output-port put-u8 put-bytevector
open-string-input-port open-string-output-port
call-with-bytevector-output-port
call-with-string-output-port
latin-1-codec utf-8-codec utf-16-codec
open-file-input-port open-file-output-port open-file-input/output-port
make-custom-textual-output-port
call-with-string-output-port
flush-output-port put-string
get-char get-datum get-line get-string-all get-string-n get-string-n!
lookahead-char
put-char put-datum put-string
standard-input-port standard-output-port standard-error-port
;; (rnrs io simple)
call-with-input-file call-with-output-file current-input-port
current-output-port current-error-port with-input-from-file
with-output-to-file open-input-file open-output-file close-input-port
close-output-port read-char peek-char read write-char newline display
write
;; (rnrs lists)
find for-all exists filter partition fold-left fold-right remp remove
remv remq memp member memv memq assp assoc assv assq cons*
;; (rnrs programs)
command-line exit
;; (rnrs records inspection)
record? record-rtd record-type-name record-type-parent
record-type-uid record-type-generative? record-type-sealed?
record-type-opaque? record-type-field-names record-field-mutable?
;; (rnrs records procedural)
make-record-type-descriptor record-type-descriptor?
make-record-constructor-descriptor record-constructor record-predicate
record-accessor record-mutator
;; (rnrs records syntactic)
define-record-type record-type-descriptor
record-constructor-descriptor
;; (rnrs sorting)
list-sort vector-sort vector-sort!
;; (rnrs syntax-case)
make-variable-transformer syntax
;; Until the deprecated support for a unified modules and
;; bindings namespace is removed, we need to manually resolve
;; a conflict between two bindings: that of the (rnrs
;; syntax-case) module, and the imported `syntax-case'
;; binding. We do so here and below by renaming the macro
;; import.
(rename (syntax-case-hack syntax-case))
identifier? bound-identifier=? free-identifier=?
syntax->datum datum->syntax generate-temporaries with-syntax
quasisyntax unsyntax unsyntax-splicing syntax-violation
;; (rnrs unicode)
char-upcase char-downcase char-titlecase char-foldcase
char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=?
char-alphabetic? char-numeric? char-whitespace? char-upper-case?
char-lower-case? char-title-case? char-general-category
string-upcase string-downcase string-titlecase string-foldcase
string-ci=? string-ci<? string-ci>? string-ci<=? string-ci>=?
string-normalize-nfd string-normalize-nfkd string-normalize-nfc
string-normalize-nfkc)
(import (rnrs arithmetic bitwise (6))
(rnrs arithmetic fixnums (6))
(rnrs arithmetic flonums (6))
(rnrs base (6))
(rnrs bytevectors (6))
(rnrs conditions (6))
(rnrs control (6))
(rnrs enums (6))
(rnrs exceptions (6))
(rnrs files (6))
(rnrs hashtables (6))
(rnrs io ports (6))
(rnrs io simple (6))
(rnrs lists (6))
(rnrs programs (6))
(rnrs records inspection (6))
(rnrs records procedural (6))
(rnrs records syntactic (6))
(rnrs sorting (6))
;; See note above on exporting syntax-case.
(rename (rnrs syntax-case (6))
(syntax-case syntax-case-hack))
(rnrs unicode (6))))
;;; bitwise.scm --- The R6RS bitwise arithmetic operations library
;; Copyright (C) 2010, 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs arithmetic bitwise (6))
(export bitwise-not
bitwise-and
bitwise-ior
bitwise-xor
bitwise-if
bitwise-bit-count
bitwise-length
bitwise-first-bit-set
bitwise-bit-set?
bitwise-copy-bit
bitwise-bit-field
bitwise-copy-bit-field
bitwise-arithmetic-shift
bitwise-arithmetic-shift-left
bitwise-arithmetic-shift-right
bitwise-rotate-bit-field
bitwise-reverse-bit-field)
(import (rnrs base (6))
(rnrs control (6))
(rename (only (srfi srfi-60) bitwise-if
integer-length
first-set-bit
copy-bit
bit-field
copy-bit-field
rotate-bit-field
reverse-bit-field)
(integer-length bitwise-length)
(first-set-bit bitwise-first-bit-set)
(bit-field bitwise-bit-field)
(reverse-bit-field bitwise-reverse-bit-field))
(rename (only (guile) lognot
logand
logior
logxor
logcount
logbit?
modulo
ash)
(lognot bitwise-not)
(logand bitwise-and)
(logior bitwise-ior)
(logxor bitwise-xor)
(ash bitwise-arithmetic-shift)))
(define (bitwise-bit-count ei)
(if (negative? ei)
(bitwise-not (logcount ei))
(logcount ei)))
(define (bitwise-bit-set? ei1 ei2) (logbit? ei2 ei1))
(define (bitwise-copy-bit ei1 ei2 ei3)
;; The specification states that ei3 should be either 0 or 1.
;; However, other values have been tolerated by both Guile 2.0.x and
;; the sample implementation given the R6RS library document, so for
;; backward compatibility we continue to permit it.
(copy-bit ei2 ei1 (logbit? 0 ei3)))
(define (bitwise-copy-bit-field ei1 ei2 ei3 ei4)
(copy-bit-field ei1 ei4 ei2 ei3))
(define (bitwise-rotate-bit-field ei1 ei2 ei3 ei4)
(rotate-bit-field ei1 ei4 ei2 ei3))
(define bitwise-arithmetic-shift-left bitwise-arithmetic-shift)
(define (bitwise-arithmetic-shift-right ei1 ei2)
(bitwise-arithmetic-shift ei1 (- ei2))))
;;; fixnums.scm --- The R6RS fixnums arithmetic library
;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs arithmetic fixnums (6))
(export fixnum?
fixnum-width
least-fixnum
greatest-fixnum
fx=?
fx>?
fx<?
fx>=?
fx<=?
fxzero?
fxpositive?
fxnegative?
fxodd?
fxeven?
fxmax
fxmin
fx+
fx*
fx-
fxdiv-and-mod
fxdiv
fxmod
fxdiv0-and-mod0
fxdiv0
fxmod0
fx+/carry
fx-/carry
fx*/carry
fxnot
fxand
fxior
fxxor
fxif
fxbit-count
fxlength
fxfirst-bit-set
fxbit-set?
fxcopy-bit
fxbit-field
fxcopy-bit-field
fxarithmetic-shift
fxarithmetic-shift-left
fxarithmetic-shift-right
fxrotate-bit-field
fxreverse-bit-field)
(import (only (guile) ash
cons*
define-inlinable
inexact->exact
logand
logbit?
logcount
logior
lognot
logxor
most-positive-fixnum
most-negative-fixnum
object-address)
(ice-9 optargs)
(rnrs base (6))
(rnrs control (6))
(rnrs arithmetic bitwise (6))
(rnrs conditions (6))
(rnrs exceptions (6))
(rnrs lists (6)))
(define fixnum-width
(let ((w (do ((i 0 (+ 1 i))
(n 1 (* 2 n)))
((> n most-positive-fixnum)
(+ 1 i)))))
(lambda () w)))
(define (greatest-fixnum) most-positive-fixnum)
(define (least-fixnum) most-negative-fixnum)
(define (fixnum? obj)
(not (= 0 (logand 2 (object-address obj)))))
(define-inlinable (inline-fixnum? obj)
(not (= 0 (logand 2 (object-address obj)))))
(define-syntax assert-fixnum
(syntax-rules ()
((_ arg ...)
(or (and (inline-fixnum? arg) ...)
(raise (make-assertion-violation))))))
(define (assert-fixnums args)
(or (for-all inline-fixnum? args) (raise (make-assertion-violation))))
(define-syntax define-fxop*
(syntax-rules ()
((_ name op)
(define name
(case-lambda
((x y)
(assert-fixnum x y)
(op x y))
(args
(assert-fixnums args)
(apply op args)))))))
;; All these predicates don't check their arguments for fixnum-ness,
;; as this doesn't seem to be strictly required by R6RS.
(define fx=? =)
(define fx>? >)
(define fx<? <)
(define fx>=? >=)
(define fx<=? <=)
(define fxzero? zero?)
(define fxpositive? positive?)
(define fxnegative? negative?)
(define fxodd? odd?)
(define fxeven? even?)
(define-fxop* fxmax max)
(define-fxop* fxmin min)
(define (fx+ fx1 fx2)
(assert-fixnum fx1 fx2)
(let ((r (+ fx1 fx2)))
(or (inline-fixnum? r)
(raise (make-implementation-restriction-violation)))
r))
(define (fx* fx1 fx2)
(assert-fixnum fx1 fx2)
(let ((r (* fx1 fx2)))
(or (inline-fixnum? r)
(raise (make-implementation-restriction-violation)))
r))
(define* (fx- fx1 #\optional fx2)
(assert-fixnum fx1)
(if fx2
(begin
(assert-fixnum fx2)
(let ((r (- fx1 fx2)))
(or (inline-fixnum? r) (raise (make-assertion-violation)))
r))
(let ((r (- fx1)))
(or (inline-fixnum? r) (raise (make-assertion-violation)))
r)))
(define (fxdiv fx1 fx2)
(assert-fixnum fx1 fx2)
(div fx1 fx2))
(define (fxmod fx1 fx2)
(assert-fixnum fx1 fx2)
(mod fx1 fx2))
(define (fxdiv-and-mod fx1 fx2)
(assert-fixnum fx1 fx2)
(div-and-mod fx1 fx2))
(define (fxdiv0 fx1 fx2)
(assert-fixnum fx1 fx2)
(div0 fx1 fx2))
(define (fxmod0 fx1 fx2)
(assert-fixnum fx1 fx2)
(mod0 fx1 fx2))
(define (fxdiv0-and-mod0 fx1 fx2)
(assert-fixnum fx1 fx2)
(div0-and-mod0 fx1 fx2))
(define (fx+/carry fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(let* ((s (+ fx1 fx2 fx3))
(s0 (mod0 s (expt 2 (fixnum-width))))
(s1 (div0 s (expt 2 (fixnum-width)))))
(values s0 s1)))
(define (fx-/carry fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(let* ((d (- fx1 fx2 fx3))
(d0 (mod0 d (expt 2 (fixnum-width))))
(d1 (div0 d (expt 2 (fixnum-width)))))
(values d0 d1)))
(define (fx*/carry fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(let* ((s (+ (* fx1 fx2) fx3))
(s0 (mod0 s (expt 2 (fixnum-width))))
(s1 (div0 s (expt 2 (fixnum-width)))))
(values s0 s1)))
(define (fxnot fx) (assert-fixnum fx) (lognot fx))
(define-fxop* fxand logand)
(define-fxop* fxior logior)
(define-fxop* fxxor logxor)
(define (fxif fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(bitwise-if fx1 fx2 fx3))
(define (fxbit-count fx)
(assert-fixnum fx)
(if (negative? fx)
(bitwise-not (logcount fx))
(logcount fx)))
(define (fxlength fx) (assert-fixnum fx) (bitwise-length fx))
(define (fxfirst-bit-set fx) (assert-fixnum fx) (bitwise-first-bit-set fx))
(define (fxbit-set? fx1 fx2) (assert-fixnum fx1 fx2) (logbit? fx2 fx1))
(define (fxcopy-bit fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(bitwise-copy-bit fx1 fx2 fx3))
(define (fxbit-field fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(bitwise-bit-field fx1 fx2 fx3))
(define (fxcopy-bit-field fx1 fx2 fx3 fx4)
(assert-fixnum fx1 fx2 fx3 fx4)
(bitwise-copy-bit-field fx1 fx2 fx3 fx4))
(define (fxarithmetic-shift fx1 fx2) (assert-fixnum fx1 fx2) (ash fx1 fx2))
(define fxarithmetic-shift-left fxarithmetic-shift)
(define (fxarithmetic-shift-right fx1 fx2)
(assert-fixnum fx1 fx2) (ash fx1 (- fx2)))
(define (fxrotate-bit-field fx1 fx2 fx3 fx4)
(assert-fixnum fx1 fx2 fx3 fx4)
(bitwise-rotate-bit-field fx1 fx2 fx3 fx4))
(define (fxreverse-bit-field fx1 fx2 fx3)
(assert-fixnum fx1 fx2 fx3)
(bitwise-reverse-bit-field fx1 fx2 fx3))
)
;;; flonums.scm --- The R6RS flonums arithmetic library
;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs arithmetic flonums (6))
(export flonum?
real->flonum
fl=? fl<? fl<=? fl>? fl>=?
flinteger? flzero? flpositive? flnegative? flodd? fleven? flfinite?
flinfinite? flnan?
flmax flmin
fl+ fl* fl- fl/
flabs
fldiv-and-mod
fldiv
flmod
fldiv0-and-mod0
fldiv0
flmod0
flnumerator
fldenominator
flfloor flceiling fltruncate flround
flexp fllog flsin flcos fltan flacos flasin flatan
flsqrt flexpt
&no-infinities
make-no-infinities-violation
no-infinities-violation?
&no-nans
make-no-nans-violation
no-nans-violation?
fixnum->flonum)
(import (ice-9 optargs)
(only (guile) inf?)
(rnrs arithmetic fixnums (6))
(rnrs base (6))
(rnrs control (6))
(rnrs conditions (6))
(rnrs exceptions (6))
(rnrs lists (6))
(rnrs r5rs (6)))
(define (flonum? obj) (and (real? obj) (inexact? obj)))
(define (assert-flonum . args)
(or (for-all flonum? args) (raise (make-assertion-violation))))
(define (assert-iflonum . args)
(or (for-all (lambda (i) (and (flonum? i) (integer? i))) args)
(raise (make-assertion-violation))))
(define (ensure-flonum z)
(cond ((real? z) z)
((zero? (imag-part z)) (real-part z))
(else +nan.0)))
(define (real->flonum x)
(or (real? x) (raise (make-assertion-violation)))
(exact->inexact x))
(define (fl=? . args) (apply assert-flonum args) (apply = args))
(define (fl<? . args) (apply assert-flonum args) (apply < args))
(define (fl<=? . args) (apply assert-flonum args) (apply <= args))
(define (fl>? . args) (apply assert-flonum args) (apply > args))
(define (fl>=? . args) (apply assert-flonum args) (apply >= args))
(define (flinteger? fl) (assert-flonum fl) (integer? fl))
(define (flzero? fl) (assert-flonum fl) (zero? fl))
(define (flpositive? fl) (assert-flonum fl) (positive? fl))
(define (flnegative? fl) (assert-flonum fl) (negative? fl))
(define (flodd? ifl) (assert-iflonum ifl) (odd? ifl))
(define (fleven? ifl) (assert-iflonum ifl) (even? ifl))
(define (flfinite? fl) (assert-flonum fl) (not (or (inf? fl) (nan? fl))))
(define (flinfinite? fl) (assert-flonum fl) (inf? fl))
(define (flnan? fl) (assert-flonum fl) (nan? fl))
(define (flmax fl1 . args)
(let ((flargs (cons fl1 args)))
(apply assert-flonum flargs)
(apply max flargs)))
(define (flmin fl1 . args)
(let ((flargs (cons fl1 args)))
(apply assert-flonum flargs)
(apply min flargs)))
(define (fl+ . args)
(apply assert-flonum args)
(if (null? args) 0.0 (apply + args)))
(define (fl* . args)
(apply assert-flonum args)
(if (null? args) 1.0 (apply * args)))
(define (fl- fl1 . args)
(let ((flargs (cons fl1 args)))
(apply assert-flonum flargs)
(apply - flargs)))
(define (fl/ fl1 . args)
(let ((flargs (cons fl1 args)))
(apply assert-flonum flargs)
(apply / flargs)))
(define (flabs fl) (assert-flonum fl) (abs fl))
(define (fldiv-and-mod fl1 fl2)
(assert-iflonum fl1 fl2)
(div-and-mod fl1 fl2))
(define (fldiv fl1 fl2)
(assert-iflonum fl1 fl2)
(div fl1 fl2))
(define (flmod fl1 fl2)
(assert-iflonum fl1 fl2)
(mod fl1 fl2))
(define (fldiv0-and-mod0 fl1 fl2)
(assert-iflonum fl1 fl2)
(div0-and-mod0 fl1 fl2))
(define (fldiv0 fl1 fl2)
(assert-iflonum fl1 fl2)
(div0 fl1 fl2))
(define (flmod0 fl1 fl2)
(assert-iflonum fl1 fl2)
(mod0 fl1 fl2))
(define (flnumerator fl) (assert-flonum fl) (numerator fl))
(define (fldenominator fl) (assert-flonum fl) (denominator fl))
(define (flfloor fl) (assert-flonum fl) (floor fl))
(define (flceiling fl) (assert-flonum fl) (ceiling fl))
(define (fltruncate fl) (assert-flonum fl) (truncate fl))
(define (flround fl) (assert-flonum fl) (round fl))
(define (flexp fl) (assert-flonum fl) (exp fl))
(define fllog
(case-lambda
((fl)
(assert-flonum fl)
;; add 0.0 to fl, to change -0.0 to 0.0,
;; so that (fllog -0.0) will be -inf.0, not -inf.0+pi*i.
(ensure-flonum (log (+ fl 0.0))))
((fl fl2)
(assert-flonum fl fl2)
(ensure-flonum (/ (log (+ fl 0.0))
(log (+ fl2 0.0)))))))
(define (flsin fl) (assert-flonum fl) (sin fl))
(define (flcos fl) (assert-flonum fl) (cos fl))
(define (fltan fl) (assert-flonum fl) (tan fl))
(define (flasin fl) (assert-flonum fl) (ensure-flonum (asin fl)))
(define (flacos fl) (assert-flonum fl) (ensure-flonum (acos fl)))
(define flatan
(case-lambda
((fl) (assert-flonum fl) (atan fl))
((fl fl2) (assert-flonum fl fl2) (atan fl fl2))))
(define (flsqrt fl) (assert-flonum fl) (ensure-flonum (sqrt fl)))
(define (flexpt fl1 fl2) (assert-flonum fl1 fl2) (ensure-flonum (expt fl1 fl2)))
(define-condition-type &no-infinities
&implementation-restriction
make-no-infinities-violation
no-infinities-violation?)
(define-condition-type &no-nans
&implementation-restriction
make-no-nans-violation
no-nans-violation?)
(define (fixnum->flonum fx)
(or (fixnum? fx) (raise (make-assertion-violation)))
(exact->inexact fx))
)
;;; base.scm --- The R6RS base library
;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs base (6))
(export boolean? symbol? char? vector? null? pair? number? string? procedure?
define define-syntax syntax-rules lambda let let* let-values
let*-values letrec letrec* begin
quote lambda if set! cond case
or and not
eqv? equal? eq?
+ - * / max min abs numerator denominator gcd lcm floor ceiling
truncate round rationalize real-part imag-part make-rectangular angle
div mod div-and-mod div0 mod0 div0-and-mod0
expt exact-integer-sqrt sqrt exp log sin cos tan asin acos atan
make-polar magnitude angle
complex? real? rational? integer? exact? inexact? real-valued?
rational-valued? integer-valued? zero? positive? negative? odd? even?
nan? finite? infinite?
exact inexact = < > <= >=
number->string string->number
boolean=?
cons car cdr caar cadr cdar cddr caaar caadr cadar cdaar caddr cdadr
cddar cdddr caaaar caaadr caadar cadaar cdaaar cddaar cdadar cdaadr
cadadr caaddr caddar cadddr cdaddr cddadr cdddar cddddr
list? list length append reverse list-tail list-ref map for-each
symbol->string string->symbol symbol=?
char->integer integer->char char=? char<? char>? char<=? char>=?
make-string string string-length string-ref string=? string<? string>?
string<=? string>=? substring string-append string->list list->string
string-for-each string-copy
vector? make-vector vector vector-length vector-ref vector-set!
vector->list list->vector vector-fill! vector-map vector-for-each
error assertion-violation assert
call-with-current-continuation call/cc call-with-values dynamic-wind
values apply
quasiquote unquote unquote-splicing
let-syntax letrec-syntax
syntax-rules identifier-syntax)
(import (rename (except (guile) error raise map string-for-each)
(log log-internal)
(euclidean-quotient div)
(euclidean-remainder mod)
(euclidean/ div-and-mod)
(centered-quotient div0)
(centered-remainder mod0)
(centered/ div0-and-mod0)
(inf? infinite?)
(exact->inexact inexact)
(inexact->exact exact))
(srfi srfi-11))
(define string-for-each
(case-lambda
((proc string)
(let ((end (string-length string)))
(let loop ((i 0))
(unless (= i end)
(proc (string-ref string i))
(loop (+ i 1))))))
((proc string1 string2)
(let ((end1 (string-length string1))
(end2 (string-length string2)))
(unless (= end1 end2)
(assertion-violation 'string-for-each
"string arguments must all have the same length"
string1 string2))
(let loop ((i 0))
(unless (= i end1)
(proc (string-ref string1 i)
(string-ref string2 i))
(loop (+ i 1))))))
((proc string . strings)
(let ((end (string-length string))
(ends (map string-length strings)))
(for-each (lambda (x)
(unless (= end x)
(apply assertion-violation
'string-for-each
"string arguments must all have the same length"
string strings)))
ends)
(let loop ((i 0))
(unless (= i end)
(apply proc
(string-ref string i)
(map (lambda (s) (string-ref s i)) strings))
(loop (+ i 1))))))))
(define map
(case-lambda
((f l)
(let map1 ((hare l) (tortoise l) (move? #f) (out '()))
(if (pair? hare)
(if move?
(if (eq? tortoise hare)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l) #f)
(map1 (cdr hare) (cdr tortoise) #f
(cons (f (car hare)) out)))
(map1 (cdr hare) tortoise #t
(cons (f (car hare)) out)))
(if (null? hare)
(reverse out)
(scm-error 'wrong-type-arg "map" "Not a list: ~S"
(list l) #f)))))
((f l1 l2)
(let map2 ((h1 l1) (h2 l2) (t1 l1) (t2 l2) (move? #f) (out '()))
(cond
((pair? h1)
(cond
((not (pair? h2))
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
((not move?)
(map2 (cdr h1) (cdr h2) t1 t2 #t
(cons (f (car h1) (car h2)) out)))
((eq? t1 h1)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l1) #f))
((eq? t2 h2)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l2) #f))
(else
(map2 (cdr h1) (cdr h2) (cdr t1) (cdr t2) #f
(cons (f (car h1) (car h2)) out)))))
((and (null? h1) (null? h2))
(reverse out))
((null? h1)
(scm-error 'wrong-type-arg "map"
(if (list? h2)
"List of wrong length: ~S"
"Not a list: ~S")
(list l2) #f))
(else
(scm-error 'wrong-type-arg "map"
"Not a list: ~S"
(list l1) #f)))))
((f l1 . rest)
(let ((len (length l1)))
(let mapn ((rest rest))
(or (null? rest)
(if (= (length (car rest)) len)
(mapn (cdr rest))
(scm-error 'wrong-type-arg "map" "List of wrong length: ~S"
(list (car rest)) #f)))))
(let mapn ((l1 l1) (rest rest) (out '()))
(if (null? l1)
(reverse out)
(mapn (cdr l1) (map cdr rest)
(cons (apply f (car l1) (map car rest)) out)))))))
(define log
(case-lambda
((n)
(log-internal n))
((n base)
(/ (log n)
(log base)))))
(define (boolean=? . bools)
(define (boolean=?-internal lst last)
(or (null? lst)
(let ((bool (car lst)))
(and (eqv? bool last) (boolean=?-internal (cdr lst) bool)))))
(or (null? bools)
(let ((bool (car bools)))
(and (boolean? bool) (boolean=?-internal (cdr bools) bool)))))
(define (symbol=? . syms)
(define (symbol=?-internal lst last)
(or (null? lst)
(let ((sym (car lst)))
(and (eq? sym last) (symbol=?-internal (cdr lst) sym)))))
(or (null? syms)
(let ((sym (car syms)))
(and (symbol? sym) (symbol=?-internal (cdr syms) sym)))))
(define (real-valued? x)
(and (complex? x)
(zero? (imag-part x))))
(define (rational-valued? x)
(and (real-valued? x)
(rational? (real-part x))))
(define (integer-valued? x)
(and (rational-valued? x)
(= x (floor (real-part x)))))
(define (vector-for-each proc . vecs)
(apply for-each (cons proc (map vector->list vecs))))
(define (vector-map proc . vecs)
(list->vector (apply map (cons proc (map vector->list vecs)))))
(define-syntax define-proxy
(syntax-rules (@)
;; Define BINDING to point to (@ MODULE ORIGINAL). This hack is to
;; make sure MODULE is loaded lazily, at run-time, when BINDING is
;; encountered, rather than being loaded while compiling and
;; loading (rnrs base).
;; This avoids circular dependencies among modules and makes
;; (rnrs base) more lightweight.
((_ binding (@ module original))
(define-syntax binding
(identifier-syntax
(module-ref (resolve-interface 'module) 'original))))))
(define-proxy raise
(@ (rnrs exceptions) raise))
(define-proxy condition
(@ (rnrs conditions) condition))
(define-proxy make-error
(@ (rnrs conditions) make-error))
(define-proxy make-assertion-violation
(@ (rnrs conditions) make-assertion-violation))
(define-proxy make-who-condition
(@ (rnrs conditions) make-who-condition))
(define-proxy make-message-condition
(@ (rnrs conditions) make-message-condition))
(define-proxy make-irritants-condition
(@ (rnrs conditions) make-irritants-condition))
(define (error who message . irritants)
(raise (apply condition
(append (list (make-error))
(if who (list (make-who-condition who)) '())
(list (make-message-condition message)
(make-irritants-condition irritants))))))
(define (assertion-violation who message . irritants)
(raise (apply condition
(append (list (make-assertion-violation))
(if who (list (make-who-condition who)) '())
(list (make-message-condition message)
(make-irritants-condition irritants))))))
(define-syntax assert
(syntax-rules ()
((_ expression)
(or expression
(raise (condition
(make-assertion-violation)
(make-message-condition
(format #f "assertion failed: ~s" 'expression))))))))
)
;;;; bytevectors.scm --- R6RS bytevector API -*- coding: utf-8 -*-
;;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;;;
;;; A "bytevector" is a raw bit string. This module provides procedures to
;;; manipulate bytevectors and interpret their contents in a number of ways:
;;; bytevector contents can be accessed as signed or unsigned integer of
;;; various sizes and endianness, as IEEE-754 floating point numbers, or as
;;; strings. It is a useful tool to decode binary data.
;;;
;;; Code:
(define-module (rnrs bytevectors)
#\version (6)
#\export-syntax (endianness)
#\export (native-endianness bytevector?
make-bytevector bytevector-length bytevector=? bytevector-fill!
bytevector-copy! bytevector-copy
uniform-array->bytevector
bytevector-u8-ref bytevector-s8-ref
bytevector-u8-set! bytevector-s8-set! bytevector->u8-list
u8-list->bytevector
bytevector-uint-ref bytevector-uint-set!
bytevector-sint-ref bytevector-sint-set!
bytevector->sint-list bytevector->uint-list
uint-list->bytevector sint-list->bytevector
bytevector-u16-ref bytevector-s16-ref
bytevector-u16-set! bytevector-s16-set!
bytevector-u16-native-ref bytevector-s16-native-ref
bytevector-u16-native-set! bytevector-s16-native-set!
bytevector-u32-ref bytevector-s32-ref
bytevector-u32-set! bytevector-s32-set!
bytevector-u32-native-ref bytevector-s32-native-ref
bytevector-u32-native-set! bytevector-s32-native-set!
bytevector-u64-ref bytevector-s64-ref
bytevector-u64-set! bytevector-s64-set!
bytevector-u64-native-ref bytevector-s64-native-ref
bytevector-u64-native-set! bytevector-s64-native-set!
bytevector-ieee-single-ref
bytevector-ieee-single-set!
bytevector-ieee-single-native-ref
bytevector-ieee-single-native-set!
bytevector-ieee-double-ref
bytevector-ieee-double-set!
bytevector-ieee-double-native-ref
bytevector-ieee-double-native-set!
string->utf8 string->utf16 string->utf32
utf8->string utf16->string utf32->string))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_bytevectors")
(define-macro (endianness sym)
(if (memq sym '(big little))
`(quote ,sym)
(error "unsupported endianness" sym)))
;;; bytevector.scm ends here
;;; conditions.scm --- The R6RS conditions library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs conditions (6))
(export &condition
condition
simple-conditions
condition?
condition-predicate
condition-accessor
define-condition-type
&message
make-message-condition
message-condition?
condition-message
&warning
make-warning
warning?
&serious
make-serious-condition
serious-condition?
&error
make-error
error?
&violation
make-violation
violation?
&assertion
make-assertion-violation
assertion-violation?
&irritants
make-irritants-condition
irritants-condition?
condition-irritants
&who
make-who-condition
who-condition?
condition-who
&non-continuable
make-non-continuable-violation
non-continuable-violation?
&implementation-restriction
make-implementation-restriction-violation
implementation-restriction-violation?
&lexical
make-lexical-violation
lexical-violation?
&syntax
make-syntax-violation
syntax-violation?
syntax-violation-form
syntax-violation-subform
&undefined
make-undefined-violation
undefined-violation?)
(import (only (guile) and=> @@)
(rnrs base (6))
(rnrs lists (6))
(rnrs records procedural (6)))
(define &compound-condition (make-record-type-descriptor
'&compound-condition #f #f #f #f
'#((immutable components))))
(define compound-condition? (record-predicate &compound-condition))
(define make-compound-condition
(record-constructor (make-record-constructor-descriptor
&compound-condition #f #f)))
(define simple-conditions
(let ((compound-ref (record-accessor &compound-condition 0)))
(lambda (condition)
(cond ((compound-condition? condition)
(compound-ref condition))
((condition-internal? condition)
(list condition))
(else
(assertion-violation 'simple-conditions
"not a condition"
condition))))))
(define (condition? obj)
(or (compound-condition? obj) (condition-internal? obj)))
(define condition
(lambda conditions
(define (flatten cond)
(if (compound-condition? cond) (simple-conditions cond) (list cond)))
(or (for-all condition? conditions)
(assertion-violation 'condition "non-condition argument" conditions))
(if (or (null? conditions) (> (length conditions) 1))
(make-compound-condition (apply append (map flatten conditions)))
(car conditions))))
(define-syntax define-condition-type
(syntax-rules ()
((_ condition-type supertype constructor predicate
(field accessor) ...)
(letrec-syntax
((transform-fields
(syntax-rules ()
((_ (f a) . rest)
(cons '(immutable f a) (transform-fields . rest)))
((_) '())))
(generate-accessors
(syntax-rules ()
((_ counter (f a) . rest)
(begin (define a
(condition-accessor
condition-type
(record-accessor condition-type counter)))
(generate-accessors (+ counter 1) . rest)))
((_ counter) (begin)))))
(begin
(define condition-type
(make-record-type-descriptor
'condition-type supertype #f #f #f
(list->vector (transform-fields (field accessor) ...))))
(define constructor
(record-constructor
(make-record-constructor-descriptor condition-type #f #f)))
(define predicate (condition-predicate condition-type))
(generate-accessors 0 (field accessor) ...))))))
(define &condition (@@ (rnrs records procedural) &condition))
(define &condition-constructor-descriptor
(make-record-constructor-descriptor &condition #f #f))
(define condition-internal? (record-predicate &condition))
(define (condition-predicate rtd)
(let ((rtd-predicate (record-predicate rtd)))
(lambda (obj)
(cond ((compound-condition? obj)
(exists rtd-predicate (simple-conditions obj)))
((condition-internal? obj) (rtd-predicate obj))
(else #f)))))
(define (condition-accessor rtd proc)
(let ((rtd-predicate (record-predicate rtd)))
(lambda (obj)
(cond ((rtd-predicate obj) (proc obj))
((compound-condition? obj)
(and=> (find rtd-predicate (simple-conditions obj)) proc))
(else #f)))))
(define-condition-type &message &condition
make-message-condition message-condition?
(message condition-message))
(define-condition-type &warning &condition make-warning warning?)
(define &serious (@@ (rnrs records procedural) &serious))
(define make-serious-condition
(@@ (rnrs records procedural) make-serious-condition))
(define serious-condition? (condition-predicate &serious))
(define-condition-type &error &serious make-error error?)
(define &violation (@@ (rnrs records procedural) &violation))
(define make-violation (@@ (rnrs records procedural) make-violation))
(define violation? (condition-predicate &violation))
(define &assertion (@@ (rnrs records procedural) &assertion))
(define make-assertion-violation
(@@ (rnrs records procedural) make-assertion-violation))
(define assertion-violation? (condition-predicate &assertion))
(define-condition-type &irritants &condition
make-irritants-condition irritants-condition?
(irritants condition-irritants))
(define-condition-type &who &condition
make-who-condition who-condition?
(who condition-who))
(define-condition-type &non-continuable &violation
make-non-continuable-violation
non-continuable-violation?)
(define-condition-type &implementation-restriction
&violation
make-implementation-restriction-violation
implementation-restriction-violation?)
(define-condition-type &lexical &violation
make-lexical-violation lexical-violation?)
(define-condition-type &syntax &violation
make-syntax-violation syntax-violation?
(form syntax-violation-form)
(subform syntax-violation-subform))
(define-condition-type &undefined &violation
make-undefined-violation undefined-violation?)
)
;;; control.scm --- The R6RS control structures library
;; Copyright (C) 2010, 2012 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs control (6))
(export when unless do case-lambda)
(import (only (guile) when unless do case-lambda)))
;;; enums.scm --- The R6RS enumerations library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs enums (6))
(export make-enumeration enum-set-universe enum-set-indexer
enum-set-constructor enum-set->list enum-set-member? enum-set-subset?
enum-set=? enum-set-union enum-set-intersection enum-set-difference
enum-set-complement enum-set-projection define-enumeration)
(import (only (guile) and=>)
(rnrs base (6))
(rnrs conditions (6))
(rnrs exceptions (6))
(rnrs records procedural (6))
(rnrs syntax-case (6))
(srfi 1))
(define enum-set-rtd (make-record-type-descriptor
'enum-set #f #f #f #f '#((mutable universe)
(immutable set))))
(define make-enum-set
(record-constructor
(make-record-constructor-descriptor enum-set-rtd #f #f)))
(define enum-set-universe-internal (record-accessor enum-set-rtd 0))
(define enum-set-universe-set! (record-mutator enum-set-rtd 0))
(define enum-set-set (record-accessor enum-set-rtd 1))
(define (make-enumeration symbol-list)
(let ((es (make-enum-set #f symbol-list)))
(enum-set-universe-set! es es)))
(define (enum-set-universe enum-set)
(or (enum-set-universe-internal enum-set)
enum-set))
(define (enum-set-indexer enum-set)
(let* ((symbols (enum-set->list (enum-set-universe enum-set)))
(cardinality (length symbols)))
(lambda (x)
(and=> (memq x symbols)
(lambda (probe) (- cardinality (length probe)))))))
(define (enum-set-constructor enum-set)
(lambda (symbol-list)
(make-enum-set (enum-set-universe enum-set)
(list-copy symbol-list))))
(define (enum-set->list enum-set)
(lset-intersection eq?
(enum-set-set (enum-set-universe enum-set))
(enum-set-set enum-set)))
(define (enum-set-member? symbol enum-set)
(and (memq symbol (enum-set-set enum-set)) #t))
(define (enum-set-subset? enum-set-1 enum-set-2)
(and (lset<= eq?
(enum-set-set (enum-set-universe enum-set-1))
(enum-set-set (enum-set-universe enum-set-2)))
(lset<= eq? (enum-set-set enum-set-1) (enum-set-set enum-set-2))))
(define (enum-set=? enum-set-1 enum-set-2)
(and (enum-set-subset? enum-set-1 enum-set-2)
(enum-set-subset? enum-set-2 enum-set-1)))
(define (enum-set-union enum-set-1 enum-set-2)
(if (equal? (enum-set-universe enum-set-1)
(enum-set-universe enum-set-2))
(make-enum-set (enum-set-universe enum-set-1)
(lset-union eq?
(enum-set-set enum-set-1)
(enum-set-set enum-set-2)))
(raise (make-assertion-violation))))
(define (enum-set-intersection enum-set-1 enum-set-2)
(if (equal? (enum-set-universe enum-set-1)
(enum-set-universe enum-set-2))
(make-enum-set (enum-set-universe enum-set-1)
(lset-intersection eq?
(enum-set-set enum-set-1)
(enum-set-set enum-set-2)))
(raise (make-assertion-violation))))
(define (enum-set-difference enum-set-1 enum-set-2)
(if (equal? (enum-set-universe enum-set-1)
(enum-set-universe enum-set-2))
(make-enum-set (enum-set-universe enum-set-1)
(lset-difference eq?
(enum-set-set enum-set-1)
(enum-set-set enum-set-2)))
(raise (make-assertion-violation))))
(define (enum-set-complement enum-set)
(let ((universe (enum-set-universe enum-set)))
(make-enum-set universe
(lset-difference
eq? (enum-set->list universe) (enum-set-set enum-set)))))
(define (enum-set-projection enum-set-1 enum-set-2)
(make-enum-set (enum-set-universe enum-set-2)
(lset-intersection eq?
(enum-set-set enum-set-1)
(enum-set->list
(enum-set-universe enum-set-2)))))
(define-syntax define-enumeration
(syntax-rules ()
((_ type-name (symbol ...) constructor-syntax)
(begin
(define-syntax type-name
(lambda (s)
(syntax-case s ()
((type-name sym)
(if (memq (syntax->datum #'sym) '(symbol ...))
#'(quote sym)
(syntax-violation (symbol->string 'type-name)
"not a member of the set"
#f))))))
(define-syntax constructor-syntax
(lambda (s)
(syntax-case s ()
((_ sym (... ...))
(let* ((universe '(symbol ...))
(syms (syntax->datum #'(sym (... ...))))
(quoted-universe
(datum->syntax s (list 'quote universe)))
(quoted-syms (datum->syntax s (list 'quote syms))))
(or (every (lambda (x) (memq x universe)) syms)
(syntax-violation (symbol->string 'constructor-syntax)
"not a subset of the universe"
#f))
#`((enum-set-constructor (make-enumeration #,quoted-universe))
#,quoted-syms))))))))))
)
;;; eval.scm --- The R6RS `eval' library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs eval (6))
(export eval environment)
(import (only (guile) eval
make-module
module-uses
beautify-user-module!
set-module-uses!)
(rnrs base (6))
(rnrs io simple (6))
(rnrs lists (6)))
(define (environment . import-specs)
(let ((module (make-module))
(needs-purify? (not (member '(guile) import-specs))))
(beautify-user-module! module)
(for-each (lambda (import-spec) (eval (list 'import import-spec) module))
import-specs)
(if needs-purify? (set-module-uses! module (cdr (module-uses module))))
module))
)
;;; exceptions.scm --- The R6RS exceptions library
;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs exceptions (6))
(export guard with-exception-handler raise raise-continuable)
(import (rnrs base (6))
(rnrs control (6))
(rnrs conditions (6))
(rnrs records procedural (6))
(rnrs records inspection (6))
(only (guile)
format
newline
display
filter
acons
assv-ref
throw
set-exception-printer!
with-throw-handler
*unspecified*
@@))
;; When a native guile exception is caught by an R6RS exception
;; handler, we convert it to an R6RS compound condition that includes
;; not only the standard condition objects expected by R6RS code, but
;; also a special &guile condition that preserves the original KEY and
;; ARGS passed to the native Guile catch handler.
(define-condition-type &guile &condition
make-guile-condition guile-condition?
(key guile-condition-key)
(args guile-condition-args))
(define (default-guile-condition-converter key args)
(condition (make-serious-condition)
(guile-common-conditions key args)))
(define (guile-common-conditions key args)
(apply (case-lambda
((subr msg margs . _)
(condition (make-who-condition subr)
(make-message-condition msg)
(make-irritants-condition margs)))
(_ (make-irritants-condition args)))
args))
(define (convert-guile-condition key args)
(let ((converter (assv-ref guile-condition-converters key)))
(condition (or (and converter (converter key args))
(default-guile-condition-converter key args))
;; Preserve the original KEY and ARGS in the R6RS
;; condition object.
(make-guile-condition key args))))
;; If an R6RS exception handler chooses not to handle a given
;; condition, it will re-raise the condition to pass it on to the next
;; handler. If the condition was converted from a native Guile
;; exception, we must re-raise using the native Guile facilities and
;; the original exception KEY and ARGS. We arrange for this in
;; 'raise' so that native Guile exception handlers will continue to
;; work when mixed with R6RS code.
(define (raise obj)
(if (guile-condition? obj)
(apply throw (guile-condition-key obj) (guile-condition-args obj))
((@@ (rnrs records procedural) r6rs-raise) obj)))
(define raise-continuable
(@@ (rnrs records procedural) r6rs-raise-continuable))
(define raise-object-wrapper?
(@@ (rnrs records procedural) raise-object-wrapper?))
(define raise-object-wrapper-obj
(@@ (rnrs records procedural) raise-object-wrapper-obj))
(define raise-object-wrapper-continuation
(@@ (rnrs records procedural) raise-object-wrapper-continuation))
(define (with-exception-handler handler thunk)
(with-throw-handler #t
thunk
(lambda (key . args)
(cond ((not (eq? key 'r6rs:exception))
(let ((obj (convert-guile-condition key args)))
(handler obj)
(raise (make-non-continuable-violation))))
((and (not (null? args))
(raise-object-wrapper? (car args)))
(let* ((cargs (car args))
(obj (raise-object-wrapper-obj cargs))
(continuation (raise-object-wrapper-continuation cargs))
(handler-return (handler obj)))
(if continuation
(continuation handler-return)
(raise (make-non-continuable-violation)))))))))
(define-syntax guard0
(syntax-rules ()
((_ (variable cond-clause ...) . body)
(call/cc (lambda (continuation)
(with-exception-handler
(lambda (variable)
(continuation (cond cond-clause ...)))
(lambda () . body)))))))
(define-syntax guard
(syntax-rules (else)
((_ (variable cond-clause ... . ((else else-clause ...))) . body)
(guard0 (variable cond-clause ... (else else-clause ...)) . body))
((_ (variable cond-clause ...) . body)
(guard0 (variable cond-clause ... (else (raise variable))) . body))))
;;; Exception printing
(define (exception-printer port key args punt)
(cond ((and (= 1 (length args))
(raise-object-wrapper? (car args)))
(let ((obj (raise-object-wrapper-obj (car args))))
(cond ((condition? obj)
(display "ERROR: R6RS exception:\n" port)
(format-condition port obj))
(else
(format port "ERROR: R6RS exception: `~s'" obj)))))
(else
(punt))))
(define (format-condition port condition)
(let ((components (simple-conditions condition)))
(if (null? components)
(format port "Empty condition object")
(let loop ((i 1) (components components))
(cond ((pair? components)
(format port " ~a. " i)
(format-simple-condition port (car components))
(when (pair? (cdr components))
(newline port))
(loop (+ i 1) (cdr components))))))))
(define (format-simple-condition port condition)
(define (print-rtd-fields rtd field-names)
(let ((n-fields (vector-length field-names)))
(do ((i 0 (+ i 1)))
((>= i n-fields))
(format port " ~a: ~s"
(vector-ref field-names i)
((record-accessor rtd i) condition))
(unless (= i (- n-fields 1))
(newline port)))))
(let ((condition-name (record-type-name (record-rtd condition))))
(let loop ((rtd (record-rtd condition))
(rtd.fields-list '())
(n-fields 0))
(cond (rtd
(let ((field-names (record-type-field-names rtd)))
(loop (record-type-parent rtd)
(cons (cons rtd field-names) rtd.fields-list)
(+ n-fields (vector-length field-names)))))
(else
(let ((rtd.fields-list
(filter (lambda (rtd.fields)
(not (zero? (vector-length (cdr rtd.fields)))))
(reverse rtd.fields-list))))
(case n-fields
((0) (format port "~a" condition-name))
((1) (format port "~a: ~s"
condition-name
((record-accessor (caar rtd.fields-list) 0)
condition)))
(else
(format port "~a:\n" condition-name)
(let loop ((lst rtd.fields-list))
(when (pair? lst)
(let ((rtd.fields (car lst)))
(print-rtd-fields (car rtd.fields) (cdr rtd.fields))
(when (pair? (cdr lst))
(newline port))
(loop (cdr lst)))))))))))))
(set-exception-printer! 'r6rs:exception exception-printer)
;; Guile condition converters
;;
;; Each converter is a procedure (converter KEY ARGS) that returns
;; either an R6RS condition or #f. If #f is returned,
;; 'default-guile-condition-converter' will be used.
(define (guile-syntax-violation-converter key args)
(apply (case-lambda
((who what where form subform . extra)
(condition (make-syntax-violation form subform)
(make-who-condition who)
(make-message-condition what)))
(_ #f))
args))
(define (guile-lexical-violation-converter key args)
(condition (make-lexical-violation) (guile-common-conditions key args)))
(define (guile-assertion-violation-converter key args)
(condition (make-assertion-violation) (guile-common-conditions key args)))
(define (guile-undefined-violation-converter key args)
(condition (make-undefined-violation) (guile-common-conditions key args)))
(define (guile-implementation-restriction-converter key args)
(condition (make-implementation-restriction-violation)
(guile-common-conditions key args)))
(define (guile-error-converter key args)
(condition (make-error) (guile-common-conditions key args)))
(define (guile-system-error-converter key args)
(apply (case-lambda
((subr msg msg-args errno . rest)
;; XXX TODO we should return a more specific error
;; (usually an I/O error) as expected by R6RS programs.
;; Unfortunately this often requires the 'filename' (or
;; other?) which is not currently provided by the native
;; Guile exceptions.
(condition (make-error) (guile-common-conditions key args)))
(_ (guile-error-converter key args)))
args))
;; TODO: Arrange to have the needed information included in native
;; Guile I/O exceptions, and arrange here to convert them to the
;; proper conditions. Remove the earlier exception conversion
;; mechanism: search for 'with-throw-handler' in the 'rnrs'
;; tree, e.g. 'with-i/o-filename-conditions' and
;; 'with-i/o-port-error' in (rnrs io ports).
;; XXX TODO: How should we handle the 'misc-error', 'vm-error', and
;; 'signal' native Guile exceptions?
;; XXX TODO: Should we handle the 'quit' exception specially?
;; An alist mapping native Guile exception keys to converters.
(define guile-condition-converters
`((read-error . ,guile-lexical-violation-converter)
(syntax-error . ,guile-syntax-violation-converter)
(unbound-variable . ,guile-undefined-violation-converter)
(wrong-number-of-args . ,guile-assertion-violation-converter)
(wrong-type-arg . ,guile-assertion-violation-converter)
(keyword-argument-error . ,guile-assertion-violation-converter)
(out-of-range . ,guile-assertion-violation-converter)
(regular-expression-syntax . ,guile-assertion-violation-converter)
(program-error . ,guile-assertion-violation-converter)
(goops-error . ,guile-assertion-violation-converter)
(null-pointer-error . ,guile-assertion-violation-converter)
(system-error . ,guile-system-error-converter)
(host-not-found . ,guile-error-converter)
(getaddrinfo-error . ,guile-error-converter)
(no-data . ,guile-error-converter)
(no-recovery . ,guile-error-converter)
(try-again . ,guile-error-converter)
(stack-overflow . ,guile-implementation-restriction-converter)
(numerical-overflow . ,guile-implementation-restriction-converter)
(memory-allocation-error . ,guile-implementation-restriction-converter)))
(define (set-guile-condition-converter! key proc)
(set! guile-condition-converters
(acons key proc guile-condition-converters))))
;;; files.scm --- The R6RS file system library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs files (6))
(export file-exists?
delete-file
&i/o make-i/o-error i/o-error?
&i/o-read make-i/o-read-error i/o-read-error?
&i/o-write make-i/o-write-error i/o-write-error?
&i/o-invalid-position
make-i/o-invalid-position-error
i/o-invalid-position-error?
i/o-error-position
&i/o-filename
make-i/o-filename-error
i/o-filename-error?
i/o-error-filename
&i/o-file-protection
make-i/o-file-protection-error
i/o-file-protection-error?
&i/o-file-is-read-only
make-i/o-file-is-read-only-error
i/o-file-is-read-only-error?
&i/o-file-already-exists
make-i/o-file-already-exists-error
i/o-file-already-exists-error?
&i/o-file-does-not-exist
make-i/o-file-does-not-exist-error
i/o-file-does-not-exist-error?
&i/o-port
make-i/o-port-error
i/o-port-error?
i/o-error-port)
(import (rename (only (guile) file-exists? delete-file catch @@)
(delete-file delete-file-internal))
(rnrs base (6))
(rnrs conditions (6))
(rnrs exceptions (6)))
(define (delete-file filename)
(catch #t
(lambda () (delete-file-internal filename))
(lambda (key . args) (raise (make-i/o-filename-error filename)))))
;; Condition types that are used by (rnrs files), (rnrs io ports), and
;; (rnrs io simple). These are defined here so as to be easily shareable by
;; these three libraries.
(define-condition-type &i/o &error make-i/o-error i/o-error?)
(define-condition-type &i/o-read &i/o make-i/o-read-error i/o-read-error?)
(define-condition-type &i/o-write &i/o make-i/o-write-error i/o-write-error?)
(define-condition-type &i/o-invalid-position
&i/o make-i/o-invalid-position-error i/o-invalid-position-error?
(position i/o-error-position))
(define-condition-type &i/o-filename
&i/o make-i/o-filename-error i/o-filename-error?
(filename i/o-error-filename))
(define-condition-type &i/o-file-protection
&i/o-filename make-i/o-file-protection-error i/o-file-protection-error?)
(define-condition-type &i/o-file-is-read-only
&i/o-file-protection make-i/o-file-is-read-only-error
i/o-file-is-read-only-error?)
(define-condition-type &i/o-file-already-exists
&i/o-filename make-i/o-file-already-exists-error
i/o-file-already-exists-error?)
(define-condition-type &i/o-file-does-not-exist
&i/o-filename make-i/o-file-does-not-exist-error
i/o-file-does-not-exist-error?)
(define-condition-type &i/o-port &i/o make-i/o-port-error i/o-port-error?
(port i/o-error-port))
)
;;; hashtables.scm --- The R6RS hashtables library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs hashtables (6))
(export make-eq-hashtable
make-eqv-hashtable
make-hashtable
hashtable?
hashtable-size
hashtable-ref
hashtable-set!
hashtable-delete!
hashtable-contains?
hashtable-update!
hashtable-copy
hashtable-clear!
hashtable-keys
hashtable-entries
hashtable-equivalence-function
hashtable-hash-function
hashtable-mutable?
equal-hash
string-hash
string-ci-hash
symbol-hash)
(import (rename (only (guile) string-hash-ci
string-hash
hashq
hashv
modulo
*unspecified*
@@)
(string-hash-ci string-ci-hash))
(only (ice-9 optargs) define*)
(rename (only (srfi 69) make-hash-table
hash
hash-by-identity
hash-table-size
hash-table-ref/default
hash-table-set!
hash-table-delete!
hash-table-exists?
hash-table-update!/default
hash-table-copy
hash-table-equivalence-function
hash-table-hash-function
hash-table-keys
hash-table-fold)
(hash equal-hash)
(hash-by-identity symbol-hash))
(rnrs base (6))
(rnrs records procedural (6)))
(define r6rs:hashtable
(make-record-type-descriptor
'r6rs:hashtable #f #f #t #t
'#((mutable wrapped-table)
(immutable orig-hash-function)
(immutable mutable))))
(define hashtable? (record-predicate r6rs:hashtable))
(define make-r6rs-hashtable
(record-constructor (make-record-constructor-descriptor
r6rs:hashtable #f #f)))
(define r6rs:hashtable-wrapped-table (record-accessor r6rs:hashtable 0))
(define r6rs:hashtable-set-wrapped-table! (record-mutator r6rs:hashtable 0))
(define r6rs:hashtable-orig-hash-function (record-accessor r6rs:hashtable 1))
(define r6rs:hashtable-mutable? (record-accessor r6rs:hashtable 2))
(define hashtable-mutable? r6rs:hashtable-mutable?)
(define hash-by-value ((@@ (srfi srfi-69) caller-with-default-size) hashv))
(define (wrap-hash-function proc)
(lambda (key capacity) (modulo (proc key) capacity)))
(define* (make-eq-hashtable #\optional k)
(make-r6rs-hashtable
(if k (make-hash-table eq? hashq k) (make-hash-table eq? symbol-hash))
symbol-hash
#t))
(define* (make-eqv-hashtable #\optional k)
(make-r6rs-hashtable
(if k (make-hash-table eqv? hashv k) (make-hash-table eqv? hash-by-value))
hash-by-value
#t))
(define* (make-hashtable hash-function equiv #\optional k)
(let ((wrapped-hash-function (wrap-hash-function hash-function)))
(make-r6rs-hashtable
(if k
(make-hash-table equiv wrapped-hash-function k)
(make-hash-table equiv wrapped-hash-function))
hash-function
#t)))
(define (hashtable-size hashtable)
(hash-table-size (r6rs:hashtable-wrapped-table hashtable)))
(define (hashtable-ref hashtable key default)
(hash-table-ref/default
(r6rs:hashtable-wrapped-table hashtable) key default))
(define (hashtable-set! hashtable key obj)
(if (r6rs:hashtable-mutable? hashtable)
(hash-table-set! (r6rs:hashtable-wrapped-table hashtable) key obj))
*unspecified*)
(define (hashtable-delete! hashtable key)
(if (r6rs:hashtable-mutable? hashtable)
(hash-table-delete! (r6rs:hashtable-wrapped-table hashtable) key))
*unspecified*)
(define (hashtable-contains? hashtable key)
(hash-table-exists? (r6rs:hashtable-wrapped-table hashtable) key))
(define (hashtable-update! hashtable key proc default)
(if (r6rs:hashtable-mutable? hashtable)
(hash-table-update!/default
(r6rs:hashtable-wrapped-table hashtable) key proc default))
*unspecified*)
(define* (hashtable-copy hashtable #\optional mutable)
(make-r6rs-hashtable
(hash-table-copy (r6rs:hashtable-wrapped-table hashtable))
(r6rs:hashtable-orig-hash-function hashtable)
(and mutable #t)))
(define* (hashtable-clear! hashtable #\optional k)
(if (r6rs:hashtable-mutable? hashtable)
(let* ((ht (r6rs:hashtable-wrapped-table hashtable))
(equiv (hash-table-equivalence-function ht))
(hash-function (r6rs:hashtable-orig-hash-function hashtable))
(wrapped-hash-function (wrap-hash-function hash-function)))
(r6rs:hashtable-set-wrapped-table!
hashtable
(if k
(make-hash-table equiv wrapped-hash-function k)
(make-hash-table equiv wrapped-hash-function)))))
*unspecified*)
(define (hashtable-keys hashtable)
(list->vector (hash-table-keys (r6rs:hashtable-wrapped-table hashtable))))
(define (hashtable-entries hashtable)
(let* ((ht (r6rs:hashtable-wrapped-table hashtable))
(size (hash-table-size ht))
(keys (make-vector size))
(vals (make-vector size)))
(hash-table-fold (r6rs:hashtable-wrapped-table hashtable)
(lambda (k v i)
(vector-set! keys i k)
(vector-set! vals i v)
(+ i 1))
0)
(values keys vals)))
(define (hashtable-equivalence-function hashtable)
(hash-table-equivalence-function (r6rs:hashtable-wrapped-table hashtable)))
(define (hashtable-hash-function hashtable)
(r6rs:hashtable-orig-hash-function hashtable)))
;;;; ports.scm --- R6RS port API -*- coding: utf-8 -*-
;;;; Copyright (C) 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;;;
;;; The I/O port API of the R6RS is provided by this module. In many areas
;;; it complements or refines Guile's own historical port API. For instance,
;;; it allows for binary I/O with bytevectors.
;;;
;;; Code:
(library (rnrs io ports (6))
(export eof-object eof-object?
;; auxiliary types
file-options buffer-mode buffer-mode?
eol-style native-eol-style error-handling-mode
make-transcoder transcoder-codec transcoder-eol-style
transcoder-error-handling-mode native-transcoder
latin-1-codec utf-8-codec utf-16-codec
;; input & output ports
port? input-port? output-port?
port-eof?
port-transcoder binary-port? textual-port? transcoded-port
port-position set-port-position!
port-has-port-position? port-has-set-port-position!?
call-with-port close-port
;; input ports
open-bytevector-input-port
open-string-input-port
open-file-input-port
make-custom-binary-input-port
;; binary input
get-u8 lookahead-u8
get-bytevector-n get-bytevector-n!
get-bytevector-some get-bytevector-all
;; output ports
open-bytevector-output-port
open-string-output-port
open-file-output-port
make-custom-binary-output-port
call-with-bytevector-output-port
call-with-string-output-port
make-custom-textual-output-port
flush-output-port
;; input/output ports
open-file-input/output-port
;; binary output
put-u8 put-bytevector
;; textual input
get-char get-datum get-line get-string-all get-string-n get-string-n!
lookahead-char
;; textual output
put-char put-datum put-string
;; standard ports
standard-input-port standard-output-port standard-error-port
current-input-port current-output-port current-error-port
;; condition types
&i/o i/o-error? make-i/o-error
&i/o-read i/o-read-error? make-i/o-read-error
&i/o-write i/o-write-error? make-i/o-write-error
&i/o-invalid-position i/o-invalid-position-error?
make-i/o-invalid-position-error
&i/o-filename i/o-filename-error? make-i/o-filename-error
i/o-error-filename
&i/o-file-protection i/o-file-protection-error?
make-i/o-file-protection-error
&i/o-file-is-read-only i/o-file-is-read-only-error?
make-i/o-file-is-read-only-error
&i/o-file-already-exists i/o-file-already-exists-error?
make-i/o-file-already-exists-error
&i/o-file-does-not-exist i/o-file-does-not-exist-error?
make-i/o-file-does-not-exist-error
&i/o-port i/o-port-error? make-i/o-port-error
i/o-error-port
&i/o-decoding-error i/o-decoding-error?
make-i/o-decoding-error
&i/o-encoding-error i/o-encoding-error?
make-i/o-encoding-error i/o-encoding-error-char)
(import (ice-9 binary-ports)
(only (rnrs base) assertion-violation)
(rnrs enums)
(rnrs records syntactic)
(rnrs exceptions)
(rnrs conditions)
(rnrs files) ;for the condition types
(srfi srfi-8)
(ice-9 rdelim)
(except (guile) raise display)
(prefix (only (guile) display)
guile\:))
;;;
;;; Auxiliary types
;;;
(define-enumeration file-option
(no-create no-fail no-truncate)
file-options)
(define-enumeration buffer-mode
(none line block)
buffer-modes)
(define (buffer-mode? symbol)
(enum-set-member? symbol (enum-set-universe (buffer-modes))))
(define-enumeration eol-style
(lf cr crlf nel crnel ls none)
eol-styles)
(define (native-eol-style)
(eol-style none))
(define-enumeration error-handling-mode
(ignore raise replace)
error-handling-modes)
(define-record-type (transcoder %make-transcoder transcoder?)
(fields codec eol-style error-handling-mode))
(define* (make-transcoder codec
#\optional
(eol-style (native-eol-style))
(handling-mode (error-handling-mode replace)))
(%make-transcoder codec eol-style handling-mode))
(define (native-transcoder)
(make-transcoder (or (fluid-ref %default-port-encoding)
(latin-1-codec))))
(define (latin-1-codec)
"ISO-8859-1")
(define (utf-8-codec)
"UTF-8")
(define (utf-16-codec)
"UTF-16")
;;;
;;; Internal helpers
;;;
(define (with-i/o-filename-conditions filename thunk)
(with-throw-handler 'system-error
thunk
(lambda args
(let ((errno (system-error-errno args)))
(let ((construct-condition
(cond ((= errno EACCES)
make-i/o-file-protection-error)
((= errno EEXIST)
make-i/o-file-already-exists-error)
((= errno ENOENT)
make-i/o-file-does-not-exist-error)
((= errno EROFS)
make-i/o-file-is-read-only-error)
(else
make-i/o-filename-error))))
(raise (construct-condition filename)))))))
(define (with-i/o-port-error port make-primary-condition thunk)
(with-throw-handler 'system-error
thunk
(lambda args
(let ((errno (system-error-errno args)))
(if (memv errno (list EIO EFBIG ENOSPC EPIPE))
(raise (condition (make-primary-condition)
(make-i/o-port-error port)))
(apply throw args))))))
(define-syntax with-textual-output-conditions
(syntax-rules ()
((_ port body0 body ...)
(with-i/o-port-error port make-i/o-write-error
(lambda () (with-i/o-encoding-error body0 body ...))))))
(define-syntax with-textual-input-conditions
(syntax-rules ()
((_ port body0 body ...)
(with-i/o-port-error port make-i/o-read-error
(lambda () (with-i/o-decoding-error body0 body ...))))))
;;;
;;; Input and output ports.
;;;
(define (port-transcoder port)
"Return the transcoder object associated with @var{port}, or @code{#f}
if the port has no transcoder."
(cond ((port-encoding port)
=> (lambda (encoding)
(make-transcoder
encoding
(native-eol-style)
(case (port-conversion-strategy port)
((error) 'raise)
((substitute) 'replace)
(else
(assertion-violation 'port-transcoder
"unsupported error handling mode"))))))
(else
#f)))
(define (binary-port? port)
"Returns @code{#t} if @var{port} does not have an associated encoding,
@code{#f} otherwise."
(not (port-encoding port)))
(define (textual-port? port)
"Always returns @code{#t}, as all ports can be used for textual I/O in
Guile."
#t)
(define (port-eof? port)
(eof-object? (if (binary-port? port)
(lookahead-u8 port)
(lookahead-char port))))
(define (transcoded-port port transcoder)
"Return a new textual port based on @var{port}, using
@var{transcoder} to encode and decode data written to or
read from its underlying binary port @var{port}."
;; Hackily get at %make-transcoded-port.
(let ((result ((@@ (ice-9 binary-ports) %make-transcoded-port) port)))
(set-port-encoding! result (transcoder-codec transcoder))
(case (transcoder-error-handling-mode transcoder)
((raise)
(set-port-conversion-strategy! result 'error))
((replace)
(set-port-conversion-strategy! result 'substitute))
(else
(error "unsupported error handling mode"
(transcoder-error-handling-mode transcoder))))
result))
(define (port-position port)
"Return the offset (an integer) indicating where the next octet will be
read from/written to in @var{port}."
;; FIXME: We should raise an `&assertion' error when not supported.
(seek port 0 SEEK_CUR))
(define (set-port-position! port offset)
"Set the position where the next octet will be read from/written to
@var{port}."
;; FIXME: We should raise an `&assertion' error when not supported.
(seek port offset SEEK_SET))
(define (port-has-port-position? port)
"Return @code{#t} is @var{port} supports @code{port-position}."
(and (false-if-exception (port-position port)) #t))
(define (port-has-set-port-position!? port)
"Return @code{#t} is @var{port} supports @code{set-port-position!}."
(and (false-if-exception (set-port-position! port (port-position port)))
#t))
(define (call-with-port port proc)
"Call @var{proc}, passing it @var{port} and closing @var{port} upon exit of
@var{proc}. Return the return values of @var{proc}."
(call-with-values
(lambda () (proc port))
(lambda vals
(close-port port)
(apply values vals))))
(define* (call-with-bytevector-output-port proc #\optional (transcoder #f))
(receive (port extract) (open-bytevector-output-port transcoder)
(call-with-port port proc)
(extract)))
(define (open-string-input-port str)
"Open an input port that will read from @var{str}."
(with-fluids ((%default-port-encoding "UTF-8"))
(open-input-string str)))
(define (r6rs-open filename mode buffer-mode transcoder)
(let ((port (with-i/o-filename-conditions filename
(lambda ()
(with-fluids ((%default-port-encoding #f))
(open filename mode))))))
(cond (transcoder
(set-port-encoding! port (transcoder-codec transcoder))))
port))
(define (file-options->mode file-options base-mode)
(logior base-mode
(if (enum-set-member? 'no-create file-options)
0
O_CREAT)
(if (enum-set-member? 'no-truncate file-options)
0
O_TRUNC)
(if (enum-set-member? 'no-fail file-options)
0
O_EXCL)))
(define* (open-file-input-port filename
#\optional
(file-options (file-options))
(buffer-mode (buffer-mode block))
transcoder)
"Return an input port for reading from @var{filename}."
(r6rs-open filename O_RDONLY buffer-mode transcoder))
(define* (open-file-input/output-port filename
#\optional
(file-options (file-options))
(buffer-mode (buffer-mode block))
transcoder)
"Return a port for reading from and writing to @var{filename}."
(r6rs-open filename
(file-options->mode file-options O_RDWR)
buffer-mode
transcoder))
(define (open-string-output-port)
"Return two values: an output port that will collect characters written to it
as a string, and a thunk to retrieve the characters associated with that port."
(let ((port (with-fluids ((%default-port-encoding "UTF-8"))
(open-output-string))))
(values port
(lambda ()
(let ((s (get-output-string port)))
(seek port 0 SEEK_SET)
(truncate-file port 0)
s)))))
(define* (open-file-output-port filename
#\optional
(file-options (file-options))
(buffer-mode (buffer-mode block))
maybe-transcoder)
"Return an output port for writing to @var{filename}."
(r6rs-open filename
(file-options->mode file-options O_WRONLY)
buffer-mode
maybe-transcoder))
(define (call-with-string-output-port proc)
"Call @var{proc}, passing it a string output port. When @var{proc} returns,
return the characters accumulated in that port."
(let ((port (open-output-string)))
(proc port)
(get-output-string port)))
(define (make-custom-textual-output-port id
write!
get-position
set-position!
close)
(make-soft-port (vector (lambda (c) (write! (string c) 0 1))
(lambda (s) (write! s 0 (string-length s)))
#f ;flush
#f ;read character
close)
"w"))
(define (flush-output-port port)
(force-output port))
;;;
;;; Textual output.
;;;
(define-condition-type &i/o-encoding &i/o-port
make-i/o-encoding-error i/o-encoding-error?
(char i/o-encoding-error-char))
(define-syntax with-i/o-encoding-error
(syntax-rules ()
"Convert Guile throws to `encoding-error' to `&i/o-encoding-error'."
((_ body ...)
;; XXX: This is heavyweight for small functions like `put-char'.
(with-throw-handler 'encoding-error
(lambda ()
(begin body ...))
(lambda (key subr message errno port chr)
(raise (make-i/o-encoding-error port chr)))))))
(define (put-char port char)
(with-textual-output-conditions port (write-char char port)))
(define (put-datum port datum)
(with-textual-output-conditions port (write datum port)))
(define* (put-string port s #\optional start count)
(with-textual-output-conditions port
(cond ((not (string? s))
(assertion-violation 'put-string "expected string" s))
((and start count)
(display (substring/shared s start (+ start count)) port))
(start
(display (substring/shared s start (string-length s)) port))
(else
(display s port)))))
;; Defined here to be able to make use of `with-i/o-encoding-error', but
;; not exported from here, but from `(rnrs io simple)'.
(define* (display object #\optional (port (current-output-port)))
(with-textual-output-conditions port (guile:display object port)))
;;;
;;; Textual input.
;;;
(define-condition-type &i/o-decoding &i/o-port
make-i/o-decoding-error i/o-decoding-error?)
(define-syntax with-i/o-decoding-error
(syntax-rules ()
"Convert Guile throws to `decoding-error' to `&i/o-decoding-error'."
((_ body ...)
;; XXX: This is heavyweight for small functions like `get-char' and
;; `lookahead-char'.
(with-throw-handler 'decoding-error
(lambda ()
(begin body ...))
(lambda (key subr message errno port)
(raise (make-i/o-decoding-error port)))))))
(define (get-char port)
(with-textual-input-conditions port (read-char port)))
(define (get-datum port)
(with-textual-input-conditions port (read port)))
(define (get-line port)
(with-textual-input-conditions port (read-line port 'trim)))
(define (get-string-all port)
(with-textual-input-conditions port (read-string port)))
(define (get-string-n port count)
"Read up to @var{count} characters from @var{port}.
If no characters could be read before encountering the end of file,
return the end-of-file object, otherwise return a string containing
the characters read."
(let* ((s (make-string count))
(rv (get-string-n! port s 0 count)))
(cond ((eof-object? rv) rv)
((= rv count) s)
(else (substring/shared s 0 rv)))))
(define (lookahead-char port)
(with-textual-input-conditions port (peek-char port)))
;;;
;;; Standard ports.
;;;
(define (standard-input-port)
(with-fluids ((%default-port-encoding #f))
(dup->inport 0)))
(define (standard-output-port)
(with-fluids ((%default-port-encoding #f))
(dup->outport 1)))
(define (standard-error-port)
(with-fluids ((%default-port-encoding #f))
(dup->outport 2)))
)
;;; ports.scm ends here
;;; simple.scm --- The R6RS simple I/O library
;; Copyright (C) 2010, 2011, 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs io simple (6))
(export eof-object
eof-object?
call-with-input-file
call-with-output-file
input-port?
output-port?
current-input-port
current-output-port
current-error-port
with-input-from-file
with-output-to-file
open-input-file
open-output-file
close-input-port
close-output-port
read-char
peek-char
read
write-char
newline
display
write
&i/o make-i/o-error i/o-error?
&i/o-read make-i/o-read-error i/o-read-error?
&i/o-write make-i/o-write-error i/o-write-error?
&i/o-invalid-position
make-i/o-invalid-position-error
i/o-invalid-position-error?
i/o-error-position
&i/o-filename
make-i/o-filename-error
i/o-filename-error?
i/o-error-filename
&i/o-file-protection
make-i/o-file-protection-error
i/o-file-protection-error?
&i/o-file-is-read-only
make-i/o-file-is-read-only-error
i/o-file-is-read-only-error?
&i/o-file-already-exists
make-i/o-file-already-exists-error
i/o-file-already-exists-error?
&i/o-file-does-not-exist
make-i/o-file-does-not-exist-error
i/o-file-does-not-exist-error?
&i/o-port
make-i/o-port-error
i/o-port-error?
i/o-error-port)
(import (only (rnrs io ports)
call-with-port
close-port
open-file-input-port
open-file-output-port
eof-object
eof-object?
file-options
buffer-mode
native-transcoder
get-char
lookahead-char
get-datum
put-char
put-datum
input-port?
output-port?)
(only (guile)
@@
current-input-port
current-output-port
current-error-port
define*
with-input-from-port
with-output-to-port)
(rnrs base (6))
(rnrs files (6)) ;for the condition types
)
(define display (@@ (rnrs io ports) display))
(define (call-with-input-file filename proc)
(call-with-port (open-file-input-port filename) proc))
(define (call-with-output-file filename proc)
(call-with-port (open-file-output-port filename) proc))
(define (with-input-from-file filename thunk)
(call-with-input-file filename
(lambda (port) (with-input-from-port port thunk))))
(define (with-output-to-file filename thunk)
(call-with-output-file filename
(lambda (port) (with-output-to-port port thunk))))
(define (open-input-file filename)
(open-file-input-port filename
(file-options)
(buffer-mode block)
(native-transcoder)))
(define (open-output-file filename)
(open-file-output-port filename
(file-options)
(buffer-mode block)
(native-transcoder)))
(define close-input-port close-port)
(define close-output-port close-port)
(define* (read-char #\optional (port (current-input-port)))
(get-char port))
(define* (peek-char #\optional (port (current-input-port)))
(lookahead-char port))
(define* (read #\optional (port (current-input-port)))
(get-datum port))
(define* (write-char char #\optional (port (current-output-port)))
(put-char port char))
(define* (newline #\optional (port (current-output-port)))
(put-char port #\newline))
(define* (write object #\optional (port (current-output-port)))
(put-datum port object))
)
;;; lists.scm --- The R6RS list utilities library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs lists (6))
(export find for-all exists filter partition fold-left fold-right remp remove
remv remq memp member memv memq assp assoc assv assq cons*)
(import (rnrs base (6))
(only (guile) filter member memv memq assoc assv assq cons*)
(rename (only (srfi srfi-1) any
every
remove
member
assoc
find
partition
fold-right
filter-map)
(any exists)
(every for-all)
(remove remp)
(member memp-internal)
(assoc assp-internal)))
(define (fold-left combine nil list . lists)
(define (fold nil lists)
(if (exists null? lists)
nil
(fold (apply combine nil (map car lists))
(map cdr lists))))
(fold nil (cons list lists)))
(define (remove obj list) (remp (lambda (elt) (equal? obj elt)) list))
(define (remv obj list) (remp (lambda (elt) (eqv? obj elt)) list))
(define (remq obj list) (remp (lambda (elt) (eq? obj elt)) list))
(define (memp pred list) (memp-internal #f list (lambda (x y) (pred y))))
(define (assp pred list) (assp-internal #f list (lambda (x y) (pred y))))
)
;;; mutable-pairs.scm --- The R6RS mutable pair library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs mutable-pairs (6))
(export set-car! set-cdr!)
(import (only (guile) set-car! set-cdr!)))
;;; mutable-strings.scm --- The R6RS mutable string library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs mutable-strings (6))
(export string-set! string-fill!)
(import (only (guile) string-set! string-fill!)))
;;; programs.scm --- The R6RS process management library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs programs (6))
(export command-line exit)
(import (only (guile) command-line exit)))
;;; r5rs.scm --- The R6RS / R5RS compatibility library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs r5rs (6))
(export exact->inexact inexact->exact
quotient remainder modulo
delay force
null-environment scheme-report-environment)
(import (only (guile) exact->inexact inexact->exact
quotient remainder modulo
delay force)
(only (ice-9 r5rs) scheme-report-environment)
(only (ice-9 safe-r5rs) null-environment)))
;;; inspection.scm --- Inspection support for R6RS records
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs records inspection (6))
(export record?
record-rtd
record-type-name
record-type-parent
record-type-uid
record-type-generative?
record-type-sealed?
record-type-opaque?
record-type-field-names
record-field-mutable?)
(import (rnrs arithmetic bitwise (6))
(rnrs base (6))
(rnrs records procedural (6))
(only (guile) struct-ref struct-vtable vtable-index-layout @@))
(define record-internal? (@@ (rnrs records procedural) record-internal?))
(define rtd-index-name (@@ (rnrs records procedural) rtd-index-name))
(define rtd-index-parent (@@ (rnrs records procedural) rtd-index-parent))
(define rtd-index-uid (@@ (rnrs records procedural) rtd-index-uid))
(define rtd-index-sealed? (@@ (rnrs records procedural) rtd-index-sealed?))
(define rtd-index-opaque? (@@ (rnrs records procedural) rtd-index-opaque?))
(define rtd-index-field-names
(@@ (rnrs records procedural) rtd-index-field-names))
(define rtd-index-field-bit-field
(@@ (rnrs records procedural) rtd-index-field-bit-field))
(define (record? obj)
(and (record-internal? obj)
(not (record-type-opaque? (struct-vtable obj)))))
(define (record-rtd record)
(or (and (record-internal? record)
(let ((rtd (struct-vtable record)))
(and (not (struct-ref rtd rtd-index-opaque?)) rtd)))
(assertion-violation 'record-rtd "not a record" record)))
(define (guarantee-rtd who rtd)
(if (record-type-descriptor? rtd)
rtd
(assertion-violation who "not a record type descriptor" rtd)))
(define (record-type-name rtd)
(struct-ref (guarantee-rtd 'record-type-name rtd) rtd-index-name))
(define (record-type-parent rtd)
(struct-ref (guarantee-rtd 'record-type-parent rtd) rtd-index-parent))
(define (record-type-uid rtd)
(struct-ref (guarantee-rtd 'record-type-uid rtd) rtd-index-uid))
(define (record-type-generative? rtd)
(not (record-type-uid (guarantee-rtd 'record-type-generative? rtd))))
(define (record-type-sealed? rtd)
(struct-ref (guarantee-rtd 'record-type-sealed? rtd) rtd-index-sealed?))
(define (record-type-opaque? rtd)
(struct-ref (guarantee-rtd 'record-type-opaque? rtd) rtd-index-opaque?))
(define (record-type-field-names rtd)
(struct-ref (guarantee-rtd 'record-type-field-names rtd) rtd-index-field-names))
(define (record-field-mutable? rtd k)
(bitwise-bit-set? (struct-ref (guarantee-rtd 'record-field-mutable? rtd)
rtd-index-field-bit-field)
k))
)
;;; procedural.scm --- Procedural interface to R6RS records
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs records procedural (6))
(export make-record-type-descriptor
record-type-descriptor?
make-record-constructor-descriptor
record-constructor
record-predicate
record-accessor
record-mutator)
(import (rnrs base (6))
(only (guile) cons*
logand
logior
ash
and=>
throw
display
make-struct
make-vtable
map
simple-format
string-append
symbol-append
struct?
struct-layout
struct-ref
struct-set!
struct-vtable
vtable-index-layout
make-hash-table
hashq-ref
hashq-set!
vector->list)
(ice-9 receive)
(only (srfi 1) fold split-at take))
(define (record-internal? obj)
(and (struct? obj) (record-type-descriptor? (struct-vtable obj))))
(define rtd-index-name 8)
(define rtd-index-uid 9)
(define rtd-index-parent 10)
(define rtd-index-sealed? 11)
(define rtd-index-opaque? 12)
(define rtd-index-predicate 13)
(define rtd-index-field-names 14)
(define rtd-index-field-bit-field 15)
(define rtd-index-field-binder 16)
(define rctd-index-rtd 0)
(define rctd-index-parent 1)
(define rctd-index-protocol 2)
(define vtable-base-layout (symbol->string (struct-layout (make-vtable ""))))
(define record-type-vtable
(make-vtable (string-append vtable-base-layout "prprprprprprprprprpr")
(lambda (obj port)
(simple-format port "#<r6rs:record-type:~A>"
(struct-ref obj rtd-index-name)))))
(define record-constructor-vtable
(make-vtable "prprpr"
(lambda (obj port)
(simple-format port "#<r6rs:record-constructor:~A>"
(struct-ref (struct-ref obj rctd-index-rtd)
rtd-index-name)))))
(define uid-table (make-hash-table))
(define (make-record-type-descriptor name parent uid sealed? opaque? fields)
(define fields-pair
(let loop ((field-list (vector->list fields))
(layout-sym 'pr)
(layout-bit-field 0)
(counter 0))
(if (null? field-list)
(cons layout-sym layout-bit-field)
(case (caar field-list)
((immutable)
(loop (cdr field-list)
(symbol-append layout-sym 'pr)
layout-bit-field
(+ counter 1)))
((mutable)
(loop (cdr field-list)
(symbol-append layout-sym 'pw)
(logior layout-bit-field (ash 1 counter))
(+ counter 1)))
(else (r6rs-raise (make-assertion-violation)))))))
(define fields-layout (car fields-pair))
(define fields-bit-field (cdr fields-pair))
(define field-names (list->vector (map cadr (vector->list fields))))
(define late-rtd #f)
(define (private-record-predicate obj)
(and (record-internal? obj)
(or (eq? (struct-vtable obj) late-rtd)
(and=> (struct-ref obj 0) private-record-predicate))))
(define (field-binder parent-struct . args)
(apply make-struct (cons* late-rtd 0 parent-struct args)))
(if (and parent (struct-ref parent rtd-index-sealed?))
(r6rs-raise (make-assertion-violation)))
(let ((matching-rtd (and uid (hashq-ref uid-table uid)))
(opaque? (or opaque? (and parent (struct-ref
parent rtd-index-opaque?)))))
(if matching-rtd
(if (equal? (list name
parent
sealed?
opaque?
field-names
fields-bit-field)
(list (struct-ref matching-rtd rtd-index-name)
(struct-ref matching-rtd rtd-index-parent)
(struct-ref matching-rtd rtd-index-sealed?)
(struct-ref matching-rtd rtd-index-opaque?)
(struct-ref matching-rtd rtd-index-field-names)
(struct-ref matching-rtd
rtd-index-field-bit-field)))
matching-rtd
(r6rs-raise (make-assertion-violation)))
(let ((rtd (make-struct record-type-vtable 0
fields-layout
(lambda (obj port)
(simple-format
port "#<r6rs:record:~A>" name))
name
uid
parent
sealed?
opaque?
private-record-predicate
field-names
fields-bit-field
field-binder)))
(set! late-rtd rtd)
(if uid (hashq-set! uid-table uid rtd))
rtd))))
(define (record-type-descriptor? obj)
(and (struct? obj) (eq? (struct-vtable obj) record-type-vtable)))
(define (make-record-constructor-descriptor rtd
parent-constructor-descriptor
protocol)
(define rtd-arity (vector-length (struct-ref rtd rtd-index-field-names)))
(define (default-inherited-protocol n)
(lambda args
(receive
(n-args p-args)
(split-at args (- (length args) rtd-arity))
(let ((p (apply n n-args)))
(apply p p-args)))))
(define (default-protocol p) p)
(let* ((prtd (struct-ref rtd rtd-index-parent))
(pcd (or parent-constructor-descriptor
(and=> prtd (lambda (d) (make-record-constructor-descriptor
prtd #f #f)))))
(prot (or protocol (if pcd
default-inherited-protocol
default-protocol))))
(make-struct record-constructor-vtable 0 rtd pcd prot)))
(define (record-constructor rctd)
(let* ((rtd (struct-ref rctd rctd-index-rtd))
(parent-rctd (struct-ref rctd rctd-index-parent))
(protocol (struct-ref rctd rctd-index-protocol)))
(protocol
(if parent-rctd
(let ((parent-record-constructor (record-constructor parent-rctd))
(parent-rtd (struct-ref parent-rctd rctd-index-rtd)))
(lambda args
(let ((struct (apply parent-record-constructor args)))
(lambda args
(apply (struct-ref rtd rtd-index-field-binder)
(cons struct args))))))
(lambda args (apply (struct-ref rtd rtd-index-field-binder)
(cons #f args)))))))
(define (record-predicate rtd) (struct-ref rtd rtd-index-predicate))
(define (record-accessor rtd k)
(define (record-accessor-inner obj)
(if (eq? (struct-vtable obj) rtd)
(struct-ref obj (+ k 1))
(and=> (struct-ref obj 0) record-accessor-inner)))
(lambda (obj)
(if (not (record-internal? obj))
(r6rs-raise (make-assertion-violation)))
(record-accessor-inner obj)))
(define (record-mutator rtd k)
(define (record-mutator-inner obj val)
(and obj (or (and (eq? (struct-vtable obj) rtd)
(struct-set! obj (+ k 1) val))
(record-mutator-inner (struct-ref obj 0) val))))
(let ((bit-field (struct-ref rtd rtd-index-field-bit-field)))
(if (zero? (logand bit-field (ash 1 k)))
(r6rs-raise (make-assertion-violation))))
(lambda (obj val) (record-mutator-inner obj val)))
;; Condition types that are used in the current library. These are defined
;; here and not in (rnrs conditions) to avoid a circular dependency.
(define &condition (make-record-type-descriptor '&condition #f #f #f #f '#()))
(define &condition-constructor-descriptor
(make-record-constructor-descriptor &condition #f #f))
(define &serious (make-record-type-descriptor
'&serious &condition #f #f #f '#()))
(define &serious-constructor-descriptor
(make-record-constructor-descriptor
&serious &condition-constructor-descriptor #f))
(define make-serious-condition
(record-constructor &serious-constructor-descriptor))
(define &violation (make-record-type-descriptor
'&violation &serious #f #f #f '#()))
(define &violation-constructor-descriptor
(make-record-constructor-descriptor
&violation &serious-constructor-descriptor #f))
(define make-violation (record-constructor &violation-constructor-descriptor))
(define &assertion (make-record-type-descriptor
'&assertion &violation #f #f #f '#()))
(define make-assertion-violation
(record-constructor
(make-record-constructor-descriptor
&assertion &violation-constructor-descriptor #f)))
;; Exception wrapper type, along with a wrapping `throw' implementation.
;; These are used in the current library, and so they are defined here and not
;; in (rnrs exceptions) to avoid a circular dependency.
(define &raise-object-wrapper
(make-record-type-descriptor '&raise-object-wrapper #f #f #f #f
'#((immutable obj) (immutable continuation))))
(define make-raise-object-wrapper
(record-constructor (make-record-constructor-descriptor
&raise-object-wrapper #f #f)))
(define raise-object-wrapper? (record-predicate &raise-object-wrapper))
(define raise-object-wrapper-obj (record-accessor &raise-object-wrapper 0))
(define raise-object-wrapper-continuation
(record-accessor &raise-object-wrapper 1))
(define (r6rs-raise obj)
(throw 'r6rs:exception (make-raise-object-wrapper obj #f)))
(define (r6rs-raise-continuable obj)
(define (r6rs-raise-continuable-internal continuation)
(throw 'r6rs:exception (make-raise-object-wrapper obj continuation)))
(call/cc r6rs-raise-continuable-internal))
)
;;; syntactic.scm --- Syntactic support for R6RS records
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs records syntactic (6))
(export define-record-type
record-type-descriptor
record-constructor-descriptor)
(import (only (guile) and=> gensym)
(rnrs base (6))
(rnrs conditions (6))
(rnrs exceptions (6))
(rnrs hashtables (6))
(rnrs lists (6))
(rnrs records procedural (6))
(rnrs syntax-case (6))
(only (srfi 1) take))
(define record-type-registry (make-eq-hashtable))
(define (guess-constructor-name record-name)
(string->symbol (string-append "make-" (symbol->string record-name))))
(define (guess-predicate-name record-name)
(string->symbol (string-append (symbol->string record-name) "?")))
(define (register-record-type name rtd rcd)
(hashtable-set! record-type-registry name (cons rtd rcd)))
(define (lookup-record-type-descriptor name)
(and=> (hashtable-ref record-type-registry name #f) car))
(define (lookup-record-constructor-descriptor name)
(and=> (hashtable-ref record-type-registry name #f) cdr))
(define-syntax define-record-type
(lambda (stx)
(syntax-case stx ()
((_ (record-name constructor-name predicate-name) record-clause ...)
#'(define-record-type0
(record-name constructor-name predicate-name)
record-clause ...))
((_ record-name record-clause ...)
(let* ((record-name-sym (syntax->datum #'record-name))
(constructor-name
(datum->syntax
#'record-name (guess-constructor-name record-name-sym)))
(predicate-name
(datum->syntax
#'record-name (guess-predicate-name record-name-sym))))
#`(define-record-type0
(record-name #,constructor-name #,predicate-name)
record-clause ...))))))
(define (sequence n)
(define (seq-inner n) (if (= n 0) '(0) (cons n (seq-inner (- n 1)))))
(reverse (seq-inner n)))
(define (number-fields fields)
(define (number-fields-inner fields counter)
(if (null? fields)
'()
(cons (cons fields counter)
(number-fields-inner (cdr fields) (+ counter 1)))))
(number-fields-inner fields 0))
(define (process-fields record-name fields)
(define (wrap x) (datum->syntax record-name x))
(define (id->string x)
(symbol->string (syntax->datum x)))
(define record-name-str (id->string record-name))
(define (guess-accessor-name field-name)
(wrap
(string->symbol (string-append
record-name-str "-" (id->string field-name)))))
(define (guess-mutator-name field-name)
(wrap
(string->symbol
(string-append
record-name-str "-" (id->string field-name) "-set!"))))
(define (f x)
(syntax-case x (immutable mutable)
[(immutable name)
(list (wrap `(immutable ,(syntax->datum #'name)))
(guess-accessor-name #'name)
#f)]
[(immutable name accessor)
(list (wrap `(immutable ,(syntax->datum #'name))) #'accessor #f)]
[(mutable name)
(list (wrap `(mutable ,(syntax->datum #'name)))
(guess-accessor-name #'name)
(guess-mutator-name #'name))]
[(mutable name accessor mutator)
(list (wrap `(mutable ,(syntax->datum #'name))) #'accessor #'mutator)]
[name
(identifier? #'name)
(list (wrap `(immutable ,(syntax->datum #'name)))
(guess-accessor-name #'name)
#f)]
[else
(syntax-violation 'define-record-type "invalid field specifier" x)]))
(map f fields))
(define-syntax define-record-type0
(lambda (stx)
(define *unspecified* (cons #f #f))
(define (unspecified? obj)
(eq? *unspecified* obj))
(syntax-case stx ()
((_ (record-name constructor-name predicate-name) record-clause ...)
(let loop ((_fields *unspecified*)
(_parent *unspecified*)
(_protocol *unspecified*)
(_sealed *unspecified*)
(_opaque *unspecified*)
(_nongenerative *unspecified*)
(_constructor *unspecified*)
(_parent-rtd *unspecified*)
(record-clauses #'(record-clause ...)))
(syntax-case record-clauses
(fields parent protocol sealed opaque nongenerative
constructor parent-rtd)
[()
(let* ((fields (if (unspecified? _fields) '() _fields))
(field-names (list->vector (map car fields)))
(field-accessors
(fold-left (lambda (lst x c)
(cons #`(define #,(cadr x)
(record-accessor record-name #,c))
lst))
'() fields (sequence (length fields))))
(field-mutators
(fold-left (lambda (lst x c)
(if (caddr x)
(cons #`(define #,(caddr x)
(record-mutator record-name
#,c))
lst)
lst))
'() fields (sequence (length fields))))
(parent-cd (cond ((not (unspecified? _parent))
#`(record-constructor-descriptor
#,_parent))
((not (unspecified? _parent-rtd))
(cadr _parent-rtd))
(else #f)))
(parent-rtd (cond ((not (unspecified? _parent))
#`(record-type-descriptor #,_parent))
((not (unspecified? _parent-rtd))
(car _parent-rtd))
(else #f)))
(protocol (if (unspecified? _protocol) #f _protocol))
(uid (if (unspecified? _nongenerative) #f _nongenerative))
(sealed? (if (unspecified? _sealed) #f _sealed))
(opaque? (if (unspecified? _opaque) #f _opaque)))
#`(begin
(define record-name
(make-record-type-descriptor
(quote record-name)
#,parent-rtd #,uid #,sealed? #,opaque?
#,field-names))
(define constructor-name
(record-constructor
(make-record-constructor-descriptor
record-name #,parent-cd #,protocol)))
(define dummy
(let ()
(register-record-type
(quote record-name)
record-name (make-record-constructor-descriptor
record-name #,parent-cd #,protocol))
'dummy))
(define predicate-name (record-predicate record-name))
#,@field-accessors
#,@field-mutators))]
[((fields record-fields ...) . rest)
(if (unspecified? _fields)
(loop (process-fields #'record-name #'(record-fields ...))
_parent _protocol _sealed _opaque _nongenerative
_constructor _parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((parent parent-name) . rest)
(if (not (unspecified? _parent-rtd))
(raise (make-assertion-violation))
(if (unspecified? _parent)
(loop _fields #'parent-name _protocol _sealed _opaque
_nongenerative _constructor _parent-rtd #'rest)
(raise (make-assertion-violation))))]
[((protocol expression) . rest)
(if (unspecified? _protocol)
(loop _fields _parent #'expression _sealed _opaque
_nongenerative _constructor _parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((sealed sealed?) . rest)
(if (unspecified? _sealed)
(loop _fields _parent _protocol #'sealed? _opaque
_nongenerative _constructor _parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((opaque opaque?) . rest)
(if (unspecified? _opaque)
(loop _fields _parent _protocol _sealed #'opaque?
_nongenerative _constructor _parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((nongenerative) . rest)
(if (unspecified? _nongenerative)
(loop _fields _parent _protocol _sealed _opaque
#`(quote #,(datum->syntax #'record-name (gensym)))
_constructor _parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((nongenerative uid) . rest)
(if (unspecified? _nongenerative)
(loop _fields _parent _protocol _sealed
_opaque #''uid _constructor
_parent-rtd #'rest)
(raise (make-assertion-violation)))]
[((parent-rtd rtd cd) . rest)
(if (not (unspecified? _parent))
(raise (make-assertion-violation))
(if (unspecified? _parent-rtd)
(loop _fields _parent _protocol _sealed _opaque
_nongenerative _constructor #'(rtd cd)
#'rest)
(raise (make-assertion-violation))))]))))))
(define-syntax record-type-descriptor
(lambda (stx)
(syntax-case stx ()
((_ name) #`(lookup-record-type-descriptor
#,(datum->syntax
stx (list 'quote (syntax->datum #'name))))))))
(define-syntax record-constructor-descriptor
(lambda (stx)
(syntax-case stx ()
((_ name) #`(lookup-record-constructor-descriptor
#,(datum->syntax
stx (list 'quote (syntax->datum #'name))))))))
)
;;; sorting.scm --- The R6RS sorting library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs sorting (6))
(export list-sort vector-sort vector-sort!)
(import (rnrs base (6))
(only (guile) *unspecified* stable-sort sort!))
(define (list-sort proc list) (stable-sort list proc))
(define (vector-sort proc vector) (stable-sort vector proc))
(define (vector-sort! proc vector) (sort! vector proc) *unspecified*))
;;; syntax-case.scm --- R6RS support for `syntax-case' macros
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs syntax-case (6))
(export make-variable-transformer
syntax-case
syntax
identifier?
bound-identifier=?
free-identifier=?
syntax->datum
datum->syntax
generate-temporaries
with-syntax
quasisyntax
unsyntax
unsyntax-splicing
syntax-violation)
(import (only (guile) make-variable-transformer
syntax-case
syntax
identifier?
bound-identifier=?
free-identifier=?
syntax->datum
datum->syntax
generate-temporaries
with-syntax
quasisyntax
unsyntax
unsyntax-splicing)
(ice-9 optargs)
(rnrs base (6))
(rnrs conditions (6))
(rnrs exceptions (6))
(rnrs records procedural (6)))
(define* (syntax-violation who message form #\optional subform)
(let* ((conditions (list (make-message-condition message)
(make-syntax-violation form subform)))
(conditions (if who
(cons (make-who-condition who) conditions)
conditions)))
(raise (apply condition conditions))))
)
;;; unicode.scm --- The R6RS Unicode library
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (rnrs unicode (6))
(export char-upcase
char-downcase
char-titlecase
char-foldcase
char-ci=?
char-ci<?
char-ci>?
char-ci<=?
char-ci>=?
char-alphabetic?
char-numeric?
char-whitespace?
char-upper-case?
char-lower-case?
char-title-case?
char-general-category
string-upcase
string-downcase
string-titlecase
string-foldcase
string-ci=?
string-ci<?
string-ci>?
string-ci<=?
string-ci>=?
string-normalize-nfd
string-normalize-nfkd
string-normalize-nfc
string-normalize-nfkc)
(import (only (guile) char-upcase
char-downcase
char-titlecase
char-ci=?
char-ci<?
char-ci>?
char-ci<=?
char-ci>=?
char-alphabetic?
char-numeric?
char-whitespace?
char-upper-case?
char-lower-case?
char-set-contains?
char-set:title-case
char-general-category
char-upcase
char-downcase
char-titlecase
string-upcase
string-downcase
string-titlecase
string-ci=?
string-ci<?
string-ci>?
string-ci<=?
string-ci>=?
string-normalize-nfd
string-normalize-nfkd
string-normalize-nfc
string-normalize-nfkc)
(rnrs base (6)))
(define (char-foldcase char)
(if (or (eqv? char #\460) (eqv? char #\461))
char (char-downcase (char-upcase char))))
(define (char-title-case? char) (char-set-contains? char-set:title-case char))
(define (string-foldcase str) (string-downcase (string-upcase str)))
)
;;; api-diff --- diff guile-api.alist files
;; Copyright (C) 2002, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: api-diff [-d GROUPS] ALIST-FILE-A ALIST-FILE-B
;;
;; Read in the alists from files ALIST-FILE-A and ALIST-FILE-B
;; and display a (count) summary of the groups defined therein.
;; Optional arg "--details" (or "-d") specifies a comma-separated
;; list of groups, in which case api-diff displays instead the
;; elements added and deleted for each of the specified groups.
;;
;; For scheme programming, this module exports the proc:
;; (api-diff A-file B-file)
;;
;; Note that the convention is that the "older" alist/file is
;; specified first.
;;
;; TODO: Develop scheme interface.
;;; Code:
(define-module (scripts api-diff)
\:use-module (ice-9 common-list)
\:use-module (ice-9 format)
\:use-module (ice-9 getopt-long)
\:autoload (srfi srfi-13) (string-tokenize)
\:export (api-diff))
(define %include-in-guild-list #f)
(define %summary "Show differences between two scan-api files.")
(define (read-alist-file file)
(with-input-from-file file
(lambda () (read))))
(define put set-object-property!)
(define get object-property)
(define (read-api-alist-file file)
(let* ((alist (read-alist-file file))
(meta (assq-ref alist 'meta))
(interface (assq-ref alist 'interface)))
(put interface 'meta meta)
(put interface 'groups (let ((ht (make-hash-table 31)))
(for-each (lambda (group)
(hashq-set! ht group '()))
(assq-ref meta 'groups))
ht))
interface))
(define (hang-by-the-roots interface)
(let ((ht (get interface 'groups)))
(for-each (lambda (x)
(for-each (lambda (group)
(hashq-set! ht group
(cons (car x)
(hashq-ref ht group))))
(assq-ref x 'groups)))
interface))
interface)
(define (diff? a b)
(let ((result (set-difference a b)))
(if (null? result)
#f ; CL weenies bite me
result)))
(define (diff+note! a b note-removals note-additions note-same)
(let ((same? #t))
(cond ((diff? a b) => (lambda (x) (note-removals x) (set! same? #f))))
(cond ((diff? b a) => (lambda (x) (note-additions x) (set! same? #f))))
(and same? (note-same))))
(define (group-diff i-old i-new . options)
(let* ((i-old (hang-by-the-roots i-old))
(g-old (hash-fold acons '() (get i-old 'groups)))
(g-old-names (map car g-old))
(i-new (hang-by-the-roots i-new))
(g-new (hash-fold acons '() (get i-new 'groups)))
(g-new-names (map car g-new)))
(cond ((null? options)
(diff+note! g-old-names g-new-names
(lambda (removals)
(format #t "groups-removed: ~A\n" removals))
(lambda (additions)
(format #t "groups-added: ~A\n" additions))
(lambda () #t))
(for-each (lambda (group)
(let* ((old (assq-ref g-old group))
(new (assq-ref g-new group))
(old-count (and old (length old)))
(new-count (and new (length new)))
(delta (and old new (- new-count old-count))))
(format #t " ~5@A ~5@A : "
(or old-count "-")
(or new-count "-"))
(cond ((and old new)
(let ((add-count 0) (sub-count 0))
(diff+note!
old new
(lambda (subs)
(set! sub-count (length subs)))
(lambda (adds)
(set! add-count (length adds)))
(lambda () #t))
(format #t "~5@D ~5@D : ~5@D"
add-count (- sub-count) delta)))
(else
(format #t "~5@A ~5@A : ~5@A" "-" "-" "-")))
(format #t " ~A\n" group)))
(sort (union g-old-names g-new-names)
(lambda (a b)
(string<? (symbol->string a)
(symbol->string b))))))
((assq-ref options 'details)
=> (lambda (groups)
(for-each (lambda (group)
(let* ((old (or (assq-ref g-old group) '()))
(new (or (assq-ref g-new group) '()))
(>>! (lambda (label ls)
(format #t "~A ~A:\n" group label)
(for-each (lambda (x)
(format #t " ~A\n" x))
ls))))
(diff+note! old new
(lambda (removals)
(>>! 'removals removals))
(lambda (additions)
(>>! 'additions additions))
(lambda ()
(format #t "~A: no changes\n"
group)))))
groups)))
(else
(error "api-diff: group-diff: bad options")))))
(define (api-diff . args)
(let* ((p (getopt-long (cons 'api-diff args)
'((details (single-char #\d)
(value #t))
;; Add options here.
)))
(rest (option-ref p '() '("/dev/null" "/dev/null")))
(i-old (read-api-alist-file (car rest)))
(i-new (read-api-alist-file (cadr rest)))
(options '()))
(cond ((option-ref p 'details #f)
=> (lambda (groups)
(set! options (cons (cons 'details
(map string->symbol
(string-tokenize
groups
#\,)))
options)))))
(apply group-diff i-old i-new options)))
(define main api-diff)
;;; api-diff ends here
;;; autofrisk --- Generate module checks for use with auto* tools
;; Copyright (C) 2002, 2006, 2009, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: autofrisk [file]
;;
;; This program looks for the file modules.af in the current directory
;; and writes out modules.af.m4 containing autoconf definitions.
;; If given, look for FILE instead of modules.af and output to FILE.m4.
;;
;; After running autofrisk, you should add to configure.ac the lines:
;; AUTOFRISK_CHECKS
;; AUTOFRISK_SUMMARY
;; Then run "aclocal -I ." to update aclocal.m4, and finally autoconf.
;;
;; The modules.af file consists of a series of configuration forms (Scheme
;; lists), which have one of the following formats:
;; (files-glob PATTERN ...)
;; (non-critical-external MODULE ...)
;; (non-critical-internal MODULE ...)
;; (programs (MODULE PROG ...) ...)
;; (pww-varname VARNAME)
;; PATTERN is a string that may contain "*" and "?" characters to be
;; expanded into filenames. MODULE is a list of symbols naming a
;; module, such as `(srfi srfi-1)'. VARNAME is a shell-safe name to use
;; instead of "probably_wont_work", the default. This var is passed to
;; `AC_SUBST'. PROG is a string.
;;
;; Only the `files-glob' form is required.
;;
;; TODO: Write better commentary.
;; Make "please see README" configurable.
;;; Code:
(define-module (scripts autofrisk)
\:autoload (ice-9 popen) (open-input-pipe)
\:use-module (srfi srfi-1)
\:use-module (srfi srfi-8)
\:use-module (srfi srfi-13)
\:use-module (srfi srfi-14)
\:use-module (scripts read-scheme-source)
\:use-module (scripts frisk)
\:export (autofrisk))
(define %include-in-guild-list #f)
(define %summary "Generate snippets for use in configure.ac files.")
(define *recognized-keys* '(files-glob
non-critical-external
non-critical-internal
programs
pww-varname))
(define (canonical-configuration forms)
(let ((chk (lambda (condition . x)
(or condition (apply error "syntax error:" x)))))
(chk (list? forms) "input not a list")
(chk (every list? forms) "non-list element")
(chk (every (lambda (form) (< 1 (length form))) forms) "list too short")
(let ((un #f))
(chk (every (lambda (form)
(let ((key (car form)))
(and (symbol? key)
(or (eq? 'quote key)
(memq key *recognized-keys*)
(begin
(set! un key)
#f)))))
forms)
"unrecognized key:" un))
(let ((bunched (map (lambda (key)
(fold (lambda (form so-far)
(or (and (eq? (car form) key)
(cdr form)
(append so-far (cdr form)))
so-far))
(list key)
forms))
*recognized-keys*)))
(lambda (key)
(assq-ref bunched key)))))
(define (>>strong modules)
(for-each (lambda (module)
(format #t "GUILE_MODULE_REQUIRED~A\n" module))
modules))
(define (safe-name module)
(let ((var (object->string module)))
(string-map! (lambda (c)
(if (char-set-contains? char-set:letter+digit c)
c
#\_))
var)
var))
(define *pww* "probably_wont_work")
(define (>>weak weak-edges)
(for-each (lambda (edge)
(let* ((up (edge-up edge))
(down (edge-down edge))
(var (format #f "have_guile_module~A" (safe-name up))))
(format #t "GUILE_MODULE_AVAILABLE(~A, ~A)\n" var up)
(format #t "test \"$~A\" = no &&\n ~A=\"~A $~A\"~A"
var *pww* down *pww* "\n\n")))
weak-edges))
(define (>>program module progs)
(let ((vars (map (lambda (prog)
(format #f "guile_module~Asupport_~A"
(safe-name module)
prog))
progs)))
(for-each (lambda (var prog)
(format #t "AC_PATH_PROG(~A, ~A)\n" var prog))
vars progs)
(format #t "test \\\n")
(for-each (lambda (var)
(format #t " \"$~A\" = \"\" -o \\\n" var))
vars)
(format #t "~A &&\n~A=\"~A $~A\"\n\n"
(list-ref (list "war = peace"
"freedom = slavery"
"ignorance = strength")
(random 3))
*pww* module *pww*)))
(define (>>programs programs)
(for-each (lambda (form)
(>>program (car form) (cdr form)))
programs))
(define (unglob pattern)
(let ((p (open-input-pipe (format #f "echo '(' ~A ')'" pattern))))
(map symbol->string (read p))))
(define (>>checks forms)
(let* ((cfg (canonical-configuration forms))
(files (apply append (map unglob (cfg 'files-glob))))
(ncx (cfg 'non-critical-external))
(nci (cfg 'non-critical-internal))
(report ((make-frisker) files))
(external (report 'external)))
(let ((pww-varname (cfg 'pww-varname)))
(or (null? pww-varname) (set! *pww* (car pww-varname))))
(receive (weak strong)
(partition (lambda (module)
(or (member module ncx)
(every (lambda (i)
(member i nci))
(map edge-down (mod-down-ls module)))))
external)
(format #t "AC_DEFUN([AUTOFRISK_CHECKS],[\n\n")
(>>strong strong)
(format #t "\n~A=~S\n\n" *pww* "")
(>>weak (fold (lambda (module so-far)
(append so-far (mod-down-ls module)))
(list)
weak))
(>>programs (cfg 'programs))
(format #t "AC_SUBST(~A)\n])\n\n" *pww*))))
(define (>>summary)
(format #t
(symbol->string
'#{
AC_DEFUN([AUTOFRISK_SUMMARY],[
if test ! "$~A" = "" ; then
p=" ***"
echo "$p"
echo "$p NOTE:"
echo "$p The following modules probably won't work:"
echo "$p $~A"
echo "$p They can be installed anyway, and will work if their"
echo "$p dependencies are installed later. Please see README."
echo "$p"
fi
])
})
*pww* *pww*))
(define (autofrisk . args)
(let ((file (if (null? args) "modules.af" (car args))))
(or (file-exists? file)
(error "could not find input file:" file))
(with-output-to-file (format #f "~A.m4" file)
(lambda ()
(>>checks (read-scheme-source-silently file))
(>>summary)))))
(define main autofrisk)
;; Local variables:
;; eval: (put 'receive 'scheme-indent-function 2)
;; End:
;;; autofrisk ends here
;;; Compile --- Command-line Guile Scheme compiler -*- coding: iso-8859-1 -*-
;; Copyright 2005, 2008, 2009, 2010, 2011, 2014 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courts <ludo@gnu.org>
;;; Author: Andy Wingo <wingo@pobox.com>
;;; Commentary:
;; Usage: compile [ARGS]
;;
;; A command-line interface to the Guile compiler.
;;; Code:
(define-module (scripts compile)
#\use-module ((system base compile) #\select (compile-file))
#\use-module (system base target)
#\use-module (system base message)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-13)
#\use-module (srfi srfi-37)
#\use-module (ice-9 format)
#\export (compile))
(define %summary "Compile a file.")
(define (fail . messages)
(format (current-error-port) "error: ~{~a~}~%" messages)
(exit 1))
(define %options
;; Specifications of the command-line options.
(list (option '(#\h "help") #f #f
(lambda (opt name arg result)
(alist-cons 'help? #t result)))
(option '("version") #f #f
(lambda (opt name arg result)
(show-version)
(exit 0)))
(option '(#\L "load-path") #t #f
(lambda (opt name arg result)
(let ((load-path (assoc-ref result 'load-path)))
(alist-cons 'load-path (cons arg load-path)
result))))
(option '(#\o "output") #t #f
(lambda (opt name arg result)
(if (assoc-ref result 'output-file)
(fail "`-o' option cannot be specified more than once")
(alist-cons 'output-file arg result))))
(option '(#\W "warn") #t #f
(lambda (opt name arg result)
(if (string=? arg "help")
(begin
(show-warning-help)
(exit 0))
(let ((warnings (assoc-ref result 'warnings)))
(alist-cons 'warnings
(cons (string->symbol arg) warnings)
(alist-delete 'warnings result))))))
(option '(#\O "optimize") #f #f
(lambda (opt name arg result)
(alist-cons 'optimize? #t result)))
(option '(#\f "from") #t #f
(lambda (opt name arg result)
(if (assoc-ref result 'from)
(fail "`--from' option cannot be specified more than once")
(alist-cons 'from (string->symbol arg) result))))
(option '(#\t "to") #t #f
(lambda (opt name arg result)
(if (assoc-ref result 'to)
(fail "`--to' option cannot be specified more than once")
(alist-cons 'to (string->symbol arg) result))))
(option '(#\T "target") #t #f
(lambda (opt name arg result)
(if (assoc-ref result 'target)
(fail "`--target' option cannot be specified more than once")
(alist-cons 'target arg result))))))
(define (parse-args args)
"Parse argument list @var{args} and return an alist with all the relevant
options."
(args-fold args %options
(lambda (opt name arg result)
(format (current-error-port) "~A: unrecognized option" name)
(exit 1))
(lambda (file result)
(let ((input-files (assoc-ref result 'input-files)))
(alist-cons 'input-files (cons file input-files)
result)))
;; default option values
'((input-files)
(load-path)
(warnings unsupported-warning))))
(define (show-version)
(format #t "compile (GNU Guile) ~A~%" (version))
(format #t "Copyright (C) 2009, 2011 Free Software Foundation, Inc.
License LGPLv3+: GNU LGPL version 3 or later <http://gnu.org/licenses/lgpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.~%"))
(define (show-warning-help)
(format #t "The available warning types are:~%~%")
(for-each (lambda (wt)
(format #t " ~22A ~A~%"
(format #f "`~A'" (warning-type-name wt))
(warning-type-description wt)))
%warning-types)
(format #t "~%"))
(define (compile . args)
(let* ((options (parse-args args))
(help? (assoc-ref options 'help?))
(compile-opts (let ((o `(#\warnings
,(assoc-ref options 'warnings))))
(if (assoc-ref options 'optimize?)
(cons #\O o)
o)))
(from (or (assoc-ref options 'from) 'scheme))
(to (or (assoc-ref options 'to) 'objcode))
(target (or (assoc-ref options 'target) %host-type))
(input-files (assoc-ref options 'input-files))
(output-file (assoc-ref options 'output-file))
(load-path (assoc-ref options 'load-path)))
(if (or help? (null? input-files))
(begin
(format #t "Usage: compile [OPTION] FILE...
Compile each Guile source file FILE into a Guile object.
-h, --help print this help message
-L, --load-path=DIR add DIR to the front of the module load path
-o, --output=OFILE write output to OFILE
-W, --warn=WARNING emit warnings of type WARNING; use `--warn=help'
for a list of available warnings
-f, --from=LANG specify a source language other than `scheme'
-t, --to=LANG specify a target language other than `objcode'
-T, --target=TRIPLET produce bytecode for host TRIPLET
Note that auto-compilation will be turned off.
Report bugs to <~A>.~%"
%guile-bug-report-address)
(exit 0)))
(set! %load-path (append load-path %load-path))
(set! %load-should-auto-compile #f)
(if (and output-file
(or (null? input-files)
(not (null? (cdr input-files)))))
(fail "`-o' option can only be specified "
"when compiling a single file"))
;; Install a SIGINT handler. As a side effect, this gives unwind
;; handlers an opportunity to run upon SIGINT; this includes that of
;; 'call-with-output-file/atomic', called by 'compile-file', which
;; removes the temporary output file.
(sigaction SIGINT
(lambda args
(fail "interrupted by the user")))
(for-each (lambda (file)
(format #t "wrote `~A'\n"
(with-fluids ((*current-warning-prefix* ""))
(with-target target
(lambda ()
(compile-file file
#\output-file output-file
#\from from
#\to to
#\opts compile-opts))))))
input-files)))
(define main compile)
;;; Disassemble --- Disassemble .go files into something human-readable
;; Copyright 2005, 2008, 2009, 2011, 2014 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Author: Andy Wingo <wingo@pobox.com>
;;; Commentary:
;; Usage: disassemble [ARGS]
;;; Code:
(define-module (scripts disassemble)
#\use-module (system vm objcode)
#\use-module ((language assembly disassemble) #\prefix asm\:)
#\export (disassemble))
(define %summary "Disassemble a compiled .go file.")
(define (disassemble . files)
(for-each (lambda (file)
(asm:disassemble (load-objcode file)))
files))
(define main disassemble)
;;; display-commentary --- As advertized
;; Copyright (C) 2001, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen
;;; Commentary:
;; Usage: display-commentary REF1 REF2 ...
;;
;; Display Commentary section from REF1, REF2 and so on.
;; Each REF may be a filename or module name (list of symbols).
;; In the latter case, a filename is computed by searching `%load-path'.
;;; Code:
(define-module (scripts display-commentary)
\:use-module (ice-9 documentation)
\:export (display-commentary))
(define %summary "Display the Commentary section from a file or module.")
(define (display-commentary-one file)
(format #t "~A commentary:\n~A" file (file-commentary file)))
(define (module-name->filename-frag ls) ; todo: export or move
(let ((ls (map symbol->string ls)))
(let loop ((ls (cdr ls)) (acc (car ls)))
(if (null? ls)
acc
(loop (cdr ls) (string-append acc "/" (car ls)))))))
(define (display-module-commentary module-name)
(cond ((%search-load-path (module-name->filename-frag module-name))
=> (lambda (file)
(format #t "module ~A\n" module-name)
(display-commentary-one file)))))
(define (display-commentary . refs)
(for-each (lambda (ref)
(cond ((string? ref)
(if (equal? 0 (string-index ref #\())
(display-module-commentary
(with-input-from-string ref read))
(display-commentary-one ref)))
((list? ref)
(display-module-commentary ref))))
refs))
(define main display-commentary)
;;; display-commentary ends here
;;; doc-snarf --- Extract documentation from source files
;; Copyright (C) 2001, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Martin Grabmueller
;;; Commentary:
;; Usage: doc-snarf FILE
;;
;; This program reads in a Scheme source file and extracts docstrings
;; in the format specified below. Additionally, a procedure protoype
;; is infered from the procedure definition line starting with
;; (define... ).
;;
;; Currently, two output modi are implemented: texinfo and plaintext.
;; Default is plaintext, texinfo can be switched on with the
;; `--texinfo, -t' command line option.
;;
;; Format: A docstring can span multiple lines and a docstring line
;; begins with `;; ' (two semicoli and a space). A docstring is ended
;; by either a line beginning with (define ...) or one or more lines
;; beginning with `;;-' (two semicoli and a dash). These lines are
;; called `options' and begin with a keyword, followed by a colon and
;; a string.
;;
;; Additionally, "standard internal docstrings" (for Scheme source) are
;; recognized and output as "options". The output formatting is likely
;; to change in the future.
;;
;; Example:
;; This procedure foos, or bars, depending on the argument @var{braz}.
;;-Author: Martin Grabmueller
(define (foo/bar braz)
(if braz 'foo 'bar))
;;; Which results in the following docstring if texinfo output is
;;; enabled:
;; TODO: Convert option lines to alist.
;; More parameterization.
;; (maybe) Use in Guile build itself.
(define doc-snarf-version "0.0.2") ; please update before publishing!
;;; Code:
(define-module (scripts doc-snarf)
\:use-module (ice-9 getopt-long)
\:use-module (ice-9 regex)
\:use-module (ice-9 string-fun)
\:use-module (ice-9 rdelim)
\:export (doc-snarf))
(define %summary "Snarf out documentation from a file.")
(define command-synopsis
'((version (single-char #\v) (value #f))
(help (single-char #\h) (value #f))
(output (single-char #\o) (value #t))
(texinfo (single-char #\t) (value #f))
(lang (single-char #\l) (value #t))))
;; Display version information and exit.
;;-ttn-mod: use var
(define (display-version)
(display "doc-snarf ") (display doc-snarf-version) (newline))
;; Display the usage help message and exit.
;;-ttn-mod: change option "source" to "lang"
(define (display-help)
(display "Usage: doc-snarf [options...] inputfile\n")
(display " --help, -h Show this usage information\n")
(display " --version, -v Show version information\n")
(display
" --output=FILE, -o Specify output file [default=stdout]\n")
(display " --texinfo, -t Format output as texinfo\n")
(display " --lang=[c,scheme], -l Specify the input language\n"))
;; Main program.
;;-ttn-mod: canonicalize lang
(define (doc-snarf . args)
(let ((options (getopt-long (cons "doc-snarf" args) command-synopsis)))
(let ((help-wanted (option-ref options 'help #f))
(version-wanted (option-ref options 'version #f))
(texinfo-wanted (option-ref options 'texinfo #f))
(lang (string->symbol
(string-downcase (option-ref options 'lang "scheme")))))
(cond
(version-wanted (display-version))
(help-wanted (display-help))
(else
(let ((input (option-ref options '() #f))
(output (option-ref options 'output #f)))
(if
;; Bonard B. Timmons III says `(pair? input)' alone is sufficient.
;; (and input (pair? input))
(pair? input)
(snarf-file (car input) output texinfo-wanted lang)
(display-help))))))))
(define main doc-snarf)
;; Supported languages and their parameters. Each element has form:
;; (LANG DOC-START DOC-END DOC-PREFIX OPT-PREFIX SIG-START STD-INT-DOC?)
;; LANG is a symbol, STD-INT-DOC? is a boolean indicating whether or not
;; LANG supports "standard internal docstring" (a string after the formals),
;; everything else is a string specifying a regexp.
;;-ttn-mod: new var
(define supported-languages
'((c
"^/\\*(.*)"
"^ \\*/"
"^ \\* (.*)"
"^ \\*-(.*)"
"NOTHING AT THIS TIME!!!"
#f
)
(scheme
"^;; (.*)"
"^;;\\."
"^;; (.*)"
"^;;-(.*)"
"^\\(define"
#t
)))
;; Get @var{lang}'s @var{parameter}. Both args are symbols.
;;-ttn-mod: new proc
(define (lang-parm lang parm)
(list-ref (assq-ref supported-languages lang)
(case parm
((docstring-start) 0)
((docstring-end) 1)
((docstring-prefix) 2)
((option-prefix) 3)
((signature-start) 4)
((std-int-doc?) 5))))
;; Snarf all docstrings from the file @var{input} and write them to
;; file @var{output}. Use texinfo format for the output if
;; @var{texinfo?} is true.
;;-ttn-mod: don't use string comparison, consult table instead
(define (snarf-file input output texinfo? lang)
(or (memq lang (map car supported-languages))
(error "doc-snarf: input language must be c or scheme."))
(write-output (snarf input lang) output
(if texinfo? format-texinfo format-plain)))
;; fixme: this comment is required to trigger standard internal
;; docstring snarfing... ideally, it wouldn't be necessary.
;;-ttn-mod: new proc, from snarf-docs (aren't these names fun?)
(define (find-std-int-doc line input-port)
"Unread @var{line} from @var{input-port}, then read in the entire form and
return the standard internal docstring if found. Return #f if not."
(unread-string line input-port) ; ugh
(let ((form (read input-port)))
(cond ((and (list? form) ; (define (PROC ARGS) "DOC" ...)
(< 3 (length form))
(eq? 'define (car form))
(pair? (cadr form))
(symbol? (caadr form))
(string? (caddr form)))
(caddr form))
((and (list? form) ; (define VAR (lambda ARGS "DOC" ...))
(< 2 (length form))
(eq? 'define (car form))
(symbol? (cadr form))
(list? (caddr form))
(< 3 (length (caddr form)))
(eq? 'lambda (car (caddr form)))
(string? (caddr (caddr form))))
(caddr (caddr form)))
(else #f))))
;; Split @var{string} into lines, adding @var{prefix} to each.
;;-ttn-mod: new proc
(define (split-prefixed string prefix)
(separate-fields-discarding-char
#\newline string
(lambda lines
(map (lambda (line)
(string-append prefix line))
lines))))
;; snarf input-file output-file
;; Extract docstrings from the input file @var{input}, presumed
;; to be written in language @var{lang}.
;;-Author: Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
;;-Created: 2001-02-17
;;-ttn-mod: regluarize lang parm lookup, add "std int doc" snarfing (2 places)
(define (snarf input-file lang)
(let* ((i-p (open-input-file input-file))
(parm-regexp (lambda (parm) (make-regexp (lang-parm lang parm))))
(docstring-start (parm-regexp 'docstring-start))
(docstring-end (parm-regexp 'docstring-end))
(docstring-prefix (parm-regexp 'docstring-prefix))
(option-prefix (parm-regexp 'option-prefix))
(signature-start (parm-regexp 'signature-start))
(augmented-options
(lambda (line i-p options)
(let ((int-doc (and (lang-parm lang 'std-int-doc?)
(let ((d (find-std-int-doc line i-p)))
(and d (split-prefixed d "internal: "))))))
(if int-doc
(append (reverse int-doc) options)
options)))))
(let lp ((line (read-line i-p)) (state 'neutral) (doc-strings '())
(options '()) (entries '()) (lno 0))
(cond
((eof-object? line)
(close-input-port i-p)
(reverse entries))
;; State 'neutral: we're currently not within a docstring or
;; option section
((eq? state 'neutral)
(let ((m (regexp-exec docstring-start line)))
(if m
(lp (read-line i-p) 'doc-string
(list (match:substring m 1)) '() entries (+ lno 1))
(lp (read-line i-p) state '() '() entries (+ lno 1)))))
;; State 'doc-string: we have started reading a docstring and
;; are waiting for more, for options or for a define.
((eq? state 'doc-string)
(let ((m0 (regexp-exec docstring-prefix line))
(m1 (regexp-exec option-prefix line))
(m2 (regexp-exec signature-start line))
(m3 (regexp-exec docstring-end line)))
(cond
(m0
(lp (read-line i-p) 'doc-string
(cons (match:substring m0 1) doc-strings) '() entries
(+ lno 1)))
(m1
(lp (read-line i-p) 'options
doc-strings (cons (match:substring m1 1) options) entries
(+ lno 1)))
(m2
(let ((options (augmented-options line i-p options))) ; ttn-mod
(lp (read-line i-p) 'neutral '() '()
(cons (parse-entry doc-strings options line input-file lno)
entries)
(+ lno 1))))
(m3
(lp (read-line i-p) 'neutral '() '()
(cons (parse-entry doc-strings options #f input-file lno)
entries)
(+ lno 1)))
(else
(lp (read-line i-p) 'neutral '() '() entries (+ lno 1))))))
;; State 'options: We're waiting for more options or for a
;; define.
((eq? state 'options)
(let ((m1 (regexp-exec option-prefix line))
(m2 (regexp-exec signature-start line))
(m3 (regexp-exec docstring-end line)))
(cond
(m1
(lp (read-line i-p) 'options
doc-strings (cons (match:substring m1 1) options) entries
(+ lno 1)))
(m2
(let ((options (augmented-options line i-p options))) ; ttn-mod
(lp (read-line i-p) 'neutral '() '()
(cons (parse-entry doc-strings options line input-file lno)
entries)
(+ lno 1))))
(m3
(lp (read-line i-p) 'neutral '() '()
(cons (parse-entry doc-strings options #f input-file lno)
entries)
(+ lno 1)))
(else
(lp (read-line i-p) 'neutral '() '() entries (+ lno 1))))))))))
(define (make-entry symbol signature docstrings options filename line)
(vector 'entry symbol signature docstrings options filename line))
(define (entry-symbol e)
(vector-ref e 1))
(define (entry-signature e)
(vector-ref e 2))
(define (entry-docstrings e)
(vector-ref e 3))
(define (entry-options e)
(vector-ref e 4))
(define (entry-filename e)
(vector-ref e 5))
(define (entry-line e)
"This docstring will not be snarfed, unfortunately..."
(vector-ref e 6))
;; Create a docstring entry from the docstring line list
;; @var{doc-strings}, the option line list @var{options} and the
;; define line @var{def-line}
(define (parse-entry docstrings options def-line filename line-no)
; (write-line docstrings)
(cond
(def-line
(make-entry (get-symbol def-line)
(make-prototype def-line) (reverse docstrings)
(reverse options) filename
(+ (- line-no (length docstrings) (length options)) 1)))
((> (length docstrings) 0)
(make-entry (string->symbol (car (reverse docstrings)))
(car (reverse docstrings))
(cdr (reverse docstrings))
(reverse options) filename
(+ (- line-no (length docstrings) (length options)) 1)))
(else
(make-entry 'foo "" (reverse docstrings) (reverse options) filename
(+ (- line-no (length docstrings) (length options)) 1)))))
;; Create a string which is a procedure prototype. The necessary
;; information for constructing the prototype is taken from the line
;; @var{def-line}, which is a line starting with @code{(define...}.
(define (make-prototype def-line)
(call-with-input-string
def-line
(lambda (s-p)
(let* ((paren (read-char s-p))
(keyword (read s-p))
(tmp (read s-p)))
(cond
((pair? tmp)
(join-symbols tmp))
((symbol? tmp)
(symbol->string tmp))
(else
""))))))
(define (get-symbol def-line)
(call-with-input-string
def-line
(lambda (s-p)
(let* ((paren (read-char s-p))
(keyword (read s-p))
(tmp (read s-p)))
(cond
((pair? tmp)
(car tmp))
((symbol? tmp)
tmp)
(else
'foo))))))
;; Append the symbols in the string list @var{s}, separated with a
;; space character.
(define (join-symbols s)
(cond ((null? s)
"")
((symbol? s)
(string-append ". " (symbol->string s)))
((null? (cdr s))
(symbol->string (car s)))
(else
(string-append (symbol->string (car s)) " " (join-symbols (cdr s))))))
;; Write @var{entries} to @var{output-file} using @var{writer}.
;; @var{writer} is a proc that takes one entry.
;; If @var{output-file} is #f, write to stdout.
;;-ttn-mod: new proc
(define (write-output entries output-file writer)
(with-output-to-port (cond (output-file (open-output-file output-file))
(else (current-output-port)))
(lambda () (for-each writer entries))))
;; Write an @var{entry} using texinfo format.
;;-ttn-mod: renamed from `texinfo-output', distilled
(define (format-texinfo entry)
(display "\n\f")
(display (entry-symbol entry))
(newline)
(display "@c snarfed from ")
(display (entry-filename entry))
(display ":")
(display (entry-line entry))
(newline)
(display "@deffn procedure ")
(display (entry-signature entry))
(newline)
(for-each (lambda (s) (write-line s))
(entry-docstrings entry))
(for-each (lambda (s) (display "@c ") (write-line s))
(entry-options entry))
(write-line "@end deffn"))
;; Write an @var{entry} using plain format.
;;-ttn-mod: renamed from `texinfo-output', distilled
(define (format-plain entry)
(display "Procedure: ")
(display (entry-signature entry))
(newline)
(for-each (lambda (s) (write-line s))
(entry-docstrings entry))
(for-each (lambda (s) (display ";; ") (write-line s))
(entry-options entry))
(display "Snarfed from ")
(display (entry-filename entry))
(display ":")
(display (entry-line entry))
(newline)
(write-line "\f"))
;;; doc-snarf ends here
;;; frisk --- Grok the module interfaces of a body of files
;; Copyright (C) 2002, 2006, 2010, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: frisk [options] file ...
;;
;; Analyze FILE... module interfaces in aggregate (as a "body"),
;; and display a summary. Modules that are `define-module'd are
;; considered "internal" (and those not, "external"). When module X
;; uses module Y, X is said to be "(a) downstream of" Y, and Y is
;; "(an) upstream of" X.
;;
;; Normally, the summary displays external modules and their internal
;; downstreams, as this is the usual question asked by a body. There
;; are several options that modify this output.
;;
;; -u, --upstream show upstream edges
;; -d, --downstream show downstream edges (default)
;; -i, --internal show internal modules
;; -x, --external show external modules (default)
;;
;; If given both `upstream' and `downstream' options ("frisk -ud"), the
;; output is formatted: "C MODULE --- UP-LS --- DOWN-LS", where C is
;; either `i' or `x', and each element of UP-LS and DOWN-LS is (TYPE
;; MODULE-NAME ...).
;;
;; In all other cases, the "C MODULE" occupies its own line, and
;; subsequent lines list the up- or downstream edges, respectively,
;; indented by some non-zero amount of whitespace.
;;
;; Top-level `use-modules' (or `load' or 'primitive-load') forms in a
;; file that do not follow a `define-module' result an edge where the
;; downstream is the "default module", normally `(guile-user)'. This
;; can be set to another value by using:
;;
;; -m, --default-module MOD set MOD as the default module
;; Usage from a Scheme Program: (use-modules (scripts frisk))
;;
;; Module export list:
;; (frisk . args)
;; (make-frisker . options) => (lambda (files) ...) [see below]
;; (mod-up-ls module) => upstream edges
;; (mod-down-ls module) => downstream edges
;; (mod-int? module) => is the module internal?
;; (edge-type edge) => symbol: {regular,autoload,computed}
;; (edge-up edge) => upstream module
;; (edge-down edge) => downstream module
;;
;; OPTIONS is an alist. Recognized keys are:
;; default-module
;;
;; `make-frisker' returns a procedure that takes a list of files, the
;; FRISKER. FRISKER returns a closure, REPORT, that takes one of the
;; keys:
;; modules -- entire list of modules
;; internal -- list of internal modules
;; external -- list of external modules
;; i-up -- list of modules upstream of internal modules
;; x-up -- list of modules upstream of external modules
;; i-down -- list of modules downstream of internal modules
;; x-down -- list of modules downstream of external modules
;; edges -- list of edges
;; Note that `x-up' should always be null, since by (lack of!)
;; definition, we only know external modules by reference.
;;
;; The module and edge objects managed by REPORT can be examined in
;; detail by using the other (self-explanatory) procedures. Be careful
;; not to confuse a freshly consed list of symbols, like `(a b c)' with
;; the module `(a b c)'. If you want to find the module by that name,
;; try: (cond ((member '(a b c) (REPORT 'modules)) => car)).
;; TODO: Make "frisk -ud" output less ugly.
;; Consider default module as internal; add option to invert.
;; Support `edge-misc' data.
;;; Code:
(define-module (scripts frisk)
\:autoload (ice-9 getopt-long) (getopt-long)
\:use-module ((srfi srfi-1) \:select (filter remove))
\:export (frisk
make-frisker
mod-up-ls mod-down-ls mod-int?
edge-type edge-up edge-down))
(define %include-in-guild-list #f)
(define %summary "Show dependency information for a module.")
(define *default-module* '(guile-user))
(define (grok-proc default-module note-use!)
(lambda (filename)
(let* ((p (open-file filename "r"))
(next (lambda () (read p)))
(ferret (lambda (use) ;;; handle "((foo bar) \:select ...)"
(let ((maybe (car use)))
(if (list? maybe)
maybe
use))))
(curmod #f))
(let loop ((form (next)))
(cond ((eof-object? form))
((not (list? form)) (loop (next)))
(else (case (car form)
((define-module)
(let ((module (cadr form)))
(set! curmod module)
(note-use! 'def module #f)
(let loop ((ls form))
(or (null? ls)
(case (car ls)
((#\use-module \:use-module)
(note-use! 'regular module (ferret (cadr ls)))
(loop (cddr ls)))
((#\autoload \:autoload)
(note-use! 'autoload module (cadr ls))
(loop (cdddr ls)))
(else (loop (cdr ls))))))))
((use-modules)
(for-each (lambda (use)
(note-use! 'regular
(or curmod default-module)
(ferret use)))
(cdr form)))
((load primitive-load)
(note-use! 'computed
(or curmod default-module)
(let ((file (cadr form)))
(if (string? file)
file
(format #f "[computed in ~A]"
filename))))))
(loop (next))))))))
(define up-ls (make-object-property)) ; list
(define dn-ls (make-object-property)) ; list
(define int? (make-object-property)) ; defined via `define-module'
(define mod-up-ls up-ls)
(define mod-down-ls dn-ls)
(define mod-int? int?)
(define (i-or-x module)
(if (int? module) 'i 'x))
(define edge-type (make-object-property)) ; symbol
(define (make-edge type up down)
(let ((new (cons up down)))
(set! (edge-type new) type)
new))
(define edge-up car)
(define edge-down cdr)
(define (up-ls+! m new) (set! (up-ls m) (cons new (up-ls m))))
(define (dn-ls+! m new) (set! (dn-ls m) (cons new (dn-ls m))))
(define (make-body alist)
(lambda (key)
(assq-ref alist key)))
(define (scan default-module files)
(let* ((modules (list))
(edges (list))
(intern (lambda (module)
(cond ((member module modules) => car)
(else (set! (up-ls module) (list))
(set! (dn-ls module) (list))
(set! modules (cons module modules))
module))))
(grok (grok-proc default-module
(lambda (type d u)
(let ((d (intern d)))
(if (eq? type 'def)
(set! (int? d) #t)
(let* ((u (intern u))
(edge (make-edge type u d)))
(set! edges (cons edge edges))
(up-ls+! d edge)
(dn-ls+! u edge))))))))
(for-each grok files)
(make-body
`((modules . ,modules)
(internal . ,(filter int? modules))
(external . ,(remove int? modules))
(i-up . ,(filter int? (map edge-down edges)))
(x-up . ,(remove int? (map edge-down edges)))
(i-down . ,(filter int? (map edge-up edges)))
(x-down . ,(remove int? (map edge-up edges)))
(edges . ,edges)))))
(define (make-frisker . options)
(let ((default-module (or (assq-ref options 'default-module)
*default-module*)))
(lambda (files)
(scan default-module files))))
(define (dump-updown modules)
(for-each (lambda (m)
(format #t "~A ~A --- ~A --- ~A\n"
(i-or-x m) m
(map (lambda (edge)
(cons (edge-type edge)
(edge-up edge)))
(up-ls m))
(map (lambda (edge)
(cons (edge-type edge)
(edge-down edge)))
(dn-ls m))))
modules))
(define (dump-up modules)
(for-each (lambda (m)
(format #t "~A ~A\n" (i-or-x m) m)
(for-each (lambda (edge)
(format #t "\t\t\t ~A\t~A\n"
(edge-type edge) (edge-up edge)))
(up-ls m)))
modules))
(define (dump-down modules)
(for-each (lambda (m)
(format #t "~A ~A\n" (i-or-x m) m)
(for-each (lambda (edge)
(format #t "\t\t\t ~A\t~A\n"
(edge-type edge) (edge-down edge)))
(dn-ls m)))
modules))
(define (frisk . args)
(let* ((parsed-opts (getopt-long
(cons "frisk" args) ;;; kludge
'((upstream (single-char #\u))
(downstream (single-char #\d))
(internal (single-char #\i))
(external (single-char #\x))
(default-module
(single-char #\m)
(value #t)))))
(=u (option-ref parsed-opts 'upstream #f))
(=d (option-ref parsed-opts 'downstream #f))
(=i (option-ref parsed-opts 'internal #f))
(=x (option-ref parsed-opts 'external #f))
(files (option-ref parsed-opts '() (list)))
(report ((make-frisker
`(default-module
. ,(option-ref parsed-opts 'default-module
*default-module*)))
files))
(modules (report 'modules))
(internal (report 'internal))
(external (report 'external))
(edges (report 'edges)))
(format #t "~A ~A, ~A ~A (~A ~A, ~A ~A), ~A ~A\n\n"
(length files) "files"
(length modules) "modules"
(length internal) "internal"
(length external) "external"
(length edges) "edges")
((cond ((and =u =d) dump-updown)
(=u dump-up)
(else dump-down))
(cond ((and =i =x) modules)
(=i internal)
(else external)))))
(define main frisk)
;;; frisk ends here
;;; generate-autoload --- Display define-module form with autoload info
;; Copyright (C) 2001, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen
;;; Commentary:
;; Usage: generate-autoload [OPTIONS] FILE1 FILE2 ...
;;
;; The autoload form is displayed to standard output:
;;
;; (define-module (guile-user)
;; :autoload (ZAR FOO) (FOO-1 FOO-2 ...)
;; :
;; :
;; :autoload (ZAR BAR) (BAR-1 BAR-2 ...))
;;
;; For each file, a symbol triggers an autoload if it is found in one
;; of these situations:
;; - in the `:export' clause of a `define-module' form
;; - in a top-level `export' or `export-syntax' form
;; - in a `define-public' form
;; - in a `defmacro-public' form
;;
;; The module name is inferred from the `define-module' form. If either the
;; module name or the exports list cannot be determined, no autoload entry is
;; generated for that file.
;;
;; Options:
;; --target MODULE-NAME -- Use MODULE-NAME instead of `(guile-user)'.
;; Note that some shells may require you to
;; quote the argument to handle parentheses
;; and spaces.
;;
;; Usage examples from Scheme code as a module:
;; (use-modules (scripts generate-autoload))
;; (generate-autoload "generate-autoload")
;; (generate-autoload "--target" "(my module)" "generate-autoload")
;; (apply generate-autoload "--target" "(my module)" '("foo" "bar" "baz"))
;;; Code:
(define-module (scripts generate-autoload)
\:export (generate-autoload))
(define %include-in-guild-list #f)
(define %summary "Generate #\autoload clauses for a module.")
(define (autoload-info file)
(let ((p (open-input-file file)))
(let loop ((form (read p)) (module-name #f) (exports '()))
(if (eof-object? form)
(and module-name
(not (null? exports))
(list module-name exports)) ; ret
(cond ((and (list? form)
(< 1 (length form))
(eq? 'define-module (car form)))
(loop (read p)
(cadr form)
(cond ((member '\:export form)
=> (lambda (val)
(append (cadr val) exports)))
(else exports))))
((and (list? form)
(< 1 (length form))
(memq (car form) '(export export-syntax)))
(loop (read p)
module-name
(append (cdr form) exports)))
((and (list? form)
(< 2 (length form))
(eq? 'define-public (car form))
(list? (cadr form))
(symbol? (caadr form)))
(loop (read p)
module-name
(cons (caadr form) exports)))
((and (list? form)
(< 2 (length form))
(eq? 'define-public (car form))
(symbol? (cadr form)))
(loop (read p)
module-name
(cons (cadr form) exports)))
((and (list? form)
(< 3 (length form))
(eq? 'defmacro-public (car form))
(symbol? (cadr form)))
(loop (read p)
module-name
(cons (cadr form) exports)))
(else (loop (read p) module-name exports)))))))
(define (generate-autoload . args)
(let* ((module-count 0)
(syms-count 0)
(target-override (cond ((member "--target" args) => cadr)
(else #f)))
(files (if target-override (cddr args) (cdr args))))
(display ";;; do not edit --- generated ")
(display (strftime "%Y-%m-%d %H:%M:%S" (localtime (current-time))))
(newline)
(display "(define-module ")
(display (or target-override "(guile-user)"))
(for-each (lambda (file)
(cond ((autoload-info file)
=> (lambda (info)
(and info
(apply (lambda (module-name exports)
(set! module-count (1+ module-count))
(set! syms-count (+ (length exports)
syms-count))
(for-each display
(list "\n :autoload "
module-name " "
exports)))
info))))))
files)
(display ")")
(newline)
(for-each display (list " ;;; "
syms-count " symbols in "
module-count " modules\n"))))
(define main generate-autoload)
;;; generate-autoload ends here
;;; Help --- Show help on guild commands
;;;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free
;;;; Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;;;; Boston, MA 02110-1301 USA
;;; Commentary:
;; Usage: help
;;
;; Show help for Guild scripts.
;;; Code:
(define-module (scripts help)
#\use-module (ice-9 format)
#\use-module (ice-9 documentation)
#\use-module ((srfi srfi-1) #\select (fold append-map))
#\export (show-help show-summary show-usage main))
(define %summary "Show a brief help message.")
(define %synopsis "help\nhelp --all\nhelp COMMAND")
(define %help "
Show help on guild commands. With --all, show arcane incantations as
well. With COMMAND, show more detailed help for a particular command.
")
(define (directory-files dir)
(if (and (file-exists? dir) (file-is-directory? dir))
(let ((dir-stream (opendir dir)))
(let loop ((new (readdir dir-stream))
(acc '()))
(if (eof-object? new)
(begin
(closedir dir-stream)
acc)
(loop (readdir dir-stream)
(if (or (string=? "." new) ; ignore
(string=? ".." new)) ; ignore
acc
(cons new acc))))))
'()))
(define (strip-extensions path)
(or-map (lambda (ext)
(and
(string-suffix? ext path)
;; We really can't be adding e.g. ChangeLog-2008 to the set
;; of runnable scripts, just because "" is a valid
;; extension, by default. So hack around that here.
(not (string-null? ext))
(substring path 0
(- (string-length path) (string-length ext)))))
(append %load-compiled-extensions %load-extensions)))
(define (unique l)
(cond ((null? l) l)
((null? (cdr l)) l)
((equal? (car l) (cadr l)) (unique (cdr l)))
(else (cons (car l) (unique (cdr l))))))
(define (find-submodules head)
(let ((shead (map symbol->string head)))
(unique
(sort
(append-map (lambda (path)
(fold (lambda (x rest)
(let ((stripped (strip-extensions x)))
(if stripped (cons stripped rest) rest)))
'()
(directory-files
(fold (lambda (x y) (in-vicinity y x)) path shead))))
%load-path)
string<?))))
(define (list-commands all?)
(display "\\
Usage: guild COMMAND [ARGS]
Run command-line scripts provided by GNU Guile and related programs.
Commands:
")
(for-each
(lambda (name)
(let* ((modname `(scripts ,(string->symbol name)))
(mod (resolve-module modname #\ensure #f))
(summary (and mod (and=> (module-variable mod '%summary)
variable-ref))))
(if (and mod
(or all?
(let ((v (module-variable mod '%include-in-guild-list)))
(if v (variable-ref v) #t))))
(if summary
(format #t " ~A ~23t~a\n" name summary)
(format #t " ~A\n" name)))))
(find-submodules '(scripts)))
(format #t "
For help on a specific command, try \"guild help COMMAND\".
Report guild bugs to ~a
GNU Guile home page: <http://www.gnu.org/software/guile/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info guile 'Using Guile Tools'
" %guile-bug-report-address))
(define (module-commentary mod)
(file-commentary
(%search-load-path (module-filename mod))))
(define (module-command-name mod)
(symbol->string (car (last-pair (module-name mod)))))
(define* (show-usage mod #\optional (port (current-output-port)))
(let ((usages (string-split
(let ((var (module-variable mod '%synopsis)))
(if var
(variable-ref var)
(string-append (module-command-name mod)
" OPTION...")))
#\newline)))
(display "Usage: guild " port)
(display (car usages))
(newline port)
(for-each (lambda (u)
(display " guild " port)
(display u port)
(newline port))
(cdr usages))))
(define* (show-summary mod #\optional (port (current-output-port)))
(let ((var (module-variable mod '%summary)))
(if var
(begin
(display (variable-ref var) port)
(newline port)))))
(define* (show-help mod #\optional (port (current-output-port)))
(show-usage mod port)
(show-summary mod port)
(cond
((module-variable mod '%help)
=> (lambda (var)
(display (variable-ref var) port)
(newline port)))
((module-commentary mod)
=> (lambda (commentary)
(newline port)
(display commentary port)))
(else
(format #t "No documentation found for command \"~a\".\n"
(module-command-name mod)))))
(define %mod (current-module))
(define (main . args)
(cond
((null? args)
(list-commands #f))
((or (equal? args '("--all")) (equal? args '("-a")))
(list-commands #t))
((and (null? (cdr args)) (not (string-prefix? "-" (car args))))
;; help for particular command
(let ((name (car args)))
(cond
((resolve-module `(scripts ,(string->symbol name)) #\ensure #f)
=> (lambda (mod)
(show-help mod)
(exit 0)))
(else
(format #t "No command named \"~a\".\n" name)
(exit 1)))))
(else
(show-help %mod (current-error-port))
(exit 1))))
;;; lint --- Preemptive checks for coding errors in Guile Scheme code
;; Copyright (C) 2002, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Neil Jerram
;;; Commentary:
;; Usage: lint FILE1 FILE2 ...
;;
;; Perform various preemptive checks for coding errors in Guile Scheme
;; code.
;;
;; Right now, there is only one check available, for unresolved free
;; variables. The intention is that future lint-like checks will be
;; implemented by adding to this script file.
;;
;; Unresolved free variables
;; -------------------------
;;
;; Free variables are those whose definitions come from outside the
;; module under investigation. In Guile, these definitions are
;; imported from other modules using `#\use-module' forms.
;;
;; This tool scans the specified files for unresolved free variables -
;; i.e. variables for which you may have forgotten the appropriate
;; `#\use-module', or for which the module that is supposed to export
;; them forgot to.
;;
;; It isn't guaranteed that the scan will find absolutely all such
;; errors. Quoted (and quasiquoted) expressions are skipped, since
;; they are most commonly used to describe constant data, not code, so
;; code that is explicitly evaluated using `eval' will not be checked.
;; For example, the `unresolved-var' in `(eval 'unresolved-var
;; (current-module))' would be missed.
;;
;; False positives are also possible. Firstly, the tool doesn't
;; understand all possible forms of implicit quoting; in particular,
;; it doesn't detect and expand uses of macros. Secondly, it picks up
;; explicit compatibility code like `(if (defined? 'x) (define y x))'.
;; Thirdly, there are occasional oddities like `next-method'.
;; However, the number of false positives for realistic code is
;; hopefully small enough that they can be individually considered and
;; ignored.
;;
;; Example
;; -------
;;
;; Note: most of the unresolved variables found in this example are
;; false positives, as you would hope. => scope for improvement.
;;
;; $ guild lint `guild`
;; No unresolved free variables in PROGRAM
;; No unresolved free variables in autofrisk
;; No unresolved free variables in display-commentary
;; Unresolved free variables in doc-snarf:
;; doc-snarf-version
;; No unresolved free variables in frisk
;; No unresolved free variables in generate-autoload
;; No unresolved free variables in lint
;; No unresolved free variables in punify
;; No unresolved free variables in read-scheme-source
;; Unresolved free variables in snarf-check-and-output-texi:
;; name
;; pos
;; line
;; x
;; rest
;; ...
;; do-argpos
;; do-command
;; do-args
;; type
;; num
;; file
;; do-arglist
;; req
;; opt
;; var
;; command
;; do-directive
;; s
;; ?
;; No unresolved free variables in use2dot
;;; Code:
(define-module (scripts lint)
#\use-module (ice-9 common-list)
#\use-module (ice-9 format)
#\export (lint))
(define %include-in-guild-list #f)
(define %summary "Check for bugs and style errors in a Scheme file.")
(define (lint filename)
(let ((module-name (scan-file-for-module-name filename))
(free-vars (uniq (scan-file-for-free-variables filename))))
(let ((module (resolve-module module-name))
(all-resolved? #t))
(format #t "Resolved module: ~S\n" module)
(let loop ((free-vars free-vars))
(or (null? free-vars)
(begin
(catch #t
(lambda ()
(eval (car free-vars) module))
(lambda args
(if all-resolved?
(format #t
"Unresolved free variables in ~A:\n"
filename))
(write-char #\tab)
(write (car free-vars))
(newline)
(set! all-resolved? #f)))
(loop (cdr free-vars)))))
(if all-resolved?
(format #t
"No unresolved free variables in ~A\n"
filename)))))
(define (scan-file-for-module-name filename)
(with-input-from-file filename
(lambda ()
(let loop ((x (read)))
(cond ((eof-object? x) #f)
((and (pair? x)
(eq? (car x) 'define-module))
(cadr x))
(else (loop (read))))))))
(define (scan-file-for-free-variables filename)
(with-input-from-file filename
(lambda ()
(let loop ((x (read)) (fvlists '()))
(if (eof-object? x)
(apply append fvlists)
(loop (read) (cons (detect-free-variables x '()) fvlists)))))))
; guile> (detect-free-variables '(let ((a 1)) a) '())
; ()
; guile> (detect-free-variables '(let ((a 1)) b) '())
; (b)
; guile> (detect-free-variables '(let ((a 1) (b a)) b) '())
; (a)
; guile> (detect-free-variables '(let* ((a 1) (b a)) b) '())
; ()
; guile> (detect-free-variables '(define a 1) '())
; ()
; guile> (detect-free-variables '(define a b) '())
; (b)
; guile> (detect-free-variables '(define (a b c) b) '())
; ()
; guile> (detect-free-variables '(define (a b c) e) '())
; (e)
(define (detect-free-variables x locals)
;; Given an expression @var{x} and a list @var{locals} of local
;; variables (symbols) that are in scope for @var{x}, return a list
;; of free variable symbols.
(cond ((symbol? x)
(if (memq x locals) '() (list x)))
((pair? x)
(case (car x)
((define-module define-generic quote quasiquote)
;; No code of interest in these expressions.
'())
((let letrec)
;; Check for named let. If there is a name, transform the
;; expression so that it looks like an unnamed let with
;; the name as one of the bindings.
(if (symbol? (cadr x))
(set-cdr! x (cons (cons (list (cadr x) #f) (caddr x))
(cdddr x))))
;; Unnamed let processing.
(let ((letrec? (eq? (car x) 'letrec))
(locals-for-let-body (append locals (map car (cadr x)))))
(append (apply append
(map (lambda (binding)
(detect-free-variables (cadr binding)
(if letrec?
locals-for-let-body
locals)))
(cadr x)))
(apply append
(map (lambda (bodyform)
(detect-free-variables bodyform
locals-for-let-body))
(cddr x))))))
((let* and-let*)
;; Handle bindings recursively.
(if (null? (cadr x))
(apply append
(map (lambda (bodyform)
(detect-free-variables bodyform locals))
(cddr x)))
(append (detect-free-variables (cadr (caadr x)) locals)
(detect-free-variables `(let* ,(cdadr x) ,@(cddr x))
(cons (caaadr x) locals)))))
((define define-public define-macro)
(if (pair? (cadr x))
(begin
(set! locals (cons (caadr x) locals))
(detect-free-variables `(lambda ,(cdadr x) ,@(cddr x))
locals))
(begin
(set! locals (cons (cadr x) locals))
(detect-free-variables (caddr x) locals))))
((lambda lambda*)
(let ((locals-for-lambda-body (let loop ((locals locals)
(args (cadr x)))
(cond ((null? args) locals)
((pair? args)
(loop (cons (car args) locals)
(cdr args)))
(else
(cons args locals))))))
(apply append
(map (lambda (bodyform)
(detect-free-variables bodyform
locals-for-lambda-body))
(cddr x)))))
((receive)
(let ((locals-for-receive-body (append locals (cadr x))))
(apply append
(detect-free-variables (caddr x) locals)
(map (lambda (bodyform)
(detect-free-variables bodyform
locals-for-receive-body))
(cdddr x)))))
((define-method define*)
(let ((locals-for-method-body (let loop ((locals locals)
(args (cdadr x)))
(cond ((null? args) locals)
((pair? args)
(loop (cons (if (pair? (car args))
(caar args)
(car args))
locals)
(cdr args)))
(else
(cons args locals))))))
(apply append
(map (lambda (bodyform)
(detect-free-variables bodyform
locals-for-method-body))
(cddr x)))))
((define-class)
;; Avoid picking up slot names at the start of slot
;; definitions.
(apply append
(map (lambda (slot/option)
(detect-free-variables-noncar (if (pair? slot/option)
(cdr slot/option)
slot/option)
locals))
(cdddr x))))
((case)
(apply append
(detect-free-variables (cadr x) locals)
(map (lambda (case)
(detect-free-variables (cdr case) locals))
(cddr x))))
((unquote unquote-splicing else =>)
(detect-free-variables-noncar (cdr x) locals))
(else (append (detect-free-variables (car x) locals)
(detect-free-variables-noncar (cdr x) locals)))))
(else '())))
(define (detect-free-variables-noncar x locals)
;; Given an expression @var{x} and a list @var{locals} of local
;; variables (symbols) that are in scope for @var{x}, return a list
;; of free variable symbols.
(cond ((symbol? x)
(if (memq x locals) '() (list x)))
((pair? x)
(case (car x)
((=>)
(detect-free-variables-noncar (cdr x) locals))
(else (append (detect-free-variables (car x) locals)
(detect-free-variables-noncar (cdr x) locals)))))
(else '())))
(define (main . files)
(for-each lint files))
;;; lint ends here
;;; List --- List scripts that can be invoked by guild -*- coding: iso-8859-1 -*-
;;;; Copyright (C) 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free
;;;; Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
;;;; Boston, MA 02110-1301 USA
;;; Commentary:
;; Usage: list
;;
;; List scripts that can be invoked by guild.
;;; Code:
(define-module (scripts list)
#\use-module (srfi srfi-1)
#\export (list-scripts))
(define %include-in-guild-list #f)
(define %summary "An alias for \"help\".")
(define (directory-files dir)
(if (and (file-exists? dir) (file-is-directory? dir))
(let ((dir-stream (opendir dir)))
(let loop ((new (readdir dir-stream))
(acc '()))
(if (eof-object? new)
(begin
(closedir dir-stream)
acc)
(loop (readdir dir-stream)
(if (or (string=? "." new) ; ignore
(string=? ".." new)) ; ignore
acc
(cons new acc))))))
'()))
(define (strip-extensions path)
(or-map (lambda (ext)
(and
(string-suffix? ext path)
;; We really can't be adding e.g. ChangeLog-2008 to the set
;; of runnable scripts, just because "" is a valid
;; extension, by default. So hack around that here.
(not (string-null? ext))
(substring path 0
(- (string-length path) (string-length ext)))))
(append %load-compiled-extensions %load-extensions)))
(define (unique l)
(cond ((null? l) l)
((null? (cdr l)) l)
((equal? (car l) (cadr l)) (unique (cdr l)))
(else (cons (car l) (unique (cdr l))))))
(define (find-submodules head)
(let ((shead (map symbol->string head)))
(unique
(sort
(append-map (lambda (path)
(fold (lambda (x rest)
(let ((stripped (strip-extensions x)))
(if stripped (cons stripped rest) rest)))
'()
(directory-files
(fold (lambda (x y) (in-vicinity y x)) path shead))))
%load-path)
string<?))))
(define (list-scripts . args)
(for-each (lambda (x)
;; would be nice to show a summary.
(format #t "~A\n" x))
(find-submodules '(scripts))))
(define (main . args)
(apply (@@ (scripts help) main) args))
;;; punify --- Display Scheme code w/o unnecessary comments / whitespace
;; Copyright (C) 2001, 2006 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen
;;; Commentary:
;; Usage: punify FILE1 FILE2 ...
;;
;; Each file's forms are read and written to stdout.
;; The effect is to remove comments and much non-essential whitespace.
;; This is useful when installing Scheme source to space-limited media.
;;
;; Example:
;; $ wc ./punify ; ./punify ./punify | wc
;; 89 384 3031 ./punify
;; 0 42 920
;;
;; TODO: Read from stdin.
;; Handle vectors.
;; Identifier punification.
;;; Code:
(define-module (scripts punify)
\:export (punify))
(define %include-in-guild-list #f)
(define %summary "Strip comments and whitespace from a Scheme file.")
(define (write-punily form)
(cond ((and (list? form) (not (null? form)))
(let ((first (car form)))
(display "(")
(write-punily first)
(let loop ((ls (cdr form)) (last-was-list? (list? first)))
(if (null? ls)
(display ")")
(let* ((new-first (car ls))
(this-is-list? (list? new-first)))
(and (not last-was-list?)
(not this-is-list?)
(display " "))
(write-punily new-first)
(loop (cdr ls) this-is-list?))))))
((and (symbol? form)
(let ((ls (string->list (symbol->string form))))
(and (char=? (car ls) #\:)
(not (memq #\space ls))
(list->string (cdr ls)))))
=> (lambda (symbol-name-after-colon)
(display #\:)
(display symbol-name-after-colon)))
(else (write form))))
(define (punify-one file)
(with-input-from-file file
(lambda ()
(let ((toke (lambda () (read (current-input-port)))))
(let loop ((form (toke)))
(or (eof-object? form)
(begin
(write-punily form)
(loop (toke)))))))))
(define (punify . args)
(for-each punify-one args))
(define main punify)
;;; punify ends here
;;; read-rfc822 --- Validate RFC822 file by displaying it to stdout
;; Copyright (C) 2002, 2004, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: read-rfc822 FILE
;;
;; Read FILE, assumed to be in RFC822 format, and display it to stdout.
;; This is not very interesting, admittedly.
;;
;; For Scheme programming, this module exports two procs:
;; (read-rfc822 . args) ; only first arg used
;; (read-rfc822-silently port)
;;
;; Parse FILE (a string) or PORT, respectively, and return a query proc that
;; takes a symbol COMP, and returns the message component COMP. Supported
;; values for COMP (and the associated query return values) are:
;; from -- #f (reserved for future mbox support)
;; headers -- alist of (HEADER-SYMBOL . "VALUE-STRING") pairs, in order
;; body -- rest of the mail message, a string
;; body-lines -- rest of the mail message, as a list of lines
;; Any other query results in a "bad component" error.
;;
;; TODO: Add "-m" option (mbox support).
;;; Code:
(define-module (scripts read-rfc822)
\:use-module (ice-9 regex)
\:use-module (ice-9 rdelim)
\:autoload (srfi srfi-13) (string-join)
\:export (read-rfc822 read-rfc822-silently))
(define %include-in-guild-list #f)
(define %summary "Validate an RFC822-style file.")
(define from-line-rx (make-regexp "^From "))
(define header-name-rx (make-regexp "^([^:]+):[ \t]*"))
(define header-cont-rx (make-regexp "^[ \t]+"))
(define option #f) ; for future "-m"
(define (drain-message port)
(let loop ((line (read-line port)) (acc '()))
(cond ((eof-object? line)
(reverse acc))
((and option (regexp-exec from-line-rx line))
(for-each (lambda (c)
(unread-char c port))
(cons #\newline
(reverse (string->list line))))
(reverse acc))
(else
(loop (read-line port) (cons line acc))))))
(define (parse-message port)
(let* ((from (and option
(match:suffix (regexp-exec from-line-rx
(read-line port)))))
(body-lines #f)
(body #f)
(headers '())
(add-header! (lambda (reversed-hlines)
(let* ((hlines (reverse reversed-hlines))
(first (car hlines))
(m (regexp-exec header-name-rx first))
(name (string->symbol (match:substring m 1)))
(data (string-join
(cons (substring first (match:end m))
(cdr hlines))
" ")))
(set! headers (acons name data headers))))))
;; "From " is only one line
(let loop ((line (read-line port)) (current-header #f))
(cond ((string-null? line)
(and current-header (add-header! current-header))
(set! body-lines (drain-message port)))
((regexp-exec header-cont-rx line)
=> (lambda (m)
(loop (read-line port)
(cons (match:suffix m) current-header))))
(else
(and current-header (add-header! current-header))
(loop (read-line port) (list line)))))
(set! headers (reverse headers))
(lambda (component)
(case component
((from) from)
((body-lines) body-lines)
((headers) headers)
((body) (or body
(begin (set! body (string-join body-lines "\n" 'suffix))
body)))
(else (error "bad component:" component))))))
(define (read-rfc822-silently port)
(parse-message port))
(define (display-rfc822 parse)
(cond ((parse 'from) => (lambda (from) (format #t "From ~A\n" from))))
(for-each (lambda (header)
(format #t "~A: ~A\n" (car header) (cdr header)))
(parse 'headers))
(format #t "\n~A" (parse 'body)))
(define (read-rfc822 . args)
(let ((parse (read-rfc822-silently (open-file (car args) OPEN_READ))))
(display-rfc822 parse))
#t)
(define main read-rfc822)
;;; read-rfc822 ends here
;;; read-scheme-source --- Read a file, recognizing scheme forms and comments
;; Copyright (C) 2001, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen
;;; Commentary:
;; Usage: read-scheme-source FILE1 FILE2 ...
;;
;; This program parses each FILE and writes to stdout sexps that describe the
;; top-level structures of the file: scheme forms, single-line comments, and
;; hash-bang comments. You can further process these (to associate comments
;; w/ scheme forms as a kind of documentation, for example).
;;
;; The output sexps have one of these forms:
;;
;; (quote (filename FILENAME))
;;
;; (quote (comment :leading-semicolons N
;; :text LINE))
;;
;; (quote (whitespace :text LINE))
;;
;; (quote (hash-bang-comment :line LINUM
;; :line-count N
;; :text-list (LINE1 LINE2 ...)))
;;
;; (quote (following-form-properties :line LINUM
;; :line-count N)
;; :type TYPE
;; :signature SIGNATURE
;; :std-int-doc DOCSTRING))
;;
;; SEXP
;;
;; The first four are straightforward (both FILENAME and LINE are strings sans
;; newline, while LINUM and N are integers). The last two always go together,
;; in that order. SEXP is scheme code processed only by `read' and then
;; `write'.
;;
;; The :type field may be omitted if the form is not recognized. Otherwise,
;; TYPE may be one of: procedure, alias, define-module, variable.
;;
;; The :signature field may be omitted if the form is not a procedure.
;; Otherwise, SIGNATURE is a list showing the procedure's signature.
;;
;; If the type is `procedure' and the form has a standard internal docstring
;; (first body form a string), that is extracted in full -- including any
;; embedded newlines -- and recorded by field :std-int-doc.
;;
;;
;; Usage from a program: The output list of sexps can be retrieved by scheme
;; programs w/o having to capture stdout, like so:
;;
;; (use-modules (scripts read-scheme-source))
;; (define source-forms (read-scheme-source-silently "FILE1" "FILE2" ...))
;;
;; There are also two convenience procs exported for use by Scheme programs:
;;
;; (clump FORMS) --- filter FORMS combining contiguous comment forms that
;; have the same number of leading semicolons.
;;
;; (quoted? SYM FORM) --- see if FORM looks like: "(quote (SYM ...))", parse
;; the ":tags", and return alist of (TAG . VAL) elems.
;;
;; TODO: Add option "--clump-comments", maybe w/ different clumping styles.
;; Make `annotate!' extensible.
;;; Code:
(define-module (scripts read-scheme-source)
\:use-module (ice-9 rdelim)
\:export (read-scheme-source
read-scheme-source-silently
quoted?
clump))
(define %include-in-guild-list #f)
(define %summary "Print a parsed representation of a Scheme file.")
;; Try to figure out what FORM is and its various attributes.
;; Call proc NOTE! with key (a symbol) and value.
;;
(define (annotate! form note!)
(cond ((and (list? form)
(< 2 (length form))
(eq? 'define (car form))
(pair? (cadr form))
(symbol? (caadr form)))
(note! '\:type 'procedure)
(note! '\:signature (cadr form))
(and (< 3 (length form))
(string? (caddr form))
(note! '\:std-int-doc (caddr form))))
((and (list? form)
(< 2 (length form))
(eq? 'define (car form))
(symbol? (cadr form))
(list? (caddr form))
(< 3 (length (caddr form)))
(eq? 'lambda (car (caddr form)))
(string? (caddr (caddr form))))
(note! '\:type 'procedure)
(note! '\:signature (cons (cadr form) (cadr (caddr form))))
(note! '\:std-int-doc (caddr (caddr form))))
((and (list? form)
(= 3 (length form))
(eq? 'define (car form))
(symbol? (cadr form))
(symbol? (caddr form)))
(note! '\:type 'alias))
((and (list? form)
(eq? 'define-module (car form)))
(note! '\:type 'define-module))
;; Add other types here.
(else (note! '\:type 'variable))))
;; Process FILE, calling NB! on parsed top-level elements.
;; Recognized: #!-!# and regular comments in addition to normal forms.
;;
(define (process file nb!)
(nb! `'(filename ,file))
(let ((hash-bang-rx (make-regexp "^#!"))
(bang-hash-rx (make-regexp "^!#"))
(all-comment-rx (make-regexp "^[ \t]*(;+)"))
(all-whitespace-rx (make-regexp "^[ \t]*$"))
(p (open-input-file file)))
(let loop ((n (1+ (port-line p))) (line (read-line p)))
(or (not n)
(eof-object? line)
(begin
(cond ((regexp-exec hash-bang-rx line)
(let loop ((line (read-line p))
(text (list line)))
(if (or (eof-object? line)
(regexp-exec bang-hash-rx line))
(nb! `'(hash-bang-comment
\:line ,n
\:line-count ,(1+ (length text))
\:text-list ,(reverse
(cons line text))))
(loop (read-line p)
(cons line text)))))
((regexp-exec all-whitespace-rx line)
(nb! `'(whitespace \:text ,line)))
((regexp-exec all-comment-rx line)
=> (lambda (m)
(nb! `'(comment
\:leading-semicolons
,(let ((m1 (vector-ref m 1)))
(- (cdr m1) (car m1)))
\:text ,line))))
(else
(unread-string line p)
(let* ((form (read p))
(count (- (port-line p) n))
(props (let* ((props '())
(prop+ (lambda args
(set! props
(append props args)))))
(annotate! form prop+)
props)))
(or (= count 1) ; ugh
(begin
(read-line p)
(set! count (1+ count))))
(nb! `'(following-form-properties
\:line ,n
\:line-count ,count
,@props))
(nb! form))))
(loop (1+ (port-line p)) (read-line p)))))))
;;; entry points
(define (read-scheme-source-silently . files)
"See commentary in module (scripts read-scheme-source)."
(let* ((res '()))
(for-each (lambda (file)
(process file (lambda (e) (set! res (cons e res)))))
files)
(reverse res)))
(define (read-scheme-source . files)
"See commentary in module (scripts read-scheme-source)."
(for-each (lambda (file)
(process file (lambda (e) (write e) (newline))))
files))
;; Recognize: (quote (SYM :TAG1 VAL1 :TAG2 VAL2 ...))
;; and return alist: ((TAG1 . VAL1) (TAG2 . VAL2) ...)
;; where the tags are symbols.
;;
(define (quoted? sym form)
(and (list? form)
(= 2 (length form))
(eq? 'quote (car form))
(let ((inside (cadr form)))
(and (list? inside)
(< 0 (length inside))
(eq? sym (car inside))
(let loop ((ls (cdr inside)) (alist '()))
(if (null? ls)
alist ; retval
(let ((first (car ls)))
(or (symbol? first)
(error "bad list!"))
(loop (cddr ls)
(acons (string->symbol
(substring (symbol->string first) 1))
(cadr ls)
alist)))))))))
;; Filter FORMS, combining contiguous comment forms that have the same number
;; of leading semicolons. Do not include in them whitespace lines.
;; Whitespace lines outside of such comment groupings are ignored, as are
;; hash-bang comments. All other forms are passed through unchanged.
;;
(define (clump forms)
(let loop ((forms forms) (acc '()) (pass-this-one-through? #f))
(if (null? forms)
(reverse acc) ; retval
(let ((form (car forms)))
(cond (pass-this-one-through?
(loop (cdr forms) (cons form acc) #f))
((quoted? 'following-form-properties form)
(loop (cdr forms) (cons form acc) #t))
((quoted? 'whitespace form) ;;; ignore
(loop (cdr forms) acc #f))
((quoted? 'hash-bang-comment form) ;;; ignore for now
(loop (cdr forms) acc #f))
((quoted? 'comment form)
=> (lambda (alist)
(let cloop ((inner-forms (cdr forms))
(level (assq-ref alist 'leading-semicolons))
(text (list (assq-ref alist 'text))))
(let ((up (lambda ()
(loop inner-forms
(cons (cons level (reverse text))
acc)
#f))))
(if (null? inner-forms)
(up)
(let ((inner-form (car inner-forms)))
(cond ((quoted? 'comment inner-form)
=> (lambda (inner-alist)
(let ((new-level
(assq-ref
inner-alist
'leading-semicolons)))
(if (= new-level level)
(cloop (cdr inner-forms)
level
(cons (assq-ref
inner-alist
'text)
text))
(up)))))
(else (up)))))))))
(else (loop (cdr forms) (cons form acc) #f)))))))
;;; script entry point
(define main read-scheme-source)
;;; read-scheme-source ends here
;;; read-text-outline --- Read a text outline and display it as a sexp
;; Copyright (C) 2002, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: read-text-outline OUTLINE
;;
;; Scan OUTLINE file and display a list of trees, the structure of
;; each reflecting the "levels" in OUTLINE. The recognized outline
;; format (used to indicate outline headings) is zero or more pairs of
;; leading spaces followed by "-". Something like:
;;
;; - a 0
;; - b 1
;; - c 2
;; - d 1
;; - e 0
;; - f 1
;; - g 2
;; - h 1
;;
;; In this example the levels are shown to the right. The output for
;; such a file would be the single line:
;;
;; (("a" ("b" "c") "d") ("e" ("f" "g") "h"))
;;
;; Basically, anything at the beginning of a list is a parent, and the
;; remaining elements of that list are its children.
;;
;;
;; Usage from a Scheme program: These two procs are exported:
;;
;; (read-text-outline . args) ; only first arg is used
;; (read-text-outline-silently port)
;; (make-text-outline-reader re specs)
;;
;; `make-text-outline-reader' returns a proc that reads from PORT and
;; returns a list of trees (similar to `read-text-outline-silently').
;;
;; RE is a regular expression (string) that is used to identify a header
;; line of the outline (as opposed to a whitespace line or intervening
;; text). RE must begin w/ a sub-expression to match the "level prefix"
;; of the line. You can use `level-submatch-number' in SPECS (explained
;; below) to specify a number other than 1, the default.
;;
;; Normally, the level of the line is taken directly as the length of
;; its level prefix. This often results in adjacent levels not mapping
;; to adjacent numbers, which confuses the tree-building portion of the
;; program, which expects top-level to be 0, first sub-level to be 1,
;; etc. You can use `level-substring-divisor' or `compute-level' in
;; SPECS to specify a constant scaling factor or specify a completely
;; alternative procedure, respectively.
;;
;; SPECS is an alist which may contain the following key/value pairs:
;;
;; - level-submatch-number NUMBER
;; - level-substring-divisor NUMBER
;; - compute-level PROC
;; - body-submatch-number NUMBER
;; - extra-fields ((FIELD-1 . SUBMATCH-1) (FIELD-2 . SUBMATCH-2) ...)
;;
;; The PROC value associated with key `compute-level' should take a
;; Scheme match structure (as returned by `regexp-exec') and return a
;; number, the normalized level for that line. If this is specified,
;; it takes precedence over other level-computation methods.
;;
;; Use `body-submatch-number' if RE specifies the whole body, or if you
;; want to make use of the extra fields parsing. The `extra-fields'
;; value is a sub-alist, whose keys name additional fields that are to
;; be recognized. These fields along with `level' are set as object
;; properties of the final string ("body") that is consed into the tree.
;; If a field name ends in "?" the field value is set to be #t if there
;; is a match and the result is not an empty string, and #f otherwise.
;;
;;
;; Bugs and caveats:
;;
;; (1) Only the first file specified on the command line is scanned.
;; (2) TAB characters at the beginnings of lines are not recognized.
;; (3) Outlines that "skip" levels signal an error. In other words,
;; this will fail:
;;
;; - a 0
;; - b 1
;; - c 3 <-- skipped 2 -- error!
;; - d 1
;;
;;
;; TODO: Determine what's the right thing to do for skips.
;; Handle TABs.
;; Make line format customizable via longopts.
;;; Code:
(define-module (scripts read-text-outline)
\:export (read-text-outline
read-text-outline-silently
make-text-outline-reader)
\:use-module (ice-9 regex)
\:autoload (ice-9 rdelim) (read-line)
\:autoload (ice-9 getopt-long) (getopt-long))
(define %include-in-guild-list #f)
(define %summary "Convert textual outlines to s-expressions.")
(define (?? symbol)
(let ((name (symbol->string symbol)))
(string=? "?" (substring name (1- (string-length name))))))
(define (msub n)
(lambda (m)
(match:substring m n)))
(define (??-predicates pair)
(cons (car pair)
(if (?? (car pair))
(lambda (m)
(not (string=? "" (match:substring m (cdr pair)))))
(msub (cdr pair)))))
(define (make-line-parser re specs)
(let* ((rx (let ((fc (substring re 0 1)))
(make-regexp (if (string=? "^" fc)
re
(string-append "^" re)))))
(check (lambda (key)
(assq-ref specs key)))
(level-substring (msub (or (check 'level-submatch-number) 1)))
(extract-level (cond ((check 'compute-level)
=> (lambda (proc)
(lambda (m)
(proc m))))
((check 'level-substring-divisor)
=> (lambda (n)
(lambda (m)
(/ (string-length (level-substring m))
n))))
(else
(lambda (m)
(string-length (level-substring m))))))
(extract-body (cond ((check 'body-submatch-number)
=> msub)
(else
(lambda (m) (match:suffix m)))))
(misc-props! (cond ((check 'extra-fields)
=> (lambda (alist)
(let ((new (map ??-predicates alist)))
(lambda (obj m)
(for-each
(lambda (pair)
(set-object-property!
obj (car pair)
((cdr pair) m)))
new)))))
(else
(lambda (obj m) #t)))))
;; retval
(lambda (line)
(cond ((regexp-exec rx line)
=> (lambda (m)
(let ((level (extract-level m))
(body (extract-body m)))
(set-object-property! body 'level level)
(misc-props! body m)
body)))
(else #f)))))
(define (make-text-outline-reader re specs)
(let ((parse-line (make-line-parser re specs)))
;; retval
(lambda (port)
(let* ((all '(start))
(pchain (list))) ; parents chain
(let loop ((line (read-line port))
(prev-level -1) ; how this relates to the first input
; level determines whether or not we
; start in "sibling" or "child" mode.
; in the end, `start' is ignored and
; it's much easier to ignore parents
; than siblings (sometimes). this is
; not to encourage ignorance, however.
(tp all)) ; tail pointer
(or (eof-object? line)
(cond ((parse-line line)
=> (lambda (w)
(let* ((words (list w))
(level (object-property w 'level))
(diff (- level prev-level)))
(cond
;; sibling
((zero? diff)
;; just extend the chain
(set-cdr! tp words))
;; child
((positive? diff)
(or (= 1 diff)
(error "unhandled diff not 1:" diff line))
;; parent may be contacted by uncle later (kids
;; these days!) so save its level
(set-object-property! tp 'level prev-level)
(set! pchain (cons tp pchain))
;; "push down" car into hierarchy
(set-car! tp (cons (car tp) words)))
;; uncle
((negative? diff)
;; prune back to where levels match
(do ((p pchain (cdr p)))
((= level (object-property (car p) 'level))
(set! pchain p)))
;; resume at this level
(set-cdr! (car pchain) words)
(set! pchain (cdr pchain))))
(loop (read-line port) level words))))
(else (loop (read-line port) prev-level tp)))))
(set! all (car all))
(if (eq? 'start all)
'() ; wasteland
(cdr all))))))
(define read-text-outline-silently
(make-text-outline-reader "(([ ][ ])*)- *"
'((level-substring-divisor . 2))))
(define (read-text-outline . args)
(write (read-text-outline-silently (open-file (car args) "r")))
(newline)
#t) ; exit val
(define main read-text-outline)
;;; read-text-outline ends here
;;; scan-api --- Scan and group interpreter and libguile interface elements
;; Copyright (C) 2002, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: scan-api GUILE SOFILE [GROUPINGS ...]
;;
;; Invoke GUILE, an executable guile interpreter, and use nm(1) on SOFILE, a
;; shared-object library, to determine available interface elements, and
;; display them to stdout as an alist:
;;
;; ((meta ...) (interface ...))
;;
;; The meta fields are `GUILE_LOAD_PATH', `LTDL_LIBRARY_PATH', `guile'
;; `libguileinterface', `sofile' and `groups'. The interface elements are in
;; turn sub-alists w/ keys `groups' and `scan-data'. Interface elements
;; initially belong in one of two groups `Scheme' or `C' (but not both --
;; signal error if that happens).
;;
;; Optional GROUPINGS ... are files each containing a single "grouping
;; definition" alist with each entry of the form:
;;
;; (NAME (description "DESCRIPTION") (members SYM...))
;;
;; All of the SYM... should be proper subsets of the interface. In addition
;; to `description' and `members' forms, the entry may optionally include:
;;
;; (grok USE-MODULES (lambda (x) CODE))
;;
;; where CODE implements a group-membership predicate to be applied to `x', a
;; symbol. [When evaluated, CODE can assume (use-modules MODULE) has been
;; executed where MODULE is an element of USE-MODULES, a list. [NOT YET
;; IMPLEMENTED!]]
;;
;; Currently, there are two convenience predicates that operate on `x':
;; (in-group? x GROUP)
;; (name-prefix? x PREFIX)
;;
;; TODO: Allow for concurrent Scheme/C membership.
;; Completely separate reporting.
;;; Code:
(define-module (scripts scan-api)
\:use-module (ice-9 popen)
\:use-module (ice-9 rdelim)
\:use-module (ice-9 regex)
\:export (scan-api))
(define %include-in-guild-list #f)
(define %summary "Generate an API description for a Guile extension.")
(define put set-object-property!)
(define get object-property)
(define (add-props object . args)
(let loop ((args args))
(if (null? args)
object ; retval
(let ((key (car args))
(value (cadr args)))
(put object key value)
(loop (cddr args))))))
(define (scan re command match)
(let ((rx (make-regexp re))
(port (open-pipe command OPEN_READ)))
(let loop ((line (read-line port)))
(or (eof-object? line)
(begin
(cond ((regexp-exec rx line) => match))
(loop (read-line port)))))))
(define (scan-Scheme! ht guile)
(scan "^.guile.+: ([^ \t]+)([ \t]+(.+))*$"
(format #f "~A -c '~S ~S'"
guile
'(use-modules (ice-9 session))
'(apropos "."))
(lambda (m)
(let ((x (string->symbol (match:substring m 1))))
(put x 'Scheme (or (match:substring m 3)
""))
(hashq-set! ht x #t)))))
(define (scan-C! ht sofile)
(scan "^[0-9a-fA-F]+ ([B-TV-Z]) (.+)$"
(format #f "nm ~A" sofile)
(lambda (m)
(let ((x (string->symbol (match:substring m 2))))
(put x 'C (string->symbol (match:substring m 1)))
(and (hashq-get-handle ht x)
(error "both Scheme and C:" x))
(hashq-set! ht x #t)))))
(define THIS-MODULE (current-module))
(define (in-group? x group)
(memq group (get x 'groups)))
(define (name-prefix? x prefix)
(string-match (string-append "^" prefix) (symbol->string x)))
(define (add-group-name! x name)
(put x 'groups (cons name (get x 'groups))))
(define (make-grok-proc name form)
(let* ((predicate? (eval form THIS-MODULE))
(p (lambda (x)
(and (predicate? x)
(add-group-name! x name)))))
(put p 'name name)
p))
(define (make-members-proc name members)
(let ((p (lambda (x)
(and (memq x members)
(add-group-name! x name)))))
(put p 'name name)
p))
(define (make-grouper files) ; \/^^^o/ . o
(let ((hook (make-hook 1))) ; /\____\
(for-each
(lambda (file)
(for-each
(lambda (gdef)
(let ((name (car gdef))
(members (assq-ref gdef 'members))
(grok (assq-ref gdef 'grok)))
(or members grok
(error "bad grouping, must have `members' or `grok'"))
(add-hook! hook
(if grok
(add-props (make-grok-proc name (cadr grok))
'description
(assq-ref gdef 'description))
(make-members-proc name members))
#t))) ; append
(read (open-file file OPEN_READ))))
files)
hook))
(define (scan-api . args)
(let ((guile (list-ref args 0))
(sofile (list-ref args 1))
(grouper (false-if-exception (make-grouper (cddr args))))
(ht (make-hash-table 3331)))
(scan-Scheme! ht guile)
(scan-C! ht sofile)
(let ((all (sort (hash-fold (lambda (key value prior-result)
(add-props
key
'string (symbol->string key)
'scan-data (or (get key 'Scheme)
(get key 'C))
'groups (if (get key 'Scheme)
'(Scheme)
'(C)))
(and grouper (run-hook grouper key))
(cons key prior-result))
'()
ht)
(lambda (a b)
(string<? (get a 'string)
(get b 'string))))))
(format #t ";;; generated by scan-api -- do not edit!\n\n")
(format #t "(\n")
(format #t "(meta\n")
(format #t " (GUILE_LOAD_PATH . ~S)\n"
(or (getenv "GUILE_LOAD_PATH") ""))
(format #t " (LTDL_LIBRARY_PATH . ~S)\n"
(or (getenv "LTDL_LIBRARY_PATH") ""))
(format #t " (guile . ~S)\n" guile)
(format #t " (libguileinterface . ~S)\n"
(let ((i #f))
(scan "(.+)"
(format #f "~A -c '(display ~A)'"
guile
'(assq-ref %guile-build-info
'libguileinterface))
(lambda (m) (set! i (match:substring m 1))))
i))
(format #t " (sofile . ~S)\n" sofile)
(format #t " ~A\n"
(cons 'groups (append (if grouper
(map (lambda (p) (get p 'name))
(hook->list grouper))
'())
'(Scheme C))))
(format #t ") ;; end of meta\n")
(format #t "(interface\n")
(for-each (lambda (x)
(format #t "(~A ~A (scan-data ~S))\n"
x
(cons 'groups (get x 'groups))
(get x 'scan-data)))
all)
(format #t ") ;; end of interface\n")
(format #t ") ;; eof\n")))
#t)
(define main scan-api)
;;; scan-api ends here
;;; snarf-check-and-output-texi --- called by the doc snarfer.
;; Copyright (C) 2001, 2002, 2006, 2011, 2014 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Michael Livshin
;;; Code:
(define-module (scripts snarf-check-and-output-texi)
\:use-module (ice-9 streams)
\:use-module (ice-9 match)
\:export (snarf-check-and-output-texi))
(define %include-in-guild-list #f)
(define %summary "Transform snarfed .doc files into texinfo documentation.")
;;; why aren't these in some module?
(define-macro (when cond . body)
`(if ,cond (begin ,@body)))
(define-macro (unless cond . body)
`(if (not ,cond) (begin ,@body)))
(define *manual-flag* #f)
(define (snarf-check-and-output-texi . flags)
(if (member "--manual" flags)
(set! *manual-flag* #t))
(process-stream (current-input-port)))
(define (process-stream port)
(let loop ((input (stream-map (match-lambda
(('id . s)
(cons 'id (string->symbol s)))
(('int_dec . s)
(cons 'int (string->number s)))
(('int_oct . s)
(cons 'int (string->number s 8)))
(('int_hex . s)
(cons 'int (string->number s 16)))
((and x (? symbol?))
(cons x x))
((and x (? string?))
(cons 'string x))
(x x))
(make-stream (lambda (s)
(let loop ((s s))
(cond
((stream-null? s) #t)
((memq (stream-car s) '(eol hash))
(loop (stream-cdr s)))
(else (cons (stream-car s) (stream-cdr s))))))
(port->stream port read)))))
(unless (stream-null? input)
(let ((token (stream-car input)))
(if (eq? (car token) 'snarf_cookie)
(dispatch-top-cookie (stream-cdr input)
loop)
(loop (stream-cdr input)))))))
(define (dispatch-top-cookie input cont)
(when (stream-null? input)
(error 'syntax "premature end of file"))
(let ((token (stream-car input)))
(cond
((eq? (car token) 'brace_open)
(consume-multiline (stream-cdr input)
cont))
(else
(consume-upto-cookie process-singleline
input
cont)))))
(define (consume-upto-cookie process input cont)
(let loop ((acc '()) (input input))
(when (stream-null? input)
(error 'syntax "premature end of file in directive context"))
(let ((token (stream-car input)))
(cond
((eq? (car token) 'snarf_cookie)
(process (reverse! acc))
(cont (stream-cdr input)))
(else (loop (cons token acc) (stream-cdr input)))))))
(define (consume-multiline input cont)
(begin-multiline)
(let loop ((input input))
(when (stream-null? input)
(error 'syntax "premature end of file in multiline context"))
(let ((token (stream-car input)))
(cond
((eq? (car token) 'brace_close)
(end-multiline)
(cont (stream-cdr input)))
(else (consume-upto-cookie process-multiline-directive
input
loop))))))
(define *file* #f)
(define *line* #f)
(define *c-function-name* #f)
(define *function-name* #f)
(define *snarf-type* #f)
(define *args* #f)
(define *sig* #f)
(define *docstring* #f)
(define (begin-multiline)
(set! *file* #f)
(set! *line* #f)
(set! *c-function-name* #f)
(set! *function-name* #f)
(set! *snarf-type* #f)
(set! *args* #f)
(set! *sig* #f)
(set! *docstring* #f))
(define *primitive-deffnx-signature* "@deffnx {Scheme Procedure} ")
(define *primitive-deffnx-sig-length* (string-length *primitive-deffnx-signature*))
(define (end-multiline)
(let* ((req (car *sig*))
(opt (cadr *sig*))
(var (caddr *sig*))
(all (+ req opt var)))
(if (and (not (eqv? *snarf-type* 'register))
(not (= (length *args*) all)))
(error (format #f "~A:~A: ~A's C implementation takes ~A args (should take ~A)"
*file* *line* *function-name* (length *args*) all)))
(let ((nice-sig
(if (eq? *snarf-type* 'register)
*function-name*
(with-output-to-string
(lambda ()
(format #t "~A" *function-name*)
(let loop-req ((args *args*) (r 0))
(if (< r req)
(begin
(format #t " ~A" (car args))
(loop-req (cdr args) (+ 1 r)))
(let loop-opt ((o 0) (args args) (tail '()))
(if (< o opt)
(begin
(format #t " [~A" (car args))
(loop-opt (+ 1 o) (cdr args) (cons #\] tail)))
(begin
(if (> var 0)
(format #t " . ~A"
(car args)))
(let loop-tail ((tail tail))
(if (not (null? tail))
(begin
(format #t "~A" (car tail))
(loop-tail (cdr tail))))))))))))))
(scm-deffnx
(if (and *manual-flag* (eq? *snarf-type* 'primitive))
(with-output-to-string
(lambda ()
(format #t "@deffnx {C Function} ~A (" *c-function-name*)
(unless (null? *args*)
(format #t "~A" (car *args*))
(let loop ((args (cdr *args*)))
(unless (null? args)
(format #t ", ~A" (car args))
(loop (cdr args)))))
(format #t ")\n")))
#f)))
(format #t "\n~A\n" *function-name*)
(format #t "@c snarfed from ~A:~A\n" *file* *line*)
(format #t "@deffn {Scheme Procedure} ~A\n" nice-sig)
(let loop ((strings *docstring*) (scm-deffnx scm-deffnx))
(cond ((null? strings))
((or (not scm-deffnx)
(and (>= (string-length (car strings))
*primitive-deffnx-sig-length*)
(string=? (substring (car strings)
0 *primitive-deffnx-sig-length*)
*primitive-deffnx-signature*)))
(display (car strings))
(loop (cdr strings) scm-deffnx))
(else (display scm-deffnx)
(loop strings #f))))
(display "\n")
(display "@end deffn\n"))))
(define (texi-quote s)
(let rec ((i 0))
(if (= i (string-length s))
""
(string-append (let ((ss (substring s i (+ i 1))))
(if (string=? ss "@")
"@@"
ss))
(rec (+ i 1))))))
(define (process-multiline-directive l)
(define do-args
(match-lambda
(('(paren_close . paren_close))
'())
(('(comma . comma) rest ...)
(do-args rest))
(('(id . SCM) ('id . name) rest ...)
(cons name (do-args rest)))
(x (error (format #f "invalid argument syntax: ~A" (map cdr x))))))
(define do-arglist
(match-lambda
(('(paren_open . paren_open) '(id . void) '(paren_close . paren_close))
'())
(('(paren_open . paren_open) rest ...)
(do-args rest))
(x (error (format #f "invalid arglist syntax: ~A" (map cdr x))))))
(define do-command
(match-lambda
(('cname ('id . name))
(set! *c-function-name* (texi-quote (symbol->string name))))
(('fname ('string . name) ...)
(set! *function-name* (texi-quote (apply string-append name))))
(('type ('id . type))
(set! *snarf-type* type))
(('type ('int . num))
(set! *snarf-type* num))
(('location ('string . file) ('int . line))
(set! *file* file)
(set! *line* line))
(('arglist rest ...)
(set! *args* (do-arglist rest)))
(('argsig ('int . req) ('int . opt) ('int . var))
(set! *sig* (list req opt var)))
(x (error (format #f "unknown doc attribute: ~A" x)))))
(define do-directive
(match-lambda
((('id . command) rest ...)
(do-command (cons command rest)))
((('string . string) ...)
(set! *docstring* string))
(x (error (format #f "unknown doc attribute syntax: ~A" x)))))
(do-directive l))
(define (process-singleline l)
(define do-argpos
(match-lambda
((('id . name) ('int . pos) ('int . line))
(let ((idx (list-index *args* name)))
(when idx
(unless (= (+ idx 1) pos)
(display (format #f "~A:~A: wrong position for argument ~A: ~A (should be ~A)\n"
*file* line name pos (+ idx 1))
(current-error-port))))))
(x #f)))
(define do-command
(match-lambda
(('(id . argpos) rest ...)
(do-argpos rest))
(x (error (format #f "unknown check: ~A" x)))))
(when *function-name*
(do-command l)))
(define main snarf-check-and-output-texi)
;;; snarf-guile-m4-docs --- Parse guile.m4 comments for texi documentation
;; Copyright (C) 2002, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: snarf-guile-m4-docs FILE
;;
;; Grep FILE for comments preceding macro definitions, massage
;; them into valid texi, and display to stdout. For each comment,
;; lines preceding "^# Usage:" are discarded.
;;
;; TODO: Generalize.
;;; Code:
(define-module (scripts snarf-guile-m4-docs)
\:use-module (ice-9 rdelim)
\:export (snarf-guile-m4-docs))
(define %include-in-guild-list #f)
(define %summary "Snarf out texinfo documentation from .m4 files.")
(define (display-texi lines)
(display "@deffn {Autoconf Macro}")
(for-each (lambda (line)
(display (cond ((and (>= (string-length line) 2)
(string=? "# " (substring line 0 2)))
(substring line 2))
((string=? "#" (substring line 0 1))
(substring line 1))
(else line)))
(newline))
lines)
(display "@end deffn")
(newline) (newline))
(define (prefix? line sub)
(false-if-exception
(string=? sub (substring line 0 (string-length sub)))))
(define (massage-usage line)
(let loop ((line (string->list line)) (acc '()))
(if (null? line)
(list (list->string (reverse acc)))
(loop (cdr line)
(cons (case (car line)
((#\( #\) #\,) #\space)
(else (car line)))
acc)))))
(define (snarf-guile-m4-docs . args)
(let* ((p (open-file (car args) "r"))
(next (lambda () (read-line p))))
(let loop ((line (next)) (acc #f))
(or (eof-object? line)
(cond ((prefix? line "# Usage:")
(loop (next) (massage-usage (substring line 8))))
((prefix? line "AC_DEFUN")
(display-texi (reverse acc))
(loop (next) #f))
((and acc (prefix? line "#"))
(loop (next) (cons line acc)))
(else
(loop (next) #f)))))))
(define main snarf-guile-m4-docs)
;;; snarf-guile-m4-docs ends here
;;; summarize-guile-TODO --- Display Guile TODO list in various ways
;; Copyright (C) 2002, 2006, 2010, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen <ttn@gnu.org>
;;; Commentary:
;; Usage: summarize-guile-TODO TODOFILE
;;
;; The TODOFILE is typically Guile's (see workbook/tasks/README)
;; presumed to serve as our signal to ourselves (lest we want real
;; bosses hassling us) wrt to the overt message "items to do" as well as
;; the messages that can be inferred from its structure.
;;
;; This program reads TODOFILE and displays interpretations on its
;; structure, including registered markers and ownership, in various
;; ways.
;;
;; A primary interest in any task is its parent task. The output
;; summarization by default lists every item and its parent chain.
;; Top-level parents are not items. You can use these command-line
;; options to modify the selection and display (selection criteria
;; are ANDed together):
;;
;; -i, --involved USER -- select USER-involved items
;; -p, --personal USER -- select USER-responsible items
;; -t, --todo -- select unfinished items (status "-")
;; -d, --done -- select finished items (status "+")
;; -r, --review -- select review items (marker "R")
;;
;; -w, --who -- also show who is associated w/ the item
;; -n, --no-parent -- do not show parent chain
;;
;;
;; Usage from a Scheme program:
;; (summarize-guile-TODO . args) ; uses first arg only
;;
;;
;; Bugs: (1) Markers are scanned in sequence: D R X N%. This means "XD"
;; and the like are completely dropped. However, such strings
;; are unlikely to be used if the markers are chosen to be
;; somewhat exclusive, which is currently the case for D R X.
;; N% used w/ these needs to be something like: "D25%" (this
;; means discussion accounts for 1/4 of the task).
;;
;; TODO: Implement more various ways. (Patches welcome.)
;; Add support for ORing criteria.
;;; Code:
(debug-enable 'backtrace)
(define-module (scripts summarize-guile-TODO)
\:use-module (scripts read-text-outline)
\:use-module (ice-9 getopt-long)
\:autoload (srfi srfi-13) (string-tokenize) ; string library
\:autoload (srfi srfi-14) (char-set) ; string library
\:autoload (ice-9 common-list) (remove-if-not)
\:export (summarize-guile-TODO))
(define %include-in-guild-list #f)
(define %summary "A quaint relic of the past.")
(define put set-object-property!)
(define get object-property)
(define (as-leaf x)
(cond ((get x 'who)
=> (lambda (who)
(put x 'who
(map string->symbol
(string-tokenize who (char-set #\:)))))))
(cond ((get x 'pct-done)
=> (lambda (pct-done)
(put x 'pct-done (string->number pct-done)))))
x)
(define (hang-by-the-leaves trees)
(let ((leaves '()))
(letrec ((hang (lambda (tree parent)
(if (list? tree)
(begin
(put (car tree) 'parent parent)
(for-each (lambda (child)
(hang child (car tree)))
(cdr tree)))
(begin
(put tree 'parent parent)
(set! leaves (cons (as-leaf tree) leaves)))))))
(for-each (lambda (tree)
(hang tree #f))
trees))
leaves))
(define (read-TODO file)
(hang-by-the-leaves
((make-text-outline-reader
"(([ ][ ])*)([-+])(D*)(R*)(X*)(([0-9]+)%)* *([^[]*)(\\[(.*)\\])*"
'((level-substring-divisor . 2)
(body-submatch-number . 9)
(extra-fields . ((status . 3)
(design? . 4)
(review? . 5)
(extblock? . 6)
(pct-done . 8)
(who . 11)))))
(open-file file "r"))))
(define (select-items p items)
(let ((sub '()))
(cond ((option-ref p 'involved #f)
=> (lambda (u)
(let ((u (string->symbol u)))
(set! sub (cons
(lambda (x)
(and (get x 'who)
(memq u (get x 'who))))
sub))))))
(cond ((option-ref p 'personal #f)
=> (lambda (u)
(let ((u (string->symbol u)))
(set! sub (cons
(lambda (x)
(cond ((get x 'who)
=> (lambda (ls)
(eq? (car (reverse ls))
u)))
(else #f)))
sub))))))
(for-each (lambda (pair)
(cond ((option-ref p (car pair) #f)
(set! sub (cons (cdr pair) sub)))))
`((todo . ,(lambda (x) (string=? (get x 'status) "-")))
(done . ,(lambda (x) (string=? (get x 'status) "+")))
(review . ,(lambda (x) (get x 'review?)))))
(let loop ((sub (reverse sub)) (items items))
(if (null? sub)
(reverse items)
(loop (cdr sub) (remove-if-not (car sub) items))))))
(define (make-display-item show-who? show-parent?)
(let ((show-who
(if show-who?
(lambda (item)
(cond ((get item 'who)
=> (lambda (who) (format #f " ~A" who)))
(else "")))
(lambda (item) "")))
(show-parents
(if show-parent?
(lambda (item)
(let loop ((parent (get item 'parent)) (indent 2))
(and parent
(begin
(format #t "under : ~A~A\n"
(make-string indent #\space)
parent)
(loop (get parent 'parent) (+ 2 indent))))))
(lambda (item) #t))))
(lambda (item)
(format #t "status: ~A~A~A~A~A~A\nitem : ~A\n"
(get item 'status)
(if (get item 'design?) "D" "")
(if (get item 'review?) "R" "")
(if (get item 'extblock?) "X" "")
(cond ((get item 'pct-done)
=> (lambda (pct-done)
(format #f " ~A%" pct-done)))
(else ""))
(show-who item)
item)
(show-parents item))))
(define (display-items p items)
(let ((display-item (make-display-item (option-ref p 'who #f)
(not (option-ref p 'no-parent #f))
)))
(for-each display-item items)))
(define (summarize-guile-TODO . args)
(let ((p (getopt-long (cons "summarize-guile-TODO" args)
'((who (single-char #\w))
(no-parent (single-char #\n))
(involved (single-char #\i)
(value #t))
(personal (single-char #\p)
(value #t))
(todo (single-char #\t))
(done (single-char #\d))
(review (single-char #\r))
;; Add options here.
))))
(display-items p (select-items p (read-TODO (car (option-ref p '() #f))))))
#t) ; exit val
(define main summarize-guile-TODO)
;;; summarize-guile-TODO ends here
;;; use2dot --- Display module dependencies as a DOT specification
;; Copyright (C) 2001, 2006, 2011 Free Software Foundation, Inc.
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation; either version 3, 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this software; see the file COPYING.LESSER. If
;; not, write to the Free Software Foundation, Inc., 51 Franklin
;; Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Thien-Thi Nguyen
;;; Commentary:
;; Usage: use2dot [OPTIONS] [FILE ...]
;; Display to stdout a DOT specification that describes module dependencies
;; in FILEs.
;;
;; A top-level `use-modules' form or a `:use-module' `define-module'-component
;; results in a "solid" style edge.
;;
;; An `:autoload' `define-module'-component results in a "dotted" style edge
;; with label "N" indicating that N names are responsible for triggering the
;; autoload. [The "N" label is not implemented.]
;;
;; A top-level `load' or `primitive-load' form results in a a "bold" style
;; edge to a node named with either the file name if the `load' argument is a
;; string, or "[computed in FILE]" otherwise.
;;
;; Options:
;; -m, --default-module MOD -- Set MOD as the default module (for top-level
;; `use-modules' forms that do not follow some
;; `define-module' form in a file). MOD should be
;; be a list or `#f', in which case such top-level
;; `use-modules' forms are effectively ignored.
;; Default value: `(guile-user)'.
;;; Code:
(define-module (scripts use2dot)
\:autoload (ice-9 getopt-long) (getopt-long)
\:use-module ((srfi srfi-13) \:select (string-join))
\:use-module ((scripts frisk)
\:select (make-frisker edge-type edge-up edge-down))
\:export (use2dot))
(define %summary "Print a module's dependencies in graphviz format.")
(define *default-module* '(guile-user))
(define (q s) ; quote
(format #f "~S" s))
(define (vv pairs) ; => ("var=val" ...)
(map (lambda (pair)
(format #f "~A=~A" (car pair) (cdr pair)))
pairs))
(define (>>header)
(format #t "digraph use2dot {\n")
(for-each (lambda (s) (format #t " ~A;\n" s))
(vv `((label . ,(q "Guile Module Dependencies"))
;;(rankdir . LR)
;;(size . ,(q "7.5,10"))
(ratio . fill)
;;(nodesep . ,(q "0.05"))
))))
(define (>>body edges)
(for-each
(lambda (edge)
(format #t " \"~A\" -> \"~A\"" (edge-down edge) (edge-up edge))
(cond ((case (edge-type edge)
((autoload) '((style . dotted) (fontsize . 5)))
((computed) '((style . bold)))
(else #f))
=> (lambda (etc)
(format #t " [~A]" (string-join (vv etc) ",")))))
(format #t ";\n"))
edges))
(define (>>footer)
(format #t "}"))
(define (>> edges)
(>>header)
(>>body edges)
(>>footer))
(define (use2dot . args)
(let* ((parsed-args (getopt-long (cons "use2dot" args) ;;; kludge
'((default-module
(single-char #\m) (value #t)))))
(=m (option-ref parsed-args 'default-module *default-module*))
(scan (make-frisker `(default-module . ,=m)))
(files (option-ref parsed-args '() '())))
(>> (reverse ((scan files) 'edges)))))
(define main use2dot)
;;; use2dot ends here
;;; srfi-1.scm --- List Library
;; Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009, 2010, 2011 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Some parts from the reference implementation, which is
;;; Copyright (c) 1998, 1999 by Olin Shivers. You may do as you please with
;;; this code as long as you do not remove this copyright notice or
;;; hold me liable for its use.
;;; Author: Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
;;; Date: 2001-06-06
;;; Commentary:
;; This is an implementation of SRFI-1 (List Library).
;;
;; All procedures defined in SRFI-1, which are not already defined in
;; the Guile core library, are exported. The procedures in this
;; implementation work, but they have not been tuned for speed or
;; memory usage.
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-1)
\:export (
;;; Constructors
;; cons <= in the core
;; list <= in the core
xcons
;; cons* <= in the core
;; make-list <= in the core
list-tabulate
list-copy
circular-list
;; iota ; Extended.
;;; Predicates
proper-list?
circular-list?
dotted-list?
;; pair? <= in the core
;; null? <= in the core
null-list?
not-pair?
list=
;;; Selectors
;; car <= in the core
;; cdr <= in the core
;; caar <= in the core
;; cadr <= in the core
;; cdar <= in the core
;; cddr <= in the core
;; caaar <= in the core
;; caadr <= in the core
;; cadar <= in the core
;; caddr <= in the core
;; cdaar <= in the core
;; cdadr <= in the core
;; cddar <= in the core
;; cdddr <= in the core
;; caaaar <= in the core
;; caaadr <= in the core
;; caadar <= in the core
;; caaddr <= in the core
;; cadaar <= in the core
;; cadadr <= in the core
;; caddar <= in the core
;; cadddr <= in the core
;; cdaaar <= in the core
;; cdaadr <= in the core
;; cdadar <= in the core
;; cdaddr <= in the core
;; cddaar <= in the core
;; cddadr <= in the core
;; cdddar <= in the core
;; cddddr <= in the core
;; list-ref <= in the core
first
second
third
fourth
fifth
sixth
seventh
eighth
ninth
tenth
car+cdr
take
drop
take-right
drop-right
take!
drop-right!
split-at
split-at!
last
;; last-pair <= in the core
;;; Miscelleneous: length, append, concatenate, reverse, zip & count
;; length <= in the core
length+
;; append <= in the core
;; append! <= in the core
concatenate
concatenate!
;; reverse <= in the core
;; reverse! <= in the core
append-reverse
append-reverse!
zip
unzip1
unzip2
unzip3
unzip4
unzip5
count
;;; Fold, unfold & map
fold
fold-right
pair-fold
pair-fold-right
reduce
reduce-right
unfold
unfold-right
;; map ; Extended.
;; for-each ; Extended.
append-map
append-map!
map!
;; map-in-order ; Extended.
pair-for-each
filter-map
;;; Filtering & partitioning
;; filter <= in the core
partition
remove
;; filter! <= in the core
partition!
remove!
;;; Searching
find
find-tail
take-while
take-while!
drop-while
span
span!
break
break!
any
every
;; list-index ; Extended.
;; member ; Extended.
;; memq <= in the core
;; memv <= in the core
;;; Deletion
;; delete ; Extended.
;; delete! ; Extended.
delete-duplicates
delete-duplicates!
;;; Association lists
;; assoc ; Extended.
;; assq <= in the core
;; assv <= in the core
alist-cons
alist-copy
alist-delete
alist-delete!
;;; Set operations on lists
lset<=
lset=
lset-adjoin
lset-union
lset-intersection
lset-difference
lset-xor
lset-diff+intersection
lset-union!
lset-intersection!
lset-difference!
lset-xor!
lset-diff+intersection!
;;; Primitive side-effects
;; set-car! <= in the core
;; set-cdr! <= in the core
)
\:re-export (cons list cons* make-list pair? null?
car cdr caar cadr cdar cddr
caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
list-ref last-pair length append append! reverse reverse!
filter filter! memq memv assq assv set-car! set-cdr!)
\:replace (iota map for-each map-in-order list-copy list-index member
delete delete! assoc)
)
(cond-expand-provide (current-module) '(srfi-1))
;; Load the compiled primitives from the shared library.
;;
(load-extension (string-append "libguile-" (effective-version))
"scm_init_srfi_1")
;;; Constructors
(define (xcons d a)
"Like `cons', but with interchanged arguments. Useful mostly when passed to
higher-order procedures."
(cons a d))
(define (wrong-type-arg caller arg)
(scm-error 'wrong-type-arg (symbol->string caller)
"Wrong type argument: ~S" (list arg) '()))
(define-syntax-rule (check-arg pred arg caller)
(if (not (pred arg))
(wrong-type-arg 'caller arg)))
(define (out-of-range proc arg)
(scm-error 'out-of-range proc
"Value out of range: ~A" (list arg) (list arg)))
;; the srfi spec doesn't seem to forbid inexact integers.
(define (non-negative-integer? x) (and (integer? x) (>= x 0)))
(define (list-tabulate n init-proc)
"Return an N-element list, where each list element is produced by applying the
procedure INIT-PROC to the corresponding list index. The order in which
INIT-PROC is applied to the indices is not specified."
(check-arg non-negative-integer? n list-tabulate)
(let lp ((n n) (acc '()))
(if (<= n 0)
acc
(lp (- n 1) (cons (init-proc (- n 1)) acc)))))
(define (circular-list elt1 . elts)
(set! elts (cons elt1 elts))
(set-cdr! (last-pair elts) elts)
elts)
(define* (iota count #\optional (start 0) (step 1))
(check-arg non-negative-integer? count iota)
(let lp ((n 0) (acc '()))
(if (= n count)
(reverse! acc)
(lp (+ n 1) (cons (+ start (* n step)) acc)))))
;;; Predicates
(define (proper-list? x)
(list? x))
(define (circular-list? x)
(if (not-pair? x)
#f
(let lp ((hare (cdr x)) (tortoise x))
(if (not-pair? hare)
#f
(let ((hare (cdr hare)))
(if (not-pair? hare)
#f
(if (eq? hare tortoise)
#t
(lp (cdr hare) (cdr tortoise)))))))))
(define (dotted-list? x)
(cond
((null? x) #f)
((not-pair? x) #t)
(else
(let lp ((hare (cdr x)) (tortoise x))
(cond
((null? hare) #f)
((not-pair? hare) #t)
(else
(let ((hare (cdr hare)))
(cond
((null? hare) #f)
((not-pair? hare) #t)
((eq? hare tortoise) #f)
(else
(lp (cdr hare) (cdr tortoise)))))))))))
(define (null-list? x)
(cond
((proper-list? x)
(null? x))
((circular-list? x)
#f)
(else
(error "not a proper list in null-list?"))))
(define (not-pair? x)
"Return #t if X is not a pair, #f otherwise.
This is shorthand notation `(not (pair? X))' and is supposed to be used for
end-of-list checking in contexts where dotted lists are allowed."
(not (pair? x)))
(define (list= elt= . rest)
(define (lists-equal a b)
(let lp ((a a) (b b))
(cond ((null? a)
(null? b))
((null? b)
#f)
(else
(and (elt= (car a) (car b))
(lp (cdr a) (cdr b)))))))
(check-arg procedure? elt= list=)
(or (null? rest)
(let lp ((lists rest))
(or (null? (cdr lists))
(and (lists-equal (car lists) (cadr lists))
(lp (cdr lists)))))))
;;; Selectors
(define first car)
(define second cadr)
(define third caddr)
(define fourth cadddr)
(define (fifth x) (car (cddddr x)))
(define (sixth x) (cadr (cddddr x)))
(define (seventh x) (caddr (cddddr x)))
(define (eighth x) (cadddr (cddddr x)))
(define (ninth x) (car (cddddr (cddddr x))))
(define (tenth x) (cadr (cddddr (cddddr x))))
(define (car+cdr x)
"Return two values, the `car' and the `cdr' of PAIR."
(values (car x) (cdr x)))
(define take list-head)
(define drop list-tail)
;;; TAKE-RIGHT and DROP-RIGHT work by getting two pointers into the list,
;;; off by K, then chasing down the list until the lead pointer falls off
;;; the end. Note that they diverge for circular lists.
(define (take-right lis k)
(let lp ((lag lis) (lead (drop lis k)))
(if (pair? lead)
(lp (cdr lag) (cdr lead))
lag)))
(define (drop-right lis k)
(let lp ((lag lis) (lead (drop lis k)) (result '()))
(if (pair? lead)
(lp (cdr lag) (cdr lead) (cons (car lag) result))
(reverse result))))
(define (take! lst i)
"Linear-update variant of `take'."
(if (= i 0)
'()
(let ((tail (drop lst (- i 1))))
(set-cdr! tail '())
lst)))
(define (drop-right! lst i)
"Linear-update variant of `drop-right'."
(let ((tail (drop lst i)))
(if (null? tail)
'()
(let loop ((prev lst)
(tail (cdr tail)))
(if (null? tail)
(if (pair? prev)
(begin
(set-cdr! prev '())
lst)
lst)
(loop (cdr prev)
(cdr tail)))))))
(define (split-at lst i)
"Return two values, a list of the elements before index I in LST, and
a list of those after."
(if (< i 0)
(out-of-range 'split-at i)
(let lp ((l lst) (n i) (acc '()))
(if (<= n 0)
(values (reverse! acc) l)
(lp (cdr l) (- n 1) (cons (car l) acc))))))
(define (split-at! lst i)
"Linear-update variant of `split-at'."
(cond ((< i 0)
(out-of-range 'split-at! i))
((= i 0)
(values '() lst))
(else
(let lp ((l lst) (n (- i 1)))
(if (<= n 0)
(let ((tmp (cdr l)))
(set-cdr! l '())
(values lst tmp))
(lp (cdr l) (- n 1)))))))
(define (last pair)
"Return the last element of the non-empty, finite list PAIR."
(car (last-pair pair)))
;;; Miscelleneous: length, append, concatenate, reverse, zip & count
(define (zip clist1 . rest)
(let lp ((l (cons clist1 rest)) (acc '()))
(if (any null? l)
(reverse! acc)
(lp (map cdr l) (cons (map car l) acc)))))
(define (unzip1 l)
(map first l))
(define (unzip2 l)
(values (map first l) (map second l)))
(define (unzip3 l)
(values (map first l) (map second l) (map third l)))
(define (unzip4 l)
(values (map first l) (map second l) (map third l) (map fourth l)))
(define (unzip5 l)
(values (map first l) (map second l) (map third l) (map fourth l)
(map fifth l)))
;;; Fold, unfold & map
(define (fold kons knil list1 . rest)
"Apply PROC to the elements of LIST1 ... LISTN to build a result, and return
that result. See the manual for details."
(check-arg procedure? kons fold)
(if (null? rest)
(let f ((knil knil) (list1 list1))
(if (null? list1)
knil
(f (kons (car list1) knil) (cdr list1))))
(let f ((knil knil) (lists (cons list1 rest)))
(if (any null? lists)
knil
(let ((cars (map car lists))
(cdrs (map cdr lists)))
(f (apply kons (append! cars (list knil))) cdrs))))))
(define (fold-right kons knil clist1 . rest)
(check-arg procedure? kons fold-right)
(if (null? rest)
(let loop ((lst (reverse clist1))
(result knil))
(if (null? lst)
result
(loop (cdr lst)
(kons (car lst) result))))
(let loop ((lists (map reverse (cons clist1 rest)))
(result knil))
(if (any1 null? lists)
result
(loop (map cdr lists)
(apply kons (append! (map car lists) (list result))))))))
(define (pair-fold kons knil clist1 . rest)
(check-arg procedure? kons pair-fold)
(if (null? rest)
(let f ((knil knil) (list1 clist1))
(if (null? list1)
knil
(let ((tail (cdr list1)))
(f (kons list1 knil) tail))))
(let f ((knil knil) (lists (cons clist1 rest)))
(if (any null? lists)
knil
(let ((tails (map cdr lists)))
(f (apply kons (append! lists (list knil))) tails))))))
(define (pair-fold-right kons knil clist1 . rest)
(check-arg procedure? kons pair-fold-right)
(if (null? rest)
(let f ((list1 clist1))
(if (null? list1)
knil
(kons list1 (f (cdr list1)))))
(let f ((lists (cons clist1 rest)))
(if (any null? lists)
knil
(apply kons (append! lists (list (f (map cdr lists)))))))))
(define* (unfold p f g seed #\optional (tail-gen (lambda (x) '())))
(define (reverse+tail lst seed)
(let loop ((lst lst)
(result (tail-gen seed)))
(if (null? lst)
result
(loop (cdr lst)
(cons (car lst) result)))))
(check-arg procedure? p unfold)
(check-arg procedure? f unfold)
(check-arg procedure? g unfold)
(check-arg procedure? tail-gen unfold)
(let loop ((seed seed)
(result '()))
(if (p seed)
(reverse+tail result seed)
(loop (g seed)
(cons (f seed) result)))))
(define* (unfold-right p f g seed #\optional (tail '()))
(check-arg procedure? p unfold-right)
(check-arg procedure? f unfold-right)
(check-arg procedure? g unfold-right)
(let uf ((seed seed) (lis tail))
(if (p seed)
lis
(uf (g seed) (cons (f seed) lis)))))
(define (reduce f ridentity lst)
"`reduce' is a variant of `fold', where the first call to F is on two
elements from LST, rather than one element and a given initial value.
If LST is empty, RIDENTITY is returned. If LST has just one element
then that's the return value."
(check-arg procedure? f reduce)
(if (null? lst)
ridentity
(fold f (car lst) (cdr lst))))
(define (reduce-right f ridentity lst)
"`reduce-right' is a variant of `fold-right', where the first call to
F is on two elements from LST, rather than one element and a given
initial value. If LST is empty, RIDENTITY is returned. If LST
has just one element then that's the return value."
(reduce f ridentity (reverse lst)))
(define map
(case-lambda
((f l)
(check-arg procedure? f map)
(let map1 ((hare l) (tortoise l) (move? #f) (out '()))
(if (pair? hare)
(if move?
(if (eq? tortoise hare)
(scm-error 'wrong-type-arg "map" "Circular list: ~S"
(list l) #f)
(map1 (cdr hare) (cdr tortoise) #f
(cons (f (car hare)) out)))
(map1 (cdr hare) tortoise #t
(cons (f (car hare)) out)))
(if (null? hare)
(reverse! out)
(scm-error 'wrong-type-arg "map" "Not a list: ~S"
(list l) #f)))))
((f l1 . rest)
(check-arg procedure? f map)
(let ((len (fold (lambda (ls len)
(let ((ls-len (length+ ls)))
(if len
(if ls-len (min ls-len len) len)
ls-len)))
(length+ l1)
rest)))
(if (not len)
(scm-error 'wrong-type-arg "map"
"Args do not contain a proper (finite) list: ~S"
(list (cons l1 rest)) #f))
(let mapn ((l1 l1) (rest rest) (len len) (out '()))
(if (zero? len)
(reverse! out)
(mapn (cdr l1) (map cdr rest) (1- len)
(cons (apply f (car l1) (map car rest)) out))))))))
(define map-in-order map)
(define for-each
(case-lambda
((f l)
(check-arg procedure? f for-each)
(let for-each1 ((hare l) (tortoise l) (move? #f))
(if (pair? hare)
(if move?
(if (eq? tortoise hare)
(scm-error 'wrong-type-arg "for-each" "Circular list: ~S"
(list l) #f)
(begin
(f (car hare))
(for-each1 (cdr hare) (cdr tortoise) #f)))
(begin
(f (car hare))
(for-each1 (cdr hare) tortoise #t)))
(if (not (null? hare))
(scm-error 'wrong-type-arg "for-each" "Not a list: ~S"
(list l) #f)))))
((f l1 . rest)
(check-arg procedure? f for-each)
(let ((len (fold (lambda (ls len)
(let ((ls-len (length+ ls)))
(if len
(if ls-len (min ls-len len) len)
ls-len)))
(length+ l1)
rest)))
(if (not len)
(scm-error 'wrong-type-arg "for-each"
"Args do not contain a proper (finite) list: ~S"
(list (cons l1 rest)) #f))
(let for-eachn ((l1 l1) (rest rest) (len len))
(if (> len 0)
(begin
(apply f (car l1) (map car rest))
(for-eachn (cdr l1) (map cdr rest) (1- len)))))))))
(define (append-map f clist1 . rest)
(concatenate (apply map f clist1 rest)))
(define (append-map! f clist1 . rest)
(concatenate! (apply map f clist1 rest)))
;; OPTIMIZE-ME: Re-use cons cells of list1
(define map! map)
(define (filter-map proc list1 . rest)
"Apply PROC to the elements of LIST1... and return a list of the
results as per SRFI-1 `map', except that any #f results are omitted from
the list returned."
(check-arg procedure? proc filter-map)
(if (null? rest)
(let lp ((l list1)
(rl '()))
(if (null? l)
(reverse! rl)
(let ((res (proc (car l))))
(if res
(lp (cdr l) (cons res rl))
(lp (cdr l) rl)))))
(let lp ((l (cons list1 rest))
(rl '()))
(if (any1 null? l)
(reverse! rl)
(let ((res (apply proc (map car l))))
(if res
(lp (map cdr l) (cons res rl))
(lp (map cdr l) rl)))))))
(define (pair-for-each f clist1 . rest)
(check-arg procedure? f pair-for-each)
(if (null? rest)
(let lp ((l clist1))
(if (null? l)
(if #f #f)
(begin
(f l)
(lp (cdr l)))))
(let lp ((l (cons clist1 rest)))
(if (any1 null? l)
(if #f #f)
(begin
(apply f l)
(lp (map cdr l)))))))
;;; Searching
(define (take-while pred ls)
"Return a new list which is the longest initial prefix of LS whose
elements all satisfy the predicate PRED."
(check-arg procedure? pred take-while)
(cond ((null? ls) '())
((not (pred (car ls))) '())
(else
(let ((result (list (car ls))))
(let lp ((ls (cdr ls)) (p result))
(cond ((null? ls) result)
((not (pred (car ls))) result)
(else
(set-cdr! p (list (car ls)))
(lp (cdr ls) (cdr p)))))))))
(define (take-while! pred lst)
"Linear-update variant of `take-while'."
(check-arg procedure? pred take-while!)
(let loop ((prev #f)
(rest lst))
(cond ((null? rest)
lst)
((pred (car rest))
(loop rest (cdr rest)))
(else
(if (pair? prev)
(begin
(set-cdr! prev '())
lst)
'())))))
(define (drop-while pred lst)
"Drop the longest initial prefix of LST whose elements all satisfy the
predicate PRED."
(check-arg procedure? pred drop-while)
(let loop ((lst lst))
(cond ((null? lst)
'())
((pred (car lst))
(loop (cdr lst)))
(else lst))))
(define (span pred lst)
"Return two values, the longest initial prefix of LST whose elements
all satisfy the predicate PRED, and the remainder of LST."
(check-arg procedure? pred span)
(let lp ((lst lst) (rl '()))
(if (and (not (null? lst))
(pred (car lst)))
(lp (cdr lst) (cons (car lst) rl))
(values (reverse! rl) lst))))
(define (span! pred list)
"Linear-update variant of `span'."
(check-arg procedure? pred span!)
(let loop ((prev #f)
(rest list))
(cond ((null? rest)
(values list '()))
((pred (car rest))
(loop rest (cdr rest)))
(else
(if (pair? prev)
(begin
(set-cdr! prev '())
(values list rest))
(values '() list))))))
(define (break pred clist)
"Return two values, the longest initial prefix of LST whose elements
all fail the predicate PRED, and the remainder of LST."
(check-arg procedure? pred break)
(let lp ((clist clist) (rl '()))
(if (or (null? clist)
(pred (car clist)))
(values (reverse! rl) clist)
(lp (cdr clist) (cons (car clist) rl)))))
(define (break! pred list)
"Linear-update variant of `break'."
(check-arg procedure? pred break!)
(let loop ((l list)
(prev #f))
(cond ((null? l)
(values list '()))
((pred (car l))
(if (pair? prev)
(begin
(set-cdr! prev '())
(values list l))
(values '() list)))
(else
(loop (cdr l) l)))))
(define (any pred ls . lists)
(check-arg procedure? pred any)
(if (null? lists)
(any1 pred ls)
(let lp ((lists (cons ls lists)))
(cond ((any1 null? lists)
#f)
((any1 null? (map cdr lists))
(apply pred (map car lists)))
(else
(or (apply pred (map car lists)) (lp (map cdr lists))))))))
(define (any1 pred ls)
(let lp ((ls ls))
(cond ((null? ls)
#f)
((null? (cdr ls))
(pred (car ls)))
(else
(or (pred (car ls)) (lp (cdr ls)))))))
(define (every pred ls . lists)
(check-arg procedure? pred every)
(if (null? lists)
(every1 pred ls)
(let lp ((lists (cons ls lists)))
(cond ((any1 null? lists)
#t)
((any1 null? (map cdr lists))
(apply pred (map car lists)))
(else
(and (apply pred (map car lists)) (lp (map cdr lists))))))))
(define (every1 pred ls)
(let lp ((ls ls))
(cond ((null? ls)
#t)
((null? (cdr ls))
(pred (car ls)))
(else
(and (pred (car ls)) (lp (cdr ls)))))))
(define (list-index pred clist1 . rest)
"Return the index of the first set of elements, one from each of
CLIST1 ... CLISTN, that satisfies PRED."
(check-arg procedure? pred list-index)
(if (null? rest)
(let lp ((l clist1) (i 0))
(if (null? l)
#f
(if (pred (car l))
i
(lp (cdr l) (+ i 1)))))
(let lp ((lists (cons clist1 rest)) (i 0))
(cond ((any1 null? lists)
#f)
((apply pred (map car lists)) i)
(else
(lp (map cdr lists) (+ i 1)))))))
;;; Association lists
(define alist-cons acons)
(define (alist-copy alist)
"Return a copy of ALIST, copying both the pairs comprising the list
and those making the associations."
(let lp ((a alist)
(rl '()))
(if (null? a)
(reverse! rl)
(lp (cdr a) (alist-cons (caar a) (cdar a) rl)))))
(define* (alist-delete key alist #\optional (k= equal?))
(check-arg procedure? k= alist-delete)
(let lp ((a alist) (rl '()))
(if (null? a)
(reverse! rl)
(if (k= key (caar a))
(lp (cdr a) rl)
(lp (cdr a) (cons (car a) rl))))))
(define* (alist-delete! key alist #\optional (k= equal?))
(alist-delete key alist k=)) ; XXX:optimize
;;; Delete / assoc / member
(define* (member x ls #\optional (= equal?))
(cond
;; This might be performance-sensitive, so punt on the check here,
;; relying on memq/memv to check that = is a procedure.
((eq? = eq?) (memq x ls))
((eq? = eqv?) (memv x ls))
(else
(check-arg procedure? = member)
(find-tail (lambda (y) (= x y)) ls))))
;;; Set operations on lists
(define (lset<= = . rest)
(check-arg procedure? = lset<=)
(if (null? rest)
#t
(let lp ((f (car rest)) (r (cdr rest)))
(or (null? r)
(and (every (lambda (el) (member el (car r) =)) f)
(lp (car r) (cdr r)))))))
(define (lset= = . rest)
(check-arg procedure? = lset<=)
(if (null? rest)
#t
(let lp ((f (car rest)) (r (cdr rest)))
(or (null? r)
(and (every (lambda (el) (member el (car r) =)) f)
(every (lambda (el) (member el f (lambda (x y) (= y x)))) (car r))
(lp (car r) (cdr r)))))))
;; It's not quite clear if duplicates among the `rest' elements are meant to
;; be cast out. The spec says `=' is called as (= lstelem restelem),
;; suggesting perhaps not, but the reference implementation shows the "list"
;; at each stage as including those elements already added. The latter
;; corresponds to what's described for lset-union, so that's what's done.
;;
(define (lset-adjoin = list . rest)
"Add to LIST any of the elements of REST not already in the list.
These elements are `cons'ed onto the start of LIST (so the return shares
a common tail with LIST), but the order they're added is unspecified.
The given `=' procedure is used for comparing elements, called
as `(@var{=} listelem elem)', i.e., the second argument is one of the
given REST parameters."
;; If `=' is `eq?' or `eqv?', users won't be able to tell which arg is
;; first, so we can pass the raw procedure through to `member',
;; allowing `memq' / `memv' to be selected.
(define pred
(if (or (eq? = eq?) (eq? = eqv?))
=
(begin
(check-arg procedure? = lset-adjoin)
(lambda (x y) (= y x)))))
(let lp ((ans list) (rest rest))
(if (null? rest)
ans
(lp (if (member (car rest) ans pred)
ans
(cons (car rest) ans))
(cdr rest)))))
(define (lset-union = . rest)
;; Likewise, allow memq / memv to be used if possible.
(define pred
(if (or (eq? = eq?) (eq? = eqv?))
=
(begin
(check-arg procedure? = lset-union)
(lambda (x y) (= y x)))))
(fold (lambda (lis ans) ; Compute ANS + LIS.
(cond ((null? lis) ans) ; Don't copy any lists
((null? ans) lis) ; if we don't have to.
((eq? lis ans) ans)
(else
(fold (lambda (elt ans)
(if (member elt ans pred)
ans
(cons elt ans)))
ans lis))))
'()
rest))
(define (lset-intersection = list1 . rest)
(check-arg procedure? = lset-intersection)
(let lp ((l list1) (acc '()))
(if (null? l)
(reverse! acc)
(if (every (lambda (ll) (member (car l) ll =)) rest)
(lp (cdr l) (cons (car l) acc))
(lp (cdr l) acc)))))
(define (lset-difference = list1 . rest)
(check-arg procedure? = lset-difference)
(if (null? rest)
list1
(let lp ((l list1) (acc '()))
(if (null? l)
(reverse! acc)
(if (any (lambda (ll) (member (car l) ll =)) rest)
(lp (cdr l) acc)
(lp (cdr l) (cons (car l) acc)))))))
;(define (fold kons knil list1 . rest)
(define (lset-xor = . rest)
(check-arg procedure? = lset-xor)
(fold (lambda (lst res)
(let lp ((l lst) (acc '()))
(if (null? l)
(let lp0 ((r res) (acc acc))
(if (null? r)
(reverse! acc)
(if (member (car r) lst =)
(lp0 (cdr r) acc)
(lp0 (cdr r) (cons (car r) acc)))))
(if (member (car l) res =)
(lp (cdr l) acc)
(lp (cdr l) (cons (car l) acc))))))
'()
rest))
(define (lset-diff+intersection = list1 . rest)
(check-arg procedure? = lset-diff+intersection)
(let lp ((l list1) (accd '()) (acci '()))
(if (null? l)
(values (reverse! accd) (reverse! acci))
(let ((appears (every (lambda (ll) (member (car l) ll =)) rest)))
(if appears
(lp (cdr l) accd (cons (car l) acci))
(lp (cdr l) (cons (car l) accd) acci))))))
(define (lset-union! = . rest)
(check-arg procedure? = lset-union!)
(apply lset-union = rest)) ; XXX:optimize
(define (lset-intersection! = list1 . rest)
(check-arg procedure? = lset-intersection!)
(apply lset-intersection = list1 rest)) ; XXX:optimize
(define (lset-xor! = . rest)
(check-arg procedure? = lset-xor!)
(apply lset-xor = rest)) ; XXX:optimize
(define (lset-diff+intersection! = list1 . rest)
(check-arg procedure? = lset-diff+intersection!)
(apply lset-diff+intersection = list1 rest)) ; XXX:optimize
;;; srfi-1.scm ends here
;;; srfi-10.scm --- Hash-Comma Reader Extension
;; Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module implements the syntax extension #,(), also called
;; hash-comma, which is defined in SRFI-10.
;;
;; The support for SRFI-10 consists of the procedure
;; `define-reader-ctor' for defining new reader constructors and the
;; read syntax form
;;
;; #,(<ctor> <datum> ...)
;;
;; where <ctor> must be a symbol for which a read constructor was
;; defined previously.
;;
;; Example:
;;
;; (define-reader-ctor 'file open-input-file)
;; (define f '#,(file "/etc/passwd"))
;; (read-line f)
;; =>
;; "root:x:0:0:root:/root:/bin/bash"
;;
;; Please note the quote before the #,(file ...) expression. This is
;; necessary because ports are not self-evaluating in Guile.
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-10)
\:use-module (ice-9 rdelim)
\:export (define-reader-ctor))
(cond-expand-provide (current-module) '(srfi-10))
;; This hash table stores the association between comma-hash tags and
;; the corresponding constructor procedures.
;;
(define reader-ctors (make-hash-table 31))
;; This procedure installs the procedure @var{proc} as the constructor
;; for the comma-hash tag @var{symbol}.
;;
(define (define-reader-ctor symbol proc)
(hashq-set! reader-ctors symbol proc)
(if #f #f)) ; Return unspecified value.
;; Retrieve the constructor procedure for the tag @var{symbol} or
;; throw an error if no such tag is defined.
;;
(define (lookup symbol)
(let ((p (hashq-ref reader-ctors symbol #f)))
(if (procedure? p)
p
(error "unknown hash-comma tag " symbol))))
;; This is the actual reader extension.
;;
(define (hash-comma char port)
(let* ((obj (read port)))
(if (and (list? obj) (positive? (length obj)) (symbol? (car obj)))
(let ((p (lookup (car obj))))
(let ((res (apply p (cdr obj))))
res))
(error "syntax error in hash-comma expression"))))
;; Install the hash extension.
;;
(read-hash-extend #\, hash-comma)
;;; srfi-10.scm ends here
;;; srfi-11.scm --- let-values and let*-values
;; Copyright (C) 2000, 2001, 2002, 2004, 2006, 2009 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module exports two syntax forms: let-values and let*-values.
;;
;; Sample usage:
;;
;; (let-values (((x y . z) (foo a b))
;; ((p q) (bar c)))
;; (baz x y z p q))
;;
;; This binds `x' and `y' to the first to values returned by `foo',
;; `z' to the rest of the values from `foo', and `p' and `q' to the
;; values returned by `bar'. All of these are available to `baz'.
;;
;; let*-values : let-values :: let* : let
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-11)
\:export-syntax (let-values let*-values))
(cond-expand-provide (current-module) '(srfi-11))
;;;;;;;;;;;;;;
;; let-values
;;
;; Current approach is to translate
;;
;; (let-values (((x y . z) (foo a b))
;; ((p q) (bar c)))
;; (baz x y z p q))
;;
;; into
;;
;; (call-with-values (lambda () (foo a b))
;; (lambda (<tmp-x> <tmp-y> . <tmp-z>)
;; (call-with-values (lambda () (bar c))
;; (lambda (<tmp-p> <tmp-q>)
;; (let ((x <tmp-x>)
;; (y <tmp-y>)
;; (z <tmp-z>)
;; (p <tmp-p>)
;; (q <tmp-q>))
;; (baz x y z p q))))))
;; We could really use quasisyntax here...
(define-syntax let-values
(lambda (x)
(syntax-case x ()
((_ ((binds exp)) b0 b1 ...)
(syntax (call-with-values (lambda () exp)
(lambda binds b0 b1 ...))))
((_ (clause ...) b0 b1 ...)
(let lp ((clauses (syntax (clause ...)))
(ids '())
(tmps '()))
(if (null? clauses)
(with-syntax (((id ...) ids)
((tmp ...) tmps))
(syntax (let ((id tmp) ...)
b0 b1 ...)))
(syntax-case (car clauses) ()
(((var ...) exp)
(with-syntax (((new-tmp ...) (generate-temporaries
(syntax (var ...))))
((id ...) ids)
((tmp ...) tmps))
(with-syntax ((inner (lp (cdr clauses)
(syntax (var ... id ...))
(syntax (new-tmp ... tmp ...)))))
(syntax (call-with-values (lambda () exp)
(lambda (new-tmp ...) inner))))))
((vars exp)
(with-syntax ((((new-tmp . new-var) ...)
(let lp ((vars (syntax vars)))
(syntax-case vars ()
((id . rest)
(acons (syntax id)
(car
(generate-temporaries (syntax (id))))
(lp (syntax rest))))
(id (acons (syntax id)
(car
(generate-temporaries (syntax (id))))
'())))))
((id ...) ids)
((tmp ...) tmps))
(with-syntax ((inner (lp (cdr clauses)
(syntax (new-var ... id ...))
(syntax (new-tmp ... tmp ...))))
(args (let lp ((tmps (syntax (new-tmp ...))))
(syntax-case tmps ()
((id) (syntax id))
((id . rest) (cons (syntax id)
(lp (syntax rest))))))))
(syntax (call-with-values (lambda () exp)
(lambda args inner)))))))))))))
;;;;;;;;;;;;;;
;; let*-values
;;
;; Current approach is to translate
;;
;; (let*-values (((x y z) (foo a b))
;; ((p q) (bar c)))
;; (baz x y z p q))
;;
;; into
;;
;; (call-with-values (lambda () (foo a b))
;; (lambda (x y z)
;; (call-with-values (lambda (bar c))
;; (lambda (p q)
;; (baz x y z p q)))))
(define-syntax let*-values
(syntax-rules ()
((let*-values () body ...)
(let () body ...))
((let*-values ((vars-1 binding-1) (vars-2 binding-2) ...) body ...)
(call-with-values (lambda () binding-1)
(lambda vars-1
(let*-values ((vars-2 binding-2) ...)
body ...))))))
;;; srfi-11.scm ends here
;;; srfi-111.scm -- SRFI 111 Boxes
;; Copyright (C) 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (srfi srfi-111)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\export (box box? unbox set-box!))
(cond-expand-provide (current-module) '(srfi-111))
(define-record-type <box>
(box value)
box?
(value unbox set-box!))
(set-record-type-printer! <box>
(lambda (box port)
(display "#<box " port)
(display (number->string (object-address box) 16) port)
(display " value: ")
(write (unbox box) port)
(display ">" port)))
;;; srfi-13.scm --- String Library
;; Copyright (C) 2001, 2002, 2003, 2004, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;
;; All procedures are in the core and are simply reexported here.
;;; Code:
(define-module (srfi srfi-13))
(re-export
;;; Predicates
string?
string-null?
string-any
string-every
;;; Constructors
make-string
string
string-tabulate
;;; List/string conversion
string->list
list->string
reverse-list->string
string-join
;;; Selection
string-length
string-ref
string-copy
substring/shared
string-copy!
string-take string-take-right
string-drop string-drop-right
string-pad string-pad-right
string-trim string-trim-right
string-trim-both
;;; Modification
string-set!
string-fill!
;;; Comparison
string-compare
string-compare-ci
string= string<>
string< string>
string<= string>=
string-ci= string-ci<>
string-ci< string-ci>
string-ci<= string-ci>=
string-hash string-hash-ci
;;; Prefixes/Suffixes
string-prefix-length
string-prefix-length-ci
string-suffix-length
string-suffix-length-ci
string-prefix?
string-prefix-ci?
string-suffix?
string-suffix-ci?
;;; Searching
string-index
string-index-right
string-skip string-skip-right
string-count
string-contains string-contains-ci
;;; Alphabetic case mapping
string-upcase
string-upcase!
string-downcase
string-downcase!
string-titlecase
string-titlecase!
;;; Reverse/Append
string-reverse
string-reverse!
string-append
string-append/shared
string-concatenate
string-concatenate-reverse
string-concatenate/shared
string-concatenate-reverse/shared
;;; Fold/Unfold/Map
string-map string-map!
string-fold
string-fold-right
string-unfold
string-unfold-right
string-for-each
string-for-each-index
;;; Replicate/Rotate
xsubstring
string-xcopy!
;;; Miscellaneous
string-replace
string-tokenize
;;; Filtering/Deleting
string-filter
string-delete)
(cond-expand-provide (current-module) '(srfi-13))
;;; srfi-13.scm ends here
;;; srfi-14.scm --- Character-set Library
;; Copyright (C) 2001, 2002, 2004, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-14))
(re-export
;;; General procedures
char-set?
char-set=
char-set<=
char-set-hash
;;; Iterating over character sets
char-set-cursor
char-set-ref
char-set-cursor-next
end-of-char-set?
char-set-fold
char-set-unfold char-set-unfold!
char-set-for-each
char-set-map
;;; Creating character sets
char-set-copy
char-set
list->char-set list->char-set!
string->char-set string->char-set!
char-set-filter char-set-filter!
ucs-range->char-set ucs-range->char-set!
->char-set
;;; Querying character sets
char-set-size
char-set-count
char-set->list
char-set->string
char-set-contains?
char-set-every
char-set-any
;;; Character set algebra
char-set-adjoin char-set-adjoin!
char-set-delete char-set-delete!
char-set-complement
char-set-union
char-set-intersection
char-set-difference
char-set-xor
char-set-diff+intersection
char-set-complement!
char-set-union!
char-set-intersection!
char-set-difference!
char-set-xor!
char-set-diff+intersection!
;;; Standard character sets
char-set:lower-case
char-set:upper-case
char-set:title-case
char-set:letter
char-set:digit
char-set:letter+digit
char-set:graphic
char-set:printing
char-set:whitespace
char-set:iso-control
char-set:punctuation
char-set:symbol
char-set:hex-digit
char-set:blank
char-set:ascii
char-set:empty
char-set:full)
(cond-expand-provide (current-module) '(srfi-14))
;;; srfi-14.scm ends here
;;; srfi-16.scm --- case-lambda
;; Copyright (C) 2001, 2002, 2006, 2009, 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Martin Grabmueller
;;; Commentary:
;; Implementation of SRFI-16. `case-lambda' is a syntactic form
;; which permits writing functions acting different according to the
;; number of arguments passed.
;;
;; The syntax of the `case-lambda' form is defined in the following
;; EBNF grammar.
;;
;; <case-lambda>
;; --> (case-lambda <case-lambda-clause>)
;; <case-lambda-clause>
;; --> (<signature> <definition-or-command>*)
;; <signature>
;; --> (<identifier>*)
;; | (<identifier>* . <identifier>)
;; | <identifier>
;;
;; The value returned by a `case-lambda' form is a procedure which
;; matches the number of actual arguments against the signatures in
;; the various clauses, in order. The first matching clause is
;; selected, the corresponding values from the actual parameter list
;; are bound to the variable names in the clauses and the body of the
;; clause is evaluated.
;;; Code:
(define-module (srfi srfi-16)
#\re-export (case-lambda))
;; Case-lambda is now provided by core psyntax.
;;; srfi-17.scm --- Generalized set!
;; Copyright (C) 2001, 2002, 2003, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Matthias Koeppe <mkoeppe@mail.math.uni-magdeburg.de>
;;; Commentary:
;; This is an implementation of SRFI-17: Generalized set!
;;
;; It exports the Guile procedure `make-procedure-with-setter' under
;; the SRFI name `getter-with-setter' and exports the standard
;; procedures `car', `cdr', ..., `cdddr', `string-ref' and
;; `vector-ref' as procedures with setters, as required by the SRFI.
;;
;; SRFI-17 was heavily criticized during its discussion period but it
;; was finalized anyway. One issue was its concept of globally
;; associating setter "properties" with (procedure) values, which is
;; non-Schemy. For this reason, this implementation chooses not to
;; provide a way to set the setter of a procedure. In fact, (set!
;; (setter PROC) SETTER) signals an error. The only way to attach a
;; setter to a procedure is to create a new object (a "procedure with
;; setter") via the `getter-with-setter' procedure. This procedure is
;; also specified in the SRFI. Using it avoids the described
;; problems.
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-17)
\:export (getter-with-setter)
\:replace (;; redefined standard procedures
setter
car cdr caar cadr cdar cddr caaar caadr cadar caddr cdaar
cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr
caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr
cdddar cddddr string-ref vector-ref))
(cond-expand-provide (current-module) '(srfi-17))
;;; Procedures
(define getter-with-setter make-procedure-with-setter)
(define setter
(getter-with-setter
(@ (guile) setter)
(lambda args
(error "Setting setters is not supported for a good reason."))))
;;; Redefine R5RS procedures to appropriate procedures with setters
(define (compose-setter setter location)
(lambda (obj value)
(setter (location obj) value)))
(define car
(getter-with-setter (@ (guile) car)
set-car!))
(define cdr
(getter-with-setter (@ (guile) cdr)
set-cdr!))
(define caar
(getter-with-setter (@ (guile) caar)
(compose-setter set-car! (@ (guile) car))))
(define cadr
(getter-with-setter (@ (guile) cadr)
(compose-setter set-car! (@ (guile) cdr))))
(define cdar
(getter-with-setter (@ (guile) cdar)
(compose-setter set-cdr! (@ (guile) car))))
(define cddr
(getter-with-setter (@ (guile) cddr)
(compose-setter set-cdr! (@ (guile) cdr))))
(define caaar
(getter-with-setter (@ (guile) caaar)
(compose-setter set-car! (@ (guile) caar))))
(define caadr
(getter-with-setter (@ (guile) caadr)
(compose-setter set-car! (@ (guile) cadr))))
(define cadar
(getter-with-setter (@ (guile) cadar)
(compose-setter set-car! (@ (guile) cdar))))
(define caddr
(getter-with-setter (@ (guile) caddr)
(compose-setter set-car! (@ (guile) cddr))))
(define cdaar
(getter-with-setter (@ (guile) cdaar)
(compose-setter set-cdr! (@ (guile) caar))))
(define cdadr
(getter-with-setter (@ (guile) cdadr)
(compose-setter set-cdr! (@ (guile) cadr))))
(define cddar
(getter-with-setter (@ (guile) cddar)
(compose-setter set-cdr! (@ (guile) cdar))))
(define cdddr
(getter-with-setter (@ (guile) cdddr)
(compose-setter set-cdr! (@ (guile) cddr))))
(define caaaar
(getter-with-setter (@ (guile) caaaar)
(compose-setter set-car! (@ (guile) caaar))))
(define caaadr
(getter-with-setter (@ (guile) caaadr)
(compose-setter set-car! (@ (guile) caadr))))
(define caadar
(getter-with-setter (@ (guile) caadar)
(compose-setter set-car! (@ (guile) cadar))))
(define caaddr
(getter-with-setter (@ (guile) caaddr)
(compose-setter set-car! (@ (guile) caddr))))
(define cadaar
(getter-with-setter (@ (guile) cadaar)
(compose-setter set-car! (@ (guile) cdaar))))
(define cadadr
(getter-with-setter (@ (guile) cadadr)
(compose-setter set-car! (@ (guile) cdadr))))
(define caddar
(getter-with-setter (@ (guile) caddar)
(compose-setter set-car! (@ (guile) cddar))))
(define cadddr
(getter-with-setter (@ (guile) cadddr)
(compose-setter set-car! (@ (guile) cdddr))))
(define cdaaar
(getter-with-setter (@ (guile) cdaaar)
(compose-setter set-cdr! (@ (guile) caaar))))
(define cdaadr
(getter-with-setter (@ (guile) cdaadr)
(compose-setter set-cdr! (@ (guile) caadr))))
(define cdadar
(getter-with-setter (@ (guile) cdadar)
(compose-setter set-cdr! (@ (guile) cadar))))
(define cdaddr
(getter-with-setter (@ (guile) cdaddr)
(compose-setter set-cdr! (@ (guile) caddr))))
(define cddaar
(getter-with-setter (@ (guile) cddaar)
(compose-setter set-cdr! (@ (guile) cdaar))))
(define cddadr
(getter-with-setter (@ (guile) cddadr)
(compose-setter set-cdr! (@ (guile) cdadr))))
(define cdddar
(getter-with-setter (@ (guile) cdddar)
(compose-setter set-cdr! (@ (guile) cddar))))
(define cddddr
(getter-with-setter (@ (guile) cddddr)
(compose-setter set-cdr! (@ (guile) cdddr))))
(define string-ref
(getter-with-setter (@ (guile) string-ref)
string-set!))
(define vector-ref
(getter-with-setter (@ (guile) vector-ref)
vector-set!))
;;; srfi-17.scm ends here
;;; srfi-18.scm --- Multithreading support
;; Copyright (C) 2008, 2009, 2010, 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Julian Graham <julian.graham@aya.yale.edu>
;;; Date: 2008-04-11
;;; Commentary:
;; This is an implementation of SRFI-18 (Multithreading support).
;;
;; All procedures defined in SRFI-18, which are not already defined in
;; the Guile core library, are exported.
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-18)
\:use-module (srfi srfi-34)
\:export (
;;; Threads
;; current-thread <= in the core
;; thread? <= in the core
make-thread
thread-name
thread-specific
thread-specific-set!
thread-start!
thread-yield!
thread-sleep!
thread-terminate!
thread-join!
;;; Mutexes
;; mutex? <= in the core
make-mutex
mutex-name
mutex-specific
mutex-specific-set!
mutex-state
mutex-lock!
mutex-unlock!
;;; Condition variables
;; condition-variable? <= in the core
make-condition-variable
condition-variable-name
condition-variable-specific
condition-variable-specific-set!
condition-variable-signal!
condition-variable-broadcast!
condition-variable-wait!
;;; Time
current-time
time?
time->seconds
seconds->time
current-exception-handler
with-exception-handler
raise
join-timeout-exception?
abandoned-mutex-exception?
terminated-thread-exception?
uncaught-exception?
uncaught-exception-reason
)
\:re-export (current-thread thread? mutex? condition-variable?)
\:replace (current-time
make-thread
make-mutex
make-condition-variable
raise))
(if (not (provided? 'threads))
(error "SRFI-18 requires Guile with threads support"))
(cond-expand-provide (current-module) '(srfi-18))
(define (check-arg-type pred arg caller)
(if (pred arg)
arg
(scm-error 'wrong-type-arg caller
"Wrong type argument: ~S" (list arg) '())))
(define abandoned-mutex-exception (list 'abandoned-mutex-exception))
(define join-timeout-exception (list 'join-timeout-exception))
(define terminated-thread-exception (list 'terminated-thread-exception))
(define uncaught-exception (list 'uncaught-exception))
(define object-names (make-weak-key-hash-table))
(define object-specifics (make-weak-key-hash-table))
(define thread-start-conds (make-weak-key-hash-table))
(define thread-exception-handlers (make-weak-key-hash-table))
;; EXCEPTIONS
(define raise (@ (srfi srfi-34) raise))
(define (initial-handler obj)
(srfi-18-exception-preserver (cons uncaught-exception obj)))
(define thread->exception (make-object-property))
(define (srfi-18-exception-preserver obj)
(if (or (terminated-thread-exception? obj)
(uncaught-exception? obj))
(set! (thread->exception (current-thread)) obj)))
(define (srfi-18-exception-handler key . args)
;; SRFI 34 exceptions continue to bubble up no matter who handles them, so
;; if one is caught at this level, it has already been taken care of by
;; `initial-handler'.
(and (not (eq? key 'srfi-34))
(srfi-18-exception-preserver (if (null? args)
(cons uncaught-exception key)
(cons* uncaught-exception key args)))))
(define (current-handler-stack)
(let ((ct (current-thread)))
(or (hashq-ref thread-exception-handlers ct)
(hashq-set! thread-exception-handlers ct (list initial-handler)))))
(define (with-exception-handler handler thunk)
(let ((ct (current-thread))
(hl (current-handler-stack)))
(check-arg-type procedure? handler "with-exception-handler")
(check-arg-type thunk? thunk "with-exception-handler")
(hashq-set! thread-exception-handlers ct (cons handler hl))
(apply (@ (srfi srfi-34) with-exception-handler)
(list (lambda (obj)
(hashq-set! thread-exception-handlers ct hl)
(handler obj))
(lambda ()
(call-with-values thunk
(lambda res
(hashq-set! thread-exception-handlers ct hl)
(apply values res))))))))
(define (current-exception-handler)
(car (current-handler-stack)))
(define (join-timeout-exception? obj) (eq? obj join-timeout-exception))
(define (abandoned-mutex-exception? obj) (eq? obj abandoned-mutex-exception))
(define (uncaught-exception? obj)
(and (pair? obj) (eq? (car obj) uncaught-exception)))
(define (uncaught-exception-reason exc)
(cdr (check-arg-type uncaught-exception? exc "uncaught-exception-reason")))
(define (terminated-thread-exception? obj)
(eq? obj terminated-thread-exception))
;; THREADS
;; Create a new thread and prevent it from starting using a condition variable.
;; Once started, install a top-level exception handler that rethrows any
;; exceptions wrapped in an uncaught-exception wrapper.
(define make-thread
(let ((make-cond-wrapper (lambda (thunk lcond lmutex scond smutex)
(lambda ()
(lock-mutex lmutex)
(signal-condition-variable lcond)
(lock-mutex smutex)
(unlock-mutex lmutex)
(wait-condition-variable scond smutex)
(unlock-mutex smutex)
(with-exception-handler initial-handler
thunk)))))
(lambda (thunk . name)
(let ((n (and (pair? name) (car name)))
(lm (make-mutex 'launch-mutex))
(lc (make-condition-variable 'launch-condition-variable))
(sm (make-mutex 'start-mutex))
(sc (make-condition-variable 'start-condition-variable)))
(lock-mutex lm)
(let ((t (call-with-new-thread (make-cond-wrapper thunk lc lm sc sm)
srfi-18-exception-handler)))
(hashq-set! thread-start-conds t (cons sm sc))
(and n (hashq-set! object-names t n))
(wait-condition-variable lc lm)
(unlock-mutex lm)
t)))))
(define (thread-name thread)
(hashq-ref object-names (check-arg-type thread? thread "thread-name")))
(define (thread-specific thread)
(hashq-ref object-specifics
(check-arg-type thread? thread "thread-specific")))
(define (thread-specific-set! thread obj)
(hashq-set! object-specifics
(check-arg-type thread? thread "thread-specific-set!")
obj)
*unspecified*)
(define (thread-start! thread)
(let ((x (hashq-ref thread-start-conds
(check-arg-type thread? thread "thread-start!"))))
(and x (let ((smutex (car x))
(scond (cdr x)))
(hashq-remove! thread-start-conds thread)
(lock-mutex smutex)
(signal-condition-variable scond)
(unlock-mutex smutex)))
thread))
(define (thread-yield!) (yield) *unspecified*)
(define (thread-sleep! timeout)
(let* ((ct (time->seconds (current-time)))
(t (cond ((time? timeout) (- (time->seconds timeout) ct))
((number? timeout) (- timeout ct))
(else (scm-error 'wrong-type-arg "thread-sleep!"
"Wrong type argument: ~S"
(list timeout)
'()))))
(secs (inexact->exact (truncate t)))
(usecs (inexact->exact (truncate (* (- t secs) 1000000)))))
(and (> secs 0) (sleep secs))
(and (> usecs 0) (usleep usecs))
*unspecified*))
;; A convenience function for installing exception handlers on SRFI-18
;; primitives that resume the calling continuation after the handler is
;; invoked -- this resolves a behavioral incompatibility with Guile's
;; implementation of SRFI-34, which uses lazy-catch and rethrows handled
;; exceptions. (SRFI-18, "Primitives and exceptions")
(define (wrap thunk)
(lambda (continuation)
(with-exception-handler (lambda (obj)
((current-exception-handler) obj)
(continuation))
thunk)))
;; A pass-thru to cancel-thread that first installs a handler that throws
;; terminated-thread exception, as per SRFI-18,
(define (thread-terminate! thread)
(define (thread-terminate-inner!)
(let ((current-handler (thread-cleanup thread)))
(if (thunk? current-handler)
(set-thread-cleanup! thread
(lambda ()
(with-exception-handler initial-handler
current-handler)
(srfi-18-exception-preserver
terminated-thread-exception)))
(set-thread-cleanup! thread
(lambda () (srfi-18-exception-preserver
terminated-thread-exception))))
(cancel-thread thread)
*unspecified*))
(thread-terminate-inner!))
(define (thread-join! thread . args)
(define thread-join-inner!
(wrap (lambda ()
(let ((v (apply join-thread (cons thread args)))
(e (thread->exception thread)))
(if (and (= (length args) 1) (not v))
(raise join-timeout-exception))
(if e (raise e))
v))))
(call/cc thread-join-inner!))
;; MUTEXES
;; These functions are all pass-thrus to the existing Guile implementations.
(define make-mutex
(lambda name
(let ((n (and (pair? name) (car name)))
(m ((@ (guile) make-mutex)
'unchecked-unlock
'allow-external-unlock
'recursive)))
(and n (hashq-set! object-names m n)) m)))
(define (mutex-name mutex)
(hashq-ref object-names (check-arg-type mutex? mutex "mutex-name")))
(define (mutex-specific mutex)
(hashq-ref object-specifics
(check-arg-type mutex? mutex "mutex-specific")))
(define (mutex-specific-set! mutex obj)
(hashq-set! object-specifics
(check-arg-type mutex? mutex "mutex-specific-set!")
obj)
*unspecified*)
(define (mutex-state mutex)
(let ((owner (mutex-owner mutex)))
(if owner
(if (thread-exited? owner) 'abandoned owner)
(if (> (mutex-level mutex) 0) 'not-owned 'not-abandoned))))
(define (mutex-lock! mutex . args)
(define mutex-lock-inner!
(wrap (lambda ()
(catch 'abandoned-mutex-error
(lambda () (apply lock-mutex (cons mutex args)))
(lambda (key . args) (raise abandoned-mutex-exception))))))
(call/cc mutex-lock-inner!))
(define (mutex-unlock! mutex . args)
(apply unlock-mutex (cons mutex args)))
;; CONDITION VARIABLES
;; These functions are all pass-thrus to the existing Guile implementations.
(define make-condition-variable
(lambda name
(let ((n (and (pair? name) (car name)))
(m ((@ (guile) make-condition-variable))))
(and n (hashq-set! object-names m n)) m)))
(define (condition-variable-name condition-variable)
(hashq-ref object-names (check-arg-type condition-variable?
condition-variable
"condition-variable-name")))
(define (condition-variable-specific condition-variable)
(hashq-ref object-specifics (check-arg-type condition-variable?
condition-variable
"condition-variable-specific")))
(define (condition-variable-specific-set! condition-variable obj)
(hashq-set! object-specifics
(check-arg-type condition-variable?
condition-variable
"condition-variable-specific-set!")
obj)
*unspecified*)
(define (condition-variable-signal! cond)
(signal-condition-variable cond)
*unspecified*)
(define (condition-variable-broadcast! cond)
(broadcast-condition-variable cond)
*unspecified*)
;; TIME
(define current-time gettimeofday)
(define (time? obj)
(and (pair? obj)
(let ((co (car obj))) (and (integer? co) (>= co 0)))
(let ((co (cdr obj))) (and (integer? co) (>= co 0)))))
(define (time->seconds time)
(and (check-arg-type time? time "time->seconds")
(+ (car time) (/ (cdr time) 1000000))))
(define (seconds->time x)
(and (check-arg-type number? x "seconds->time")
(let ((fx (truncate x)))
(cons (inexact->exact fx)
(inexact->exact (truncate (* (- x fx) 1000000)))))))
;; srfi-18.scm ends here
;;; srfi-19.scm --- Time/Date Library
;; Copyright (C) 2001-2003, 2005-2011, 2014, 2016
;; Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Rob Browning <rlb@cs.utexas.edu>
;;; Originally from SRFI reference implementation by Will Fitzgerald.
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
;; FIXME: I haven't checked a decent amount of this code for potential
;; performance improvements, but I suspect that there may be some
;; substantial ones to be realized, esp. in the later "parsing" half
;; of the file, by rewriting the code with use of more Guile native
;; functions that do more work in a "chunk".
;;
;; FIXME: mkoeppe: Time zones are treated a little simplistic in
;; SRFI-19; they are only a numeric offset. Thus, printing time zones
;; (LOCALE-PRINT-TIME-ZONE) can't be implemented sensibly. The
;; functions taking an optional TZ-OFFSET should be extended to take a
;; symbolic time-zone (like "CET"); this string should be stored in
;; the DATE structure.
(define-module (srfi srfi-19)
\:use-module (srfi srfi-6)
\:use-module (srfi srfi-8)
\:use-module (srfi srfi-9)
\:autoload (ice-9 rdelim) (read-line)
\:use-module (ice-9 i18n)
\:replace (current-time)
\:export (;; Constants
time-duration
time-monotonic
time-process
time-tai
time-thread
time-utc
;; Current time and clock resolution
current-date
current-julian-day
current-modified-julian-day
time-resolution
;; Time object and accessors
make-time
time?
time-type
time-nanosecond
time-second
set-time-type!
set-time-nanosecond!
set-time-second!
copy-time
;; Time comparison procedures
time<=?
time<?
time=?
time>=?
time>?
;; Time arithmetic procedures
time-difference
time-difference!
add-duration
add-duration!
subtract-duration
subtract-duration!
;; Date object and accessors
make-date
date?
date-nanosecond
date-second
date-minute
date-hour
date-day
date-month
date-year
date-zone-offset
date-year-day
date-week-day
date-week-number
;; Time/Date/Julian Day/Modified Julian Day converters
date->julian-day
date->modified-julian-day
date->time-monotonic
date->time-tai
date->time-utc
julian-day->date
julian-day->time-monotonic
julian-day->time-tai
julian-day->time-utc
modified-julian-day->date
modified-julian-day->time-monotonic
modified-julian-day->time-tai
modified-julian-day->time-utc
time-monotonic->date
time-monotonic->julian-day
time-monotonic->modified-julian-day
time-monotonic->time-tai
time-monotonic->time-tai!
time-monotonic->time-utc
time-monotonic->time-utc!
time-tai->date
time-tai->julian-day
time-tai->modified-julian-day
time-tai->time-monotonic
time-tai->time-monotonic!
time-tai->time-utc
time-tai->time-utc!
time-utc->date
time-utc->julian-day
time-utc->modified-julian-day
time-utc->time-monotonic
time-utc->time-monotonic!
time-utc->time-tai
time-utc->time-tai!
;; Date to string/string to date converters.
date->string
string->date))
(cond-expand-provide (current-module) '(srfi-19))
(define time-tai 'time-tai)
(define time-utc 'time-utc)
(define time-monotonic 'time-monotonic)
(define time-thread 'time-thread)
(define time-process 'time-process)
(define time-duration 'time-duration)
;; FIXME: do we want to add gc time?
;; (define time-gc 'time-gc)
;;-- LOCALE dependent constants
;; See date->string
(define locale-date-time-format "~a ~b ~d ~H:~M:~S~z ~Y")
(define locale-short-date-format "~m/~d/~y")
(define locale-time-format "~H:~M:~S")
(define iso-8601-date-time-format "~Y-~m-~dT~H:~M:~S~z")
;;-- Miscellaneous Constants.
;;-- only the tai-epoch-in-jd might need changing if
;; a different epoch is used.
(define nano 1000000000) ; nanoseconds in a second
(define sid 86400) ; seconds in a day
(define sihd 43200) ; seconds in a half day
(define tai-epoch-in-jd 4881175/2) ; julian day number for 'the epoch'
;; FIXME: should this be something other than misc-error?
(define (time-error caller type value)
(if value
(throw 'misc-error caller "TIME-ERROR type ~A: ~S" (list type value) #f)
(throw 'misc-error caller "TIME-ERROR type ~A" (list type) #f)))
;; A table of leap seconds
;; See ftp://maia.usno.navy.mil/ser7/tai-utc.dat
;; and update as necessary.
;; this procedures reads the file in the above
;; format and creates the leap second table
;; it also calls the almost standard, but not R5 procedures read-line
;; & open-input-string
;; ie (set! leap-second-table (read-tai-utc-date "tai-utc.dat"))
(define (read-tai-utc-data filename)
(define (convert-jd jd)
(* (- (inexact->exact jd) tai-epoch-in-jd) sid))
(define (convert-sec sec)
(inexact->exact sec))
(let ((port (open-input-file filename))
(table '()))
(let loop ((line (read-line port)))
(if (not (eof-object? line))
(begin
(let* ((data (read (open-input-string
(string-append "(" line ")"))))
(year (car data))
(jd (cadddr (cdr data)))
(secs (cadddr (cdddr data))))
(if (>= year 1972)
(set! table (cons
(cons (convert-jd jd) (convert-sec secs))
table)))
(loop (read-line port))))))
table))
;; each entry is (tai seconds since epoch . # seconds to subtract for utc)
;; note they go higher to lower, and end in 1972.
(define leap-second-table
'((1435708800 . 36)
(1341100800 . 35)
(1230768000 . 34)
(1136073600 . 33)
(915148800 . 32)
(867715200 . 31)
(820454400 . 30)
(773020800 . 29)
(741484800 . 28)
(709948800 . 27)
(662688000 . 26)
(631152000 . 25)
(567993600 . 24)
(489024000 . 23)
(425865600 . 22)
(394329600 . 21)
(362793600 . 20)
(315532800 . 19)
(283996800 . 18)
(252460800 . 17)
(220924800 . 16)
(189302400 . 15)
(157766400 . 14)
(126230400 . 13)
(94694400 . 12)
(78796800 . 11)
(63072000 . 10)))
(define (read-leap-second-table filename)
(set! leap-second-table (read-tai-utc-data filename)))
(define (leap-second-delta utc-seconds)
(letrec ((lsd (lambda (table)
(cond ((>= utc-seconds (caar table))
(cdar table))
(else (lsd (cdr table)))))))
(if (< utc-seconds (* (- 1972 1970) 365 sid)) 0
(lsd leap-second-table))))
;;; the TIME structure; creates the accessors, too.
(define-record-type time
(make-time-unnormalized type nanosecond second)
time?
(type time-type set-time-type!)
(nanosecond time-nanosecond set-time-nanosecond!)
(second time-second set-time-second!))
(define (copy-time time)
(make-time (time-type time) (time-nanosecond time) (time-second time)))
(define (split-real r)
(if (integer? r)
(values (inexact->exact r) 0)
(let ((l (truncate r)))
(values (inexact->exact l) (- r l)))))
(define (time-normalize! t)
(if (>= (abs (time-nanosecond t)) 1000000000)
(receive (int frac)
(split-real (time-nanosecond t))
(set-time-second! t (+ (time-second t)
(quotient int 1000000000)))
(set-time-nanosecond! t (+ (remainder int 1000000000)
frac))))
(if (and (positive? (time-second t))
(negative? (time-nanosecond t)))
(begin
(set-time-second! t (- (time-second t) 1))
(set-time-nanosecond! t (+ 1000000000 (time-nanosecond t))))
(if (and (negative? (time-second t))
(positive? (time-nanosecond t)))
(begin
(set-time-second! t (+ (time-second t) 1))
(set-time-nanosecond! t (+ 1000000000 (time-nanosecond t))))))
t)
(define (make-time type nanosecond second)
(time-normalize! (make-time-unnormalized type nanosecond second)))
;; Helpers
;; FIXME: finish this and publish it?
(define (date->broken-down-time date)
(let ((result (mktime 0)))
;; FIXME: What should we do about leap-seconds which may overflow
;; set-tm:sec?
(set-tm:sec result (date-second date))
(set-tm:min result (date-minute date))
(set-tm:hour result (date-hour date))
;; FIXME: SRFI day ranges from 0-31. (not compatible with set-tm:mday).
(set-tm:mday result (date-day date))
(set-tm:mon result (- (date-month date) 1))
;; FIXME: need to signal error on range violation.
(set-tm:year result (+ 1900 (date-year date)))
(set-tm:isdst result -1)
(set-tm:gmtoff result (- (date-zone-offset date)))
result))
;;; current-time
;;; specific time getters.
(define (current-time-utc)
;; Resolution is microseconds.
(let ((tod (gettimeofday)))
(make-time time-utc (* (cdr tod) 1000) (car tod))))
(define (current-time-tai)
;; Resolution is microseconds.
(let* ((tod (gettimeofday))
(sec (car tod))
(usec (cdr tod)))
(make-time time-tai
(* usec 1000)
(+ (car tod) (leap-second-delta sec)))))
;;(define (current-time-ms-time time-type proc)
;; (let ((current-ms (proc)))
;; (make-time time-type
;; (quotient current-ms 10000)
;; (* (remainder current-ms 1000) 10000))))
;; -- we define it to be the same as TAI.
;; A different implemation of current-time-montonic
;; will require rewriting all of the time-monotonic converters,
;; of course.
(define (current-time-monotonic)
;; Resolution is microseconds.
(current-time-tai))
(define (current-time-thread)
(time-error 'current-time 'unsupported-clock-type 'time-thread))
(define ns-per-guile-tick (/ 1000000000 internal-time-units-per-second))
(define (current-time-process)
(let ((run-time (get-internal-run-time)))
(make-time
time-process
(* (remainder run-time internal-time-units-per-second)
ns-per-guile-tick)
(quotient run-time internal-time-units-per-second))))
;;(define (current-time-gc)
;; (current-time-ms-time time-gc current-gc-milliseconds))
(define (current-time . clock-type)
(let ((clock-type (if (null? clock-type) time-utc (car clock-type))))
(cond
((eq? clock-type time-tai) (current-time-tai))
((eq? clock-type time-utc) (current-time-utc))
((eq? clock-type time-monotonic) (current-time-monotonic))
((eq? clock-type time-thread) (current-time-thread))
((eq? clock-type time-process) (current-time-process))
;; ((eq? clock-type time-gc) (current-time-gc))
(else (time-error 'current-time 'invalid-clock-type clock-type)))))
;; -- Time Resolution
;; This is the resolution of the clock in nanoseconds.
;; This will be implementation specific.
(define (time-resolution . clock-type)
(let ((clock-type (if (null? clock-type) time-utc (car clock-type))))
(case clock-type
((time-tai) 1000)
((time-utc) 1000)
((time-monotonic) 1000)
((time-process) ns-per-guile-tick)
;; ((eq? clock-type time-thread) 1000)
;; ((eq? clock-type time-gc) 10000)
(else (time-error 'time-resolution 'invalid-clock-type clock-type)))))
;; -- Time comparisons
(define (time=? t1 t2)
;; Arrange tests for speed and presume that t1 and t2 are actually times.
;; also presume it will be rare to check two times of different types.
(and (= (time-second t1) (time-second t2))
(= (time-nanosecond t1) (time-nanosecond t2))
(eq? (time-type t1) (time-type t2))))
(define (time>? t1 t2)
(or (> (time-second t1) (time-second t2))
(and (= (time-second t1) (time-second t2))
(> (time-nanosecond t1) (time-nanosecond t2)))))
(define (time<? t1 t2)
(or (< (time-second t1) (time-second t2))
(and (= (time-second t1) (time-second t2))
(< (time-nanosecond t1) (time-nanosecond t2)))))
(define (time>=? t1 t2)
(or (> (time-second t1) (time-second t2))
(and (= (time-second t1) (time-second t2))
(>= (time-nanosecond t1) (time-nanosecond t2)))))
(define (time<=? t1 t2)
(or (< (time-second t1) (time-second t2))
(and (= (time-second t1) (time-second t2))
(<= (time-nanosecond t1) (time-nanosecond t2)))))
;; -- Time arithmetic
(define (time-difference! time1 time2)
(let ((sec-diff (- (time-second time1) (time-second time2)))
(nsec-diff (- (time-nanosecond time1) (time-nanosecond time2))))
(set-time-type! time1 time-duration)
(set-time-second! time1 sec-diff)
(set-time-nanosecond! time1 nsec-diff)
(time-normalize! time1)))
(define (time-difference time1 time2)
(let ((result (copy-time time1)))
(time-difference! result time2)))
(define (add-duration! t duration)
(if (not (eq? (time-type duration) time-duration))
(time-error 'add-duration 'not-duration duration)
(let ((sec-plus (+ (time-second t) (time-second duration)))
(nsec-plus (+ (time-nanosecond t) (time-nanosecond duration))))
(set-time-second! t sec-plus)
(set-time-nanosecond! t nsec-plus)
(time-normalize! t))))
(define (add-duration t duration)
(let ((result (copy-time t)))
(add-duration! result duration)))
(define (subtract-duration! t duration)
(if (not (eq? (time-type duration) time-duration))
(time-error 'add-duration 'not-duration duration)
(let ((sec-minus (- (time-second t) (time-second duration)))
(nsec-minus (- (time-nanosecond t) (time-nanosecond duration))))
(set-time-second! t sec-minus)
(set-time-nanosecond! t nsec-minus)
(time-normalize! t))))
(define (subtract-duration time1 duration)
(let ((result (copy-time time1)))
(subtract-duration! result duration)))
;; -- Converters between types.
(define (priv:time-tai->time-utc! time-in time-out caller)
(if (not (eq? (time-type time-in) time-tai))
(time-error caller 'incompatible-time-types time-in))
(set-time-type! time-out time-utc)
(set-time-nanosecond! time-out (time-nanosecond time-in))
(set-time-second! time-out (- (time-second time-in)
(leap-second-delta
(time-second time-in))))
time-out)
(define (time-tai->time-utc time-in)
(priv:time-tai->time-utc! time-in (make-time-unnormalized #f #f #f) 'time-tai->time-utc))
(define (time-tai->time-utc! time-in)
(priv:time-tai->time-utc! time-in time-in 'time-tai->time-utc!))
(define (priv:time-utc->time-tai! time-in time-out caller)
(if (not (eq? (time-type time-in) time-utc))
(time-error caller 'incompatible-time-types time-in))
(set-time-type! time-out time-tai)
(set-time-nanosecond! time-out (time-nanosecond time-in))
(set-time-second! time-out (+ (time-second time-in)
(leap-second-delta
(time-second time-in))))
time-out)
(define (time-utc->time-tai time-in)
(priv:time-utc->time-tai! time-in (make-time-unnormalized #f #f #f) 'time-utc->time-tai))
(define (time-utc->time-tai! time-in)
(priv:time-utc->time-tai! time-in time-in 'time-utc->time-tai!))
;; -- these depend on time-monotonic having the same definition as time-tai!
(define (time-monotonic->time-utc time-in)
(if (not (eq? (time-type time-in) time-monotonic))
(time-error 'time-monotonic->time-utc
'incompatible-time-types time-in))
(let ((ntime (copy-time time-in)))
(set-time-type! ntime time-tai)
(priv:time-tai->time-utc! ntime ntime 'time-monotonic->time-utc)))
(define (time-monotonic->time-utc! time-in)
(if (not (eq? (time-type time-in) time-monotonic))
(time-error 'time-monotonic->time-utc!
'incompatible-time-types time-in))
(set-time-type! time-in time-tai)
(priv:time-tai->time-utc! time-in time-in 'time-monotonic->time-utc))
(define (time-monotonic->time-tai time-in)
(if (not (eq? (time-type time-in) time-monotonic))
(time-error 'time-monotonic->time-tai
'incompatible-time-types time-in))
(let ((ntime (copy-time time-in)))
(set-time-type! ntime time-tai)
ntime))
(define (time-monotonic->time-tai! time-in)
(if (not (eq? (time-type time-in) time-monotonic))
(time-error 'time-monotonic->time-tai!
'incompatible-time-types time-in))
(set-time-type! time-in time-tai)
time-in)
(define (time-utc->time-monotonic time-in)
(if (not (eq? (time-type time-in) time-utc))
(time-error 'time-utc->time-monotonic
'incompatible-time-types time-in))
(let ((ntime (priv:time-utc->time-tai! time-in (make-time-unnormalized #f #f #f)
'time-utc->time-monotonic)))
(set-time-type! ntime time-monotonic)
ntime))
(define (time-utc->time-monotonic! time-in)
(if (not (eq? (time-type time-in) time-utc))
(time-error 'time-utc->time-monotonic!
'incompatible-time-types time-in))
(let ((ntime (priv:time-utc->time-tai! time-in time-in
'time-utc->time-monotonic!)))
(set-time-type! ntime time-monotonic)
ntime))
(define (time-tai->time-monotonic time-in)
(if (not (eq? (time-type time-in) time-tai))
(time-error 'time-tai->time-monotonic
'incompatible-time-types time-in))
(let ((ntime (copy-time time-in)))
(set-time-type! ntime time-monotonic)
ntime))
(define (time-tai->time-monotonic! time-in)
(if (not (eq? (time-type time-in) time-tai))
(time-error 'time-tai->time-monotonic!
'incompatible-time-types time-in))
(set-time-type! time-in time-monotonic)
time-in)
;; -- Date Structures
;; FIXME: to be really safe, perhaps we should normalize the
;; seconds/nanoseconds/minutes coming in to make-date...
(define-record-type date
(make-date nanosecond second minute
hour day month
year
zone-offset)
date?
(nanosecond date-nanosecond set-date-nanosecond!)
(second date-second set-date-second!)
(minute date-minute set-date-minute!)
(hour date-hour set-date-hour!)
(day date-day set-date-day!)
(month date-month set-date-month!)
(year date-year set-date-year!)
(zone-offset date-zone-offset set-date-zone-offset!))
;; gives the julian day which starts at noon.
(define (encode-julian-day-number day month year)
(let* ((a (quotient (- 14 month) 12))
(y (- (+ year 4800) a (if (negative? year) -1 0)))
(m (- (+ month (* 12 a)) 3)))
(+ day
(quotient (+ (* 153 m) 2) 5)
(* 365 y)
(quotient y 4)
(- (quotient y 100))
(quotient y 400)
-32045)))
;; gives the seconds/date/month/year
(define (decode-julian-day-number jdn)
(let* ((days (inexact->exact (truncate jdn)))
(a (+ days 32044))
(b (quotient (+ (* 4 a) 3) 146097))
(c (- a (quotient (* 146097 b) 4)))
(d (quotient (+ (* 4 c) 3) 1461))
(e (- c (quotient (* 1461 d) 4)))
(m (quotient (+ (* 5 e) 2) 153))
(y (+ (* 100 b) d -4800 (quotient m 10))))
(values ; seconds date month year
(* (- jdn days) sid)
(+ e (- (quotient (+ (* 153 m) 2) 5)) 1)
(+ m 3 (* -12 (quotient m 10)))
(if (>= 0 y) (- y 1) y))))
;; relies on the fact that we named our time zone accessor
;; differently from MzScheme's....
;; This should be written to be OS specific.
(define (local-tz-offset utc-time)
;; SRFI uses seconds West, but guile (and libc) use seconds East.
(- (tm:gmtoff (localtime (time-second utc-time)))))
;; special thing -- ignores nanos
(define (time->julian-day-number seconds tz-offset)
(+ (/ (+ seconds tz-offset sihd)
sid)
tai-epoch-in-jd))
(define (leap-second? second)
(and (assoc second leap-second-table) #t))
(define (time-utc->date time . tz-offset)
(if (not (eq? (time-type time) time-utc))
(time-error 'time->date 'incompatible-time-types time))
(let* ((offset (if (null? tz-offset)
(local-tz-offset time)
(car tz-offset)))
(leap-second? (leap-second? (+ offset (time-second time))))
(jdn (time->julian-day-number (if leap-second?
(- (time-second time) 1)
(time-second time))
offset)))
(call-with-values (lambda () (decode-julian-day-number jdn))
(lambda (secs date month year)
;; secs is a real because jdn is a real in Guile;
;; but it is conceptionally an integer.
(let* ((int-secs (inexact->exact (round secs)))
(hours (quotient int-secs (* 60 60)))
(rem (remainder int-secs (* 60 60)))
(minutes (quotient rem 60))
(seconds (remainder rem 60)))
(make-date (time-nanosecond time)
(if leap-second? (+ seconds 1) seconds)
minutes
hours
date
month
year
offset))))))
(define (time-tai->date time . tz-offset)
(if (not (eq? (time-type time) time-tai))
(time-error 'time->date 'incompatible-time-types time))
(let* ((offset (if (null? tz-offset)
(local-tz-offset (time-tai->time-utc time))
(car tz-offset)))
(seconds (- (time-second time)
(leap-second-delta (time-second time))))
(leap-second? (leap-second? (+ offset seconds)))
(jdn (time->julian-day-number (if leap-second?
(- seconds 1)
seconds)
offset)))
(call-with-values (lambda () (decode-julian-day-number jdn))
(lambda (secs date month year)
;; secs is a real because jdn is a real in Guile;
;; but it is conceptionally an integer.
;; adjust for leap seconds if necessary ...
(let* ((int-secs (inexact->exact (round secs)))
(hours (quotient int-secs (* 60 60)))
(rem (remainder int-secs (* 60 60)))
(minutes (quotient rem 60))
(seconds (remainder rem 60)))
(make-date (time-nanosecond time)
(if leap-second? (+ seconds 1) seconds)
minutes
hours
date
month
year
offset))))))
;; this is the same as time-tai->date.
(define (time-monotonic->date time . tz-offset)
(if (not (eq? (time-type time) time-monotonic))
(time-error 'time->date 'incompatible-time-types time))
(let* ((offset (if (null? tz-offset)
(local-tz-offset (time-monotonic->time-utc time))
(car tz-offset)))
(seconds (- (time-second time)
(leap-second-delta (time-second time))))
(leap-second? (leap-second? (+ offset seconds)))
(jdn (time->julian-day-number (if leap-second?
(- seconds 1)
seconds)
offset)))
(call-with-values (lambda () (decode-julian-day-number jdn))
(lambda (secs date month year)
;; secs is a real because jdn is a real in Guile;
;; but it is conceptionally an integer.
;; adjust for leap seconds if necessary ...
(let* ((int-secs (inexact->exact (round secs)))
(hours (quotient int-secs (* 60 60)))
(rem (remainder int-secs (* 60 60)))
(minutes (quotient rem 60))
(seconds (remainder rem 60)))
(make-date (time-nanosecond time)
(if leap-second? (+ seconds 1) seconds)
minutes
hours
date
month
year
offset))))))
(define (date->time-utc date)
(let* ((jdays (- (encode-julian-day-number (date-day date)
(date-month date)
(date-year date))
tai-epoch-in-jd))
;; jdays is an integer plus 1/2,
(jdays-1/2 (inexact->exact (- jdays 1/2))))
(make-time
time-utc
(date-nanosecond date)
(+ (* jdays-1/2 24 60 60)
(* (date-hour date) 60 60)
(* (date-minute date) 60)
(date-second date)
(- (date-zone-offset date))))))
(define (date->time-tai date)
(time-utc->time-tai! (date->time-utc date)))
(define (date->time-monotonic date)
(time-utc->time-monotonic! (date->time-utc date)))
(define (leap-year? year)
(or (= (modulo year 400) 0)
(and (= (modulo year 4) 0) (not (= (modulo year 100) 0)))))
;; Map 1-based month number M to number of days in the year before the
;; start of month M (in a non-leap year).
(define month-assoc '((1 . 0) (2 . 31) (3 . 59) (4 . 90)
(5 . 120) (6 . 151) (7 . 181) (8 . 212)
(9 . 243) (10 . 273) (11 . 304) (12 . 334)))
(define (year-day day month year)
(let ((days-pr (assoc month month-assoc)))
(if (not days-pr)
(time-error 'date-year-day 'invalid-month-specification month))
(if (and (leap-year? year) (> month 2))
(+ day (cdr days-pr) 1)
(+ day (cdr days-pr)))))
(define (date-year-day date)
(year-day (date-day date) (date-month date) (date-year date)))
;; from calendar faq
(define (week-day day month year)
(let* ((a (quotient (- 14 month) 12))
(y (- year a))
(m (+ month (* 12 a) -2)))
(modulo (+ day
y
(quotient y 4)
(- (quotient y 100))
(quotient y 400)
(quotient (* 31 m) 12))
7)))
(define (date-week-day date)
(week-day (date-day date) (date-month date) (date-year date)))
(define (days-before-first-week date day-of-week-starting-week)
(let* ((first-day (make-date 0 0 0 0
1
1
(date-year date)
#f))
(fdweek-day (date-week-day first-day)))
(modulo (- day-of-week-starting-week fdweek-day)
7)))
;; The "-1" here is a fix for the reference implementation, to make a new
;; week start on the given day-of-week-starting-week. date-year-day returns
;; a day starting from 1 for 1st Jan.
;;
(define (date-week-number date day-of-week-starting-week)
(quotient (- (date-year-day date)
1
(days-before-first-week date day-of-week-starting-week))
7))
(define (current-date . tz-offset)
(let ((time (current-time time-utc)))
(time-utc->date
time
(if (null? tz-offset)
(local-tz-offset time)
(car tz-offset)))))
;; given a 'two digit' number, find the year within 50 years +/-
(define (natural-year n)
(let* ((current-year (date-year (current-date)))
(current-century (* (quotient current-year 100) 100)))
(cond
((>= n 100) n)
((< n 0) n)
((<= (- (+ current-century n) current-year) 50) (+ current-century n))
(else (+ (- current-century 100) n)))))
(define (date->julian-day date)
(let ((nanosecond (date-nanosecond date))
(second (date-second date))
(minute (date-minute date))
(hour (date-hour date))
(day (date-day date))
(month (date-month date))
(year (date-year date))
(offset (date-zone-offset date)))
(+ (encode-julian-day-number day month year)
(- 1/2)
(+ (/ (+ (- offset)
(* hour 60 60)
(* minute 60)
second
(/ nanosecond nano))
sid)))))
(define (date->modified-julian-day date)
(- (date->julian-day date)
4800001/2))
(define (time-utc->julian-day time)
(if (not (eq? (time-type time) time-utc))
(time-error 'time->date 'incompatible-time-types time))
(+ (/ (+ (time-second time) (/ (time-nanosecond time) nano))
sid)
tai-epoch-in-jd))
(define (time-utc->modified-julian-day time)
(- (time-utc->julian-day time)
4800001/2))
(define (time-tai->julian-day time)
(if (not (eq? (time-type time) time-tai))
(time-error 'time->date 'incompatible-time-types time))
(+ (/ (+ (- (time-second time)
(leap-second-delta (time-second time)))
(/ (time-nanosecond time) nano))
sid)
tai-epoch-in-jd))
(define (time-tai->modified-julian-day time)
(- (time-tai->julian-day time)
4800001/2))
;; this is the same as time-tai->julian-day
(define (time-monotonic->julian-day time)
(if (not (eq? (time-type time) time-monotonic))
(time-error 'time->date 'incompatible-time-types time))
(+ (/ (+ (- (time-second time)
(leap-second-delta (time-second time)))
(/ (time-nanosecond time) nano))
sid)
tai-epoch-in-jd))
(define (time-monotonic->modified-julian-day time)
(- (time-monotonic->julian-day time)
4800001/2))
(define (julian-day->time-utc jdn)
(let ((secs (* sid (- jdn tai-epoch-in-jd))))
(receive (seconds parts)
(split-real secs)
(make-time time-utc
(* parts nano)
seconds))))
(define (julian-day->time-tai jdn)
(time-utc->time-tai! (julian-day->time-utc jdn)))
(define (julian-day->time-monotonic jdn)
(time-utc->time-monotonic! (julian-day->time-utc jdn)))
(define (julian-day->date jdn . tz-offset)
(let* ((time (julian-day->time-utc jdn))
(offset (if (null? tz-offset)
(local-tz-offset time)
(car tz-offset))))
(time-utc->date time offset)))
(define (modified-julian-day->date jdn . tz-offset)
(apply julian-day->date (+ jdn 4800001/2)
tz-offset))
(define (modified-julian-day->time-utc jdn)
(julian-day->time-utc (+ jdn 4800001/2)))
(define (modified-julian-day->time-tai jdn)
(julian-day->time-tai (+ jdn 4800001/2)))
(define (modified-julian-day->time-monotonic jdn)
(julian-day->time-monotonic (+ jdn 4800001/2)))
(define (current-julian-day)
(time-utc->julian-day (current-time time-utc)))
(define (current-modified-julian-day)
(time-utc->modified-julian-day (current-time time-utc)))
;; returns a string rep. of number N, of minimum LENGTH, padded with
;; character PAD-WITH. If PAD-WITH is #f, no padding is done, and it's
;; as if number->string was used. if string is longer than or equal
;; in length to LENGTH, it's as if number->string was used.
(define (padding n pad-with length)
(let* ((str (number->string n))
(str-len (string-length str)))
(if (or (>= str-len length)
(not pad-with))
str
(string-append (make-string (- length str-len) pad-with) str))))
(define (last-n-digits i n)
(abs (remainder i (expt 10 n))))
(define (locale-abbr-weekday n) (locale-day-short (+ 1 n)))
(define (locale-long-weekday n) (locale-day (+ 1 n)))
(define locale-abbr-month locale-month-short)
(define locale-long-month locale-month)
(define (date-reverse-lookup needle haystack-ref haystack-len
same?)
;; Lookup NEEDLE (a string) using HAYSTACK-REF (a one argument procedure
;; that returns a string corresponding to the given index) by passing it
;; indices lower than HAYSTACK-LEN.
(let loop ((index 1))
(cond ((> index haystack-len) #f)
((same? needle (haystack-ref index))
index)
(else (loop (+ index 1))))))
(define (locale-abbr-weekday->index string)
(date-reverse-lookup string locale-day-short 7 string=?))
(define (locale-long-weekday->index string)
(date-reverse-lookup string locale-day 7 string=?))
(define (locale-abbr-month->index string)
(date-reverse-lookup string locale-abbr-month 12 string=?))
(define (locale-long-month->index string)
(date-reverse-lookup string locale-long-month 12 string=?))
;; FIXME: mkoeppe: Put a symbolic time zone in the date structs.
;; Print it here instead of the numerical offset if available.
(define (locale-print-time-zone date port)
(tz-printer (date-zone-offset date) port))
(define (locale-am-string/pm hr)
(if (> hr 11) (locale-pm-string) (locale-am-string)))
(define (tz-printer offset port)
(cond
((= offset 0) (display "Z" port))
((negative? offset) (display "-" port))
(else (display "+" port)))
(if (not (= offset 0))
(let ((hours (abs (quotient offset (* 60 60))))
(minutes (abs (quotient (remainder offset (* 60 60)) 60))))
(display (padding hours #\0 2) port)
(display (padding minutes #\0 2) port))))
;; A table of output formatting directives.
;; the first time is the format char.
;; the second is a procedure that takes the date, a padding character
;; (which might be #f), and the output port.
;;
(define directives
(list
(cons #\~ (lambda (date pad-with port)
(display #\~ port)))
(cons #\a (lambda (date pad-with port)
(display (locale-abbr-weekday (date-week-day date))
port)))
(cons #\A (lambda (date pad-with port)
(display (locale-long-weekday (date-week-day date))
port)))
(cons #\b (lambda (date pad-with port)
(display (locale-abbr-month (date-month date))
port)))
(cons #\B (lambda (date pad-with port)
(display (locale-long-month (date-month date))
port)))
(cons #\c (lambda (date pad-with port)
(display (date->string date locale-date-time-format) port)))
(cons #\d (lambda (date pad-with port)
(display (padding (date-day date)
#\0 2)
port)))
(cons #\D (lambda (date pad-with port)
(display (date->string date "~m/~d/~y") port)))
(cons #\e (lambda (date pad-with port)
(display (padding (date-day date)
#\Space 2)
port)))
(cons #\f (lambda (date pad-with port)
(if (> (date-nanosecond date)
nano)
(display (padding (+ (date-second date) 1)
pad-with 2)
port)
(display (padding (date-second date)
pad-with 2)
port))
(receive (i f)
(split-real (/
(date-nanosecond date)
nano 1.0))
(let* ((ns (number->string f))
(le (string-length ns)))
(if (> le 2)
(begin
(display (locale-decimal-point) port)
(display (substring ns 2 le) port)))))))
(cons #\h (lambda (date pad-with port)
(display (date->string date "~b") port)))
(cons #\H (lambda (date pad-with port)
(display (padding (date-hour date)
pad-with 2)
port)))
(cons #\I (lambda (date pad-with port)
(let ((hr (date-hour date)))
(if (> hr 12)
(display (padding (- hr 12)
pad-with 2)
port)
(display (padding hr
pad-with 2)
port)))))
(cons #\j (lambda (date pad-with port)
(display (padding (date-year-day date)
pad-with 3)
port)))
(cons #\k (lambda (date pad-with port)
(display (padding (date-hour date)
#\Space 2)
port)))
(cons #\l (lambda (date pad-with port)
(let ((hr (if (> (date-hour date) 12)
(- (date-hour date) 12) (date-hour date))))
(display (padding hr #\Space 2)
port))))
(cons #\m (lambda (date pad-with port)
(display (padding (date-month date)
pad-with 2)
port)))
(cons #\M (lambda (date pad-with port)
(display (padding (date-minute date)
pad-with 2)
port)))
(cons #\n (lambda (date pad-with port)
(newline port)))
(cons #\N (lambda (date pad-with port)
(display (padding (date-nanosecond date)
pad-with 7)
port)))
(cons #\p (lambda (date pad-with port)
(display (locale-am-string/pm (date-hour date)) port)))
(cons #\r (lambda (date pad-with port)
(display (date->string date "~I:~M:~S ~p") port)))
(cons #\s (lambda (date pad-with port)
(display (time-second (date->time-utc date)) port)))
(cons #\S (lambda (date pad-with port)
(if (> (date-nanosecond date)
nano)
(display (padding (+ (date-second date) 1)
pad-with 2)
port)
(display (padding (date-second date)
pad-with 2)
port))))
(cons #\t (lambda (date pad-with port)
(display #\Tab port)))
(cons #\T (lambda (date pad-with port)
(display (date->string date "~H:~M:~S") port)))
(cons #\U (lambda (date pad-with port)
(if (> (days-before-first-week date 0) 0)
(display (padding (+ (date-week-number date 0) 1)
#\0 2) port)
(display (padding (date-week-number date 0)
#\0 2) port))))
(cons #\V (lambda (date pad-with port)
(display (padding (date-week-number date 1)
#\0 2) port)))
(cons #\w (lambda (date pad-with port)
(display (date-week-day date) port)))
(cons #\x (lambda (date pad-with port)
(display (date->string date locale-short-date-format) port)))
(cons #\X (lambda (date pad-with port)
(display (date->string date locale-time-format) port)))
(cons #\W (lambda (date pad-with port)
(if (> (days-before-first-week date 1) 0)
(display (padding (+ (date-week-number date 1) 1)
#\0 2) port)
(display (padding (date-week-number date 1)
#\0 2) port))))
(cons #\y (lambda (date pad-with port)
(display (padding (last-n-digits
(date-year date) 2)
pad-with
2)
port)))
(cons #\Y (lambda (date pad-with port)
(display (date-year date) port)))
(cons #\z (lambda (date pad-with port)
(tz-printer (date-zone-offset date) port)))
(cons #\Z (lambda (date pad-with port)
(locale-print-time-zone date port)))
(cons #\1 (lambda (date pad-with port)
(display (date->string date "~Y-~m-~d") port)))
(cons #\2 (lambda (date pad-with port)
(display (date->string date "~H:~M:~S~z") port)))
(cons #\3 (lambda (date pad-with port)
(display (date->string date "~H:~M:~S") port)))
(cons #\4 (lambda (date pad-with port)
(display (date->string date "~Y-~m-~dT~H:~M:~S~z") port)))
(cons #\5 (lambda (date pad-with port)
(display (date->string date "~Y-~m-~dT~H:~M:~S") port)))))
(define (get-formatter char)
(let ((associated (assoc char directives)))
(if associated (cdr associated) #f)))
(define (date-printer date index format-string str-len port)
(if (< index str-len)
(let ((current-char (string-ref format-string index)))
(if (not (char=? current-char #\~))
(begin
(display current-char port)
(date-printer date (+ index 1) format-string str-len port))
(if (= (+ index 1) str-len) ; bad format string.
(time-error 'date-printer 'bad-date-format-string
format-string)
(let ((pad-char? (string-ref format-string (+ index 1))))
(cond
((char=? pad-char? #\-)
(if (= (+ index 2) str-len) ; bad format string.
(time-error 'date-printer
'bad-date-format-string
format-string)
(let ((formatter (get-formatter
(string-ref format-string
(+ index 2)))))
(if (not formatter)
(time-error 'date-printer
'bad-date-format-string
format-string)
(begin
(formatter date #f port)
(date-printer date
(+ index 3)
format-string
str-len
port))))))
((char=? pad-char? #\_)
(if (= (+ index 2) str-len) ; bad format string.
(time-error 'date-printer
'bad-date-format-string
format-string)
(let ((formatter (get-formatter
(string-ref format-string
(+ index 2)))))
(if (not formatter)
(time-error 'date-printer
'bad-date-format-string
format-string)
(begin
(formatter date #\Space port)
(date-printer date
(+ index 3)
format-string
str-len
port))))))
(else
(let ((formatter (get-formatter
(string-ref format-string
(+ index 1)))))
(if (not formatter)
(time-error 'date-printer
'bad-date-format-string
format-string)
(begin
(formatter date #\0 port)
(date-printer date
(+ index 2)
format-string
str-len
port))))))))))))
(define (date->string date . format-string)
(let ((str-port (open-output-string))
(fmt-str (if (null? format-string) "~c" (car format-string))))
(date-printer date 0 fmt-str (string-length fmt-str) str-port)
(get-output-string str-port)))
(define (char->int ch)
(case ch
((#\0) 0)
((#\1) 1)
((#\2) 2)
((#\3) 3)
((#\4) 4)
((#\5) 5)
((#\6) 6)
((#\7) 7)
((#\8) 8)
((#\9) 9)
(else (time-error 'char->int 'bad-date-template-string
(list "Non-integer character" ch)))))
;; read an integer upto n characters long on port; upto -> #f is any length
(define (integer-reader upto port)
(let loop ((accum 0) (nchars 0))
(let ((ch (peek-char port)))
(if (or (eof-object? ch)
(not (char-numeric? ch))
(and upto (>= nchars upto)))
accum
(loop (+ (* accum 10) (char->int (read-char port)))
(+ nchars 1))))))
(define (make-integer-reader upto)
(lambda (port)
(integer-reader upto port)))
;; read *exactly* n characters and convert to integer; could be padded
(define (integer-reader-exact n port)
(let ((padding-ok #t))
(define (accum-int port accum nchars)
(let ((ch (peek-char port)))
(cond
((>= nchars n) accum)
((eof-object? ch)
(time-error 'string->date 'bad-date-template-string
"Premature ending to integer read."))
((char-numeric? ch)
(set! padding-ok #f)
(accum-int port
(+ (* accum 10) (char->int (read-char port)))
(+ nchars 1)))
(padding-ok
(read-char port) ; consume padding
(accum-int port accum (+ nchars 1)))
(else ; padding where it shouldn't be
(time-error 'string->date 'bad-date-template-string
"Non-numeric characters in integer read.")))))
(accum-int port 0 0)))
(define (make-integer-exact-reader n)
(lambda (port)
(integer-reader-exact n port)))
(define (zone-reader port)
(let ((offset 0)
(positive? #f))
(let ((ch (read-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone +/-" ch)))
(if (or (char=? ch #\Z) (char=? ch #\z))
0
(begin
(cond
((char=? ch #\+) (set! positive? #t))
((char=? ch #\-) (set! positive? #f))
(else
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone +/-" ch))))
(let ((ch (read-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone number" ch)))
(set! offset (* (char->int ch)
10 60 60)))
(let ((ch (read-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone number" ch)))
(set! offset (+ offset (* (char->int ch)
60 60))))
(let ((ch (read-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone number" ch)))
(set! offset (+ offset (* (char->int ch)
10 60))))
(let ((ch (read-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-template-string
(list "Invalid time zone number" ch)))
(set! offset (+ offset (* (char->int ch)
60))))
(if positive? offset (- offset)))))))
;; looking at a char, read the char string, run thru indexer, return index
(define (locale-reader port indexer)
(define (read-char-string result)
(let ((ch (peek-char port)))
(if (char-alphabetic? ch)
(read-char-string (cons (read-char port) result))
(list->string (reverse! result)))))
(let* ((str (read-char-string '()))
(index (indexer str)))
(if index index (time-error 'string->date
'bad-date-template-string
(list "Invalid string for " indexer)))))
(define (make-locale-reader indexer)
(lambda (port)
(locale-reader port indexer)))
(define (make-char-id-reader char)
(lambda (port)
(if (char=? char (read-char port))
char
(time-error 'string->date
'bad-date-template-string
"Invalid character match."))))
;; A List of formatted read directives.
;; Each entry is a list.
;; 1. the character directive;
;; a procedure, which takes a character as input & returns
;; 2. #t as soon as a character on the input port is acceptable
;; for input,
;; 3. a port reader procedure that knows how to read the current port
;; for a value. Its one parameter is the port.
;; 4. an optional action procedure, that takes the value (from 3.) and
;; some object (here, always the date) and (probably) side-effects it.
;; If no action is required, as with ~A, this element may be #f.
(define read-directives
(let ((ireader4 (make-integer-reader 4))
(ireader2 (make-integer-reader 2))
(eireader2 (make-integer-exact-reader 2))
(locale-reader-abbr-weekday (make-locale-reader
locale-abbr-weekday->index))
(locale-reader-long-weekday (make-locale-reader
locale-long-weekday->index))
(locale-reader-abbr-month (make-locale-reader
locale-abbr-month->index))
(locale-reader-long-month (make-locale-reader
locale-long-month->index))
(char-fail (lambda (ch) #t)))
(list
(list #\~ char-fail (make-char-id-reader #\~) #f)
(list #\a char-alphabetic? locale-reader-abbr-weekday #f)
(list #\A char-alphabetic? locale-reader-long-weekday #f)
(list #\b char-alphabetic? locale-reader-abbr-month
(lambda (val object)
(set-date-month! object val)))
(list #\B char-alphabetic? locale-reader-long-month
(lambda (val object)
(set-date-month! object val)))
(list #\d char-numeric? ireader2 (lambda (val object)
(set-date-day!
object val)))
(list #\e char-fail eireader2 (lambda (val object)
(set-date-day! object val)))
(list #\h char-alphabetic? locale-reader-abbr-month
(lambda (val object)
(set-date-month! object val)))
(list #\H char-numeric? ireader2 (lambda (val object)
(set-date-hour! object val)))
(list #\k char-fail eireader2 (lambda (val object)
(set-date-hour! object val)))
(list #\m char-numeric? ireader2 (lambda (val object)
(set-date-month! object val)))
(list #\M char-numeric? ireader2 (lambda (val object)
(set-date-minute!
object val)))
(list #\S char-numeric? ireader2 (lambda (val object)
(set-date-second! object val)))
(list #\y char-fail eireader2
(lambda (val object)
(set-date-year! object (natural-year val))))
(list #\Y char-numeric? ireader4 (lambda (val object)
(set-date-year! object val)))
(list #\z (lambda (c)
(or (char=? c #\Z)
(char=? c #\z)
(char=? c #\+)
(char=? c #\-)))
zone-reader (lambda (val object)
(set-date-zone-offset! object val))))))
(define (priv:string->date date index format-string str-len port template-string)
(define (skip-until port skipper)
(let ((ch (peek-char port)))
(if (eof-object? ch)
(time-error 'string->date 'bad-date-format-string template-string)
(if (not (skipper ch))
(begin (read-char port) (skip-until port skipper))))))
(if (< index str-len)
(let ((current-char (string-ref format-string index)))
(if (not (char=? current-char #\~))
(let ((port-char (read-char port)))
(if (or (eof-object? port-char)
(not (char=? current-char port-char)))
(time-error 'string->date
'bad-date-format-string template-string))
(priv:string->date date
(+ index 1)
format-string
str-len
port
template-string))
;; otherwise, it's an escape, we hope
(if (> (+ index 1) str-len)
(time-error 'string->date
'bad-date-format-string template-string)
(let* ((format-char (string-ref format-string (+ index 1)))
(format-info (assoc format-char read-directives)))
(if (not format-info)
(time-error 'string->date
'bad-date-format-string template-string)
(begin
(let ((skipper (cadr format-info))
(reader (caddr format-info))
(actor (cadddr format-info)))
(skip-until port skipper)
(let ((val (reader port)))
(if (eof-object? val)
(time-error 'string->date
'bad-date-format-string
template-string)
(if actor (actor val date))))
(priv:string->date date
(+ index 2)
format-string
str-len
port
template-string))))))))))
(define (string->date input-string template-string)
(define (date-ok? date)
(and (date-nanosecond date)
(date-second date)
(date-minute date)
(date-hour date)
(date-day date)
(date-month date)
(date-year date)
(date-zone-offset date)))
(let ((newdate (make-date 0 0 0 0 #f #f #f #f)))
(priv:string->date newdate
0
template-string
(string-length template-string)
(open-input-string input-string)
template-string)
(if (not (date-zone-offset newdate))
(begin
;; this is necessary to get DST right -- as far as we can
;; get it right (think of the double/missing hour in the
;; night when we are switching between normal time and DST).
(set-date-zone-offset! newdate
(local-tz-offset
(make-time time-utc 0 0)))
(set-date-zone-offset! newdate
(local-tz-offset
(date->time-utc newdate)))))
(if (date-ok? newdate)
newdate
(time-error
'string->date
'bad-date-format-string
(list "Incomplete date read. " newdate template-string)))))
;;; srfi-19.scm ends here
;;; srfi-2.scm --- and-let*
;; Copyright (C) 2001, 2002, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-2)
\:use-module (ice-9 and-let-star)
\:re-export-syntax (and-let*))
(cond-expand-provide (current-module) '(srfi-2))
;;; srfi-2.scm ends here
;;; srfi-26.scm --- specializing parameters without currying.
;; Copyright (C) 2002, 2006, 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (srfi srfi-26)
\:export (cut cute))
(cond-expand-provide (current-module) '(srfi-26))
(define-syntax cut
(lambda (stx)
(syntax-case stx ()
((cut slot0 slot1+ ...)
(let loop ((slots #'(slot0 slot1+ ...))
(params '())
(args '()))
(if (null? slots)
#`(lambda #,(reverse params) #,(reverse args))
(let ((s (car slots))
(rest (cdr slots)))
(with-syntax (((var) (generate-temporaries '(var))))
(syntax-case s (<> <___>)
(<>
(loop rest (cons #'var params) (cons #'var args)))
(<___>
(if (pair? rest)
(error "<___> not on the end of cut expression"))
#`(lambda #,(append (reverse params) #'var)
(apply #,@(reverse (cons #'var args)))))
(else
(loop rest params (cons s args))))))))))))
(define-syntax cute
(lambda (stx)
(syntax-case stx ()
((cute slots ...)
(let loop ((slots #'(slots ...))
(bindings '())
(arguments '()))
(define (process-hole)
(loop (cdr slots) bindings (cons (car slots) arguments)))
(if (null? slots)
#`(let #,bindings
(cut #,@(reverse arguments)))
(syntax-case (car slots) (<> <___>)
(<> (process-hole))
(<___> (process-hole))
(expr
(with-syntax (((t) (generate-temporaries '(t))))
(loop (cdr slots)
(cons #'(t expr) bindings)
(cons #'t arguments)))))))))))
;;; srfi-27.scm --- Sources of Random Bits
;; Copyright (C) 2010 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;; This library 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
;; Lesser General Public License for more details.
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library. If not, see
;; <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-27)
#\export (random-integer
random-real
default-random-source
make-random-source
random-source?
random-source-state-ref
random-source-state-set!
random-source-randomize!
random-source-pseudo-randomize!
random-source-make-integers
random-source-make-reals)
#\use-module (srfi srfi-9))
(cond-expand-provide (current-module) '(srfi-27))
(define-record-type \:random-source
(%make-random-source state)
random-source?
(state random-source-state set-random-source-state!))
(define (make-random-source)
(%make-random-source (seed->random-state 0)))
(define (random-source-state-ref s)
(random-state->datum (random-source-state s)))
(define (random-source-state-set! s state)
(set-random-source-state! s (datum->random-state state)))
(define (random-source-randomize! s)
(let ((time (gettimeofday)))
(set-random-source-state! s (seed->random-state
(+ (* (car time) 1e6) (cdr time))))))
(define (random-source-pseudo-randomize! s i j)
(set-random-source-state! s (seed->random-state (i+j->seed i j))))
(define (i+j->seed i j)
(logior (ash (spread i 2) 1)
(spread j 2)))
(define (spread n amount)
(let loop ((result 0) (n n) (shift 0))
(if (zero? n)
result
(loop (logior result
(ash (logand n 1) shift))
(ash n -1)
(+ shift amount)))))
(define (random-source-make-integers s)
(lambda (n)
(random n (random-source-state s))))
(define random-source-make-reals
(case-lambda
((s)
(lambda ()
(let loop ()
(let ((x (random:uniform (random-source-state s))))
(if (zero? x)
(loop)
x)))))
((s unit)
(or (and (real? unit) (< 0 unit 1))
(error "unit must be real between 0 and 1" unit))
(random-source-make-reals s))))
(define default-random-source (make-random-source))
(define random-integer (random-source-make-integers default-random-source))
(define random-real (random-source-make-reals default-random-source))
;;; srfi-28.scm --- Basic Format Strings
;; Copyright (C) 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module provides a wrapper for simple-format that always outputs
;; to a string.
;;
;; This module is documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-28)
#\replace (format))
(define (format message . args)
(apply simple-format #f message args))
(cond-expand-provide (current-module) '(srfi-28))
;;; srfi-31.scm --- special form for recursive evaluation
;; Copyright (C) 2004, 2006, 2012 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Original author: Rob Browning <rlb@defaultvalue.org>
(define-module (srfi srfi-31)
#\export (rec))
(cond-expand-provide (current-module) '(srfi-31))
(define-syntax rec
(syntax-rules ()
"Return the given object, defined in a lexical environment where
NAME is bound to itself."
((_ (name . formals) body ...) ; procedure
(letrec ((name (lambda formals body ...)))
name))
((_ name expr) ; arbitrary object
(letrec ((name expr))
name))))
;;; srfi-34.scm --- Exception handling for programs
;; Copyright (C) 2003, 2006, 2008, 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Neil Jerram <neil@ossau.uklinux.net>
;;; Commentary:
;; This is an implementation of SRFI-34: Exception Handling for
;; Programs. For documentation please see the SRFI-34 document; this
;; module is not yet documented at all in the Guile manual.
;;; Code:
(define-module (srfi srfi-34)
#\export (with-exception-handler)
#\replace (raise)
#\export-syntax (guard))
(cond-expand-provide (current-module) '(srfi-34))
(define throw-key 'srfi-34)
(define (with-exception-handler handler thunk)
"Returns the result(s) of invoking THUNK. HANDLER must be a
procedure that accepts one argument. It is installed as the current
exception handler for the dynamic extent (as determined by
dynamic-wind) of the invocation of THUNK."
(with-throw-handler throw-key
thunk
(lambda (key obj)
(handler obj))))
(define (raise obj)
"Invokes the current exception handler on OBJ. The handler is
called in the dynamic environment of the call to raise, except that
the current exception handler is that in place for the call to
with-exception-handler that installed the handler being called. The
handler's continuation is otherwise unspecified."
(throw throw-key obj))
(define-syntax guard
(syntax-rules (else)
"Syntax: (guard (<var> <clause1> <clause2> ...) <body>)
Each <clause> should have the same form as a `cond' clause.
Semantics: Evaluating a guard form evaluates <body> with an exception
handler that binds the raised object to <var> and within the scope of
that binding evaluates the clauses as if they were the clauses of a
cond expression. That implicit cond expression is evaluated with the
continuation and dynamic environment of the guard expression. If
every <clause>'s <test> evaluates to false and there is no else
clause, then raise is re-invoked on the raised object within the
dynamic environment of the original call to raise except that the
current exception handler is that of the guard expression."
((guard (var clause ... (else e e* ...)) body body* ...)
(catch throw-key
(lambda () body body* ...)
(lambda (key var)
(cond clause ...
(else e e* ...)))))
((guard (var clause clause* ...) body body* ...)
(catch throw-key
(lambda () body body* ...)
(lambda (key var)
(cond clause clause* ...
(else (throw key var))))))))
;;; (srfi srfi-34) ends here.
;;; srfi-35.scm --- Conditions -*- coding: utf-8 -*-
;; Copyright (C) 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;; This is an implementation of SRFI-35, "Conditions". Conditions are a
;; means to convey information about exceptional conditions between parts of
;; a program.
;;; Code:
(define-module (srfi srfi-35)
#\use-module (srfi srfi-1)
#\export (make-condition-type condition-type?
make-condition condition? condition-has-type? condition-ref
make-compound-condition extract-condition
define-condition-type condition
&condition
&message message-condition? condition-message
&serious serious-condition?
&error error?))
(cond-expand-provide (current-module) '(srfi-35))
;;;
;;; Condition types.
;;;
(define %condition-type-vtable
;; The vtable of all condition types.
;; vtable fields: vtable, self, printer
;; user fields: id, parent, all-field-names
(let ((s (make-vtable (string-append standard-vtable-fields "prprpr")
(lambda (ct port)
(format port "#<condition-type ~a ~a>"
(condition-type-id ct)
(number->string (object-address ct)
16))))))
(set-struct-vtable-name! s 'condition-type)
s))
(define (%make-condition-type layout id parent all-fields)
(let ((struct (make-struct %condition-type-vtable 0
(make-struct-layout layout) ;; layout
print-condition ;; printer
id parent all-fields)))
;; Hack to associate STRUCT with a name, providing a better name for
;; GOOPS classes as returned by `class-of' et al.
(set-struct-vtable-name! struct (cond ((symbol? id) id)
((string? id) (string->symbol id))
(else (string->symbol ""))))
struct))
(define (condition-type? obj)
"Return true if OBJ is a condition type."
(and (struct? obj)
(eq? (struct-vtable obj)
%condition-type-vtable)))
(define (condition-type-id ct)
(and (condition-type? ct)
(struct-ref ct (+ vtable-offset-user 0))))
(define (condition-type-parent ct)
(and (condition-type? ct)
(struct-ref ct (+ vtable-offset-user 1))))
(define (condition-type-all-fields ct)
(and (condition-type? ct)
(struct-ref ct (+ vtable-offset-user 2))))
(define (struct-layout-for-condition field-names)
;; Return a string denoting the layout required to hold the fields listed
;; in FIELD-NAMES.
(let loop ((field-names field-names)
(layout '("pr")))
(if (null? field-names)
(string-concatenate/shared layout)
(loop (cdr field-names)
(cons "pr" layout)))))
(define (print-condition c port)
;; Print condition C to PORT in a way similar to how records print:
;; #<condition TYPE [FIELD: VALUE ...] ADDRESS>.
(define (field-values)
(let* ((type (struct-vtable c))
(strings (fold (lambda (field result)
(cons (format #f "~A: ~S" field
(condition-ref c field))
result))
'()
(condition-type-all-fields type))))
(string-join (reverse strings) " ")))
(format port "#<condition ~a [~a] ~a>"
(condition-type-id (condition-type c))
(field-values)
(number->string (object-address c) 16)))
(define (make-condition-type id parent field-names)
"Return a new condition type named ID, inheriting from PARENT, and with the
fields whose names are listed in FIELD-NAMES. FIELD-NAMES must be a list of
symbols and must not contain names already used by PARENT or one of its
supertypes."
(if (symbol? id)
(if (condition-type? parent)
(let ((parent-fields (condition-type-all-fields parent)))
(if (and (every symbol? field-names)
(null? (lset-intersection eq?
field-names parent-fields)))
(let* ((all-fields (append parent-fields field-names))
(layout (struct-layout-for-condition all-fields)))
(%make-condition-type layout
id parent all-fields))
(error "invalid condition type field names"
field-names)))
(error "parent is not a condition type" parent))
(error "condition type identifier is not a symbol" id)))
(define (make-compound-condition-type id parents)
;; Return a compound condition type made of the types listed in PARENTS.
;; All fields from PARENTS are kept, even same-named ones, since they are
;; needed by `extract-condition'.
(cond ((null? parents)
(error "`make-compound-condition-type' passed empty parent list"
id))
((null? (cdr parents))
(car parents))
(else
(let* ((all-fields (append-map condition-type-all-fields
parents))
(layout (struct-layout-for-condition all-fields)))
(%make-condition-type layout
id
parents ;; list of parents!
all-fields)))))
;;;
;;; Conditions.
;;;
(define (condition? c)
"Return true if C is a condition."
(and (struct? c)
(condition-type? (struct-vtable c))))
(define (condition-type c)
(and (struct? c)
(let ((vtable (struct-vtable c)))
(if (condition-type? vtable)
vtable
#f))))
(define (condition-has-type? c type)
"Return true if condition C has type TYPE."
(if (and (condition? c) (condition-type? type))
(let loop ((ct (condition-type c)))
(or (eq? ct type)
(and ct
(let ((parent (condition-type-parent ct)))
(if (list? parent)
(any loop parent) ;; compound condition
(loop (condition-type-parent ct)))))))
(throw 'wrong-type-arg "condition-has-type?"
"Wrong type argument")))
(define (condition-ref c field-name)
"Return the value of the field named FIELD-NAME from condition C."
(if (condition? c)
(if (symbol? field-name)
(let* ((type (condition-type c))
(fields (condition-type-all-fields type))
(index (list-index (lambda (name)
(eq? name field-name))
fields)))
(if index
(struct-ref c index)
(error "invalid field name" field-name)))
(error "field name is not a symbol" field-name))
(throw 'wrong-type-arg "condition-ref"
"Wrong type argument: ~S" c)))
(define (make-condition-from-values type values)
(apply make-struct type 0 values))
(define (make-condition type . field+value)
"Return a new condition of type TYPE with fields initialized as specified
by FIELD+VALUE, a sequence of field names (symbols) and values."
(if (condition-type? type)
(let* ((all-fields (condition-type-all-fields type))
(inits (fold-right (lambda (field inits)
(let ((v (memq field field+value)))
(if (pair? v)
(cons (cadr v) inits)
(error "field not specified"
field))))
'()
all-fields)))
(make-condition-from-values type inits))
(throw 'wrong-type-arg "make-condition"
"Wrong type argument: ~S" type)))
(define (make-compound-condition . conditions)
"Return a new compound condition composed of CONDITIONS."
(let* ((types (map condition-type conditions))
(ct (make-compound-condition-type 'compound types))
(inits (append-map (lambda (c)
(let ((ct (condition-type c)))
(map (lambda (f)
(condition-ref c f))
(condition-type-all-fields ct))))
conditions)))
(make-condition-from-values ct inits)))
(define (extract-condition c type)
"Return a condition of condition type TYPE with the field values specified
by C."
(define (first-field-index parents)
;; Return the index of the first field of TYPE within C.
(let loop ((parents parents)
(index 0))
(let ((parent (car parents)))
(cond ((null? parents)
#f)
((eq? parent type)
index)
((pair? parent)
(or (loop parent index)
(loop (cdr parents)
(+ index
(apply + (map condition-type-all-fields
parent))))))
(else
(let ((shift (length (condition-type-all-fields parent))))
(loop (cdr parents)
(+ index shift))))))))
(define (list-fields start-index field-names)
;; Return a list of the form `(FIELD-NAME VALUE...)'.
(let loop ((index start-index)
(field-names field-names)
(result '()))
(if (null? field-names)
(reverse! result)
(loop (+ 1 index)
(cdr field-names)
(cons* (struct-ref c index)
(car field-names)
result)))))
(if (and (condition? c) (condition-type? type))
(let* ((ct (condition-type c))
(parent (condition-type-parent ct)))
(cond ((eq? type ct)
c)
((pair? parent)
;; C is a compound condition.
(let ((field-index (first-field-index parent)))
;;(format #t "field-index: ~a ~a~%" field-index
;; (list-fields field-index
;; (condition-type-all-fields type)))
(apply make-condition type
(list-fields field-index
(condition-type-all-fields type)))))
(else
;; C does not have type TYPE.
#f)))
(throw 'wrong-type-arg "extract-condition"
"Wrong type argument")))
;;;
;;; Syntax.
;;;
(define-syntax-rule (define-condition-type name parent pred (field-name field-accessor) ...)
(begin
(define name
(make-condition-type 'name parent '(field-name ...)))
(define (pred c)
(condition-has-type? c name))
(define (field-accessor c)
(condition-ref c 'field-name))
...))
(define-syntax-rule (compound-condition (type ...) (field ...))
;; Create a compound condition using `make-compound-condition-type'.
(condition ((make-compound-condition-type '%compound `(,type ...))
field ...)))
(define-syntax condition-instantiation
;; Build the `(make-condition type ...)' call.
(syntax-rules ()
((_ type (out ...))
(make-condition type out ...))
((_ type (out ...) (field-name field-value) rest ...)
(condition-instantiation type (out ... 'field-name field-value) rest ...))))
(define-syntax condition
(syntax-rules ()
((_ (type field ...))
(condition-instantiation type () field ...))
((_ (type field ...) ...)
(compound-condition (type ...) (field ... ...)))))
;;;
;;; Standard condition types.
;;;
(define &condition
;; The root condition type.
(make-struct %condition-type-vtable 0
(make-struct-layout "")
(lambda (c port)
(display "<&condition>"))
'&condition #f '() '()))
(define-condition-type &message &condition
message-condition?
(message condition-message))
(define-condition-type &serious &condition
serious-condition?)
(define-condition-type &error &serious
error?)
;;; srfi-35.scm ends here
;;; srfi-37.scm --- args-fold
;; Copyright (C) 2007, 2008, 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;;
;; To use this module with Guile, use (cdr (program-arguments)) as
;; the ARGS argument to `args-fold'. Here is a short example:
;;
;; (args-fold (cdr (program-arguments))
;; (let ((display-and-exit-proc
;; (lambda (msg)
;; (lambda (opt name arg)
;; (display msg) (quit) (values)))))
;; (list (option '(#\v "version") #f #f
;; (display-and-exit-proc "Foo version 42.0\n"))
;; (option '(#\h "help") #f #f
;; (display-and-exit-proc
;; "Usage: foo scheme-file ..."))))
;; (lambda (opt name arg)
;; (error "Unrecognized option `~A'" name))
;; (lambda (op) (load op) (values)))
;;
;;; Code:
;;;; Module definition & exports
(define-module (srfi srfi-37)
#\use-module (srfi srfi-9)
#\export (option option-names option-required-arg?
option-optional-arg? option-processor
args-fold))
(cond-expand-provide (current-module) '(srfi-37))
;;;; args-fold and periphery procedures
;;; An option as answered by `option'. `names' is a list of
;;; characters and strings, representing associated short-options and
;;; long-options respectively that should use this option's
;;; `processor' in an `args-fold' call.
;;;
;;; `required-arg?' and `optional-arg?' are mutually exclusive
;;; booleans and indicate whether an argument must be or may be
;;; provided. Besides the obvious, this affects semantics of
;;; short-options, as short-options with a required or optional
;;; argument cannot be followed by other short options in the same
;;; program-arguments string, as they will be interpreted collectively
;;; as the option's argument.
;;;
;;; `processor' is called when this option is encountered. It should
;;; accept the containing option, the element of `names' (by `equal?')
;;; encountered, the option's argument (or #f if none), and the seeds
;;; as variadic arguments, answering the new seeds as values.
(define-record-type srfi-37:option
(option names required-arg? optional-arg? processor)
option?
(names option-names)
(required-arg? option-required-arg?)
(optional-arg? option-optional-arg?)
(processor option-processor))
(define (error-duplicate-option option-name)
(scm-error 'program-error "args-fold"
"Duplicate option name `~A~A'"
(list (if (char? option-name) #\- "--")
option-name)
#f))
(define (build-options-lookup options)
"Answer an `equal?' Guile hash-table that maps OPTIONS' names back
to the containing options, signalling an error if a name is
encountered more than once."
(let ((lookup (make-hash-table (* 2 (length options)))))
(for-each
(lambda (opt)
(for-each (lambda (name)
(let ((assoc (hash-create-handle!
lookup name #f)))
(if (cdr assoc)
(error-duplicate-option (car assoc))
(set-cdr! assoc opt))))
(option-names opt)))
options)
lookup))
(define (args-fold args options unrecognized-option-proc
operand-proc . seeds)
"Answer the results of folding SEEDS as multiple values against the
program-arguments in ARGS, as decided by the OPTIONS'
`option-processor's, UNRECOGNIZED-OPTION-PROC, and OPERAND-PROC."
(let ((lookup (build-options-lookup options)))
;; I don't like Guile's `error' here
(define (error msg . args)
(scm-error 'misc-error "args-fold" msg args #f))
(define (mutate-seeds! procedure . params)
(set! seeds (call-with-values
(lambda ()
(apply procedure (append params seeds)))
list)))
;; Clean up the rest of ARGS, assuming they're all operands.
(define (rest-operands)
(for-each (lambda (arg) (mutate-seeds! operand-proc arg))
args)
(set! args '()))
;; Call OPT's processor with OPT, NAME, an argument to be decided,
;; and the seeds. Depending on OPT's *-arg? specification, get
;; the parameter by calling REQ-ARG-PROC or OPT-ARG-PROC thunks;
;; if no argument is allowed, call NO-ARG-PROC thunk.
(define (invoke-option-processor
opt name req-arg-proc opt-arg-proc no-arg-proc)
(mutate-seeds!
(option-processor opt) opt name
(cond ((option-required-arg? opt) (req-arg-proc))
((option-optional-arg? opt) (opt-arg-proc))
(else (no-arg-proc) #f))))
;; Compute and answer a short option argument, advancing ARGS as
;; necessary, for the short option whose character is at POSITION
;; in the current ARG.
(define (short-option-argument position)
(cond ((< (1+ position) (string-length (car args)))
(let ((result (substring (car args) (1+ position))))
(set! args (cdr args))
result))
((pair? (cdr args))
(let ((result (cadr args)))
(set! args (cddr args))
result))
((pair? args)
(set! args (cdr args))
#f)
(else #f)))
;; Interpret the short-option at index POSITION in (car ARGS),
;; followed by the remaining short options in (car ARGS).
(define (short-option position)
(if (>= position (string-length (car args)))
(begin
(set! args (cdr args))
(next-arg))
(let* ((opt-name (string-ref (car args) position))
(option-here (hash-ref lookup opt-name)))
(cond ((not option-here)
(mutate-seeds! unrecognized-option-proc
(option (list opt-name) #f #f
unrecognized-option-proc)
opt-name #f)
(short-option (1+ position)))
(else
(invoke-option-processor
option-here opt-name
(lambda ()
(or (short-option-argument position)
(error "Missing required argument after `-~A'" opt-name)))
(lambda ()
;; edge case: -xo -zf or -xo -- where opt-name=#\o
;; GNU getopt_long resolves these like I do
(short-option-argument position))
(lambda () #f))
(if (not (or (option-required-arg? option-here)
(option-optional-arg? option-here)))
(short-option (1+ position))))))))
;; Process the long option in (car ARGS). We make the
;; interesting, possibly non-standard assumption that long option
;; names might contain #\=, so keep looking for more #\= in (car
;; ARGS) until we find a named option in lookup.
(define (long-option)
(let ((arg (car args)))
(let place-=-after ((start-pos 2))
(let* ((index (string-index arg #\= start-pos))
(opt-name (substring arg 2 (or index (string-length arg))))
(option-here (hash-ref lookup opt-name)))
(if (not option-here)
;; look for a later #\=, unless there can't be one
(if index
(place-=-after (1+ index))
(mutate-seeds!
unrecognized-option-proc
(option (list opt-name) #f #f unrecognized-option-proc)
opt-name #f))
(invoke-option-processor
option-here opt-name
(lambda ()
(if index
(substring arg (1+ index))
(error "Missing required argument after `--~A'" opt-name)))
(lambda () (and index (substring arg (1+ index))))
(lambda ()
(if index
(error "Extraneous argument after `--~A'" opt-name))))))))
(set! args (cdr args)))
;; Process the remaining in ARGS. Basically like calling
;; `args-fold', but without having to regenerate `lookup' and the
;; funcs above.
(define (next-arg)
(if (null? args)
(apply values seeds)
(let ((arg (car args)))
(cond ((or (not (char=? #\- (string-ref arg 0)))
(= 1 (string-length arg))) ;"-"
(mutate-seeds! operand-proc arg)
(set! args (cdr args)))
((char=? #\- (string-ref arg 1))
(if (= 2 (string-length arg)) ;"--"
(begin (set! args (cdr args)) (rest-operands))
(long-option)))
(else (short-option 1)))
(next-arg))))
(next-arg)))
;;; srfi-37.scm ends here
;; Copyright (C) 2010 Free Software Foundation, Inc.
;; Copyright (C) Ray Dillinger 2003. All Rights Reserved.
;;
;; Contains code based upon Alex Shinn's public-domain implementation of
;; `read-with-shared-structure' found in Chicken's SRFI 38 egg.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-module (srfi srfi-38)
#\export (write-with-shared-structure
read-with-shared-structure)
#\use-module (rnrs bytevectors)
#\use-module (srfi srfi-8)
#\use-module (srfi srfi-69)
#\use-module (system vm trap-state))
(cond-expand-provide (current-module) '(srfi-38))
;; A printer that shows all sharing of substructures. Uses the Common
;; Lisp print-circle notation: #n# refers to a previous substructure
;; labeled with #n=. Takes O(n^2) time.
;; Code attributed to Al Petrofsky, modified by Ray Dillinger.
;; Modified in 2010 by Andreas Rottmann to use SRFI 69 hashtables,
;; making the time O(n), and adding some of Guile's data types to the
;; `interesting' objects.
(define* (write-with-shared-structure obj
#\optional
(outport (current-output-port))
(optarg #f))
;; We only track duplicates of pairs, vectors, strings, bytevectors,
;; structs (which subsume R6RS and SRFI-9 records), ports and (native)
;; hash-tables. We ignore zero-length vectors and strings because
;; r5rs doesn't guarantee that eq? treats them sanely (and they aren't
;; very interesting anyway).
(define (interesting? obj)
(or (pair? obj)
(and (vector? obj) (not (zero? (vector-length obj))))
(and (string? obj) (not (zero? (string-length obj))))
(bytevector? obj)
(struct? obj)
(port? obj)
(hash-table? obj)))
;; (write-obj OBJ STATE):
;;
;; STATE is a hashtable which has an entry for each interesting part
;; of OBJ. The associated value will be:
;;
;; -- a number if the part has been given one,
;; -- #t if the part will need to be assigned a number but has not been yet,
;; -- #f if the part will not need a number.
;; The entry `counter' in STATE should be the most recently
;; assigned number.
;;
;; Mutates STATE for any parts that had numbers assigned.
(define (write-obj obj state)
(define (write-interesting)
(cond ((pair? obj)
(display "(" outport)
(write-obj (car obj) state)
(let write-cdr ((obj (cdr obj)))
(cond ((and (pair? obj) (not (hash-table-ref state obj)))
(display " " outport)
(write-obj (car obj) state)
(write-cdr (cdr obj)))
((null? obj)
(display ")" outport))
(else
(display " . " outport)
(write-obj obj state)
(display ")" outport)))))
((vector? obj)
(display "#(" outport)
(let ((len (vector-length obj)))
(write-obj (vector-ref obj 0) state)
(let write-vec ((i 1))
(cond ((= i len) (display ")" outport))
(else (display " " outport)
(write-obj (vector-ref obj i) state)
(write-vec (+ i 1)))))))
;; else it's a string
(else (write obj outport))))
(cond ((interesting? obj)
(let ((val (hash-table-ref state obj)))
(cond ((not val) (write-interesting))
((number? val)
(begin (display "#" outport)
(write val outport)
(display "#" outport)))
(else
(let ((n (+ 1 (hash-table-ref state 'counter))))
(display "#" outport)
(write n outport)
(display "=" outport)
(hash-table-set! state 'counter n)
(hash-table-set! state obj n)
(write-interesting))))))
(else
(write obj outport))))
;; Scan computes the initial value of the hash table, which maps each
;; interesting part of the object to #t if it occurs multiple times,
;; #f if only once.
(define (scan obj state)
(cond ((not (interesting? obj)))
((hash-table-exists? state obj)
(hash-table-set! state obj #t))
(else
(hash-table-set! state obj #f)
(cond ((pair? obj)
(scan (car obj) state)
(scan (cdr obj) state))
((vector? obj)
(let ((len (vector-length obj)))
(do ((i 0 (+ 1 i)))
((= i len))
(scan (vector-ref obj i) state))))))))
(let ((state (make-hash-table eq?)))
(scan obj state)
(hash-table-set! state 'counter 0)
(write-obj obj state)))
;; A reader that understands the output of the above writer. This has
;; been written by Andreas Rottmann to re-use Guile's built-in reader,
;; with inspiration from Alex Shinn's public-domain implementation of
;; `read-with-shared-structure' found in Chicken's SRFI 38 egg.
(define* (read-with-shared-structure #\optional (port (current-input-port)))
(let ((parts-table (make-hash-table eqv?)))
;; reads chars that match PRED and returns them as a string.
(define (read-some-chars pred initial)
(let iter ((chars initial))
(let ((c (peek-char port)))
(if (or (eof-object? c) (not (pred c)))
(list->string (reverse chars))
(iter (cons (read-char port) chars))))))
(define (read-hash c port)
(let* ((n (string->number (read-some-chars char-numeric? (list c))))
(c (read-char port))
(thunk (hash-table-ref/default parts-table n #f)))
(case c
((#\=)
(if thunk
(error "Double declaration of part " n))
(let* ((cell (list #f))
(thunk (lambda () (car cell))))
(hash-table-set! parts-table n thunk)
(let ((obj (read port)))
(set-car! cell obj)
obj)))
((#\#)
(or thunk
(error "Use of undeclared part " n)))
(else
(error "Malformed shared part specifier")))))
(with-fluid* %read-hash-procedures (fluid-ref %read-hash-procedures)
(lambda ()
(for-each (lambda (digit)
(read-hash-extend digit read-hash))
'(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9))
(let ((result (read port)))
(if (< 0 (hash-table-size parts-table))
(patch! result))
result)))))
(define (hole? x) (procedure? x))
(define (fill-hole x) (if (hole? x) (fill-hole (x)) x))
(define (patch! x)
(cond
((pair? x)
(if (hole? (car x)) (set-car! x (fill-hole (car x))) (patch! (car x)))
(if (hole? (cdr x)) (set-cdr! x (fill-hole (cdr x))) (patch! (cdr x))))
((vector? x)
(do ((i (- (vector-length x) 1) (- i 1)))
((< i 0))
(let ((elt (vector-ref x i)))
(if (hole? elt)
(vector-set! x i (fill-hole elt))
(patch! elt)))))))
;;; srfi-39.scm --- Parameter objects
;; Copyright (C) 2004, 2005, 2006, 2008, 2011 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Jose Antonio Ortega Ruiz <jao@gnu.org>
;;; Date: 2004-05-05
;;; Commentary:
;; This is an implementation of SRFI-39 (Parameter objects).
;;
;; The implementation is based on Guile's fluid objects, and is, therefore,
;; thread-safe (parameters are thread-local).
;;
;; In addition to the forms defined in SRFI-39 (`make-parameter',
;; `parameterize'), a new procedure `with-parameters*' is provided.
;; This procedures is analogous to `with-fluids*' but taking as first
;; argument a list of parameter objects instead of a list of fluids.
;;
;;; Code:
(define-module (srfi srfi-39)
;; helper procedure not in srfi-39.
#\export (with-parameters*)
#\re-export (make-parameter
parameterize
current-input-port current-output-port current-error-port))
(cond-expand-provide (current-module) '(srfi-39))
(define (with-parameters* params values thunk)
(let more ((params params)
(values values)
(fluids '()) ;; fluids from each of PARAMS
(convs '())) ;; VALUES with conversion proc applied
(if (null? params)
(with-fluids* fluids convs thunk)
(more (cdr params) (cdr values)
(cons (parameter-fluid (car params)) fluids)
(cons ((parameter-converter (car params)) (car values)) convs)))))
;;; srfi-4.scm --- Homogeneous Numeric Vector Datatypes
;; Copyright (C) 2001, 2002, 2004, 2006, 2009, 2010,
;; 2012, 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Martin Grabmueller <mgrabmue@cs.tu-berlin.de>
;;; Commentary:
;; This module exports the homogeneous numeric vector procedures as
;; defined in SRFI-4. They are fully documented in the Guile
;; Reference Manual.
;;; Code:
(define-module (srfi srfi-4)
#\use-module (rnrs bytevectors)
#\export (;; Unsigned 8-bit vectors.
u8vector? make-u8vector u8vector u8vector-length u8vector-ref
u8vector-set! u8vector->list list->u8vector
;; Signed 8-bit vectors.
s8vector? make-s8vector s8vector s8vector-length s8vector-ref
s8vector-set! s8vector->list list->s8vector
;; Unsigned 16-bit vectors.
u16vector? make-u16vector u16vector u16vector-length u16vector-ref
u16vector-set! u16vector->list list->u16vector
;; Signed 16-bit vectors.
s16vector? make-s16vector s16vector s16vector-length s16vector-ref
s16vector-set! s16vector->list list->s16vector
;; Unsigned 32-bit vectors.
u32vector? make-u32vector u32vector u32vector-length u32vector-ref
u32vector-set! u32vector->list list->u32vector
;; Signed 32-bit vectors.
s32vector? make-s32vector s32vector s32vector-length s32vector-ref
s32vector-set! s32vector->list list->s32vector
;; Unsigned 64-bit vectors.
u64vector? make-u64vector u64vector u64vector-length u64vector-ref
u64vector-set! u64vector->list list->u64vector
;; Signed 64-bit vectors.
s64vector? make-s64vector s64vector s64vector-length s64vector-ref
s64vector-set! s64vector->list list->s64vector
;; 32-bit floating point vectors.
f32vector? make-f32vector f32vector f32vector-length f32vector-ref
f32vector-set! f32vector->list list->f32vector
;; 64-bit floating point vectors.
f64vector? make-f64vector f64vector f64vector-length f64vector-ref
f64vector-set! f64vector->list list->f64vector))
(cond-expand-provide (current-module) '(srfi-4))
;; Need quasisyntax to do this effectively using syntax-case
(define-macro (define-bytevector-type tag infix size)
`(begin
(define (,(symbol-append tag 'vector?) obj)
(and (bytevector? obj) (eq? (array-type obj) ',tag)))
(define (,(symbol-append 'make- tag 'vector) len . fill)
(apply make-srfi-4-vector ',tag len fill))
(define (,(symbol-append tag 'vector-length) v)
(let ((len (/ (bytevector-length v) ,size)))
(if (integer? len)
len
(error "fractional length" v ',tag ,size))))
(define (,(symbol-append tag 'vector) . elts)
(,(symbol-append 'list-> tag 'vector) elts))
(define (,(symbol-append 'list-> tag 'vector) elts)
(let* ((len (length elts))
(v (,(symbol-append 'make- tag 'vector) len)))
(let lp ((i 0) (elts elts))
(if (and (< i len) (pair? elts))
(begin
(,(symbol-append tag 'vector-set!) v i (car elts))
(lp (1+ i) (cdr elts)))
v))))
(define (,(symbol-append tag 'vector->list) v)
(let lp ((i (1- (,(symbol-append tag 'vector-length) v))) (elts '()))
(if (< i 0)
elts
(lp (1- i) (cons (,(symbol-append tag 'vector-ref) v i) elts)))))
(define (,(symbol-append tag 'vector-ref) v i)
(,(symbol-append 'bytevector- infix '-ref) v (* i ,size)))
(define (,(symbol-append tag 'vector-set!) v i x)
(,(symbol-append 'bytevector- infix '-set!) v (* i ,size) x))
(define (,(symbol-append tag 'vector-set!) v i x)
(,(symbol-append 'bytevector- infix '-set!) v (* i ,size) x))))
(define-bytevector-type u8 u8 1)
(define-bytevector-type s8 s8 1)
(define-bytevector-type u16 u16-native 2)
(define-bytevector-type s16 s16-native 2)
(define-bytevector-type u32 u32-native 4)
(define-bytevector-type s32 s32-native 4)
(define-bytevector-type u64 u64-native 8)
(define-bytevector-type s64 s64-native 8)
(define-bytevector-type f32 ieee-single-native 4)
(define-bytevector-type f64 ieee-double-native 8)
;;; Extensions to SRFI-4
;; Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; Extensions to SRFI-4. Fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-4 gnu)
#\use-module (rnrs bytevectors)
#\use-module (srfi srfi-4)
#\export (;; Complex numbers with 32- and 64-bit components.
c32vector? make-c32vector c32vector c32vector-length c32vector-ref
c32vector-set! c32vector->list list->c32vector
c64vector? make-c64vector c64vector c64vector-length c64vector-ref
c64vector-set! c64vector->list list->c64vector
make-srfi-4-vector
;; Somewhat polymorphic conversions.
any->u8vector any->s8vector any->u16vector any->s16vector
any->u32vector any->s32vector any->u64vector any->s64vector
any->f32vector any->f64vector any->c32vector any->c64vector))
(define make-srfi-4-vector (@@ (srfi srfi-4) make-srfi-4-vector))
(define (bytevector-c32-native-ref v i)
(make-rectangular (bytevector-ieee-single-native-ref v i)
(bytevector-ieee-single-native-ref v (+ i 4))))
(define (bytevector-c32-native-set! v i x)
(bytevector-ieee-single-native-set! v i (real-part x))
(bytevector-ieee-single-native-set! v (+ i 4) (imag-part x)))
(define (bytevector-c64-native-ref v i)
(make-rectangular (bytevector-ieee-double-native-ref v i)
(bytevector-ieee-double-native-ref v (+ i 8))))
(define (bytevector-c64-native-set! v i x)
(bytevector-ieee-double-native-set! v i (real-part x))
(bytevector-ieee-double-native-set! v (+ i 8) (imag-part x)))
((@@ (srfi srfi-4) define-bytevector-type) c32 c32-native 8)
((@@ (srfi srfi-4) define-bytevector-type) c64 c64-native 16)
(define-macro (define-any->vector . tags)
`(begin
,@(map (lambda (tag)
`(define (,(symbol-append 'any-> tag 'vector) obj)
(cond ((,(symbol-append tag 'vector?) obj) obj)
((pair? obj) (,(symbol-append 'list-> tag 'vector) obj))
((and (array? obj) (eqv? 1 (array-rank obj)))
(let* ((len (array-length obj))
(v (,(symbol-append 'make- tag 'vector) len)))
(let lp ((i 0))
(if (< i len)
(begin
(,(symbol-append tag 'vector-set!)
v i (array-ref obj i))
(lp (1+ i)))
v))))
(else (scm-error 'wrong-type-arg #f "" '() (list obj))))))
tags)))
(define-any->vector u8 s8 u16 s16 u32 s32 u64 s64 f32 f64 c32 c64)
;;; srfi-41.scm -- SRFI 41 streams
;; Copyright (c) 2007 Philip L. Bewig
;; Copyright (c) 2011, 2012, 2013 Free Software Foundation, Inc.
;; Permission is hereby granted, free of charge, to any person obtaining
;; a copy of this software and associated documentation files (the
;; "Software"), to deal in the Software without restriction, including
;; without limitation the rights to use, copy, modify, merge, publish,
;; distribute, sublicense, and/or sell copies of the Software, and to
;; permit persons to whom the Software is furnished to do so, subject to
;; the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
;; OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-module (srfi srfi-41)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-8)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (srfi srfi-26)
#\use-module (ice-9 match)
#\export (stream-null stream-cons stream? stream-null? stream-pair?
stream-car stream-cdr stream-lambda define-stream
list->stream port->stream stream stream->list stream-append
stream-concat stream-constant stream-drop stream-drop-while
stream-filter stream-fold stream-for-each stream-from
stream-iterate stream-length stream-let stream-map
stream-match stream-of stream-range stream-ref stream-reverse
stream-scan stream-take stream-take-while stream-unfold
stream-unfolds stream-zip))
(cond-expand-provide (current-module) '(srfi-41))
;;; Private supporting functions and macros.
(define-syntax-rule (must pred obj func msg args ...)
(let ((item obj))
(unless (pred item)
(throw 'wrong-type-arg func msg (list args ...) (list item)))))
(define-syntax-rule (must-not pred obj func msg args ...)
(let ((item obj))
(when (pred item)
(throw 'wrong-type-arg func msg (list args ...) (list item)))))
(define-syntax-rule (must-every pred objs func msg args ...)
(let ((flunk (remove pred objs)))
(unless (null? flunk)
(throw 'wrong-type-arg func msg (list args ...) flunk))))
(define-syntax-rule (first-value expr)
(receive (first . _) expr
first))
(define-syntax-rule (second-value expr)
(receive (first second . _) expr
second))
(define-syntax-rule (third-value expr)
(receive (first second third . _) expr
third))
(define-syntax define-syntax*
(syntax-rules ()
((_ (name . args) body ...)
(define-syntax name (lambda* args body ...)))
((_ name syntax)
(define-syntax name syntax))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Here we include a copy of the code of srfi-45.scm (but with renamed
;; identifiers), in order to create a new promise type that's disjoint
;; from the promises created by srfi-45. Ideally this should be done
;; using a 'make-promise-type' macro that instantiates a copy of this
;; code, but a psyntax bug in Guile 2.0 prevents this from working
;; properly: <http://bugs.gnu.org/13995>. So for now, we duplicate the
;; code.
;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
;; Copyright (C) 2003 André van Tonder. All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(define-record-type stream-promise (make-stream-promise val) stream-promise?
(val stream-promise-val stream-promise-val-set!))
(define-record-type stream-value (make-stream-value tag proc) stream-value?
(tag stream-value-tag stream-value-tag-set!)
(proc stream-value-proc stream-value-proc-set!))
(define-syntax-rule (stream-lazy exp)
(make-stream-promise (make-stream-value 'lazy (lambda () exp))))
(define (stream-eager x)
(make-stream-promise (make-stream-value 'eager x)))
(define-syntax-rule (stream-delay exp)
(stream-lazy (stream-eager exp)))
(define (stream-force promise)
(let ((content (stream-promise-val promise)))
(case (stream-value-tag content)
((eager) (stream-value-proc content))
((lazy) (let* ((promise* ((stream-value-proc content)))
(content (stream-promise-val promise)))
(if (not (eqv? (stream-value-tag content) 'eager))
(begin (stream-value-tag-set! content
(stream-value-tag (stream-promise-val promise*)))
(stream-value-proc-set! content
(stream-value-proc (stream-promise-val promise*)))
(stream-promise-val-set! promise* content)))
(stream-force promise))))))
;;
;; End of the copy of the code from srfi-45.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Primitive stream functions and macros: (streams primitive)
(define stream? stream-promise?)
(define %stream-null (cons 'stream 'null))
(define stream-null (stream-eager %stream-null))
(define (stream-null? obj)
(and (stream-promise? obj)
(eqv? (stream-force obj) %stream-null)))
(define-record-type stream-pare (make-stream-pare kar kdr) stream-pare?
(kar stream-kar)
(kdr stream-kdr))
(define (stream-pair? obj)
(and (stream-promise? obj) (stream-pare? (stream-force obj))))
(define-syntax-rule (stream-cons obj strm)
(stream-eager (make-stream-pare (stream-delay obj) (stream-lazy strm))))
(define (stream-car strm)
(must stream? strm 'stream-car "non-stream")
(let ((pare (stream-force strm)))
(must stream-pare? pare 'stream-car "null stream")
(stream-force (stream-kar pare))))
(define (stream-cdr strm)
(must stream? strm 'stream-cdr "non-stream")
(let ((pare (stream-force strm)))
(must stream-pare? pare 'stream-cdr "null stream")
(stream-kdr pare)))
(define-syntax-rule (stream-lambda formals body0 body1 ...)
(lambda formals (stream-lazy (begin body0 body1 ...))))
(define* (stream-promise-visit promise #\key on-eager on-lazy)
(define content (stream-promise-val promise))
(case (stream-value-tag content)
((eager) (on-eager (stream-value-proc content)))
((lazy) (on-lazy (stream-value-proc content)))))
(set-record-type-printer! stream-promise
(lambda (strm port)
(display "#<stream" port)
(let loop ((strm strm))
(stream-promise-visit strm
#\on-eager (lambda (pare)
(cond ((eq? pare %stream-null)
(write-char #\> port))
(else
(write-char #\space port)
(stream-promise-visit (stream-kar pare)
#\on-eager (cut write <> port)
#\on-lazy (lambda (_) (write-char #\? port)))
(loop (stream-kdr pare)))))
#\on-lazy (lambda (_) (display " ...>" port))))))
;;; Derived stream functions and macros: (streams derived)
(define-syntax-rule (define-stream (name . formal) body0 body1 ...)
(define name (stream-lambda formal body0 body1 ...)))
(define-syntax-rule (stream-let tag ((name val) ...) body1 body2 ...)
((letrec ((tag (stream-lambda (name ...) body1 body2 ...))) tag) val ...))
(define (list->stream objs)
(define (list? x)
(or (proper-list? x) (circular-list? x)))
(must list? objs 'list->stream "non-list argument")
(stream-let recur ((objs objs))
(if (null? objs) stream-null
(stream-cons (car objs) (recur (cdr objs))))))
(define* (port->stream #\optional (port (current-input-port)))
(must input-port? port 'port->stream "non-input-port argument")
(stream-let recur ()
(let ((c (read-char port)))
(if (eof-object? c) stream-null
(stream-cons c (recur))))))
(define-syntax stream
(syntax-rules ()
((_) stream-null)
((_ x y ...) (stream-cons x (stream y ...)))))
;; Common helper for the various eager-folding functions, such as
;; stream-fold, stream-drop, stream->list, stream-length, etc.
(define-inlinable (stream-fold-aux proc base strm limit)
(do ((val base (and proc (proc val (stream-car strm))))
(strm strm (stream-cdr strm))
(limit limit (and limit (1- limit))))
((or (and limit (zero? limit)) (stream-null? strm))
(values val strm limit))))
(define stream->list
(case-lambda
((strm) (stream->list #f strm))
((n strm)
(must stream? strm 'stream->list "non-stream argument")
(when n
(must integer? n 'stream->list "non-integer count")
(must exact? n 'stream->list "inexact count")
(must-not negative? n 'stream->list "negative count"))
(reverse! (first-value (stream-fold-aux xcons '() strm n))))))
(define (stream-append . strms)
(must-every stream? strms 'stream-append "non-stream argument")
(stream-let recur ((strms strms))
(if (null? strms) stream-null
(let ((strm (car strms)))
(if (stream-null? strm) (recur (cdr strms))
(stream-cons (stream-car strm)
(recur (cons (stream-cdr strm) (cdr strms)))))))))
(define (stream-concat strms)
(must stream? strms 'stream-concat "non-stream argument")
(stream-let recur ((strms strms))
(if (stream-null? strms) stream-null
(let ((strm (stream-car strms)))
(must stream? strm 'stream-concat "non-stream object in input stream")
(if (stream-null? strm) (recur (stream-cdr strms))
(stream-cons (stream-car strm)
(recur (stream-cons (stream-cdr strm)
(stream-cdr strms)))))))))
(define stream-constant
(case-lambda
(() stream-null)
(objs (list->stream (apply circular-list objs)))))
(define-syntax* (stream-do x)
(define (end x)
(syntax-case x ()
(() #'(if #f #f))
((result) #'result)
((result ...) #'(begin result ...))))
(define (var-step v s)
(syntax-case s ()
(() v)
((e) #'e)
(_ (syntax-violation 'stream-do "bad step expression" x s))))
(syntax-case x ()
((_ ((var init . step) ...)
(test result ...)
expr ...)
(with-syntax ((result (end #'(result ...)))
((step ...) (map var-step #'(var ...) #'(step ...))))
#'(stream-let loop ((var init) ...)
(if test result
(begin
expr ...
(loop step ...))))))))
(define (stream-drop n strm)
(must integer? n 'stream-drop "non-integer argument")
(must exact? n 'stream-drop "inexact argument")
(must-not negative? n 'stream-drop "negative argument")
(must stream? strm 'stream-drop "non-stream argument")
(second-value (stream-fold-aux #f #f strm n)))
(define (stream-drop-while pred? strm)
(must procedure? pred? 'stream-drop-while "non-procedural argument")
(must stream? strm 'stream-drop-while "non-stream argument")
(stream-do ((strm strm (stream-cdr strm)))
((or (stream-null? strm) (not (pred? (stream-car strm)))) strm)))
(define (stream-filter pred? strm)
(must procedure? pred? 'stream-filter "non-procedural argument")
(must stream? strm 'stream-filter "non-stream argument")
(stream-let recur ((strm strm))
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (recur (stream-cdr strm))))
(else (recur (stream-cdr strm))))))
(define (stream-fold proc base strm)
(must procedure? proc 'stream-fold "non-procedural argument")
(must stream? strm 'stream-fold "non-stream argument")
(first-value (stream-fold-aux proc base strm #f)))
(define stream-for-each
(case-lambda
((proc strm)
(must procedure? proc 'stream-for-each "non-procedural argument")
(must stream? strm 'stream-for-each "non-stream argument")
(do ((strm strm (stream-cdr strm)))
((stream-null? strm))
(proc (stream-car strm))))
((proc strm . rest)
(let ((strms (cons strm rest)))
(must procedure? proc 'stream-for-each "non-procedural argument")
(must-every stream? strms 'stream-for-each "non-stream argument")
(do ((strms strms (map stream-cdr strms)))
((any stream-null? strms))
(apply proc (map stream-car strms)))))))
(define* (stream-from first #\optional (step 1))
(must number? first 'stream-from "non-numeric starting number")
(must number? step 'stream-from "non-numeric step size")
(stream-let recur ((first first))
(stream-cons first (recur (+ first step)))))
(define (stream-iterate proc base)
(must procedure? proc 'stream-iterate "non-procedural argument")
(stream-let recur ((base base))
(stream-cons base (recur (proc base)))))
(define (stream-length strm)
(must stream? strm 'stream-length "non-stream argument")
(- -1 (third-value (stream-fold-aux #f #f strm -1))))
(define stream-map
(case-lambda
((proc strm)
(must procedure? proc 'stream-map "non-procedural argument")
(must stream? strm 'stream-map "non-stream argument")
(stream-let recur ((strm strm))
(if (stream-null? strm) stream-null
(stream-cons (proc (stream-car strm))
(recur (stream-cdr strm))))))
((proc strm . rest)
(let ((strms (cons strm rest)))
(must procedure? proc 'stream-map "non-procedural argument")
(must-every stream? strms 'stream-map "non-stream argument")
(stream-let recur ((strms strms))
(if (any stream-null? strms) stream-null
(stream-cons (apply proc (map stream-car strms))
(recur (map stream-cdr strms)))))))))
(define-syntax* (stream-match x)
(define (make-matcher x)
(syntax-case x ()
(() #'(? stream-null?))
(rest (identifier? #'rest) #'rest)
((var . rest) (identifier? #'var)
(with-syntax ((next (make-matcher #'rest)))
#'(? (negate stream-null?)
(= stream-car var)
(= stream-cdr next))))))
(define (make-guarded x fail)
(syntax-case (list x fail) ()
(((expr) _) #'expr)
(((guard expr) fail) #'(if guard expr (fail)))))
(syntax-case x ()
((_ strm-expr (pat . expr) ...)
(with-syntax (((fail ...) (generate-temporaries #'(pat ...))))
(with-syntax (((matcher ...) (map make-matcher #'(pat ...)))
((expr ...) (map make-guarded #'(expr ...) #'(fail ...))))
#'(let ((strm strm-expr))
(must stream? strm 'stream-match "non-stream argument")
(match strm (matcher (=> fail) expr) ...)))))))
(define-syntax-rule (stream-of expr rest ...)
(stream-of-aux expr stream-null rest ...))
(define-syntax stream-of-aux
(syntax-rules (in is)
((_ expr base)
(stream-cons expr base))
((_ expr base (var in stream) rest ...)
(stream-let recur ((strm stream))
(if (stream-null? strm) base
(let ((var (stream-car strm)))
(stream-of-aux expr (recur (stream-cdr strm)) rest ...)))))
((_ expr base (var is exp) rest ...)
(let ((var exp)) (stream-of-aux expr base rest ...)))
((_ expr base pred? rest ...)
(if pred? (stream-of-aux expr base rest ...) base))))
(define* (stream-range first past #\optional step)
(must number? first 'stream-range "non-numeric starting number")
(must number? past 'stream-range "non-numeric ending number")
(when step
(must number? step 'stream-range "non-numeric step size"))
(let* ((step (or step (if (< first past) 1 -1)))
(lt? (if (< 0 step) < >)))
(stream-let recur ((first first))
(if (lt? first past)
(stream-cons first (recur (+ first step)))
stream-null))))
(define (stream-ref strm n)
(must stream? strm 'stream-ref "non-stream argument")
(must integer? n 'stream-ref "non-integer argument")
(must exact? n 'stream-ref "inexact argument")
(must-not negative? n 'stream-ref "negative argument")
(let ((res (stream-drop n strm)))
(must-not stream-null? res 'stream-ref "beyond end of stream")
(stream-car res)))
(define (stream-reverse strm)
(must stream? strm 'stream-reverse "non-stream argument")
(stream-do ((strm strm (stream-cdr strm))
(rev stream-null (stream-cons (stream-car strm) rev)))
((stream-null? strm) rev)))
(define (stream-scan proc base strm)
(must procedure? proc 'stream-scan "non-procedural argument")
(must stream? strm 'stream-scan "non-stream argument")
(stream-let recur ((base base) (strm strm))
(if (stream-null? strm) (stream base)
(stream-cons base (recur (proc base (stream-car strm))
(stream-cdr strm))))))
(define (stream-take n strm)
(must stream? strm 'stream-take "non-stream argument")
(must integer? n 'stream-take "non-integer argument")
(must exact? n 'stream-take "inexact argument")
(must-not negative? n 'stream-take "negative argument")
(stream-let recur ((n n) (strm strm))
(if (or (zero? n) (stream-null? strm)) stream-null
(stream-cons (stream-car strm) (recur (1- n) (stream-cdr strm))))))
(define (stream-take-while pred? strm)
(must procedure? pred? 'stream-take-while "non-procedural argument")
(must stream? strm 'stream-take-while "non-stream argument")
(stream-let recur ((strm strm))
(cond ((stream-null? strm) stream-null)
((pred? (stream-car strm))
(stream-cons (stream-car strm) (recur (stream-cdr strm))))
(else stream-null))))
(define (stream-unfold mapper pred? generator base)
(must procedure? mapper 'stream-unfold "non-procedural mapper")
(must procedure? pred? 'stream-unfold "non-procedural pred?")
(must procedure? generator 'stream-unfold "non-procedural generator")
(stream-let recur ((base base))
(if (pred? base)
(stream-cons (mapper base) (recur (generator base)))
stream-null)))
(define (stream-unfolds gen seed)
(define-stream (generator-stream seed)
(receive (next . items) (gen seed)
(stream-cons (list->vector items) (generator-stream next))))
(define-stream (make-result-stream genstrm index)
(define head (vector-ref (stream-car genstrm) index))
(define-stream (tail) (make-result-stream (stream-cdr genstrm) index))
(match head
(() stream-null)
(#f (tail))
((item) (stream-cons item (tail)))
((? list? items) (stream-append (list->stream items) (tail)))))
(must procedure? gen 'stream-unfolds "non-procedural argument")
(let ((genstrm (generator-stream seed)))
(apply values (list-tabulate (vector-length (stream-car genstrm))
(cut make-result-stream genstrm <>)))))
(define (stream-zip strm . rest)
(let ((strms (cons strm rest)))
(must-every stream? strms 'stream-zip "non-stream argument")
(stream-let recur ((strms strms))
(if (any stream-null? strms) stream-null
(stream-cons (map stream-car strms) (recur (map stream-cdr strms)))))))
;;; srfi-42.scm --- Eager comprehensions
;; Copyright (C) 2010 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;; This library 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
;; Lesser General Public License for more details.
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library. If not, see
;; <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module is not yet documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-42)
#\export (\:
\:-dispatch-ref
\:-dispatch-set!
\:char-range
\:dispatched
\:do
\:generator-proc
\:integers
\:let
\:list
\:parallel
\:port
\:range
\:real-range
\:string
\:until
\:vector
\:while
any?-ec
append-ec
dispatch-union
do-ec
every?-ec
first-ec
fold-ec
fold3-ec
last-ec
list-ec
make-initial-\:-dispatch
max-ec
min-ec
product-ec
string-append-ec
string-ec
sum-ec
vector-ec
vector-of-length-ec))
(cond-expand-provide (current-module) '(srfi-42))
(include-from-path "srfi/srfi-42/ec.scm")
; <PLAINTEXT>
; Eager Comprehensions in [outer..inner|expr]-Convention
; ======================================================
;
; sebastian.egner@philips.com, Eindhoven, The Netherlands, 26-Dec-2007
; Scheme R5RS (incl. macros), SRFI-23 (error).
;
; Loading the implementation into Scheme48 0.57:
; ,open srfi-23
; ,load ec.scm
;
; Loading the implementation into PLT/DrScheme 317:
; ; File > Open ... "ec.scm", click Execute
;
; Loading the implementation into SCM 5d7:
; (require 'macro) (require 'record)
; (load "ec.scm")
;
; Implementation comments:
; * All local (not exported) identifiers are named ec-<something>.
; * This implementation focuses on portability, performance,
; readability, and simplicity roughly in this order. Design
; decisions related to performance are taken for Scheme48.
; * Alternative implementations, Comments and Warnings are
; mentioned after the definition with a heading.
; ==========================================================================
; The fundamental comprehension do-ec
; ==========================================================================
;
; All eager comprehensions are reduced into do-ec and
; all generators are reduced to :do.
;
; We use the following short names for syntactic variables
; q - qualifier
; cc - current continuation, thing to call at the end;
; the CPS is (m (cc ...) arg ...) -> (cc ... expr ...)
; cmd - an expression being evaluated for its side-effects
; expr - an expression
; gen - a generator of an eager comprehension
; ob - outer binding
; oc - outer command
; lb - loop binding
; ne1? - not-end1? (before the payload)
; ib - inner binding
; ic - inner command
; ne2? - not-end2? (after the payload)
; ls - loop step
; etc - more arguments of mixed type
; (do-ec q ... cmd)
; handles nested, if/not/and/or, begin, :let, and calls generator
; macros in CPS to transform them into fully decorated :do.
; The code generation for a :do is delegated to do-ec:do.
(define-syntax do-ec
(syntax-rules (nested if not and or begin \:do let)
; explicit nesting -> implicit nesting
((do-ec (nested q ...) etc ...)
(do-ec q ... etc ...) )
; implicit nesting -> fold do-ec
((do-ec q1 q2 etc1 etc ...)
(do-ec q1 (do-ec q2 etc1 etc ...)) )
; no qualifiers at all -> evaluate cmd once
((do-ec cmd)
(begin cmd (if #f #f)) )
; now (do-ec q cmd) remains
; filter -> make conditional
((do-ec (if test) cmd)
(if test (do-ec cmd)) )
((do-ec (not test) cmd)
(if (not test) (do-ec cmd)) )
((do-ec (and test ...) cmd)
(if (and test ...) (do-ec cmd)) )
((do-ec (or test ...) cmd)
(if (or test ...) (do-ec cmd)) )
; begin -> make a sequence
((do-ec (begin etc ...) cmd)
(begin etc ... (do-ec cmd)) )
; fully decorated :do-generator -> delegate to do-ec:do
((do-ec (#\:do olet lbs ne1? ilet ne2? lss) cmd)
(do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss)) )
; anything else -> call generator-macro in CPS; reentry at (*)
((do-ec (g arg1 arg ...) cmd)
(g (do-ec:do cmd) arg1 arg ...) )))
; (do-ec:do cmd (#\:do olet lbs ne1? ilet ne2? lss))
; generates code for a single fully decorated :do-generator
; with cmd as payload, taking care of special cases.
(define-syntax do-ec:do
(syntax-rules (#\:do let)
; reentry point (*) -> generate code
((do-ec:do cmd
(#\:do (let obs oc ...)
lbs
ne1?
(let ibs ic ...)
ne2?
(ls ...) ))
(ec-simplify
(let obs
oc ...
(let loop lbs
(ec-simplify
(if ne1?
(ec-simplify
(let ibs
ic ...
cmd
(ec-simplify
(if ne2?
(loop ls ...) )))))))))) ))
; (ec-simplify <expression>)
; generates potentially more efficient code for <expression>.
; The macro handles if, (begin <command>*), and (let () <command>*)
; and takes care of special cases.
(define-syntax ec-simplify
(syntax-rules (if not let begin)
; one- and two-sided if
; literal <test>
((ec-simplify (if #t consequent))
consequent )
((ec-simplify (if #f consequent))
(if #f #f) )
((ec-simplify (if #t consequent alternate))
consequent )
((ec-simplify (if #f consequent alternate))
alternate )
; (not (not <test>))
((ec-simplify (if (not (not test)) consequent))
(ec-simplify (if test consequent)) )
((ec-simplify (if (not (not test)) consequent alternate))
(ec-simplify (if test consequent alternate)) )
; (let () <command>*)
; empty <binding spec>*
((ec-simplify (let () command ...))
(ec-simplify (begin command ...)) )
; begin
; flatten use helper (ec-simplify 1 done to-do)
((ec-simplify (begin command ...))
(ec-simplify 1 () (command ...)) )
((ec-simplify 1 done ((begin to-do1 ...) to-do2 ...))
(ec-simplify 1 done (to-do1 ... to-do2 ...)) )
((ec-simplify 1 (done ...) (to-do1 to-do ...))
(ec-simplify 1 (done ... to-do1) (to-do ...)) )
; exit helper
((ec-simplify 1 () ())
(if #f #f) )
((ec-simplify 1 (command) ())
command )
((ec-simplify 1 (command1 command ...) ())
(begin command1 command ...) )
; anything else
((ec-simplify expression)
expression )))
; ==========================================================================
; The special generators :do, :let, :parallel, :while, and :until
; ==========================================================================
(define-syntax \:do
(syntax-rules ()
; full decorated -> continue with cc, reentry at (*)
((#\:do (cc ...) olet lbs ne1? ilet ne2? lss)
(cc ... (#\:do olet lbs ne1? ilet ne2? lss)) )
; short form -> fill in default values
((#\:do cc lbs ne1? lss)
(#\:do cc (let ()) lbs ne1? (let ()) #t lss) )))
(define-syntax \:let
(syntax-rules (index)
((\:let cc var (index i) expression)
(#\:do cc (let ((var expression) (i 0))) () #t (let ()) #f ()) )
((\:let cc var expression)
(#\:do cc (let ((var expression))) () #t (let ()) #f ()) )))
(define-syntax \:parallel
(syntax-rules (#\:do)
((\:parallel cc)
cc )
((\:parallel cc (g arg1 arg ...) gen ...)
(g (\:parallel-1 cc (gen ...)) arg1 arg ...) )))
; (\:parallel-1 cc (to-do ...) result [ next ] )
; iterates over to-do by converting the first generator into
; the :do-generator next and merging next into result.
(define-syntax \:parallel-1 ; used as
(syntax-rules (#\:do let)
; process next element of to-do, reentry at (**)
((\:parallel-1 cc ((g arg1 arg ...) gen ...) result)
(g (\:parallel-1 cc (gen ...) result) arg1 arg ...) )
; reentry point (**) -> merge next into result
((\:parallel-1
cc
gens
(#\:do (let (ob1 ...) oc1 ...)
(lb1 ...)
ne1?1
(let (ib1 ...) ic1 ...)
ne2?1
(ls1 ...) )
(#\:do (let (ob2 ...) oc2 ...)
(lb2 ...)
ne1?2
(let (ib2 ...) ic2 ...)
ne2?2
(ls2 ...) ))
(\:parallel-1
cc
gens
(#\:do (let (ob1 ... ob2 ...) oc1 ... oc2 ...)
(lb1 ... lb2 ...)
(and ne1?1 ne1?2)
(let (ib1 ... ib2 ...) ic1 ... ic2 ...)
(and ne2?1 ne2?2)
(ls1 ... ls2 ...) )))
; no more gens -> continue with cc, reentry at (*)
((\:parallel-1 (cc ...) () result)
(cc ... result) )))
(define-syntax \:while
(syntax-rules ()
((\:while cc (g arg1 arg ...) test)
(g (\:while-1 cc test) arg1 arg ...) )))
; (\:while-1 cc test (#\:do ...))
; modifies the fully decorated :do-generator such that it
; runs while test is a true value.
; The original implementation just replaced ne1? by
; (and ne1? test) as follows:
;
; (define-syntax \:while-1
; (syntax-rules (#\:do)
; ((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
; (#\:do cc olet lbs (and ne1? test) ilet ne2? lss) )))
;
; Bug #1:
; Unfortunately, this code is wrong because ne1? may depend
; in the inner bindings introduced in ilet, but ne1? is evaluated
; outside of the inner bindings. (Refer to the specification of
; :do to see the structure.)
; The problem manifests itself (as sunnan@handgranat.org
; observed, 25-Apr-2005) when the :list-generator is modified:
;
; (do-ec (\:while (\:list x '(1 2)) (= x 1)) (display x)).
;
; In order to generate proper code, we introduce temporary
; variables saving the values of the inner bindings. The inner
; bindings are executed in a new ne1?, which also evaluates ne1?
; outside the scope of the inner bindings, then the inner commands
; are executed (possibly changing the variables), and then the
; values of the inner bindings are saved and (and ne1? test) is
; returned. In the new ilet, the inner variables are bound and
; initialized and their values are restored. So we construct:
;
; (let (ob .. (ib-tmp #f) ...)
; oc ...
; (let loop (lb ...)
; (if (let (ne1?-value ne1?)
; (let ((ib-var ib-rhs) ...)
; ic ...
; (set! ib-tmp ib-var) ...)
; (and ne1?-value test))
; (let ((ib-var ib-tmp) ...)
; /payload/
; (if ne2?
; (loop ls ...) )))))
;
; Bug #2:
; Unfortunately, the above expansion is still incorrect (as Jens-Axel
; Soegaard pointed out, 4-Jun-2007) because ib-rhs are evaluated even
; if ne1?-value is #f, indicating that the loop has ended.
; The problem manifests itself in the following example:
;
; (do-ec (\:while (\:list x '(1)) #t) (display x))
;
; Which iterates :list beyond exhausting the list '(1).
;
; For the fix, we follow Jens-Axel's approach of guarding the evaluation
; of ib-rhs with a check on ne1?-value.
(define-syntax \:while-1
(syntax-rules (#\:do let)
((\:while-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(\:while-2 cc test () () () (#\:do olet lbs ne1? ilet ne2? lss)))))
(define-syntax \:while-2
(syntax-rules (#\:do let)
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do olet
lbs
ne1?
(let ((ib-var ib-rhs) ib ...) ic ...)
ne2?
lss))
(\:while-2 cc
test
(ib-let ... (ib-tmp #f))
(ib-save ... (ib-var ib-rhs))
(ib-restore ... (ib-var ib-tmp))
(#\:do olet
lbs
ne1?
(let (ib ...) ic ... (set! ib-tmp ib-var))
ne2?
lss)))
((\:while-2 cc
test
(ib-let ...)
(ib-save ...)
(ib-restore ...)
(#\:do (let (ob ...) oc ...) lbs ne1? (let () ic ...) ne2? lss))
(#\:do cc
(let (ob ... ib-let ...) oc ...)
lbs
(let ((ne1?-value ne1?))
(and ne1?-value
(let (ib-save ...)
ic ...
test)))
(let (ib-restore ...))
ne2?
lss))))
(define-syntax \:until
(syntax-rules ()
((\:until cc (g arg1 arg ...) test)
(g (\:until-1 cc test) arg1 arg ...) )))
(define-syntax \:until-1
(syntax-rules (#\:do)
((\:until-1 cc test (#\:do olet lbs ne1? ilet ne2? lss))
(#\:do cc olet lbs ne1? ilet (and ne2? (not test)) lss) )))
; ==========================================================================
; The typed generators :list :string :vector etc.
; ==========================================================================
(define-syntax \:list
(syntax-rules (index)
((\:list cc var (index i) arg ...)
(\:parallel cc (\:list var arg ...) (\:integers i)) )
((\:list cc var arg1 arg2 arg ...)
(\:list cc var (append arg1 arg2 arg ...)) )
((\:list cc var arg)
(#\:do cc
(let ())
((t arg))
(not (null? t))
(let ((var (car t))))
#t
((cdr t)) ))))
(define-syntax \:string
(syntax-rules (index)
((\:string cc var (index i) arg)
(#\:do cc
(let ((str arg) (len 0))
(set! len (string-length str)))
((i 0))
(< i len)
(let ((var (string-ref str i))))
#t
((+ i 1)) ))
((\:string cc var (index i) arg1 arg2 arg ...)
(\:string cc var (index i) (string-append arg1 arg2 arg ...)) )
((\:string cc var arg1 arg ...)
(\:string cc var (index i) arg1 arg ...) )))
; Alternative: An implementation in the style of :vector can also
; be used for :string. However, it is less interesting as the
; overhead of string-append is much less than for 'vector-append'.
(define-syntax \:vector
(syntax-rules (index)
((\:vector cc var arg)
(\:vector cc var (index i) arg) )
((\:vector cc var (index i) arg)
(#\:do cc
(let ((vec arg) (len 0))
(set! len (vector-length vec)))
((i 0))
(< i len)
(let ((var (vector-ref vec i))))
#t
((+ i 1)) ))
((\:vector cc var (index i) arg1 arg2 arg ...)
(\:parallel cc (\:vector cc var arg1 arg2 arg ...) (\:integers i)) )
((\:vector cc var arg1 arg2 arg ...)
(#\:do cc
(let ((vec #f)
(len 0)
(vecs (ec-:vector-filter (list arg1 arg2 arg ...))) ))
((k 0))
(if (< k len)
#t
(if (null? vecs)
#f
(begin (set! vec (car vecs))
(set! vecs (cdr vecs))
(set! len (vector-length vec))
(set! k 0)
#t )))
(let ((var (vector-ref vec k))))
#t
((+ k 1)) ))))
(define (ec-:vector-filter vecs)
(if (null? vecs)
'()
(if (zero? (vector-length (car vecs)))
(ec-:vector-filter (cdr vecs))
(cons (car vecs) (ec-:vector-filter (cdr vecs))) )))
; Alternative: A simpler implementation for :vector uses vector->list
; append and :list in the multi-argument case. Please refer to the
; 'design.scm' for more details.
(define-syntax \:integers
(syntax-rules (index)
((\:integers cc var (index i))
(#\:do cc ((var 0) (i 0)) #t ((+ var 1) (+ i 1))) )
((\:integers cc var)
(#\:do cc ((var 0)) #t ((+ var 1))) )))
(define-syntax \:range
(syntax-rules (index)
; handle index variable and add optional args
((\:range cc var (index i) arg1 arg ...)
(\:parallel cc (\:range var arg1 arg ...) (\:integers i)) )
((\:range cc var arg1)
(\:range cc var 0 arg1 1) )
((\:range cc var arg1 arg2)
(\:range cc var arg1 arg2 1) )
; special cases (partially evaluated by hand from general case)
((\:range cc var 0 arg2 1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var 0 arg2 -1)
(#\:do cc
(let ((b arg2))
(if (not (and (integer? b) (exact? b)))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" 0 b 1 )))
((var 0))
(> var b)
(let ())
#t
((- var 1)) ))
((\:range cc var arg1 arg2 1)
(#\:do cc
(let ((a arg1) (b arg2))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b 1 )) )
((var a))
(< var b)
(let ())
#t
((+ var 1)) ))
((\:range cc var arg1 arg2 -1)
(#\:do cc
(let ((a arg1) (b arg2) (s -1) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b -1 )) )
((var a))
(> var b)
(let ())
#t
((- var 1)) ))
; the general case
((\:range cc var arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (stop 0))
(if (not (and (integer? a) (exact? a)
(integer? b) (exact? b)
(integer? s) (exact? s) ))
(error
"arguments of :range are not exact integer "
"(use :real-range?)" a b s ))
(if (zero? s)
(error "step size must not be zero in :range") )
(set! stop (+ a (* (max 0 (ceiling (/ (- b a) s))) s))) )
((var a))
(not (= var stop))
(let ())
#t
((+ var s)) ))))
; Comment: The macro :range inserts some code to make sure the values
; are exact integers. This overhead has proven very helpful for
; saving users from themselves.
(define-syntax \:real-range
(syntax-rules (index)
; add optional args and index variable
((\:real-range cc var arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var (index i) arg1)
(\:real-range cc var (index i) 0 arg1 1) )
((\:real-range cc var arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var (index i) arg1 arg2)
(\:real-range cc var (index i) arg1 arg2 1) )
((\:real-range cc var arg1 arg2 arg3)
(\:real-range cc var (index i) arg1 arg2 arg3) )
; the fully qualified case
((\:real-range cc var (index i) arg1 arg2 arg3)
(#\:do cc
(let ((a arg1) (b arg2) (s arg3) (istop 0))
(if (not (and (real? a) (real? b) (real? s)))
(error "arguments of :real-range are not real" a b s) )
(if (and (exact? a) (or (not (exact? b)) (not (exact? s))))
(set! a (exact->inexact a)) )
(set! istop (/ (- b a) s)) )
((i 0))
(< i istop)
(let ((var (+ a (* s i)))))
#t
((+ i 1)) ))))
; Comment: The macro :real-range adapts the exactness of the start
; value in case any of the other values is inexact. This is a
; precaution to avoid (list-ec (\: x 0 3.0) x) => '(0 1.0 2.0).
(define-syntax \:char-range
(syntax-rules (index)
((\:char-range cc var (index i) arg1 arg2)
(\:parallel cc (\:char-range var arg1 arg2) (\:integers i)) )
((\:char-range cc var arg1 arg2)
(#\:do cc
(let ((imax (char->integer arg2))))
((i (char->integer arg1)))
(<= i imax)
(let ((var (integer->char i))))
#t
((+ i 1)) ))))
; Warning: There is no R5RS-way to implement the :char-range generator
; because the integers obtained by char->integer are not necessarily
; consecutive. We simply assume this anyhow for illustration.
(define-syntax \:port
(syntax-rules (index)
((\:port cc var (index i) arg1 arg ...)
(\:parallel cc (\:port var arg1 arg ...) (\:integers i)) )
((\:port cc var arg)
(\:port cc var arg read) )
((\:port cc var arg1 arg2)
(#\:do cc
(let ((port arg1) (read-proc arg2)))
((var (read-proc port)))
(not (eof-object? var))
(let ())
#t
((read-proc port)) ))))
; ==========================================================================
; The typed generator :dispatched and utilities for constructing dispatchers
; ==========================================================================
(define-syntax \:dispatched
(syntax-rules (index)
((\:dispatched cc var (index i) dispatch arg1 arg ...)
(\:parallel cc
(\:integers i)
(\:dispatched var dispatch arg1 arg ...) ))
((\:dispatched cc var dispatch arg1 arg ...)
(#\:do cc
(let ((d dispatch)
(args (list arg1 arg ...))
(g #f)
(empty (list #f)) )
(set! g (d args))
(if (not (procedure? g))
(error "unrecognized arguments in dispatching"
args
(d '()) )))
((var (g empty)))
(not (eq? var empty))
(let ())
#t
((g empty)) ))))
; Comment: The unique object empty is created as a newly allocated
; non-empty list. It is compared using eq? which distinguishes
; the object from any other object, according to R5RS 6.1.
(define-syntax \:generator-proc
(syntax-rules (#\:do let)
; call g with a variable, reentry at (**)
((\:generator-proc (g arg ...))
(g (\:generator-proc var) var arg ...) )
; reentry point (**) -> make the code from a single :do
((\:generator-proc
var
(#\:do (let obs oc ...)
((lv li) ...)
ne1?
(let ((i v) ...) ic ...)
ne2?
(ls ...)) )
(ec-simplify
(let obs
oc ...
(let ((lv li) ... (ne2 #t))
(ec-simplify
(let ((i #f) ...) ; v not yet valid
(lambda (empty)
(if (and ne1? ne2)
(ec-simplify
(begin
(set! i v) ...
ic ...
(let ((value var))
(ec-simplify
(if ne2?
(ec-simplify
(begin (set! lv ls) ...) )
(set! ne2 #f) ))
value )))
empty ))))))))
; silence warnings of some macro expanders
((\:generator-proc var)
(error "illegal macro call") )))
(define (dispatch-union d1 d2)
(lambda (args)
(let ((g1 (d1 args)) (g2 (d2 args)))
(if g1
(if g2
(if (null? args)
(append (if (list? g1) g1 (list g1))
(if (list? g2) g2 (list g2)) )
(error "dispatching conflict" args (d1 '()) (d2 '())) )
g1 )
(if g2 g2 #f) ))))
; ==========================================================================
; The dispatching generator :
; ==========================================================================
(define (make-initial-\:-dispatch)
(lambda (args)
(case (length args)
((0) 'SRFI42)
((1) (let ((a1 (car args)))
(cond
((list? a1)
(\:generator-proc (\:list a1)) )
((string? a1)
(\:generator-proc (\:string a1)) )
((vector? a1)
(\:generator-proc (\:vector a1)) )
((and (integer? a1) (exact? a1))
(\:generator-proc (\:range a1)) )
((real? a1)
(\:generator-proc (\:real-range a1)) )
((input-port? a1)
(\:generator-proc (\:port a1)) )
(else
#f ))))
((2) (let ((a1 (car args)) (a2 (cadr args)))
(cond
((and (list? a1) (list? a2))
(\:generator-proc (\:list a1 a2)) )
((and (string? a1) (string? a1))
(\:generator-proc (\:string a1 a2)) )
((and (vector? a1) (vector? a2))
(\:generator-proc (\:vector a1 a2)) )
((and (integer? a1) (exact? a1) (integer? a2) (exact? a2))
(\:generator-proc (\:range a1 a2)) )
((and (real? a1) (real? a2))
(\:generator-proc (\:real-range a1 a2)) )
((and (char? a1) (char? a2))
(\:generator-proc (\:char-range a1 a2)) )
((and (input-port? a1) (procedure? a2))
(\:generator-proc (\:port a1 a2)) )
(else
#f ))))
((3) (let ((a1 (car args)) (a2 (cadr args)) (a3 (caddr args)))
(cond
((and (list? a1) (list? a2) (list? a3))
(\:generator-proc (\:list a1 a2 a3)) )
((and (string? a1) (string? a1) (string? a3))
(\:generator-proc (\:string a1 a2 a3)) )
((and (vector? a1) (vector? a2) (vector? a3))
(\:generator-proc (\:vector a1 a2 a3)) )
((and (integer? a1) (exact? a1)
(integer? a2) (exact? a2)
(integer? a3) (exact? a3))
(\:generator-proc (\:range a1 a2 a3)) )
((and (real? a1) (real? a2) (real? a3))
(\:generator-proc (\:real-range a1 a2 a3)) )
(else
#f ))))
(else
(letrec ((every?
(lambda (pred args)
(if (null? args)
#t
(and (pred (car args))
(every? pred (cdr args)) )))))
(cond
((every? list? args)
(\:generator-proc (\:list (apply append args))) )
((every? string? args)
(\:generator-proc (\:string (apply string-append args))) )
((every? vector? args)
(\:generator-proc (\:list (apply append (map vector->list args)))) )
(else
#f )))))))
(define \\:-dispatch
(make-initial-\:-dispatch) )
(define (\\:-dispatch-ref)
\:-dispatch )
(define (\\:-dispatch-set! dispatch)
(if (not (procedure? dispatch))
(error "not a procedure" dispatch) )
(set! \:-dispatch dispatch) )
(define-syntax \:
(syntax-rules (index)
((\: cc var (index i) arg1 arg ...)
(\:dispatched cc var (index i) \:-dispatch arg1 arg ...) )
((\: cc var arg1 arg ...)
(\:dispatched cc var \:-dispatch arg1 arg ...) )))
; ==========================================================================
; The utility comprehensions fold-ec, fold3-ec
; ==========================================================================
(define-syntax fold3-ec
(syntax-rules (nested)
((fold3-ec x0 (nested q1 ...) q etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 ... q) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 q1 q2 etc1 etc2 etc3 etc ...)
(fold3-ec x0 (nested q1 q2) etc1 etc2 etc3 etc ...) )
((fold3-ec x0 expression f1 f2)
(fold3-ec x0 (nested) expression f1 f2) )
((fold3-ec x0 qualifier expression f1 f2)
(let ((result #f) (empty #t))
(do-ec qualifier
(let ((value expression)) ; don't duplicate
(if empty
(begin (set! result (f1 value))
(set! empty #f) )
(set! result (f2 value result)) )))
(if empty x0 result) ))))
(define-syntax fold-ec
(syntax-rules (nested)
((fold-ec x0 (nested q1 ...) q etc1 etc2 etc ...)
(fold-ec x0 (nested q1 ... q) etc1 etc2 etc ...) )
((fold-ec x0 q1 q2 etc1 etc2 etc ...)
(fold-ec x0 (nested q1 q2) etc1 etc2 etc ...) )
((fold-ec x0 expression f2)
(fold-ec x0 (nested) expression f2) )
((fold-ec x0 qualifier expression f2)
(let ((result x0))
(do-ec qualifier (set! result (f2 expression result)))
result ))))
; ==========================================================================
; The comprehensions list-ec string-ec vector-ec etc.
; ==========================================================================
(define-syntax list-ec
(syntax-rules ()
((list-ec etc1 etc ...)
(reverse (fold-ec '() etc1 etc ... cons)) )))
; Alternative: Reverse can safely be replaced by reverse! if you have it.
;
; Alternative: It is possible to construct the result in the correct order
; using set-cdr! to add at the tail. This removes the overhead of copying
; at the end, at the cost of more book-keeping.
(define-syntax append-ec
(syntax-rules ()
((append-ec etc1 etc ...)
(apply append (list-ec etc1 etc ...)) )))
(define-syntax string-ec
(syntax-rules ()
((string-ec etc1 etc ...)
(list->string (list-ec etc1 etc ...)) )))
; Alternative: For very long strings, the intermediate list may be a
; problem. A more space-aware implementation collect the characters
; in an intermediate list and when this list becomes too large it is
; converted into an intermediate string. At the end, the intermediate
; strings are concatenated with string-append.
(define-syntax string-append-ec
(syntax-rules ()
((string-append-ec etc1 etc ...)
(apply string-append (list-ec etc1 etc ...)) )))
(define-syntax vector-ec
(syntax-rules ()
((vector-ec etc1 etc ...)
(list->vector (list-ec etc1 etc ...)) )))
; Comment: A similar approach as for string-ec can be used for vector-ec.
; However, the space overhead for the intermediate list is much lower
; than for string-ec and as there is no vector-append, the intermediate
; vectors must be copied explicitly.
(define-syntax vector-of-length-ec
(syntax-rules (nested)
((vector-of-length-ec k (nested q1 ...) q etc1 etc ...)
(vector-of-length-ec k (nested q1 ... q) etc1 etc ...) )
((vector-of-length-ec k q1 q2 etc1 etc ...)
(vector-of-length-ec k (nested q1 q2) etc1 etc ...) )
((vector-of-length-ec k expression)
(vector-of-length-ec k (nested) expression) )
((vector-of-length-ec k qualifier expression)
(let ((len k))
(let ((vec (make-vector len))
(i 0) )
(do-ec qualifier
(if (< i len)
(begin (vector-set! vec i expression)
(set! i (+ i 1)) )
(error "vector is too short for the comprehension") ))
(if (= i len)
vec
(error "vector is too long for the comprehension") ))))))
(define-syntax sum-ec
(syntax-rules ()
((sum-ec etc1 etc ...)
(fold-ec (+) etc1 etc ... +) )))
(define-syntax product-ec
(syntax-rules ()
((product-ec etc1 etc ...)
(fold-ec (*) etc1 etc ... *) )))
(define-syntax min-ec
(syntax-rules ()
((min-ec etc1 etc ...)
(fold3-ec (min) etc1 etc ... min min) )))
(define-syntax max-ec
(syntax-rules ()
((max-ec etc1 etc ...)
(fold3-ec (max) etc1 etc ... max max) )))
(define-syntax last-ec
(syntax-rules (nested)
((last-ec default (nested q1 ...) q etc1 etc ...)
(last-ec default (nested q1 ... q) etc1 etc ...) )
((last-ec default q1 q2 etc1 etc ...)
(last-ec default (nested q1 q2) etc1 etc ...) )
((last-ec default expression)
(last-ec default (nested) expression) )
((last-ec default qualifier expression)
(let ((result default))
(do-ec qualifier (set! result expression))
result ))))
; ==========================================================================
; The fundamental early-stopping comprehension first-ec
; ==========================================================================
(define-syntax first-ec
(syntax-rules (nested)
((first-ec default (nested q1 ...) q etc1 etc ...)
(first-ec default (nested q1 ... q) etc1 etc ...) )
((first-ec default q1 q2 etc1 etc ...)
(first-ec default (nested q1 q2) etc1 etc ...) )
((first-ec default expression)
(first-ec default (nested) expression) )
((first-ec default qualifier expression)
(let ((result default) (stop #f))
(ec-guarded-do-ec
stop
(nested qualifier)
(begin (set! result expression)
(set! stop #t) ))
result ))))
; (ec-guarded-do-ec stop (nested q ...) cmd)
; constructs (do-ec q ... cmd) where the generators gen in q ... are
; replaced by (\:until gen stop).
(define-syntax ec-guarded-do-ec
(syntax-rules (nested if not and or begin)
((ec-guarded-do-ec stop (nested (nested q1 ...) q2 ...) cmd)
(ec-guarded-do-ec stop (nested q1 ... q2 ...) cmd) )
((ec-guarded-do-ec stop (nested (if test) q ...) cmd)
(if test (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (not test) q ...) cmd)
(if (not test) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (and test ...) q ...) cmd)
(if (and test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (or test ...) q ...) cmd)
(if (or test ...) (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested (begin etc ...) q ...) cmd)
(begin etc ... (ec-guarded-do-ec stop (nested q ...) cmd)) )
((ec-guarded-do-ec stop (nested gen q ...) cmd)
(do-ec
(\:until gen stop)
(ec-guarded-do-ec stop (nested q ...) cmd) ))
((ec-guarded-do-ec stop (nested) cmd)
(do-ec cmd) )))
; Alternative: Instead of modifying the generator with :until, it is
; possible to use call-with-current-continuation:
;
; (define-synatx first-ec
; ...same as above...
; ((first-ec default qualifier expression)
; (call-with-current-continuation
; (lambda (cc)
; (do-ec qualifier (cc expression))
; default ))) ))
;
; This is much simpler but not necessarily as efficient.
; ==========================================================================
; The early-stopping comprehensions any?-ec every?-ec
; ==========================================================================
(define-syntax any?-ec
(syntax-rules (nested)
((any?-ec (nested q1 ...) q etc1 etc ...)
(any?-ec (nested q1 ... q) etc1 etc ...) )
((any?-ec q1 q2 etc1 etc ...)
(any?-ec (nested q1 q2) etc1 etc ...) )
((any?-ec expression)
(any?-ec (nested) expression) )
((any?-ec qualifier expression)
(first-ec #f qualifier (if expression) #t) )))
(define-syntax every?-ec
(syntax-rules (nested)
((every?-ec (nested q1 ...) q etc1 etc ...)
(every?-ec (nested q1 ... q) etc1 etc ...) )
((every?-ec q1 q2 etc1 etc ...)
(every?-ec (nested q1 q2) etc1 etc ...) )
((every?-ec expression)
(every?-ec (nested) expression) )
((every?-ec qualifier expression)
(first-ec #t qualifier (if (not expression)) #f) )))
;;; srfi-43.scm -- SRFI 43 Vector library
;; Copyright (C) 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Mark H Weaver <mhw@netris.org>
(define-module (srfi srfi-43)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-8)
#\re-export (make-vector vector vector? vector-ref vector-set!
vector-length)
#\replace (vector-copy vector-fill! list->vector vector->list)
#\export (vector-empty? vector= vector-unfold vector-unfold-right
vector-reverse-copy
vector-append vector-concatenate
vector-fold vector-fold-right
vector-map vector-map!
vector-for-each vector-count
vector-index vector-index-right
vector-skip vector-skip-right
vector-binary-search
vector-any vector-every
vector-swap! vector-reverse!
vector-copy! vector-reverse-copy!
reverse-vector->list
reverse-list->vector))
(cond-expand-provide (current-module) '(srfi-43))
(define (error-from who msg . args)
(apply error
(string-append (symbol->string who) ": " msg)
args))
(define-syntax-rule (assert-nonneg-exact-integer k who)
(unless (and (exact-integer? k)
(not (negative? k)))
(error-from who "expected non-negative exact integer, got" k)))
(define-syntax-rule (assert-procedure f who)
(unless (procedure? f)
(error-from who "expected procedure, got" f)))
(define-syntax-rule (assert-vector v who)
(unless (vector? v)
(error-from who "expected vector, got" v)))
(define-syntax-rule (assert-valid-index i len who)
(unless (and (exact-integer? i)
(<= 0 i len))
(error-from who "invalid index" i)))
(define-syntax-rule (assert-valid-start start len who)
(unless (and (exact-integer? start)
(<= 0 start len))
(error-from who "invalid start index" start)))
(define-syntax-rule (assert-valid-range start end len who)
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end len))
(error-from who "invalid index range" start end)))
(define-syntax-rule (assert-vectors vs who)
(let loop ((vs vs))
(unless (null? vs)
(assert-vector (car vs) who)
(loop (cdr vs)))))
;; Return the length of the shortest vector in VS.
;; VS must have at least one element.
(define (min-length vs)
(let loop ((vs (cdr vs))
(result (vector-length (car vs))))
(if (null? vs)
result
(loop (cdr vs) (min result (vector-length (car vs)))))))
;; Return a list of the Ith elements of the vectors in VS.
(define (vectors-ref vs i)
(let loop ((vs vs) (xs '()))
(if (null? vs)
(reverse! xs)
(loop (cdr vs) (cons (vector-ref (car vs) i)
xs)))))
(define vector-unfold
(case-lambda
"(vector-unfold f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from 0 up to LENGTH - 1,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i))
(loop (+ i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed seed))
(unless (= i len)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (+ i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seed1 seed1) (seed2 seed2))
(unless (= i len)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (+ i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold)
(assert-nonneg-exact-integer len 'vector-unfold)
(let ((v (make-vector len)))
(let loop ((i 0) (seeds seeds))
(unless (= i len)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (+ i 1) seeds))))
v))))
(define vector-unfold-right
(case-lambda
"(vector-unfold-right f length initial-seed ...) -> vector
The fundamental vector constructor. Create a vector whose length is
LENGTH and iterates across each index k from LENGTH - 1 down to 0,
applying F at each iteration to the current index and current seeds, in
that order, to receive n + 1 values: the element to put in the kth slot
of the new vector, and n new seeds for the next iteration. It is an
error for the number of seeds to vary between iterations."
((f len)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)))
(unless (negative? i)
(vector-set! v i (f i))
(loop (- i 1))))
v))
((f len seed)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed seed))
(unless (negative? i)
(receive (x seed) (f i seed)
(vector-set! v i x)
(loop (- i 1) seed))))
v))
((f len seed1 seed2)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seed1 seed1) (seed2 seed2))
(unless (negative? i)
(receive (x seed1 seed2) (f i seed1 seed2)
(vector-set! v i x)
(loop (- i 1) seed1 seed2))))
v))
((f len . seeds)
(assert-procedure f 'vector-unfold-right)
(assert-nonneg-exact-integer len 'vector-unfold-right)
(let ((v (make-vector len)))
(let loop ((i (- len 1)) (seeds seeds))
(unless (negative? i)
(receive (x . seeds) (apply f i seeds)
(vector-set! v i x)
(loop (- i 1) seeds))))
v))))
(define guile-vector-copy (@ (guile) vector-copy))
;; TODO: Enhance Guile core 'vector-copy' to do this.
(define vector-copy
(case-lambda*
"(vector-copy vec [start [end [fill]]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec starting at index START
and stopping at index END. START defaults to 0 and END defaults to
the value of (vector-length VEC). If END extends beyond the length of
VEC, the slots in the new vector that obviously cannot be filled by
elements from VEC are filled with FILL, whose default value is
unspecified."
((v) (guile-vector-copy v))
((v start)
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(assert-valid-start start len 'vector-copy)
(let ((result (make-vector (- len start))))
(vector-move-left! v start len result 0)
result)))
((v start end #\optional (fill *unspecified*))
(assert-vector v 'vector-copy)
(let ((len (vector-length v)))
(unless (and (exact-integer? start)
(exact-integer? end)
(<= 0 start end))
(error-from 'vector-copy "invalid index range" start end))
(let ((result (make-vector (- end start) fill)))
(vector-move-left! v start (min end len) result 0)
result)))))
(define vector-reverse-copy
(let ()
(define (%vector-reverse-copy vec start end)
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (j (- end 1)))
(unless (= i len)
(vector-set! result i (vector-ref vec j))
(loop (+ i 1) (- j 1))))
result))
(case-lambda
"(vector-reverse-copy vec [start [end]]) -> vector
Allocate a new vector whose length is END - START and fills it with
elements from vec, taking elements from vec in reverse order starting
at index START and stopping at index END. START defaults to 0 and END
defaults to the value of (vector-length VEC)."
((vec)
(assert-vector vec 'vector-reverse-copy)
(%vector-reverse-copy vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse-copy)
(%vector-reverse-copy vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse-copy)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse-copy)
(%vector-reverse-copy vec start end))))))
(define (%vector-concatenate vs)
(let* ((result-len (let loop ((vs vs) (len 0))
(if (null? vs)
len
(loop (cdr vs) (+ len (vector-length (car vs)))))))
(result (make-vector result-len)))
(let loop ((vs vs) (pos 0))
(unless (null? vs)
(let* ((v (car vs))
(len (vector-length v)))
(vector-move-left! v 0 len result pos)
(loop (cdr vs) (+ pos len)))))
result))
(define vector-append
(case-lambda
"(vector-append vec ...) -> vector
Return a newly allocated vector that contains all elements in order
from the subsequent locations in VEC ..."
(() (vector))
((v)
(assert-vector v 'vector-append)
(guile-vector-copy v))
((v1 v2)
(assert-vector v1 'vector-append)
(assert-vector v2 'vector-append)
(let ((len1 (vector-length v1))
(len2 (vector-length v2)))
(let ((result (make-vector (+ len1 len2))))
(vector-move-left! v1 0 len1 result 0)
(vector-move-left! v2 0 len2 result len1)
result)))
(vs
(assert-vectors vs 'vector-append)
(%vector-concatenate vs))))
(define (vector-concatenate vs)
"(vector-concatenate list-of-vectors) -> vector
Append each vector in LIST-OF-VECTORS. Equivalent to:
(apply vector-append LIST-OF-VECTORS)"
(assert-vectors vs 'vector-concatenate)
(%vector-concatenate vs))
(define (vector-empty? vec)
"(vector-empty? vec) -> boolean
Return true if VEC is empty, i.e. its length is 0, and false if not."
(assert-vector vec 'vector-empty?)
(zero? (vector-length vec)))
(define vector=
(let ()
(define (all-of-length? len vs)
(or (null? vs)
(and (= len (vector-length (car vs)))
(all-of-length? len (cdr vs)))))
(define (=up-to? i elt=? v1 v2)
(or (negative? i)
(let ((x1 (vector-ref v1 i))
(x2 (vector-ref v2 i)))
(and (or (eq? x1 x2) (elt=? x1 x2))
(=up-to? (- i 1) elt=? v1 v2)))))
(case-lambda
"(vector= elt=? vec ...) -> boolean
Return true if the vectors VEC ... have equal lengths and equal
elements according to ELT=?. ELT=? is always applied to two
arguments. Element comparison must be consistent with eq?, in the
following sense: if (eq? a b) returns true, then (elt=? a b) must also
return true. The order in which comparisons are performed is
unspecified."
((elt=?)
(assert-procedure elt=? 'vector=)
#t)
((elt=? v)
(assert-procedure elt=? 'vector=)
(assert-vector v 'vector=)
#t)
((elt=? v1 v2)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vector v2 'vector=)
(let ((len (vector-length v1)))
(and (= len (vector-length v2))
(=up-to? (- len 1) elt=? v1 v2))))
((elt=? v1 . vs)
(assert-procedure elt=? 'vector=)
(assert-vector v1 'vector=)
(assert-vectors vs 'vector=)
(let ((len (vector-length v1)))
(and (all-of-length? len vs)
(let loop ((vs vs))
(or (null? vs)
(and (=up-to? (- len 1) elt=? v1 (car vs))
(loop (cdr vs)))))))))))
(define vector-fold
(case-lambda
"(vector-fold kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
all of the vectors, stopping at the end of the shortest; KONS is
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
left-to-right."
((kcons knil v)
(assert-procedure kcons 'vector-fold)
(assert-vector v 'vector-fold)
(let ((len (vector-length v)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold)
(assert-vector v1 'vector-fold)
(assert-vector v2 'vector-fold)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold)
(assert-vectors vs 'vector-fold)
(let ((len (min-length vs)))
(let loop ((i 0) (state knil))
(if (= i len)
state
(loop (+ i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-fold-right
(case-lambda
"(vector-fold-right kons knil vec1 vec2 ...) -> value
The fundamental vector iterator. KONS is iterated over each index in
all of the vectors, starting at the end of the shortest; KONS is
applied as (KONS i state (vector-ref VEC1 i) (vector-ref VEC2 i) ...)
where STATE is the current state value, and I is the current index.
The current state value begins with KNIL, and becomes whatever KONS
returned at the respective iteration. The iteration is strictly
right-to-left."
((kcons knil v)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v 'vector-fold-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (kcons i state (vector-ref v i)))))))
((kcons knil v1 v2)
(assert-procedure kcons 'vector-fold-right)
(assert-vector v1 'vector-fold-right)
(assert-vector v2 'vector-fold-right)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1)
(kcons i state (vector-ref v1 i) (vector-ref v2 i)))))))
((kcons knil . vs)
(assert-procedure kcons 'vector-fold-right)
(assert-vectors vs 'vector-fold-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)) (state knil))
(if (negative? i)
state
(loop (- i 1) (apply kcons i state (vectors-ref vs i)))))))))
(define vector-map
(case-lambda
"(vector-map f vec2 vec2 ...) -> vector
Return a new vector of the shortest size of the vector arguments.
Each element at index i of the new vector is mapped from the old
vectors by (F i (vector-ref VEC1 i) (vector-ref VEC2 i) ...). The
dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map)
(assert-vector v 'vector-map)
(let* ((len (vector-length v))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v i)))
(loop (+ i 1))))
result))
((f v1 v2)
(assert-procedure f 'vector-map)
(assert-vector v1 'vector-map)
(assert-vector v2 'vector-map)
(let* ((len (min (vector-length v1) (vector-length v2)))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))
result))
((f . vs)
(assert-procedure f 'vector-map)
(assert-vectors vs 'vector-map)
(let* ((len (min-length vs))
(result (make-vector len)))
(let loop ((i 0))
(unless (= i len)
(vector-set! result i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))
result))))
(define vector-map!
(case-lambda
"(vector-map! f vec2 vec2 ...) -> unspecified
Similar to vector-map, but rather than mapping the new elements into a
new vector, the new mapped elements are destructively inserted into
VEC1. The dynamic order of application of F is unspecified."
((f v)
(assert-procedure f 'vector-map!)
(assert-vector v 'vector-map!)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v i (f i (vector-ref v i)))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-map!)
(assert-vector v1 'vector-map!)
(assert-vector v2 'vector-map!)
(let ((len (min (vector-length v1) (vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (f i (vector-ref v1 i) (vector-ref v2 i)))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-map!)
(assert-vectors vs 'vector-map!)
(let ((len (min-length vs))
(v1 (car vs)))
(let loop ((i 0))
(unless (= i len)
(vector-set! v1 i (apply f i (vectors-ref vs i)))
(loop (+ i 1))))))))
(define vector-for-each
(case-lambda
"(vector-for-each f vec1 vec2 ...) -> unspecified
Call (F i VEC1[i] VEC2[i] ...) for each index i less than the length
of the shortest vector passed. The iteration is strictly
left-to-right."
((f v)
(assert-procedure f 'vector-for-each)
(assert-vector v 'vector-for-each)
(let ((len (vector-length v)))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v i))
(loop (+ i 1))))))
((f v1 v2)
(assert-procedure f 'vector-for-each)
(assert-vector v1 'vector-for-each)
(assert-vector v2 'vector-for-each)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(unless (= i len)
(f i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1))))))
((f . vs)
(assert-procedure f 'vector-for-each)
(assert-vectors vs 'vector-for-each)
(let ((len (min-length vs)))
(let loop ((i 0))
(unless (= i len)
(apply f i (vectors-ref vs i))
(loop (+ i 1))))))))
(define vector-count
(case-lambda
"(vector-count pred? vec1 vec2 ...) -> exact nonnegative integer
Count the number of indices i for which (PRED? VEC1[i] VEC2[i] ...)
returns true, where i is less than the length of the shortest vector
passed."
((pred? v)
(assert-procedure pred? 'vector-count)
(assert-vector v 'vector-count)
(let ((len (vector-length v)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-count)
(assert-vector v1 'vector-count)
(assert-vector v2 'vector-count)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((pred? i (vector-ref v1 i) (vector-ref v2 i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))
((pred? . vs)
(assert-procedure pred? 'vector-count)
(assert-vectors vs 'vector-count)
(let ((len (min-length vs)))
(let loop ((i 0) (count 0))
(cond ((= i len) count)
((apply pred? i (vectors-ref vs i))
(loop (+ i 1) (+ count 1)))
(else
(loop (+ i 1) count))))))))
(define vector-index
(case-lambda
"(vector-index pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
satisfy PRED?. If no matching element is found by the end of the
shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index)
(assert-vector v 'vector-index)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
i
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index)
(assert-vector v1 'vector-index)
(assert-vector v2 'vector-index)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index)
(assert-vectors vs 'vector-index)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
i
(loop (+ i 1)))))))))
(define vector-index-right
(case-lambda
"(vector-index-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
satisfy PRED?, searching from right-to-left. If no matching element
is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-index-right)
(assert-vector v 'vector-index-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v i))
i
(loop (- i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-index-right)
(assert-vector v1 'vector-index-right)
(assert-vector v2 'vector-index-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
i
(loop (- i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-index-right)
(assert-vectors vs 'vector-index-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (>= i 0)
(if (apply pred? (vectors-ref vs i))
i
(loop (- i 1)))))))))
(define vector-skip
(case-lambda
"(vector-skip pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the first elements in VEC1 VEC2 ... that
do not satisfy PRED?. If no matching element is found by the end of
the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip)
(assert-vector v 'vector-skip)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v i))
(loop (+ i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip)
(assert-vector v1 'vector-skip)
(assert-vector v2 'vector-skip)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip)
(assert-vectors vs 'vector-skip)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(if (apply pred? (vectors-ref vs i))
(loop (+ i 1))
i)))))))
(define vector-skip-right
(case-lambda
"(vector-skip-right pred? vec1 vec2 ...) -> exact nonnegative integer or #f
Find and return the index of the last elements in VEC1 VEC2 ... that
do not satisfy PRED?, searching from right-to-left. If no matching
element is found before the end of the shortest vector, return #f."
((pred? v)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v 'vector-skip-right)
(let ((len (vector-length v)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v i))
(loop (- i 1))
i)))))
((pred? v1 v2)
(assert-procedure pred? 'vector-skip-right)
(assert-vector v1 'vector-skip-right)
(assert-vector v2 'vector-skip-right)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (- i 1))
i)))))
((pred? . vs)
(assert-procedure pred? 'vector-skip-right)
(assert-vectors vs 'vector-skip-right)
(let ((len (min-length vs)))
(let loop ((i (- len 1)))
(and (not (negative? i))
(if (apply pred? (vectors-ref vs i))
(loop (- i 1))
i)))))))
(define vector-binary-search
(let ()
(define (%vector-binary-search vec value cmp start end)
(let loop ((lo start) (hi end))
(and (< lo hi)
(let* ((i (quotient (+ lo hi) 2))
(x (vector-ref vec i))
(c (cmp x value)))
(cond ((zero? c) i)
((positive? c) (loop lo i))
((negative? c) (loop (+ i 1) hi)))))))
(case-lambda
"(vector-binary-search vec value cmp [start [end]]) -> exact nonnegative integer or #f
Find and return an index of VEC between START and END whose value is
VALUE using a binary search. If no matching element is found, return
#f. The default START is 0 and the default END is the length of VEC.
CMP must be a procedure of two arguments such that (CMP A B) returns
a negative integer if A < B, a positive integer if A > B, or zero if
A = B. The elements of VEC must be sorted in non-decreasing order
according to CMP."
((vec value cmp)
(assert-vector vec 'vector-binary-search)
(assert-procedure cmp 'vector-binary-search)
(%vector-binary-search vec value cmp 0 (vector-length vec)))
((vec value cmp start)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-binary-search)
(%vector-binary-search vec value cmp start len)))
((vec value cmp start end)
(assert-vector vec 'vector-binary-search)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-binary-search)
(%vector-binary-search vec value cmp start end))))))
(define vector-any
(case-lambda
"(vector-any pred? vec1 vec2 ...) -> value or #f
Find the first parallel set of elements from VEC1 VEC2 ... for which
PRED? returns a true value. If such a parallel set of elements
exists, vector-any returns the value that PRED? returned for that set
of elements. The iteration is strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-any)
(assert-vector v 'vector-any)
(let ((len (vector-length v)))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v i))
(loop (+ i 1)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-any)
(assert-vector v1 'vector-any)
(assert-vector v2 'vector-any)
(let ((len (min (vector-length v1)
(vector-length v2))))
(let loop ((i 0))
(and (< i len)
(or (pred? (vector-ref v1 i)
(vector-ref v2 i))
(loop (+ i 1)))))))
((pred? . vs)
(assert-procedure pred? 'vector-any)
(assert-vectors vs 'vector-any)
(let ((len (min-length vs)))
(let loop ((i 0))
(and (< i len)
(or (apply pred? (vectors-ref vs i))
(loop (+ i 1)))))))))
(define vector-every
(case-lambda
"(vector-every pred? vec1 vec2 ...) -> value or #f
If, for every index i less than the length of the shortest vector
argument, the set of elements VEC1[i] VEC2[i] ... satisfies PRED?,
vector-every returns the value that PRED? returned for the last set of
elements, at the last index of the shortest vector. The iteration is
strictly left-to-right."
((pred? v)
(assert-procedure pred? 'vector-every)
(assert-vector v 'vector-every)
(let ((len (vector-length v)))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? v1 v2)
(assert-procedure pred? 'vector-every)
(assert-vector v1 'vector-every)
(assert-vector v2 'vector-every)
(let ((len (min (vector-length v1)
(vector-length v2))))
(or (zero? len)
(let loop ((i 0))
(let ((val (pred? (vector-ref v1 i)
(vector-ref v2 i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))
((pred? . vs)
(assert-procedure pred? 'vector-every)
(assert-vectors vs 'vector-every)
(let ((len (min-length vs)))
(or (zero? len)
(let loop ((i 0))
(let ((val (apply pred? (vectors-ref vs i)))
(next-i (+ i 1)))
(if (or (not val) (= next-i len))
val
(loop next-i)))))))))
(define (vector-swap! vec i j)
"(vector-swap! vec i j) -> unspecified
Swap the values of the locations in VEC at I and J."
(assert-vector vec 'vector-swap!)
(let ((len (vector-length vec)))
(assert-valid-index i len 'vector-swap!)
(assert-valid-index j len 'vector-swap!)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp))))
;; TODO: Enhance Guile core 'vector-fill!' to do this.
(define vector-fill!
(let ()
(define guile-vector-fill!
(@ (guile) vector-fill!))
(define (%vector-fill! vec fill start end)
(let loop ((i start))
(when (< i end)
(vector-set! vec i fill)
(loop (+ i 1)))))
(case-lambda
"(vector-fill! vec fill [start [end]]) -> unspecified
Assign the value of every location in VEC between START and END to
FILL. START defaults to 0 and END defaults to the length of VEC."
((vec fill)
(guile-vector-fill! vec fill))
((vec fill start)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-fill!)
(%vector-fill! vec fill start len)))
((vec fill start end)
(assert-vector vec 'vector-fill!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-fill!)
(%vector-fill! vec fill start end))))))
(define (%vector-reverse! vec start end)
(let loop ((i start) (j (- end 1)))
(when (< i j)
(let ((tmp (vector-ref vec i)))
(vector-set! vec i (vector-ref vec j))
(vector-set! vec j tmp)
(loop (+ i 1) (- j 1))))))
(define vector-reverse!
(case-lambda
"(vector-reverse! vec [start [end]]) -> unspecified
Destructively reverse the contents of VEC between START and END.
START defaults to 0 and END defaults to the length of VEC."
((vec)
(assert-vector vec 'vector-reverse!)
(%vector-reverse! vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector-reverse!)
(%vector-reverse! vec start len)))
((vec start end)
(assert-vector vec 'vector-reverse!)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector-reverse!)
(%vector-reverse! vec start end)))))
(define-syntax-rule (define-vector-copier! copy! docstring inner-proc)
(define copy!
(let ((%copy! inner-proc))
(case-lambda
docstring
((target tstart source)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(unless (>= tlen (+ tstart slen))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source 0 slen)))
((target tstart source sstart)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-start sstart slen 'copy!)
(unless (>= tlen (+ tstart (- slen sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart slen)))
((target tstart source sstart send)
(assert-vector target 'copy!)
(assert-vector source 'copy!)
(let ((tlen (vector-length target))
(slen (vector-length source)))
(assert-valid-start tstart tlen 'copy!)
(assert-valid-range sstart send slen 'copy!)
(unless (>= tlen (+ tstart (- send sstart)))
(error-from 'copy! "would write past end of target"))
(%copy! target tstart source sstart send)))))))
(define-vector-copier! vector-copy!
"(vector-copy! target tstart source [sstart [send]]) -> unspecified
Copy a block of elements from SOURCE to TARGET, both of which must be
vectors, starting in TARGET at TSTART and starting in SOURCE at
SSTART, ending when SEND - SSTART elements have been copied. It is an
error for TARGET to have a length less than TSTART + (SEND - SSTART).
SSTART defaults to 0 and SEND defaults to the length of SOURCE."
(lambda (target tstart source sstart send)
(if (< tstart sstart)
(vector-move-left! source sstart send target tstart)
(vector-move-right! source sstart send target tstart))))
(define-vector-copier! vector-reverse-copy!
"(vector-reverse-copy! target tstart source [sstart [send]]) -> unspecified
Like vector-copy!, but copy the elements in the reverse order. It is
an error if TARGET and SOURCE are identical vectors and the TARGET and
SOURCE ranges overlap; however, if TSTART = SSTART,
vector-reverse-copy! behaves as (vector-reverse! TARGET TSTART SEND)
would."
(lambda (target tstart source sstart send)
(if (and (eq? target source) (= tstart sstart))
(%vector-reverse! target sstart send)
(let loop ((i tstart) (j (- send 1)))
(when (>= j sstart)
(vector-set! target i (vector-ref source j))
(loop (+ i 1) (- j 1)))))))
(define vector->list
(let ()
(define (%vector->list vec start end)
(let loop ((i (- end 1))
(result '()))
(if (< i start)
result
(loop (- i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END. START defaults to 0 and END defaults to the length of
VEC."
((vec)
(assert-vector vec 'vector->list)
(%vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'vector->list)
(%vector->list vec start len)))
((vec start end)
(assert-vector vec 'vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'vector->list)
(%vector->list vec start end))))))
(define reverse-vector->list
(let ()
(define (%reverse-vector->list vec start end)
(let loop ((i start)
(result '()))
(if (>= i end)
result
(loop (+ i 1) (cons (vector-ref vec i) result)))))
(case-lambda
"(reverse-vector->list vec [start [end]]) -> proper-list
Return a newly allocated list containing the elements in VEC between
START and END in reverse order. START defaults to 0 and END defaults
to the length of VEC."
((vec)
(assert-vector vec 'reverse-vector->list)
(%reverse-vector->list vec 0 (vector-length vec)))
((vec start)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-start start len 'reverse-vector->list)
(%reverse-vector->list vec start len)))
((vec start end)
(assert-vector vec 'reverse-vector->list)
(let ((len (vector-length vec)))
(assert-valid-range start end len 'reverse-vector->list)
(%reverse-vector->list vec start end))))))
;; TODO: change to use 'case-lambda' and improve error checking.
(define* (list->vector lst #\optional (start 0) (end (length lst)))
"(list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END. START defaults to 0 and END defaults
to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i 0) (lst (drop lst start)))
(if (= i len)
result
(begin (vector-set! result i (car lst))
(loop (+ i 1) (cdr lst)))))))
;; TODO: change to use 'case-lambda' and improve error checking.
(define* (reverse-list->vector lst #\optional (start 0) (end (length lst)))
"(reverse-list->vector proper-list [start [end]]) -> vector
Return a newly allocated vector of the elements from PROPER-LIST with
indices between START and END, in reverse order. START defaults to 0
and END defaults to the length of PROPER-LIST."
(let* ((len (- end start))
(result (make-vector len)))
(let loop ((i (- len 1)) (lst (drop lst start)))
(if (negative? i)
result
(begin (vector-set! result i (car lst))
(loop (- i 1) (cdr lst)))))))
;;; srfi-45.scm -- Primitives for Expressing Iterative Lazy Algorithms
;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;; Copyright (C) 2003 André van Tonder. All Rights Reserved.
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
;;; Commentary:
;; This is the code of the reference implementation of SRFI-45, modified
;; to use SRFI-9 and to add 'promise?' to the list of exports.
;; This module is documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-45)
#\export (delay
lazy
force
eager
promise?)
#\replace (delay force promise?)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu))
(cond-expand-provide (current-module) '(srfi-45))
(define-record-type promise (make-promise val) promise?
(val promise-val promise-val-set!))
(define-record-type value (make-value tag proc) value?
(tag value-tag value-tag-set!)
(proc value-proc value-proc-set!))
(define-syntax-rule (lazy exp)
(make-promise (make-value 'lazy (lambda () exp))))
(define (eager x)
(make-promise (make-value 'eager x)))
(define-syntax-rule (delay exp)
(lazy (eager exp)))
(define (force promise)
(let ((content (promise-val promise)))
(case (value-tag content)
((eager) (value-proc content))
((lazy) (let* ((promise* ((value-proc content)))
(content (promise-val promise))) ; *
(if (not (eqv? (value-tag content) 'eager)) ; *
(begin (value-tag-set! content
(value-tag (promise-val promise*)))
(value-proc-set! content
(value-proc (promise-val promise*)))
(promise-val-set! promise* content)))
(force promise))))))
;; (*) These two lines re-fetch and check the original promise in case
;; the first line of the let* caused it to be forced. For an example
;; where this happens, see reentrancy test 3 below.
(define* (promise-visit promise #\key on-eager on-lazy)
(define content (promise-val promise))
(case (value-tag content)
((eager) (on-eager (value-proc content)))
((lazy) (on-lazy (value-proc content)))))
(set-record-type-printer! promise
(lambda (promise port)
(promise-visit promise
#\on-eager (lambda (value)
(format port "#<promise = ~s>" value))
#\on-lazy (lambda (proc)
(format port "#<promise => ~s>" proc)))))
;;; srfi-6.scm --- Basic String Ports
;; Copyright (C) 2001, 2002, 2003, 2006, 2012 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-6)
#\replace (open-input-string open-output-string)
#\re-export (get-output-string))
;; SRFI-6 says nothing about encodings, and assumes that any character
;; or string can be written to a string port. Thus, make all SRFI-6
;; string ports Unicode capable. See <http://bugs.gnu.org/11197>.
(define (open-input-string s)
(with-fluids ((%default-port-encoding "UTF-8"))
((@ (guile) open-input-string) s)))
(define (open-output-string)
(with-fluids ((%default-port-encoding "UTF-8"))
((@ (guile) open-output-string))))
(cond-expand-provide (current-module) '(srfi-6))
;;; srfi-6.scm ends here
;;; srfi-60.scm --- Integers as Bits
;; Copyright (C) 2005, 2006, 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (srfi srfi-60)
#\export (bitwise-and
bitwise-ior
bitwise-xor
bitwise-not
any-bits-set?
bitwise-if bitwise-merge
log2-binary-factors first-set-bit
bit-set?
copy-bit
bit-field
copy-bit-field
arithmetic-shift
rotate-bit-field
reverse-bit-field
integer->list
list->integer
booleans->integer)
#\replace (bit-count)
#\re-export (logand
logior
logxor
integer-length
logtest
logcount
logbit?
ash))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_srfi_60")
(define bitwise-and logand)
(define bitwise-ior logior)
(define bitwise-xor logxor)
(define bitwise-not lognot)
(define any-bits-set? logtest)
(define bit-count logcount)
(define (bitwise-if mask n0 n1)
(logior (logand mask n0)
(logand (lognot mask) n1)))
(define bitwise-merge bitwise-if)
(define first-set-bit log2-binary-factors)
(define bit-set? logbit?)
(define bit-field bit-extract)
(define (copy-bit-field n newbits start end)
(logxor n (ash (logxor (bit-extract n start end) ;; cancel old
(bit-extract newbits 0 (- end start))) ;; insert new
start)))
(define arithmetic-shift ash)
(cond-expand-provide (current-module) '(srfi-60))
;;; srfi-64.scm -- SRFI 64 - A Scheme API for test suites.
;; Copyright (C) 2014 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (srfi srfi-64)
#\export
(test-begin
test-end test-assert test-eqv test-eq test-equal
test-approximate test-assert test-error test-apply test-with-runner
test-match-nth test-match-all test-match-any test-match-name
test-skip test-expect-fail test-read-eval-string
test-runner-group-path test-group test-group-with-cleanup
test-result-ref test-result-set! test-result-clear test-result-remove
test-result-kind test-passed?
test-log-to-file
test-runner? test-runner-reset test-runner-null
test-runner-simple test-runner-current test-runner-factory test-runner-get
test-runner-create test-runner-test-name
test-runner-pass-count test-runner-pass-count!
test-runner-fail-count test-runner-fail-count!
test-runner-xpass-count test-runner-xpass-count!
test-runner-xfail-count test-runner-xfail-count!
test-runner-skip-count test-runner-skip-count!
test-runner-group-stack test-runner-group-stack!
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
test-result-alist test-result-alist!
test-runner-aux-value test-runner-aux-value!
test-on-group-begin-simple test-on-group-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
test-on-final-simple test-on-test-end-simple
test-on-final-simple))
(cond-expand-provide (current-module) '(srfi-64))
(include-from-path "srfi/srfi-64/testing.scm")
;; Copyright (c) 2005, 2006, 2007, 2012, 2013 Per Bothner
;; Added "full" support for Chicken, Gauche, Guile and SISC.
;; Alex Shinn, Copyright (c) 2005.
;; Modified for Scheme Spheres by Álvaro Castro-Castilla, Copyright (c) 2012.
;; Support for Guile 2 by Mark H Weaver <mhw@netris.org>, Copyright (c) 2014.
;;
;; Permission is hereby granted, free of charge, to any person
;; obtaining a copy of this software and associated documentation
;; files (the "Software"), to deal in the Software without
;; restriction, including without limitation the rights to use, copy,
;; modify, merge, publish, distribute, sublicense, and/or sell copies
;; of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be
;; included in all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
;; BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
;; ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
;; CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(cond-expand
(chicken
(require-extension syntax-case))
(guile-2
(use-modules (srfi srfi-9)
;; In 2.0.9, srfi-34 and srfi-35 are not well integrated
;; with either Guile's native exceptions or R6RS exceptions.
;;(srfi srfi-34) (srfi srfi-35)
(srfi srfi-39)))
(guile
(use-modules (ice-9 syncase) (srfi srfi-9)
;;(srfi srfi-34) (srfi srfi-35) - not in Guile 1.6.7
(srfi srfi-39)))
(sisc
(require-extension (srfi 9 34 35 39)))
(kawa
(module-compile-options warn-undefined-variable\: #t
warn-invoke-unknown-method\: #t)
(provide 'srfi-64)
(provide 'testing)
(require 'srfi-34)
(require 'srfi-35))
(else ()
))
(cond-expand
(kawa
(define-syntax %test-export
(syntax-rules ()
((%test-export test-begin . other-names)
(module-export %test-begin . other-names)))))
(else
(define-syntax %test-export
(syntax-rules ()
((%test-export . names) (if #f #f))))))
;; List of exported names
(%test-export
test-begin ;; must be listed first, since in Kawa (at least) it is "magic".
test-end test-assert test-eqv test-eq test-equal
test-approximate test-assert test-error test-apply test-with-runner
test-match-nth test-match-all test-match-any test-match-name
test-skip test-expect-fail test-read-eval-string
test-runner-group-path test-group test-group-with-cleanup
test-result-ref test-result-set! test-result-clear test-result-remove
test-result-kind test-passed?
test-log-to-file
; Misc test-runner functions
test-runner? test-runner-reset test-runner-null
test-runner-simple test-runner-current test-runner-factory test-runner-get
test-runner-create test-runner-test-name
;; test-runner field setter and getter functions - see %test-record-define:
test-runner-pass-count test-runner-pass-count!
test-runner-fail-count test-runner-fail-count!
test-runner-xpass-count test-runner-xpass-count!
test-runner-xfail-count test-runner-xfail-count!
test-runner-skip-count test-runner-skip-count!
test-runner-group-stack test-runner-group-stack!
test-runner-on-test-begin test-runner-on-test-begin!
test-runner-on-test-end test-runner-on-test-end!
test-runner-on-group-begin test-runner-on-group-begin!
test-runner-on-group-end test-runner-on-group-end!
test-runner-on-final test-runner-on-final!
test-runner-on-bad-count test-runner-on-bad-count!
test-runner-on-bad-end-name test-runner-on-bad-end-name!
test-result-alist test-result-alist!
test-runner-aux-value test-runner-aux-value!
;; default/simple call-back functions, used in default test-runner,
;; but can be called to construct more complex ones.
test-on-group-begin-simple test-on-group-end-simple
test-on-bad-count-simple test-on-bad-end-name-simple
test-on-final-simple test-on-test-end-simple
test-on-final-simple)
(cond-expand
(srfi-9
(define-syntax %test-record-define
(syntax-rules ()
((%test-record-define alloc runner? (name index setter getter) ...)
(define-record-type test-runner
(alloc)
runner?
(name setter getter) ...)))))
(else
(define %test-runner-cookie (list "test-runner"))
(define-syntax %test-record-define
(syntax-rules ()
((%test-record-define alloc runner? (name index getter setter) ...)
(begin
(define (runner? obj)
(and (vector? obj)
(> (vector-length obj) 1)
(eq (vector-ref obj 0) %test-runner-cookie)))
(define (alloc)
(let ((runner (make-vector 23)))
(vector-set! runner 0 %test-runner-cookie)
runner))
(begin
(define (getter runner)
(vector-ref runner index)) ...)
(begin
(define (setter runner value)
(vector-set! runner index value)) ...)))))))
(%test-record-define
%test-runner-alloc test-runner?
;; Cumulate count of all tests that have passed and were expected to.
(pass-count 1 test-runner-pass-count test-runner-pass-count!)
(fail-count 2 test-runner-fail-count test-runner-fail-count!)
(xpass-count 3 test-runner-xpass-count test-runner-xpass-count!)
(xfail-count 4 test-runner-xfail-count test-runner-xfail-count!)
(skip-count 5 test-runner-skip-count test-runner-skip-count!)
(skip-list 6 %test-runner-skip-list %test-runner-skip-list!)
(fail-list 7 %test-runner-fail-list %test-runner-fail-list!)
;; Normally #t, except when in a test-apply.
(run-list 8 %test-runner-run-list %test-runner-run-list!)
(skip-save 9 %test-runner-skip-save %test-runner-skip-save!)
(fail-save 10 %test-runner-fail-save %test-runner-fail-save!)
(group-stack 11 test-runner-group-stack test-runner-group-stack!)
(on-test-begin 12 test-runner-on-test-begin test-runner-on-test-begin!)
(on-test-end 13 test-runner-on-test-end test-runner-on-test-end!)
;; Call-back when entering a group. Takes (runner suite-name count).
(on-group-begin 14 test-runner-on-group-begin test-runner-on-group-begin!)
;; Call-back when leaving a group.
(on-group-end 15 test-runner-on-group-end test-runner-on-group-end!)
;; Call-back when leaving the outermost group.
(on-final 16 test-runner-on-final test-runner-on-final!)
;; Call-back when expected number of tests was wrong.
(on-bad-count 17 test-runner-on-bad-count test-runner-on-bad-count!)
;; Call-back when name in test=end doesn't match test-begin.
(on-bad-end-name 18 test-runner-on-bad-end-name test-runner-on-bad-end-name!)
;; Cumulate count of all tests that have been done.
(total-count 19 %test-runner-total-count %test-runner-total-count!)
;; Stack (list) of (count-at-start . expected-count):
(count-list 20 %test-runner-count-list %test-runner-count-list!)
(result-alist 21 test-result-alist test-result-alist!)
;; Field can be used by test-runner for any purpose.
;; test-runner-simple uses it for a log file.
(aux-value 22 test-runner-aux-value test-runner-aux-value!)
)
(define (test-runner-reset runner)
(test-result-alist! runner '())
(test-runner-pass-count! runner 0)
(test-runner-fail-count! runner 0)
(test-runner-xpass-count! runner 0)
(test-runner-xfail-count! runner 0)
(test-runner-skip-count! runner 0)
(%test-runner-total-count! runner 0)
(%test-runner-count-list! runner '())
(%test-runner-run-list! runner #t)
(%test-runner-skip-list! runner '())
(%test-runner-fail-list! runner '())
(%test-runner-skip-save! runner '())
(%test-runner-fail-save! runner '())
(test-runner-group-stack! runner '()))
(define (test-runner-group-path runner)
(reverse (test-runner-group-stack runner)))
(define (%test-null-callback runner) #f)
(define (test-runner-null)
(let ((runner (%test-runner-alloc)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner (lambda (runner name count) #f))
(test-runner-on-group-end! runner %test-null-callback)
(test-runner-on-final! runner %test-null-callback)
(test-runner-on-test-begin! runner %test-null-callback)
(test-runner-on-test-end! runner %test-null-callback)
(test-runner-on-bad-count! runner (lambda (runner count expected) #f))
(test-runner-on-bad-end-name! runner (lambda (runner begin end) #f))
runner))
;; Not part of the specification. FIXME
;; Controls whether a log file is generated.
(define test-log-to-file #t)
(define (test-runner-simple)
(let ((runner (%test-runner-alloc)))
(test-runner-reset runner)
(test-runner-on-group-begin! runner test-on-group-begin-simple)
(test-runner-on-group-end! runner test-on-group-end-simple)
(test-runner-on-final! runner test-on-final-simple)
(test-runner-on-test-begin! runner test-on-test-begin-simple)
(test-runner-on-test-end! runner test-on-test-end-simple)
(test-runner-on-bad-count! runner test-on-bad-count-simple)
(test-runner-on-bad-end-name! runner test-on-bad-end-name-simple)
runner))
(cond-expand
(srfi-39
(define test-runner-current (make-parameter #f))
(define test-runner-factory (make-parameter test-runner-simple)))
(else
(define %test-runner-current #f)
(define-syntax test-runner-current
(syntax-rules ()
((test-runner-current)
%test-runner-current)
((test-runner-current runner)
(set! %test-runner-current runner))))
(define %test-runner-factory test-runner-simple)
(define-syntax test-runner-factory
(syntax-rules ()
((test-runner-factory)
%test-runner-factory)
((test-runner-factory runner)
(set! %test-runner-factory runner))))))
;; A safer wrapper to test-runner-current.
(define (test-runner-get)
(let ((r (test-runner-current)))
(if (not r)
(cond-expand
(srfi-23 (error "test-runner not initialized - test-begin missing?"))
(else #t)))
r))
(define (%test-specifier-matches spec runner)
(spec runner))
(define (test-runner-create)
((test-runner-factory)))
(define (%test-any-specifier-matches list runner)
(let ((result #f))
(let loop ((l list))
(cond ((null? l) result)
(else
(if (%test-specifier-matches (car l) runner)
(set! result #t))
(loop (cdr l)))))))
;; Returns #f, #t, or 'xfail.
(define (%test-should-execute runner)
(let ((run (%test-runner-run-list runner)))
(cond ((or
(not (or (eqv? run #t)
(%test-any-specifier-matches run runner)))
(%test-any-specifier-matches
(%test-runner-skip-list runner)
runner))
(test-result-set! runner 'result-kind 'skip)
#f)
((%test-any-specifier-matches
(%test-runner-fail-list runner)
runner)
(test-result-set! runner 'result-kind 'xfail)
'xfail)
(else #t))))
(define (%test-begin suite-name count)
(if (not (test-runner-current))
(test-runner-current (test-runner-create)))
(let ((runner (test-runner-current)))
((test-runner-on-group-begin runner) runner suite-name count)
(%test-runner-skip-save! runner
(cons (%test-runner-skip-list runner)
(%test-runner-skip-save runner)))
(%test-runner-fail-save! runner
(cons (%test-runner-fail-list runner)
(%test-runner-fail-save runner)))
(%test-runner-count-list! runner
(cons (cons (%test-runner-total-count runner)
count)
(%test-runner-count-list runner)))
(test-runner-group-stack! runner (cons suite-name
(test-runner-group-stack runner)))))
(cond-expand
(kawa
;; Kawa has test-begin built in, implemented as:
;; (begin
;; (cond-expand (srfi-64 #!void) (else (require 'srfi-64)))
;; (%test-begin suite-name [count]))
;; This puts test-begin but only test-begin in the default environment.,
;; which makes normal test suites loadable without non-portable commands.
)
(else
(define-syntax test-begin
(syntax-rules ()
((test-begin suite-name)
(%test-begin suite-name #f))
((test-begin suite-name count)
(%test-begin suite-name count))))))
(define (test-on-group-begin-simple runner suite-name count)
(if (null? (test-runner-group-stack runner))
(begin
(display "%%%% Starting test ")
(display suite-name)
(if test-log-to-file
(let* ((log-file-name
(if (string? test-log-to-file) test-log-to-file
(string-append suite-name ".log")))
(log-file
(cond-expand (mzscheme
(open-output-file log-file-name 'truncate/replace))
(else (open-output-file log-file-name)))))
(display "%%%% Starting test " log-file)
(display suite-name log-file)
(newline log-file)
(test-runner-aux-value! runner log-file)
(display " (Writing full log to \"")
(display log-file-name)
(display "\")")))
(newline)))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(begin
(display "Group begin: " log)
(display suite-name log)
(newline log))))
#f)
(define (test-on-group-end-simple runner)
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(begin
(display "Group end: " log)
(display (car (test-runner-group-stack runner)) log)
(newline log))))
#f)
(define (%test-on-bad-count-write runner count expected-count port)
(display "*** Total number of tests was " port)
(display count port)
(display " but should be " port)
(display expected-count port)
(display ". ***" port)
(newline port)
(display "*** Discrepancy indicates testsuite error or exceptions. ***" port)
(newline port))
(define (test-on-bad-count-simple runner count expected-count)
(%test-on-bad-count-write runner count expected-count (current-output-port))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(%test-on-bad-count-write runner count expected-count log))))
(define (test-on-bad-end-name-simple runner begin-name end-name)
(let ((msg (string-append (%test-format-line runner) "test-end " begin-name
" does not match test-begin " end-name)))
(cond-expand
(srfi-23 (error msg))
(else (display msg) (newline)))))
(define (%test-final-report1 value label port)
(if (> value 0)
(begin
(display label port)
(display value port)
(newline port))))
(define (%test-final-report-simple runner port)
(%test-final-report1 (test-runner-pass-count runner)
"# of expected passes " port)
(%test-final-report1 (test-runner-xfail-count runner)
"# of expected failures " port)
(%test-final-report1 (test-runner-xpass-count runner)
"# of unexpected successes " port)
(%test-final-report1 (test-runner-fail-count runner)
"# of unexpected failures " port)
(%test-final-report1 (test-runner-skip-count runner)
"# of skipped tests " port))
(define (test-on-final-simple runner)
(%test-final-report-simple runner (current-output-port))
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(%test-final-report-simple runner log))))
(define (%test-format-line runner)
(let* ((line-info (test-result-alist runner))
(source-file (assq 'source-file line-info))
(source-line (assq 'source-line line-info))
(file (if source-file (cdr source-file) "")))
(if source-line
(string-append file ":"
(number->string (cdr source-line)) ": ")
"")))
(define (%test-end suite-name line-info)
(let* ((r (test-runner-get))
(groups (test-runner-group-stack r))
(line (%test-format-line r)))
(test-result-alist! r line-info)
(if (null? groups)
(let ((msg (string-append line "test-end not in a group")))
(cond-expand
(srfi-23 (error msg))
(else (display msg) (newline)))))
(if (and suite-name (not (equal? suite-name (car groups))))
((test-runner-on-bad-end-name r) r suite-name (car groups)))
(let* ((count-list (%test-runner-count-list r))
(expected-count (cdar count-list))
(saved-count (caar count-list))
(group-count (- (%test-runner-total-count r) saved-count)))
(if (and expected-count
(not (= expected-count group-count)))
((test-runner-on-bad-count r) r group-count expected-count))
((test-runner-on-group-end r) r)
(test-runner-group-stack! r (cdr (test-runner-group-stack r)))
(%test-runner-skip-list! r (car (%test-runner-skip-save r)))
(%test-runner-skip-save! r (cdr (%test-runner-skip-save r)))
(%test-runner-fail-list! r (car (%test-runner-fail-save r)))
(%test-runner-fail-save! r (cdr (%test-runner-fail-save r)))
(%test-runner-count-list! r (cdr count-list))
(if (null? (test-runner-group-stack r))
((test-runner-on-final r) r)))))
(define-syntax test-group
(syntax-rules ()
((test-group suite-name . body)
(let ((r (test-runner-current)))
;; Ideally should also set line-number, if available.
(test-result-alist! r (list (cons 'test-name suite-name)))
(if (%test-should-execute r)
(dynamic-wind
(lambda () (test-begin suite-name))
(lambda () . body)
(lambda () (test-end suite-name))))))))
(define-syntax test-group-with-cleanup
(syntax-rules ()
((test-group-with-cleanup suite-name form cleanup-form)
(test-group suite-name
(dynamic-wind
(lambda () #f)
(lambda () form)
(lambda () cleanup-form))))
((test-group-with-cleanup suite-name cleanup-form)
(test-group-with-cleanup suite-name #f cleanup-form))
((test-group-with-cleanup suite-name form1 form2 form3 . rest)
(test-group-with-cleanup suite-name (begin form1 form2) form3 . rest))))
(define (test-on-test-begin-simple runner)
(let ((log (test-runner-aux-value runner)))
(if (output-port? log)
(let* ((results (test-result-alist runner))
(source-file (assq 'source-file results))
(source-line (assq 'source-line results))
(source-form (assq 'source-form results))
(test-name (assq 'test-name results)))
(display "Test begin:" log)
(newline log)
(if test-name (%test-write-result1 test-name log))
(if source-file (%test-write-result1 source-file log))
(if source-line (%test-write-result1 source-line log))
(if source-form (%test-write-result1 source-form log))))))
(define-syntax test-result-ref
(syntax-rules ()
((test-result-ref runner pname)
(test-result-ref runner pname #f))
((test-result-ref runner pname default)
(let ((p (assq pname (test-result-alist runner))))
(if p (cdr p) default)))))
(define (test-on-test-end-simple runner)
(let ((log (test-runner-aux-value runner))
(kind (test-result-ref runner 'result-kind)))
(if (memq kind '(fail xpass))
(let* ((results (test-result-alist runner))
(source-file (assq 'source-file results))
(source-line (assq 'source-line results))
(test-name (assq 'test-name results)))
(if (or source-file source-line)
(begin
(if source-file (display (cdr source-file)))
(display ":")
(if source-line (display (cdr source-line)))
(display ": ")))
(display (if (eq? kind 'xpass) "XPASS" "FAIL"))
(if test-name
(begin
(display " ")
(display (cdr test-name))))
(newline)))
(if (output-port? log)
(begin
(display "Test end:" log)
(newline log)
(let loop ((list (test-result-alist runner)))
(if (pair? list)
(let ((pair (car list)))
;; Write out properties not written out by on-test-begin.
(if (not (memq (car pair)
'(test-name source-file source-line source-form)))
(%test-write-result1 pair log))
(loop (cdr list)))))))))
(define (%test-write-result1 pair port)
(display " " port)
(display (car pair) port)
(display ": " port)
(write (cdr pair) port)
(newline port))
(define (test-result-set! runner pname value)
(let* ((alist (test-result-alist runner))
(p (assq pname alist)))
(if p
(set-cdr! p value)
(test-result-alist! runner (cons (cons pname value) alist)))))
(define (test-result-clear runner)
(test-result-alist! runner '()))
(define (test-result-remove runner pname)
(let* ((alist (test-result-alist runner))
(p (assq pname alist)))
(if p
(test-result-alist! runner
(let loop ((r alist))
(if (eq? r p) (cdr r)
(cons (car r) (loop (cdr r)))))))))
(define (test-result-kind . rest)
(let ((runner (if (pair? rest) (car rest) (test-runner-current))))
(test-result-ref runner 'result-kind)))
(define (test-passed? . rest)
(let ((runner (if (pair? rest) (car rest) (test-runner-get))))
(memq (test-result-ref runner 'result-kind) '(pass xpass))))
(define (%test-report-result)
(let* ((r (test-runner-get))
(result-kind (test-result-kind r)))
(case result-kind
((pass)
(test-runner-pass-count! r (+ 1 (test-runner-pass-count r))))
((fail)
(test-runner-fail-count! r (+ 1 (test-runner-fail-count r))))
((xpass)
(test-runner-xpass-count! r (+ 1 (test-runner-xpass-count r))))
((xfail)
(test-runner-xfail-count! r (+ 1 (test-runner-xfail-count r))))
(else
(test-runner-skip-count! r (+ 1 (test-runner-skip-count r)))))
(%test-runner-total-count! r (+ 1 (%test-runner-total-count r)))
((test-runner-on-test-end r) r)))
(cond-expand
(guile
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(catch #t
(lambda () test-expression)
(lambda (key . args)
(test-result-set! (test-runner-current) 'actual-error
(cons key args))
#f))))))
(kawa
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(try-catch test-expression
(ex <java.lang.Throwable>
(test-result-set! (test-runner-current) 'actual-error ex)
#f))))))
(srfi-34
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(guard (err (else #f)) test-expression)))))
(chicken
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
(condition-case test-expression (ex () #f))))))
(else
(define-syntax %test-evaluate-with-catch
(syntax-rules ()
((%test-evaluate-with-catch test-expression)
test-expression)))))
(cond-expand
((or kawa mzscheme)
(cond-expand
(mzscheme
(define-for-syntax (%test-syntax-file form)
(let ((source (syntax-source form)))
(cond ((string? source) file)
((path? source) (path->string source))
(else #f)))))
(kawa
(define (%test-syntax-file form)
(syntax-source form))))
(define (%test-source-line2 form)
(let* ((line (syntax-line form))
(file (%test-syntax-file form))
(line-pair (if line (list (cons 'source-line line)) '())))
(cons (cons 'source-form (syntax-object->datum form))
(if file (cons (cons 'source-file file) line-pair) line-pair)))))
(guile-2
(define (%test-source-line2 form)
(let* ((src-props (syntax-source form))
(file (and src-props (assq-ref src-props 'filename)))
(line (and src-props (assq-ref src-props 'line)))
(file-alist (if file
`((source-file . ,file))
'()))
(line-alist (if line
`((source-line . ,(+ line 1)))
'())))
(datum->syntax (syntax here)
`((source-form . ,(syntax->datum form))
,@file-alist
,@line-alist)))))
(else
(define (%test-source-line2 form)
'())))
(define (%test-on-test-begin r)
(%test-should-execute r)
((test-runner-on-test-begin r) r)
(not (eq? 'skip (test-result-ref r 'result-kind))))
(define (%test-on-test-end r result)
(test-result-set! r 'result-kind
(if (eq? (test-result-ref r 'result-kind) 'xfail)
(if result 'xpass 'xfail)
(if result 'pass 'fail))))
(define (test-runner-test-name runner)
(test-result-ref runner 'test-name ""))
(define-syntax %test-comp2body
(syntax-rules ()
((%test-comp2body r comp expected expr)
(let ()
(if (%test-on-test-begin r)
(let ((exp expected))
(test-result-set! r 'expected-value exp)
(let ((res (%test-evaluate-with-catch expr)))
(test-result-set! r 'actual-value res)
(%test-on-test-end r (comp exp res)))))
(%test-report-result)))))
(define (%test-approximate= error)
(lambda (value expected)
(let ((rval (real-part value))
(ival (imag-part value))
(rexp (real-part expected))
(iexp (imag-part expected)))
(and (>= rval (- rexp error))
(>= ival (- iexp error))
(<= rval (+ rexp error))
(<= ival (+ iexp error))))))
(define-syntax %test-comp1body
(syntax-rules ()
((%test-comp1body r expr)
(let ()
(if (%test-on-test-begin r)
(let ()
(let ((res (%test-evaluate-with-catch expr)))
(test-result-set! r 'actual-value res)
(%test-on-test-end r res))))
(%test-report-result)))))
(cond-expand
((or kawa mzscheme guile-2)
;; Should be made to work for any Scheme with syntax-case
;; However, I haven't gotten the quoting working. FIXME.
(define-syntax test-end
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac suite-name) line)
(syntax
(%test-end suite-name line)))
(((mac) line)
(syntax
(%test-end #f line))))))
(define-syntax test-assert
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname expr) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp1body r expr))))
(((mac expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp1body r expr)))))))
(define (%test-comp2 comp x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x)) comp) ()
(((mac tname expected expr) line comp)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp2body r comp expected expr))))
(((mac expected expr) line comp)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp2body r comp expected expr))))))
(define-syntax test-eqv
(lambda (x) (%test-comp2 (syntax eqv?) x)))
(define-syntax test-eq
(lambda (x) (%test-comp2 (syntax eq?) x)))
(define-syntax test-equal
(lambda (x) (%test-comp2 (syntax equal?) x)))
(define-syntax test-approximate ;; FIXME - needed for non-Kawa
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname expected expr error) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-comp2body r (%test-approximate= error) expected expr))))
(((mac expected expr error) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-comp2body r (%test-approximate= error) expected expr))))))))
(else
(define-syntax test-end
(syntax-rules ()
((test-end)
(%test-end #f '()))
((test-end suite-name)
(%test-end suite-name '()))))
(define-syntax test-assert
(syntax-rules ()
((test-assert tname test-expression)
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r '((test-name . tname)))
(%test-comp1body r test-expression)))
((test-assert test-expression)
(let* ((r (test-runner-get)))
(test-result-alist! r '())
(%test-comp1body r test-expression)))))
(define-syntax %test-comp2
(syntax-rules ()
((%test-comp2 comp tname expected expr)
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (list (cons 'test-name tname)))
(%test-comp2body r comp expected expr)))
((%test-comp2 comp expected expr)
(let* ((r (test-runner-get)))
(test-result-alist! r '())
(%test-comp2body r comp expected expr)))))
(define-syntax test-equal
(syntax-rules ()
((test-equal . rest)
(%test-comp2 equal? . rest))))
(define-syntax test-eqv
(syntax-rules ()
((test-eqv . rest)
(%test-comp2 eqv? . rest))))
(define-syntax test-eq
(syntax-rules ()
((test-eq . rest)
(%test-comp2 eq? . rest))))
(define-syntax test-approximate
(syntax-rules ()
((test-approximate tname expected expr error)
(%test-comp2 (%test-approximate= error) tname expected expr))
((test-approximate expected expr error)
(%test-comp2 (%test-approximate= error) expected expr))))))
(cond-expand
(guile
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(cond ((%test-on-test-begin r)
(let ((et etype))
(test-result-set! r 'expected-error et)
(%test-on-test-end r
(catch #t
(lambda ()
(test-result-set! r 'actual-value expr)
#f)
(lambda (key . args)
;; TODO: decide how to specify expected
;; error types for Guile.
(test-result-set! r 'actual-error
(cons key args))
#t)))
(%test-report-result))))))))
(mzscheme
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (with-handlers (((lambda (h) #t) (lambda (h) #t)))
(let ()
(test-result-set! r 'actual-value expr)
#f)))))))
(chicken
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (condition-case expr (ex () #t)))))))
(kawa
(define-syntax %test-error
(syntax-rules ()
((%test-error r #t expr)
(cond ((%test-on-test-begin r)
(test-result-set! r 'expected-error #t)
(%test-on-test-end r
(try-catch
(let ()
(test-result-set! r 'actual-value expr)
#f)
(ex <java.lang.Throwable>
(test-result-set! r 'actual-error ex)
#t)))
(%test-report-result))))
((%test-error r etype expr)
(if (%test-on-test-begin r)
(let ((et etype))
(test-result-set! r 'expected-error et)
(%test-on-test-end r
(try-catch
(let ()
(test-result-set! r 'actual-value expr)
#f)
(ex <java.lang.Throwable>
(test-result-set! r 'actual-error ex)
(cond ((and (instance? et <gnu.bytecode.ClassType>)
(gnu.bytecode.ClassType:isSubclass et <java.lang.Throwable>))
(instance? ex et))
(else #t)))))
(%test-report-result)))))))
((and srfi-34 srfi-35)
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (guard (ex ((condition-type? etype)
(and (condition? ex) (condition-has-type? ex etype)))
((procedure? etype)
(etype ex))
((equal? etype #t)
#t)
(else #t))
expr #f))))))
(srfi-34
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(%test-comp1body r (guard (ex (else #t)) expr #f))))))
(else
(define-syntax %test-error
(syntax-rules ()
((%test-error r etype expr)
(begin
((test-runner-on-test-begin r) r)
(test-result-set! r 'result-kind 'skip)
(%test-report-result)))))))
(cond-expand
((or kawa mzscheme guile-2)
(define-syntax test-error
(lambda (x)
(syntax-case (list x (list (syntax quote) (%test-source-line2 x))) ()
(((mac tname etype expr) line)
(syntax
(let* ((r (test-runner-get))
(name tname))
(test-result-alist! r (cons (cons 'test-name tname) line))
(%test-error r etype expr))))
(((mac etype expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-error r etype expr))))
(((mac expr) line)
(syntax
(let* ((r (test-runner-get)))
(test-result-alist! r line)
(%test-error r #t expr))))))))
(else
(define-syntax test-error
(syntax-rules ()
((test-error name etype expr)
(let ((r (test-runner-get)))
(test-result-alist! r `((test-name . ,name)))
(%test-error r etype expr)))
((test-error etype expr)
(let ((r (test-runner-get)))
(test-result-alist! r '())
(%test-error r etype expr)))
((test-error expr)
(let ((r (test-runner-get)))
(test-result-alist! r '())
(%test-error r #t expr)))))))
(define (test-apply first . rest)
(if (test-runner? first)
(test-with-runner first (apply test-apply rest))
(let ((r (test-runner-current)))
(if r
(let ((run-list (%test-runner-run-list r)))
(cond ((null? rest)
(%test-runner-run-list! r (reverse run-list))
(first)) ;; actually apply procedure thunk
(else
(%test-runner-run-list!
r
(if (eq? run-list #t) (list first) (cons first run-list)))
(apply test-apply rest)
(%test-runner-run-list! r run-list))))
(let ((r (test-runner-create)))
(test-with-runner r (apply test-apply first rest))
((test-runner-on-final r) r))))))
(define-syntax test-with-runner
(syntax-rules ()
((test-with-runner runner form ...)
(let ((saved-runner (test-runner-current)))
(dynamic-wind
(lambda () (test-runner-current runner))
(lambda () form ...)
(lambda () (test-runner-current saved-runner)))))))
;;; Predicates
(define (%test-match-nth n count)
(let ((i 0))
(lambda (runner)
(set! i (+ i 1))
(and (>= i n) (< i (+ n count))))))
(define-syntax test-match-nth
(syntax-rules ()
((test-match-nth n)
(test-match-nth n 1))
((test-match-nth n count)
(%test-match-nth n count))))
(define (%test-match-all . pred-list)
(lambda (runner)
(let ((result #t))
(let loop ((l pred-list))
(if (null? l)
result
(begin
(if (not ((car l) runner))
(set! result #f))
(loop (cdr l))))))))
(define-syntax test-match-all
(syntax-rules ()
((test-match-all pred ...)
(%test-match-all (%test-as-specifier pred) ...))))
(define (%test-match-any . pred-list)
(lambda (runner)
(let ((result #f))
(let loop ((l pred-list))
(if (null? l)
result
(begin
(if ((car l) runner)
(set! result #t))
(loop (cdr l))))))))
(define-syntax test-match-any
(syntax-rules ()
((test-match-any pred ...)
(%test-match-any (%test-as-specifier pred) ...))))
;; Coerce to a predicate function:
(define (%test-as-specifier specifier)
(cond ((procedure? specifier) specifier)
((integer? specifier) (test-match-nth 1 specifier))
((string? specifier) (test-match-name specifier))
(else
(error "not a valid test specifier"))))
(define-syntax test-skip
(syntax-rules ()
((test-skip pred ...)
(let ((runner (test-runner-get)))
(%test-runner-skip-list! runner
(cons (test-match-all (%test-as-specifier pred) ...)
(%test-runner-skip-list runner)))))))
(define-syntax test-expect-fail
(syntax-rules ()
((test-expect-fail pred ...)
(let ((runner (test-runner-get)))
(%test-runner-fail-list! runner
(cons (test-match-all (%test-as-specifier pred) ...)
(%test-runner-fail-list runner)))))))
(define (test-match-name name)
(lambda (runner)
(equal? name (test-runner-test-name runner))))
(define (test-read-eval-string string)
(let* ((port (open-input-string string))
(form (read port)))
(if (eof-object? (read-char port))
(cond-expand
(guile (eval form (current-module)))
(else (eval form)))
(cond-expand
(srfi-23 (error "(not at eof)"))
(else "error")))))
;;; srfi-67.scm --- Compare Procedures
;; Copyright (C) 2010 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;; This library 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
;; Lesser General Public License for more details.
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library. If not, see
;; <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This module is not yet documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-67)
#\export (</<=?
</<?
<=/<=?
<=/<?
<=?
<?
=?
>/>=?
>/>?
>=/>=?
>=/>?
>=?
>?
boolean-compare
chain<=?
chain<?
chain=?
chain>=?
chain>?
char-compare
char-compare-ci
compare-by<
compare-by<=
compare-by=/<
compare-by=/>
compare-by>
compare-by>=
complex-compare
cond-compare
debug-compare
default-compare
if-not=?
if3
if<=?
if<?
if=?
if>=?
if>?
integer-compare
kth-largest
list-compare
list-compare-as-vector
max-compare
min-compare
not=?
number-compare
pair-compare
pair-compare-car
pair-compare-cdr
pairwise-not=?
rational-compare
real-compare
refine-compare
select-compare
symbol-compare
vector-compare
vector-compare-as-list)
#\replace (string-compare string-compare-ci)
#\use-module (srfi srfi-27))
(cond-expand-provide (current-module) '(srfi-67))
(include-from-path "srfi/srfi-67/compare.scm")
; Copyright (c) 2011 Free Software Foundation, Inc.
; Copyright (c) 2005 Sebastian Egner and Jens Axel S{\o}gaard.
;
; Permission is hereby granted, free of charge, to any person obtaining
; a copy of this software and associated documentation files (the
; ``Software''), to deal in the Software without restriction, including
; without limitation the rights to use, copy, modify, merge, publish,
; distribute, sublicense, and/or sell copies of the Software, and to
; permit persons to whom the Software is furnished to do so, subject to
; the following conditions:
;
; The above copyright notice and this permission notice shall be
; included in all copies or substantial portions of the Software.
;
; THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;
; -----------------------------------------------------------------------
;
; Compare procedures SRFI (reference implementation)
; Sebastian.Egner@philips.com, Jensaxel@soegaard.net
; history of this file:
; SE, 14-Oct-2004: first version
; SE, 18-Oct-2004: 1st redesign: axioms for 'compare function'
; SE, 29-Oct-2004: 2nd redesign: higher order reverse/map/refine/unite
; SE, 2-Nov-2004: 3rd redesign: macros cond/refine-compare replace h.o.f's
; SE, 10-Nov-2004: (im,re) replaced by (re,im) in complex-compare
; SE, 11-Nov-2004: case-compare by case (not by cond); select-compare added
; SE, 12-Jan-2005: pair-compare-cdr
; SE, 15-Feb-2005: stricter typing for compare-<type>; pairwise-not=?
; SE, 16-Feb-2005: case-compare -> if-compare -> if3; <? </<? chain<? etc.
; JS, 24-Feb-2005: selection-compare added
; SE, 25-Feb-2005: selection-compare -> kth-largest modified; if<? etc.
; JS, 28-Feb-2005: kth-largest modified - is "stable" now
; SE, 28-Feb-2005: simplified pairwise-not=?/kth-largest; min/max debugged
; SE, 07-Apr-2005: compare-based type checks made explicit
; SE, 18-Apr-2005: added (rel? compare) and eq?-test
; SE, 16-May-2005: naming convention changed; compare-by< etc. optional x y
; =============================================================================
; Reference Implementation
; ========================
;
; in R5RS (including hygienic macros)
; + SRFI-16 (case-lambda)
; + SRFI-23 (error)
; + SRFI-27 (random-integer)
; Implementation remarks:
; * In general, the emphasis of this implementation is on correctness
; and portability, not on efficiency.
; * Variable arity procedures are expressed in terms of case-lambda
; in the hope that this will produce efficient code for the case
; where the arity is statically known at the call site.
; * In procedures that are required to type-check their arguments,
; we use (compare x x) for executing extra checks. This relies on
; the assumption that eq? is used to catch this case quickly.
; * Care has been taken to reference comparison procedures of R5RS
; only at the time the operations here are being defined. This
; makes it possible to redefine these operations, if need be.
; * For the sake of efficiency, some inlining has been done by hand.
; This is mainly expressed by macros producing defines.
; * Identifiers of the form compare:<something> are private.
;
; Hints for low-level implementation:
; * The basis of this SRFI are the atomic compare procedures,
; i.e. boolean-compare, char-compare, etc. and the conditionals
; if3, if=?, if<? etc., and default-compare. These should make
; optimal use of the available type information.
; * For the sake of speed, the reference implementation does not
; use a LET to save the comparison value c for the ERROR call.
; This can be fixed in a low-level implementation at no cost.
; * Type-checks based on (compare x x) are made explicit by the
; expression (compare:check result compare x ...).
; * Eq? should can used to speed up built-in compare procedures,
; but it can only be used after type-checking at least one of
; the arguments.
(define (compare:checked result compare . args)
(for-each (lambda (x) (compare x x)) args)
result)
; 3-sided conditional
(define-syntax-rule (if3 c less equal greater)
(case c
((-1) less)
(( 0) equal)
(( 1) greater)
(else (error "comparison value not in {-1,0,1}"))))
; 2-sided conditionals for comparisons
(define-syntax compare:if-rel?
(syntax-rules ()
((compare:if-rel? c-cases a-cases c consequence)
(compare:if-rel? c-cases a-cases c consequence (if #f #f)))
((compare:if-rel? c-cases a-cases c consequence alternate)
(case c
(c-cases consequence)
(a-cases alternate)
(else (error "comparison value not in {-1,0,1}"))))))
(define-syntax-rule (if=? arg ...)
(compare:if-rel? (0) (-1 1) arg ...))
(define-syntax-rule (if<? arg ...)
(compare:if-rel? (-1) (0 1) arg ...))
(define-syntax-rule (if>? arg ...)
(compare:if-rel? (1) (-1 0) arg ...))
(define-syntax-rule (if<=? arg ...)
(compare:if-rel? (-1 0) (1) arg ...))
(define-syntax-rule (if>=? arg ...)
(compare:if-rel? (0 1) (-1) arg ...))
(define-syntax-rule (if-not=? arg ...)
(compare:if-rel? (-1 1) (0) arg ...))
; predicates from compare procedures
(define-syntax-rule (compare:define-rel? rel? if-rel?)
(define rel?
(case-lambda
(() (lambda (x y) (if-rel? (default-compare x y) #t #f)))
((compare) (lambda (x y) (if-rel? (compare x y) #t #f)))
((x y) (if-rel? (default-compare x y) #t #f))
((compare x y)
(if (procedure? compare)
(if-rel? (compare x y) #t #f)
(error "not a procedure (Did you mean rel/rel??): " compare))))))
(compare:define-rel? =? if=?)
(compare:define-rel? <? if<?)
(compare:define-rel? >? if>?)
(compare:define-rel? <=? if<=?)
(compare:define-rel? >=? if>=?)
(compare:define-rel? not=? if-not=?)
; chains of length 3
(define-syntax-rule (compare:define-rel1/rel2? rel1/rel2? if-rel1? if-rel2?)
(define rel1/rel2?
(case-lambda
(()
(lambda (x y z)
(if-rel1? (default-compare x y)
(if-rel2? (default-compare y z) #t #f)
(compare:checked #f default-compare z))))
((compare)
(lambda (x y z)
(if-rel1? (compare x y)
(if-rel2? (compare y z) #t #f)
(compare:checked #f compare z))))
((x y z)
(if-rel1? (default-compare x y)
(if-rel2? (default-compare y z) #t #f)
(compare:checked #f default-compare z)))
((compare x y z)
(if-rel1? (compare x y)
(if-rel2? (compare y z) #t #f)
(compare:checked #f compare z))))))
(compare:define-rel1/rel2? </<? if<? if<?)
(compare:define-rel1/rel2? </<=? if<? if<=?)
(compare:define-rel1/rel2? <=/<? if<=? if<?)
(compare:define-rel1/rel2? <=/<=? if<=? if<=?)
(compare:define-rel1/rel2? >/>? if>? if>?)
(compare:define-rel1/rel2? >/>=? if>? if>=?)
(compare:define-rel1/rel2? >=/>? if>=? if>?)
(compare:define-rel1/rel2? >=/>=? if>=? if>=?)
; chains of arbitrary length
(define-syntax-rule (compare:define-chain-rel? chain-rel? if-rel?)
(define chain-rel?
(case-lambda
((compare)
#t)
((compare x1)
(compare:checked #t compare x1))
((compare x1 x2)
(if-rel? (compare x1 x2) #t #f))
((compare x1 x2 x3)
(if-rel? (compare x1 x2)
(if-rel? (compare x2 x3) #t #f)
(compare:checked #f compare x3)))
((compare x1 x2 . x3+)
(if-rel? (compare x1 x2)
(let chain? ((head x2) (tail x3+))
(if (null? tail)
#t
(if-rel? (compare head (car tail))
(chain? (car tail) (cdr tail))
(apply compare:checked #f
compare (cdr tail)))))
(apply compare:checked #f compare x3+))))))
(compare:define-chain-rel? chain=? if=?)
(compare:define-chain-rel? chain<? if<?)
(compare:define-chain-rel? chain>? if>?)
(compare:define-chain-rel? chain<=? if<=?)
(compare:define-chain-rel? chain>=? if>=?)
; pairwise inequality
(define pairwise-not=?
(let ((= =) (<= <=))
(case-lambda
((compare)
#t)
((compare x1)
(compare:checked #t compare x1))
((compare x1 x2)
(if-not=? (compare x1 x2) #t #f))
((compare x1 x2 x3)
(if-not=? (compare x1 x2)
(if-not=? (compare x2 x3)
(if-not=? (compare x1 x3) #t #f)
#f)
(compare:checked #f compare x3)))
((compare . x1+)
(let unequal? ((x x1+) (n (length x1+)) (unchecked? #t))
(if (< n 2)
(if (and unchecked? (= n 1))
(compare:checked #t compare (car x))
#t)
(let* ((i-pivot (random-integer n))
(x-pivot (list-ref x i-pivot)))
(let split ((i 0) (x x) (x< '()) (x> '()))
(if (null? x)
(and (unequal? x< (length x<) #f)
(unequal? x> (length x>) #f))
(if (= i i-pivot)
(split (+ i 1) (cdr x) x< x>)
(if3 (compare (car x) x-pivot)
(split (+ i 1) (cdr x) (cons (car x) x<) x>)
(if unchecked?
(apply compare:checked #f compare (cdr x))
#f)
(split (+ i 1) (cdr x) x< (cons (car x) x>)))))))))))))
; min/max
(define min-compare
(case-lambda
((compare x1)
(compare:checked x1 compare x1))
((compare x1 x2)
(if<=? (compare x1 x2) x1 x2))
((compare x1 x2 x3)
(if<=? (compare x1 x2)
(if<=? (compare x1 x3) x1 x3)
(if<=? (compare x2 x3) x2 x3)))
((compare x1 x2 x3 x4)
(if<=? (compare x1 x2)
(if<=? (compare x1 x3)
(if<=? (compare x1 x4) x1 x4)
(if<=? (compare x3 x4) x3 x4))
(if<=? (compare x2 x3)
(if<=? (compare x2 x4) x2 x4)
(if<=? (compare x3 x4) x3 x4))))
((compare x1 x2 . x3+)
(let min ((xmin (if<=? (compare x1 x2) x1 x2)) (xs x3+))
(if (null? xs)
xmin
(min (if<=? (compare xmin (car xs)) xmin (car xs))
(cdr xs)))))))
(define max-compare
(case-lambda
((compare x1)
(compare:checked x1 compare x1))
((compare x1 x2)
(if>=? (compare x1 x2) x1 x2))
((compare x1 x2 x3)
(if>=? (compare x1 x2)
(if>=? (compare x1 x3) x1 x3)
(if>=? (compare x2 x3) x2 x3)))
((compare x1 x2 x3 x4)
(if>=? (compare x1 x2)
(if>=? (compare x1 x3)
(if>=? (compare x1 x4) x1 x4)
(if>=? (compare x3 x4) x3 x4))
(if>=? (compare x2 x3)
(if>=? (compare x2 x4) x2 x4)
(if>=? (compare x3 x4) x3 x4))))
((compare x1 x2 . x3+)
(let max ((xmax (if>=? (compare x1 x2) x1 x2)) (xs x3+))
(if (null? xs)
xmax
(max (if>=? (compare xmax (car xs)) xmax (car xs))
(cdr xs)))))))
; kth-largest
(define kth-largest
(let ((= =) (< <))
(case-lambda
((compare k x0)
(case (modulo k 1)
((0) (compare:checked x0 compare x0))
(else (error "bad index" k))))
((compare k x0 x1)
(case (modulo k 2)
((0) (if<=? (compare x0 x1) x0 x1))
((1) (if<=? (compare x0 x1) x1 x0))
(else (error "bad index" k))))
((compare k x0 x1 x2)
(case (modulo k 3)
((0) (if<=? (compare x0 x1)
(if<=? (compare x0 x2) x0 x2)
(if<=? (compare x1 x2) x1 x2)))
((1) (if3 (compare x0 x1)
(if<=? (compare x1 x2)
x1
(if<=? (compare x0 x2) x2 x0))
(if<=? (compare x0 x2) x1 x0)
(if<=? (compare x0 x2)
x0
(if<=? (compare x1 x2) x2 x1))))
((2) (if<=? (compare x0 x1)
(if<=? (compare x1 x2) x2 x1)
(if<=? (compare x0 x2) x2 x0)))
(else (error "bad index" k))))
((compare k x0 . x1+) ; |x1+| >= 1
(if (not (and (integer? k) (exact? k)))
(error "bad index" k))
(let ((n (+ 1 (length x1+))))
(let kth ((k (modulo k n))
(n n) ; = |x|
(rev #t) ; are x<, x=, x> reversed?
(x (cons x0 x1+)))
(let ((pivot (list-ref x (random-integer n))))
(let split ((x x) (x< '()) (n< 0) (x= '()) (n= 0) (x> '()) (n> 0))
(if (null? x)
(cond
((< k n<)
(kth k n< (not rev) x<))
((< k (+ n< n=))
(if rev
(list-ref x= (- (- n= 1) (- k n<)))
(list-ref x= (- k n<))))
(else
(kth (- k (+ n< n=)) n> (not rev) x>)))
(if3 (compare (car x) pivot)
(split (cdr x) (cons (car x) x<) (+ n< 1) x= n= x> n>)
(split (cdr x) x< n< (cons (car x) x=) (+ n= 1) x> n>)
(split (cdr x) x< n< x= n= (cons (car x) x>) (+ n> 1))))))))))))
; compare functions from predicates
(define compare-by<
(case-lambda
((lt) (lambda (x y) (if (lt x y) -1 (if (lt y x) 1 0))))
((lt x y) (if (lt x y) -1 (if (lt y x) 1 0)))))
(define compare-by>
(case-lambda
((gt) (lambda (x y) (if (gt x y) 1 (if (gt y x) -1 0))))
((gt x y) (if (gt x y) 1 (if (gt y x) -1 0)))))
(define compare-by<=
(case-lambda
((le) (lambda (x y) (if (le x y) (if (le y x) 0 -1) 1)))
((le x y) (if (le x y) (if (le y x) 0 -1) 1))))
(define compare-by>=
(case-lambda
((ge) (lambda (x y) (if (ge x y) (if (ge y x) 0 1) -1)))
((ge x y) (if (ge x y) (if (ge y x) 0 1) -1))))
(define compare-by=/<
(case-lambda
((eq lt) (lambda (x y) (if (eq x y) 0 (if (lt x y) -1 1))))
((eq lt x y) (if (eq x y) 0 (if (lt x y) -1 1)))))
(define compare-by=/>
(case-lambda
((eq gt) (lambda (x y) (if (eq x y) 0 (if (gt x y) 1 -1))))
((eq gt x y) (if (eq x y) 0 (if (gt x y) 1 -1)))))
; refine and extend construction
(define-syntax refine-compare
(syntax-rules ()
((refine-compare)
0)
((refine-compare c1)
c1)
((refine-compare c1 c2 cs ...)
(if3 c1 -1 (refine-compare c2 cs ...) 1))))
(define-syntax select-compare
(syntax-rules (else)
((select-compare x y clause ...)
(let ((x-val x) (y-val y))
(select-compare (x-val y-val clause ...))))
; used internally: (select-compare (x y clause ...))
((select-compare (x y))
0)
((select-compare (x y (else c ...)))
(refine-compare c ...))
((select-compare (x y (t? c ...) clause ...))
(let ((t?-val t?))
(let ((tx (t?-val x)) (ty (t?-val y)))
(if tx
(if ty (refine-compare c ...) -1)
(if ty 1 (select-compare (x y clause ...)))))))))
(define-syntax cond-compare
(syntax-rules (else)
((cond-compare)
0)
((cond-compare (else cs ...))
(refine-compare cs ...))
((cond-compare ((tx ty) cs ...) clause ...)
(let ((tx-val tx) (ty-val ty))
(if tx-val
(if ty-val (refine-compare cs ...) -1)
(if ty-val 1 (cond-compare clause ...)))))))
; R5RS atomic types
(define-syntax compare:type-check
(syntax-rules ()
((compare:type-check type? type-name x)
(if (not (type? x))
(error (string-append "not " type-name ":") x)))
((compare:type-check type? type-name x y)
(begin (compare:type-check type? type-name x)
(compare:type-check type? type-name y)))))
(define-syntax-rule (compare:define-by=/< compare = < type? type-name)
(define compare
(let ((= =) (< <))
(lambda (x y)
(if (type? x)
(if (eq? x y)
0
(if (type? y)
(if (= x y) 0 (if (< x y) -1 1))
(error (string-append "not " type-name ":") y)))
(error (string-append "not " type-name ":") x))))))
(define (boolean-compare x y)
(compare:type-check boolean? "boolean" x y)
(if x (if y 0 1) (if y -1 0)))
(compare:define-by=/< char-compare char=? char<? char? "char")
(compare:define-by=/< char-compare-ci char-ci=? char-ci<? char? "char")
(compare:define-by=/< string-compare string=? string<? string? "string")
(compare:define-by=/< string-compare-ci string-ci=? string-ci<? string? "string")
(define (symbol-compare x y)
(compare:type-check symbol? "symbol" x y)
(string-compare (symbol->string x) (symbol->string y)))
(compare:define-by=/< integer-compare = < integer? "integer")
(compare:define-by=/< rational-compare = < rational? "rational")
(compare:define-by=/< real-compare = < real? "real")
(define (complex-compare x y)
(compare:type-check complex? "complex" x y)
(if (and (real? x) (real? y))
(real-compare x y)
(refine-compare (real-compare (real-part x) (real-part y))
(real-compare (imag-part x) (imag-part y)))))
(define (number-compare x y)
(compare:type-check number? "number" x y)
(complex-compare x y))
; R5RS compound data structures: dotted pair, list, vector
(define (pair-compare-car compare)
(lambda (x y)
(compare (car x) (car y))))
(define (pair-compare-cdr compare)
(lambda (x y)
(compare (cdr x) (cdr y))))
(define pair-compare
(case-lambda
; dotted pair
((pair-compare-car pair-compare-cdr x y)
(refine-compare (pair-compare-car (car x) (car y))
(pair-compare-cdr (cdr x) (cdr y))))
; possibly improper lists
((compare x y)
(cond-compare
(((null? x) (null? y)) 0)
(((pair? x) (pair? y)) (compare (car x) (car y))
(pair-compare compare (cdr x) (cdr y)))
(else (compare x y))))
; for convenience
((x y)
(pair-compare default-compare x y))))
(define list-compare
(case-lambda
((compare x y empty? head tail)
(cond-compare
(((empty? x) (empty? y)) 0)
(else (compare (head x) (head y))
(list-compare compare (tail x) (tail y) empty? head tail))))
; for convenience
(( x y empty? head tail)
(list-compare default-compare x y empty? head tail))
((compare x y )
(list-compare compare x y null? car cdr))
(( x y )
(list-compare default-compare x y null? car cdr))))
(define list-compare-as-vector
(case-lambda
((compare x y empty? head tail)
(refine-compare
(let compare-length ((x x) (y y))
(cond-compare
(((empty? x) (empty? y)) 0)
(else (compare-length (tail x) (tail y)))))
(list-compare compare x y empty? head tail)))
; for convenience
(( x y empty? head tail)
(list-compare-as-vector default-compare x y empty? head tail))
((compare x y )
(list-compare-as-vector compare x y null? car cdr))
(( x y )
(list-compare-as-vector default-compare x y null? car cdr))))
(define vector-compare
(let ((= =))
(case-lambda
((compare x y size ref)
(let ((n (size x)) (m (size y)))
(refine-compare
(integer-compare n m)
(let compare-rest ((i 0)) ; compare x[i..n-1] y[i..n-1]
(if (= i n)
0
(refine-compare (compare (ref x i) (ref y i))
(compare-rest (+ i 1))))))))
; for convenience
(( x y size ref)
(vector-compare default-compare x y size ref))
((compare x y )
(vector-compare compare x y vector-length vector-ref))
(( x y )
(vector-compare default-compare x y vector-length vector-ref)))))
(define vector-compare-as-list
(let ((= =))
(case-lambda
((compare x y size ref)
(let ((nx (size x)) (ny (size y)))
(let ((n (min nx ny)))
(let compare-rest ((i 0)) ; compare x[i..n-1] y[i..n-1]
(if (= i n)
(integer-compare nx ny)
(refine-compare (compare (ref x i) (ref y i))
(compare-rest (+ i 1))))))))
; for convenience
(( x y size ref)
(vector-compare-as-list default-compare x y size ref))
((compare x y )
(vector-compare-as-list compare x y vector-length vector-ref))
(( x y )
(vector-compare-as-list default-compare x y vector-length vector-ref)))))
; default compare
(define (default-compare x y)
(select-compare
x y
(null? 0)
(pair? (default-compare (car x) (car y))
(default-compare (cdr x) (cdr y)))
(boolean? (boolean-compare x y))
(char? (char-compare x y))
(string? (string-compare x y))
(symbol? (symbol-compare x y))
(number? (number-compare x y))
(vector? (vector-compare default-compare x y))
(else (error "unrecognized type in default-compare" x y))))
; Note that we pass default-compare to compare-{pair,vector} explictly.
; This makes sure recursion proceeds with this default-compare, which
; need not be the one in the lexical scope of compare-{pair,vector}.
; debug compare
(define (debug-compare c)
(define (checked-value c x y)
(let ((c-xy (c x y)))
(if (or (eqv? c-xy -1) (eqv? c-xy 0) (eqv? c-xy 1))
c-xy
(error "compare value not in {-1,0,1}" c-xy (list c x y)))))
(define (random-boolean)
(zero? (random-integer 2)))
(define q ; (u v w) such that u <= v, v <= w, and not u <= w
'#(
;x < y x = y x > y [x < z]
0 0 0 ; y < z
0 (z y x) (z y x) ; y = z
0 (z y x) (z y x) ; y > z
;x < y x = y x > y [x = z]
(y z x) (z x y) 0 ; y < z
(y z x) 0 (x z y) ; y = z
0 (y x z) (x z y) ; y > z
;x < y x = y x > y [x > z]
(x y z) (x y z) 0 ; y < z
(x y z) (x y z) 0 ; y = z
0 0 0 ; y > z
))
(let ((z? #f) (z #f)) ; stored element from previous call
(lambda (x y)
(let ((c-xx (checked-value c x x))
(c-yy (checked-value c y y))
(c-xy (checked-value c x y))
(c-yx (checked-value c y x)))
(if (not (zero? c-xx))
(error "compare error: not reflexive" c x))
(if (not (zero? c-yy))
(error "compare error: not reflexive" c y))
(if (not (zero? (+ c-xy c-yx)))
(error "compare error: not anti-symmetric" c x y))
(if z?
(let ((c-xz (checked-value c x z))
(c-zx (checked-value c z x))
(c-yz (checked-value c y z))
(c-zy (checked-value c z y)))
(if (not (zero? (+ c-xz c-zx)))
(error "compare error: not anti-symmetric" c x z))
(if (not (zero? (+ c-yz c-zy)))
(error "compare error: not anti-symmetric" c y z))
(let ((ijk (vector-ref q (+ c-xy (* 3 c-yz) (* 9 c-xz) 13))))
(if (list? ijk)
(apply error
"compare error: not transitive"
c
(map (lambda (i) (case i ((x) x) ((y) y) ((z) z)))
ijk)))))
(set! z? #t))
(set! z (if (random-boolean) x y)) ; randomized testing
c-xy))))
;;; srfi-69.scm --- Basic hash tables
;; Copyright (C) 2007 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;; Commentary:
;; My `hash' is compatible with core `hash', so I replace it.
;; However, my `hash-table?' and `make-hash-table' are different, so
;; importing this module will warn about them. If you don't rename my
;; imports, you shouldn't use both my hash tables and Guile's hash
;; tables in the same module.
;;
;; SRFI-13 `string-hash' and `string-hash-ci' have more arguments, but
;; are compatible with my `string-hash' and `string-ci-hash', and are
;; furthermore primitive in Guile, so I use them as my own.
;;
;; I also have the extension of allowing hash functions that require a
;; second argument to be used as the `hash-table-hash-function', and use
;; these in defaults to avoid an indirection in the hashx functions. The
;; only deviation this causes is:
;;
;; ((hash-table-hash-function (make-hash-table)) obj)
;; error> Wrong number of arguments to #<primitive-procedure hash>
;;
;; I don't think that SRFI 69 actually specifies that I *can't* do this,
;; because it only implies the signature of a hash function by way of the
;; named, exported hash functions. However, if this matters enough I can
;; add a private derivation of hash-function to the srfi-69:hash-table
;; record type, like associator is to equivalence-function.
;;
;; Also, outside of the issue of how weak keys and values are referenced
;; outside the table, I always interpret key equivalence to be that of
;; the `hash-table-equivalence-function'. For example, given the
;; requirement that `alist->hash-table' give earlier associations
;; priority, what should these answer?
;;
;; (hash-table-keys
;; (alist->hash-table '(("xY" . 1) ("Xy" . 2)) string-ci=?))
;;
;; (let ((ht (make-hash-table string-ci=?)))
;; (hash-table-set! ht "xY" 2)
;; (hash-table-set! ht "Xy" 1)
;; (hash-table-keys ht))
;;
;; My interpretation is that they can answer either ("Xy") or ("xY"),
;; where `hash-table-values' will of course always answer (1), because
;; the keys are the same according to the equivalence function. In this
;; implementation, both answer ("xY"). However, I don't guarantee that
;; this won't change in the future.
;;; Code:
;;;; Module definition & exports
(define-module (srfi srfi-69)
#\use-module (srfi srfi-1) ;alist-cons,second&c,assoc
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-13) ;string-hash,string-hash-ci
#\use-module (ice-9 optargs)
#\export (;; Type constructors & predicate
make-hash-table hash-table? alist->hash-table
;; Reflective queries
hash-table-equivalence-function hash-table-hash-function
;; Dealing with single elements
hash-table-ref hash-table-ref/default hash-table-set!
hash-table-delete! hash-table-exists? hash-table-update!
hash-table-update!/default
;; Dealing with the whole contents
hash-table-size hash-table-keys hash-table-values
hash-table-walk hash-table-fold hash-table->alist
hash-table-copy hash-table-merge!
;; Hashing
string-ci-hash hash-by-identity)
#\re-export (string-hash)
#\replace (hash make-hash-table hash-table?))
(cond-expand-provide (current-module) '(srfi-69))
;;;; Internal helper macros
;; Define these first, so the compiler will pick them up.
;; I am a macro only for efficiency, to avoid varargs/apply.
(define-macro (hashx-invoke hashx-proc ht-var . args)
"Invoke HASHX-PROC, a `hashx-*' procedure taking a hash-function,
assoc-function, and the hash-table as first args."
`(,hashx-proc (hash-table-hash-function ,ht-var)
(ht-associator ,ht-var)
(ht-real-table ,ht-var)
. ,args))
(define-macro (with-hashx-values bindings ht-var . body-forms)
"Bind BINDINGS to the hash-function, associator, and real-table of
HT-VAR, while evaluating BODY-FORMS."
`(let ((,(first bindings) (hash-table-hash-function ,ht-var))
(,(second bindings) (ht-associator ,ht-var))
(,(third bindings) (ht-real-table ,ht-var)))
. ,body-forms))
;;;; Hashing
;;; The largest fixnum is in `most-positive-fixnum' in module (guile),
;;; though not documented anywhere but libguile/numbers.c.
(define (caller-with-default-size hash-fn)
"Answer a function that makes `most-positive-fixnum' the default
second argument to HASH-FN, a 2-arg procedure."
(lambda* (obj #\optional (size most-positive-fixnum))
(hash-fn obj size)))
(define hash (caller-with-default-size (@ (guile) hash)))
(define string-ci-hash string-hash-ci)
(define hash-by-identity (caller-with-default-size hashq))
;;;; Reflective queries, construction, predicate
(define-record-type srfi-69:hash-table
(make-srfi-69-hash-table real-table associator size weakness
equivalence-function hash-function)
hash-table?
(real-table ht-real-table)
(associator ht-associator)
;; required for O(1) by SRFI-69. It really makes a mess of things,
;; and I'd like to compute it in O(n) and memoize it because it
;; doesn't seem terribly useful, but SRFI-69 is final.
(size ht-size ht-size!)
;; required for `hash-table-copy'
(weakness ht-weakness)
;; used only to implement hash-table-equivalence-function; I don't
;; use it internally other than for `ht-associator'.
(equivalence-function hash-table-equivalence-function)
(hash-function hash-table-hash-function))
(define (guess-hash-function equal-proc)
"Guess a hash function for EQUAL-PROC, falling back on `hash', as
specified in SRFI-69 for `make-hash-table'."
(cond ((eq? equal? equal-proc) (@ (guile) hash)) ;shortcut most common case
((eq? eq? equal-proc) hashq)
((eq? eqv? equal-proc) hashv)
((eq? string=? equal-proc) string-hash)
((eq? string-ci=? equal-proc) string-ci-hash)
(else (@ (guile) hash))))
(define (without-keyword-args rest-list)
"Answer REST-LIST with all keywords removed along with items that
follow them."
(let lp ((acc '()) (rest-list rest-list))
(cond ((null? rest-list) (reverse! acc))
((keyword? (first rest-list))
(lp acc (cddr rest-list)))
(else (lp (cons (first rest-list) acc) (cdr rest-list))))))
(define (guile-ht-ctor weakness)
"Answer the Guile HT constructor for the given WEAKNESS."
(case weakness
((#f) (@ (guile) make-hash-table))
((key) make-weak-key-hash-table)
((value) make-weak-value-hash-table)
((key-or-value) make-doubly-weak-hash-table)
(else (error "Invalid weak hash table type" weakness))))
(define (equivalence-proc->associator equal-proc)
"Answer an `assoc'-like procedure that compares the argument key to
alist keys with EQUAL-PROC."
(cond ((or (eq? equal? equal-proc)
(eq? string=? equal-proc)) (@ (guile) assoc))
((eq? eq? equal-proc) assq)
((eq? eqv? equal-proc) assv)
(else (lambda (item alist)
(assoc item alist equal-proc)))))
(define* (make-hash-table
#\optional (equal-proc equal?)
(hash-proc (guess-hash-function equal-proc))
#\key (weak #f) #\rest guile-opts)
"Answer a new hash table using EQUAL-PROC as the comparison
function, and HASH-PROC as the hash function. See the reference
manual for specifics, of which there are many."
(make-srfi-69-hash-table
(apply (guile-ht-ctor weak) (without-keyword-args guile-opts))
(equivalence-proc->associator equal-proc)
0 weak equal-proc hash-proc))
(define (alist->hash-table alist . mht-args)
"Convert ALIST to a hash table created with MHT-ARGS."
(let* ((result (apply make-hash-table mht-args))
(size (ht-size result)))
(with-hashx-values (hash-proc associator real-table) result
(for-each (lambda (pair)
(let ((handle (hashx-get-handle hash-proc associator
real-table (car pair))))
(cond ((not handle)
(set! size (1+ size))
(hashx-set! hash-proc associator real-table
(car pair) (cdr pair))))))
alist))
(ht-size! result size)
result))
;;;; Accessing table items
;; We use this to denote missing or unspecified values to avoid
;; possible collision with *unspecified*.
(define ht-unspecified (cons *unspecified* "ht-value"))
(define (hash-table-ref ht key . default-thunk-lst)
"Lookup KEY in HT and answer the value, invoke DEFAULT-THUNK if KEY
isn't present, or signal an error if DEFAULT-THUNK isn't provided."
(let ((result (hashx-invoke hashx-ref ht key ht-unspecified)))
(if (eq? ht-unspecified result)
(if (pair? default-thunk-lst)
((first default-thunk-lst))
(error "Key not in table" key ht))
result)))
(define (hash-table-ref/default ht key default)
"Lookup KEY in HT and answer the value. Answer DEFAULT if KEY isn't
present."
(hashx-invoke hashx-ref ht key default))
(define (hash-table-set! ht key new-value)
"Set KEY to NEW-VALUE in HT."
(let ((handle (hashx-invoke hashx-create-handle! ht key ht-unspecified)))
(if (eq? ht-unspecified (cdr handle))
(ht-size! ht (1+ (ht-size ht))))
(set-cdr! handle new-value))
*unspecified*)
(define (hash-table-delete! ht key)
"Remove KEY's association in HT."
(with-hashx-values (h a real-ht) ht
(if (hashx-get-handle h a real-ht key)
(begin
(ht-size! ht (1- (ht-size ht)))
(hashx-remove! h a real-ht key))))
*unspecified*)
(define (hash-table-exists? ht key)
"Return whether KEY is a key in HT."
(and (hashx-invoke hashx-get-handle ht key) #t))
;;; `hashx-set!' duplicates the hash lookup, but we use it anyway to
;;; avoid creating a handle in case DEFAULT-THUNK exits
;;; `hash-table-update!' non-locally.
(define (hash-table-update! ht key modifier . default-thunk-lst)
"Modify HT's value at KEY by passing its value to MODIFIER and
setting it to the result thereof. Invoke DEFAULT-THUNK for the old
value if KEY isn't in HT, or signal an error if DEFAULT-THUNK is not
provided."
(with-hashx-values (hash-proc associator real-table) ht
(let ((handle (hashx-get-handle hash-proc associator real-table key)))
(cond (handle
(set-cdr! handle (modifier (cdr handle))))
(else
(hashx-set! hash-proc associator real-table key
(if (pair? default-thunk-lst)
(modifier ((car default-thunk-lst)))
(error "Key not in table" key ht)))
(ht-size! ht (1+ (ht-size ht)))))))
*unspecified*)
(define (hash-table-update!/default ht key modifier default)
"Modify HT's value at KEY by passing its old value, or DEFAULT if it
doesn't have one, to MODIFIER, and setting it to the result thereof."
(hash-table-update! ht key modifier (lambda () default)))
;;;; Accessing whole tables
(define (hash-table-size ht)
"Return the number of associations in HT. This is guaranteed O(1)
for tables where #:weak was #f or not specified at creation time."
(if (ht-weakness ht)
(hash-table-fold ht (lambda (k v ans) (1+ ans)) 0)
(ht-size ht)))
(define (hash-table-keys ht)
"Return a list of the keys in HT."
(hash-table-fold ht (lambda (k v lst) (cons k lst)) '()))
(define (hash-table-values ht)
"Return a list of the values in HT."
(hash-table-fold ht (lambda (k v lst) (cons v lst)) '()))
(define (hash-table-walk ht proc)
"Call PROC with each key and value as two arguments."
(hash-table-fold ht (lambda (k v unspec)
(call-with-values (lambda () (proc k v))
(lambda vals unspec)))
*unspecified*))
(define (hash-table-fold ht f knil)
"Invoke (F KEY VAL PREV) for each KEY and VAL in HT, where PREV is
the result of the previous invocation, using KNIL as the first PREV.
Answer the final F result."
(hash-fold f knil (ht-real-table ht)))
(define (hash-table->alist ht)
"Return an alist for HT."
(hash-table-fold ht alist-cons '()))
(define (hash-table-copy ht)
"Answer a copy of HT."
(with-hashx-values (h a real-ht) ht
(let* ((size (hash-table-size ht)) (weak (ht-weakness ht))
(new-real-ht ((guile-ht-ctor weak) size)))
(hash-fold (lambda (k v ign) (hashx-set! h a new-real-ht k v))
#f real-ht)
(make-srfi-69-hash-table ;real,assoc,size,weak,equiv,h
new-real-ht a size weak
(hash-table-equivalence-function ht) h))))
(define (hash-table-merge! ht other-ht)
"Add all key/value pairs from OTHER-HT to HT, overriding HT's
mappings where present. Return HT."
(hash-table-fold
ht (lambda (k v ign) (hash-table-set! ht k v)) #f)
ht)
;;; srfi-69.scm ends here
;;; srfi-8.scm --- receive
;; Copyright (C) 2000, 2001, 2002, 2006 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-8)
\:use-module (ice-9 receive)
\:re-export-syntax (receive))
(cond-expand-provide (current-module) '(srfi-8))
;;; srfi-8.scm ends here
;;; srfi-88.scm --- Keyword Objects -*- coding: utf-8 -*-
;; Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Ludovic Courtès <ludo@gnu.org>
;;; Commentary:
;; This is a convenience module providing SRFI-88 "keyword object". All it
;; does is setup the right reader option and export keyword-related
;; convenience procedures.
;;; Code:
(define-module (srfi srfi-88)
#\re-export (keyword?)
#\export (keyword->string string->keyword))
(cond-expand-provide (current-module) '(srfi-88))
;; Change the keyword syntax both at compile time and run time; the latter is
;; useful at the REPL.
(eval-when (expand load eval)
(read-set! keywords 'postfix))
(define (keyword->string k)
"Return the name of @var{k} as a string."
(symbol->string (keyword->symbol k)))
(define (string->keyword s)
"Return the keyword object whose name is @var{s}."
(symbol->keyword (string->symbol s)))
;;; Local Variables:
;;; coding: latin-1
;;; End:
;;; srfi-88.scm ends here
;;; srfi-9.scm --- define-record-type
;; Copyright (C) 2001, 2002, 2006, 2009, 2010, 2011, 2012,
;; 2013 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; This module exports the syntactic form `define-record-type', which
;; is the means for creating record types defined in SRFI-9.
;;
;; The syntax of a record type definition is:
;;
;; <record type definition>
;; -> (define-record-type <type name>
;; (<constructor name> <field tag> ...)
;; <predicate name>
;; <field spec> ...)
;;
;; <field spec> -> (<field tag> <getter name>)
;; -> (<field tag> <getter name> <setter name>)
;;
;; <field tag> -> <identifier>
;; <... name> -> <identifier>
;;
;; Usage example:
;;
;; guile> (use-modules (srfi srfi-9))
;; guile> (define-record-type :foo (make-foo x) foo?
;; (x get-x) (y get-y set-y!))
;; guile> (define f (make-foo 1))
;; guile> f
;; #<:foo x: 1 y: #f>
;; guile> (get-x f)
;; 1
;; guile> (set-y! f 2)
;; 2
;; guile> (get-y f)
;; 2
;; guile> f
;; #<:foo x: 1 y: 2>
;; guile> (foo? f)
;; #t
;; guile> (foo? 1)
;; #f
;;; Code:
(define-module (srfi srfi-9)
#\use-module (srfi srfi-1)
#\use-module (system base ck)
#\export (define-record-type))
(cond-expand-provide (current-module) '(srfi-9))
;; Roll our own instead of using the public `define-inlinable'. This is
;; because the public one has a different `make-procedure-name', so
;; using it would require users to recompile code that uses SRFI-9. See
;; <http://lists.gnu.org/archive/html/guile-devel/2011-04/msg00111.html>.
;;
(define-syntax-rule (define-inlinable (name formals ...) body ...)
(define-tagged-inlinable () (name formals ...) body ...))
;; 'define-tagged-inlinable' has an additional feature: it stores a map
;; of keys to values that can be retrieved at expansion time. This is
;; currently used to retrieve the rtd id, field index, and record copier
;; macro for an arbitrary getter.
(define-syntax-rule (%%on-error err) err)
(define %%type #f) ; a private syntax literal
(define-syntax getter-type
(syntax-rules (quote)
((_ s 'getter 'err)
(getter (%%on-error err) %%type s))))
(define %%index #f) ; a private syntax literal
(define-syntax getter-index
(syntax-rules (quote)
((_ s 'getter 'err)
(getter (%%on-error err) %%index s))))
(define %%copier #f) ; a private syntax literal
(define-syntax getter-copier
(syntax-rules (quote)
((_ s 'getter 'err)
(getter (%%on-error err) %%copier s))))
(define-syntax define-tagged-inlinable
(lambda (x)
(define (make-procedure-name name)
(datum->syntax name
(symbol-append '% (syntax->datum name)
'-procedure)))
(syntax-case x ()
((_ ((key value) ...) (name formals ...) body ...)
(identifier? #'name)
(with-syntax ((proc-name (make-procedure-name #'name))
((args ...) (generate-temporaries #'(formals ...))))
#`(begin
(define (proc-name formals ...)
body ...)
(define-syntax name
(lambda (x)
(syntax-case x (%%on-error key ...)
((_ (%%on-error err) key s) #'(ck s 'value)) ...
((_ args ...)
#'((lambda (formals ...)
body ...)
args ...))
((_ a (... ...))
(syntax-violation 'name "Wrong number of arguments" x))
(_
(identifier? x)
#'proc-name))))))))))
(define (default-record-printer s p)
(display "#<" p)
(display (record-type-name (record-type-descriptor s)) p)
(let loop ((fields (record-type-fields (record-type-descriptor s)))
(off 0))
(cond
((not (null? fields))
(display " " p)
(display (car fields) p)
(display ": " p)
(write (struct-ref s off) p)
(loop (cdr fields) (+ 1 off)))))
(display ">" p))
(define (throw-bad-struct s who)
(throw 'wrong-type-arg who
"Wrong type argument: ~S" (list s)
(list s)))
(define (make-copier-id type-name)
(datum->syntax type-name
(symbol-append '%% (syntax->datum type-name)
'-set-fields)))
(define-syntax %%set-fields
(lambda (x)
(syntax-case x ()
((_ type-name (getter-id ...) check? s (getter expr) ...)
(every identifier? #'(getter ...))
(let ((copier-name (syntax->datum (make-copier-id #'type-name)))
(getter+exprs #'((getter expr) ...)))
(define (lookup id default-expr)
(let ((results
(filter (lambda (g+e)
(free-identifier=? id (car g+e)))
getter+exprs)))
(case (length results)
((0) default-expr)
((1) (cadar results))
(else (syntax-violation
copier-name "duplicate getter" x id)))))
(for-each (lambda (id)
(or (find (lambda (getter-id)
(free-identifier=? id getter-id))
#'(getter-id ...))
(syntax-violation
copier-name "unknown getter" x id)))
#'(getter ...))
(with-syntax ((unsafe-expr
#`(make-struct
type-name 0
#,@(map (lambda (getter index)
(lookup getter #`(struct-ref s #,index)))
#'(getter-id ...)
(iota (length #'(getter-id ...)))))))
(if (syntax->datum #'check?)
#`(if (eq? (struct-vtable s) type-name)
unsafe-expr
(throw-bad-struct
s '#,(datum->syntax #'here copier-name)))
#'unsafe-expr)))))))
(define-syntax %define-record-type
(lambda (x)
(define (field-identifiers field-specs)
(map (lambda (field-spec)
(syntax-case field-spec ()
((name getter) #'name)
((name getter setter) #'name)))
field-specs))
(define (getter-identifiers field-specs)
(map (lambda (field-spec)
(syntax-case field-spec ()
((name getter) #'getter)
((name getter setter) #'getter)))
field-specs))
(define (constructor form type-name constructor-spec field-names)
(syntax-case constructor-spec ()
((ctor field ...)
(every identifier? #'(field ...))
(let ((ctor-args (map (lambda (field)
(let ((name (syntax->datum field)))
(or (memq name field-names)
(syntax-violation
(syntax-case form ()
((macro . args)
(syntax->datum #'macro)))
"unknown field in constructor spec"
form field))
(cons name field)))
#'(field ...))))
#`(define-inlinable #,constructor-spec
(make-struct #,type-name 0
#,@(map (lambda (name)
(assq-ref ctor-args name))
field-names)))))))
(define (getters type-name getter-ids copier-id)
(map (lambda (getter index)
#`(define-tagged-inlinable
((%%type #,type-name)
(%%index #,index)
(%%copier #,copier-id))
(#,getter s)
(if (eq? (struct-vtable s) #,type-name)
(struct-ref s #,index)
(throw-bad-struct s '#,getter))))
getter-ids
(iota (length getter-ids))))
(define (copier type-name getter-ids copier-id)
#`(define-syntax-rule
(#,copier-id check? s (getter expr) (... ...))
(%%set-fields #,type-name #,getter-ids
check? s (getter expr) (... ...))))
(define (setters type-name field-specs)
(filter-map (lambda (field-spec index)
(syntax-case field-spec ()
((name getter) #f)
((name getter setter)
#`(define-inlinable (setter s val)
(if (eq? (struct-vtable s) #,type-name)
(struct-set! s #,index val)
(throw-bad-struct s 'setter))))))
field-specs
(iota (length field-specs))))
(define (functional-setters copier-id field-specs)
(filter-map (lambda (field-spec index)
(syntax-case field-spec ()
((name getter) #f)
((name getter setter)
#`(define-inlinable (setter s val)
(#,copier-id #t s (getter val))))))
field-specs
(iota (length field-specs))))
(define (record-layout immutable? count)
(let ((desc (if immutable? "pr" "pw")))
(string-concatenate (make-list count desc))))
(syntax-case x ()
((_ immutable? form type-name constructor-spec predicate-name
field-spec ...)
(let ()
(define (syntax-error message subform)
(syntax-violation (syntax-case #'form ()
((macro . args) (syntax->datum #'macro)))
message #'form subform))
(and (boolean? (syntax->datum #'immutable?))
(or (identifier? #'type-name)
(syntax-error "expected type name" #'type-name))
(syntax-case #'constructor-spec ()
((ctor args ...)
(every identifier? #'(ctor args ...))
#t)
(_ (syntax-error "invalid constructor spec"
#'constructor-spec)))
(or (identifier? #'predicate-name)
(syntax-error "expected predicate name" #'predicate-name))
(every (lambda (spec)
(syntax-case spec ()
((field getter) #t)
((field getter setter) #t)
(_ (syntax-error "invalid field spec" spec))))
#'(field-spec ...))))
(let* ((field-ids (field-identifiers #'(field-spec ...)))
(getter-ids (getter-identifiers #'(field-spec ...)))
(field-count (length field-ids))
(immutable? (syntax->datum #'immutable?))
(layout (record-layout immutable? field-count))
(field-names (map syntax->datum field-ids))
(ctor-name (syntax-case #'constructor-spec ()
((ctor args ...) #'ctor)))
(copier-id (make-copier-id #'type-name)))
#`(begin
#,(constructor #'form #'type-name #'constructor-spec field-names)
(define type-name
(let ((rtd (make-struct/no-tail
record-type-vtable
'#,(datum->syntax #'here (make-struct-layout layout))
default-record-printer
'type-name
'#,field-ids)))
(set-struct-vtable-name! rtd 'type-name)
(struct-set! rtd (+ 2 vtable-offset-user) #,ctor-name)
rtd))
(define-inlinable (predicate-name obj)
(and (struct? obj)
(eq? (struct-vtable obj) type-name)))
#,@(getters #'type-name getter-ids copier-id)
#,(copier #'type-name getter-ids copier-id)
#,@(if immutable?
(functional-setters copier-id #'(field-spec ...))
(setters #'type-name #'(field-spec ...))))))
((_ immutable? form . rest)
(syntax-violation
(syntax-case #'form ()
((macro . args) (syntax->datum #'macro)))
"invalid record definition syntax"
#'form)))))
(define-syntax-rule (define-record-type name ctor pred fields ...)
(%define-record-type #f (define-record-type name ctor pred fields ...)
name ctor pred fields ...))
;;; srfi-9.scm ends here
;;; Extensions to SRFI-9
;; Copyright (C) 2010, 2012 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary:
;; Extensions to SRFI-9. Fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-9 gnu)
#\use-module (srfi srfi-1)
#\use-module (system base ck)
#\export (set-record-type-printer!
define-immutable-record-type
set-field
set-fields))
(define (set-record-type-printer! type proc)
"Set PROC as the custom printer for TYPE."
(struct-set! type vtable-index-printer proc))
(define-syntax-rule (define-immutable-record-type name ctor pred fields ...)
((@@ (srfi srfi-9) %define-record-type)
#t (define-immutable-record-type name ctor pred fields ...)
name ctor pred fields ...))
(define-syntax-rule (set-field s (getter ...) expr)
(%set-fields #t (set-field s (getter ...) expr) ()
s ((getter ...) expr)))
(define-syntax-rule (set-fields s . rest)
(%set-fields #t (set-fields s . rest) ()
s . rest))
;;
;; collate-set-field-specs is a helper for %set-fields
;; thats combines all specs with the same head together.
;;
;; For example:
;;
;; SPECS: (((a b c) expr1)
;; ((a d) expr2)
;; ((b c) expr3)
;; ((c) expr4))
;;
;; RESULT: ((a ((b c) expr1)
;; ((d) expr2))
;; (b ((c) expr3))
;; (c (() expr4)))
;;
(define (collate-set-field-specs specs)
(define (insert head tail expr result)
(cond ((find (lambda (tree)
(free-identifier=? head (car tree)))
result)
=> (lambda (tree)
`((,head (,tail ,expr)
,@(cdr tree))
,@(delq tree result))))
(else `((,head (,tail ,expr))
,@result))))
(with-syntax (((((head . tail) expr) ...) specs))
(fold insert '() #'(head ...) #'(tail ...) #'(expr ...))))
(define-syntax unknown-getter
(lambda (x)
(syntax-case x ()
((_ orig-form getter)
(syntax-violation 'set-fields "unknown getter" #'orig-form #'getter)))))
(define-syntax c-list
(lambda (x)
(syntax-case x (quote)
((_ s 'v ...)
#'(ck s '(v ...))))))
(define-syntax c-same-type-check
(lambda (x)
(syntax-case x (quote)
((_ s 'orig-form '(path ...)
'(getter0 getter ...)
'(type0 type ...)
'on-success)
(every (lambda (t g)
(or (free-identifier=? t #'type0)
(syntax-violation
'set-fields
(format #f
"\\
field paths ~a and ~a require one object to belong to two different record types (~a and ~a)"
(syntax->datum #`(path ... #,g))
(syntax->datum #'(path ... getter0))
(syntax->datum t)
(syntax->datum #'type0))
#'orig-form)))
#'(type ...)
#'(getter ...))
#'(ck s 'on-success)))))
(define-syntax %set-fields
(lambda (x)
(with-syntax ((getter-type #'(@@ (srfi srfi-9) getter-type))
(getter-index #'(@@ (srfi srfi-9) getter-index))
(getter-copier #'(@@ (srfi srfi-9) getter-copier)))
(syntax-case x ()
((_ check? orig-form (path-so-far ...)
s)
#'s)
((_ check? orig-form (path-so-far ...)
s (() e))
#'e)
((_ check? orig-form (path-so-far ...)
struct-expr ((head . tail) expr) ...)
(let ((collated-specs (collate-set-field-specs
#'(((head . tail) expr) ...))))
(with-syntax (((getter0 getter ...)
(map car collated-specs)))
(with-syntax ((err #'(unknown-getter
orig-form getter0)))
#`(ck
()
(c-same-type-check
'orig-form
'(path-so-far ...)
'(getter0 getter ...)
(c-list (getter-type 'getter0 'err)
(getter-type 'getter 'err) ...)
'(let ((s struct-expr))
((ck () (getter-copier 'getter0 'err))
check?
s
#,@(map (lambda (spec)
(with-syntax (((head (tail expr) ...) spec))
(with-syntax ((err #'(unknown-getter
orig-form head)))
#'(head (%set-fields
check?
orig-form
(path-so-far ... head)
(struct-ref s (ck () (getter-index
'head 'err)))
(tail expr) ...)))))
collated-specs)))))))))
((_ check? orig-form (path-so-far ...)
s (() e) (() e*) ...)
(syntax-violation 'set-fields "duplicate field path"
#'orig-form #'(path-so-far ...)))
((_ check? orig-form (path-so-far ...)
s ((getter ...) expr) ...)
(syntax-violation 'set-fields "one field path is a prefix of another"
#'orig-form #'(path-so-far ...)))
((_ check? orig-form . rest)
(syntax-violation 'set-fields "invalid syntax" #'orig-form))))))
;;; srfi-98.scm --- An interface to access environment variables
;; Copyright (C) 2009 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Author: Julian Graham <julian.graham@aya.yale.edu>
;;; Date: 2009-05-26
;;; Commentary:
;; This is an implementation of SRFI-98 (An interface to access environment
;; variables).
;;
;; This module is fully documented in the Guile Reference Manual.
;;; Code:
(define-module (srfi srfi-98)
\:use-module (srfi srfi-1)
\:export (get-environment-variable
get-environment-variables))
(cond-expand-provide (current-module) '(srfi-98))
(define get-environment-variable getenv)
(define (get-environment-variables)
(define (string->alist-entry str)
(let ((pvt (string-index str #\=))
(len (string-length str)))
(and pvt (cons (substring str 0 pvt) (substring str (+ pvt 1) len)))))
(filter-map string->alist-entry (environ)))
;;;; (statprof) -- a statistical profiler for Guile
;;;; -*-scheme-*-
;;;;
;;;; Copyright (C) 2009, 2010, 2011, 2015 Free Software Foundation, Inc.
;;;; Copyright (C) 2004, 2009 Andy Wingo <wingo at pobox dot com>
;;;; Copyright (C) 2001 Rob Browning <rlb at defaultvalue dot org>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;;@code{(statprof)} is intended to be a fairly simple
;;statistical profiler for guile. It is in the early stages yet, so
;;consider its output still suspect, and please report any bugs to
;;@email{guile-devel at gnu.org}, or to me directly at @email{rlb at
;;defaultvalue.org}.
;;
;;A simple use of statprof would look like this:
;;
;;@example
;; (statprof-reset 0 50000 #t)
;; (statprof-start)
;; (do-something)
;; (statprof-stop)
;; (statprof-display)
;;@end example
;;
;;This would reset statprof, clearing all accumulated statistics, then
;;start profiling, run some code, stop profiling, and finally display a
;;gprof flat-style table of statistics which will look something like
;;this:
;;
;;@example
;; % cumulative self self total
;; time seconds seconds calls ms/call ms/call name
;; 35.29 0.23 0.23 2002 0.11 0.11 -
;; 23.53 0.15 0.15 2001 0.08 0.08 positive?
;; 23.53 0.15 0.15 2000 0.08 0.08 +
;; 11.76 0.23 0.08 2000 0.04 0.11 do-nothing
;; 5.88 0.64 0.04 2001 0.02 0.32 loop
;; 0.00 0.15 0.00 1 0.00 150.59 do-something
;; ...
;;@end example
;;
;;All of the numerical data with the exception of the calls column is
;;statistically approximate. In the following column descriptions, and
;;in all of statprof, "time" refers to execution time (both user and
;;system), not wall clock time.
;;
;;@table @asis
;;@item % time
;;The percent of the time spent inside the procedure itself
;;(not counting children).
;;@item cumulative seconds
;;The total number of seconds spent in the procedure, including
;;children.
;;@item self seconds
;;The total number of seconds spent in the procedure itself (not counting
;;children).
;;@item calls
;;The total number of times the procedure was called.
;;@item self ms/call
;;The average time taken by the procedure itself on each call, in ms.
;;@item total ms/call
;;The average time taken by each call to the procedure, including time
;;spent in child functions.
;;@item name
;;The name of the procedure.
;;@end table
;;
;;The profiler uses @code{eq?} and the procedure object itself to
;;identify the procedures, so it won't confuse different procedures with
;;the same name. They will show up as two different rows in the output.
;;
;;Right now the profiler is quite simplistic. I cannot provide
;;call-graphs or other higher level information. What you see in the
;;table is pretty much all there is. Patches are welcome :-)
;;
;;@section Implementation notes
;;
;;The profiler works by setting the unix profiling signal
;;@code{ITIMER_PROF} to go off after the interval you define in the call
;;to @code{statprof-reset}. When the signal fires, a sampling routine is
;;run which looks at the current procedure that's executing, and then
;;crawls up the stack, and for each procedure encountered, increments
;;that procedure's sample count. Note that if a procedure is encountered
;;multiple times on a given stack, it is only counted once. After the
;;sampling is complete, the profiler resets profiling timer to fire
;;again after the appropriate interval.
;;
;;Meanwhile, the profiler keeps track, via @code{get-internal-run-time},
;;how much CPU time (system and user -- which is also what
;;@code{ITIMER_PROF} tracks), has elapsed while code has been executing
;;within a statprof-start/stop block.
;;
;;The profiler also tries to avoid counting or timing its own code as
;;much as possible.
;;
;;; Code:
;; When you add new features, please also add tests to ./tests/ if you
;; have time, and then add the new files to ./run-tests. Also, if
;; anyone's bored, there are a lot of existing API bits that don't
;; have tests yet.
;; TODO
;;
;; Check about profiling C functions -- does profiling primitives work?
;; Also look into stealing code from qprof so we can sample the C stack
;; Call graphs?
(define-module (statprof)
#\use-module (srfi srfi-1)
#\autoload (ice-9 format) (format)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module (system vm program)
#\export (statprof-active?
statprof-start
statprof-stop
statprof-reset
statprof-accumulated-time
statprof-sample-count
statprof-fold-call-data
statprof-proc-call-data
statprof-call-data-name
statprof-call-data-calls
statprof-call-data-cum-samples
statprof-call-data-self-samples
statprof-call-data->stats
statprof-stats-proc-name
statprof-stats-%-time-in-proc
statprof-stats-cum-secs-in-proc
statprof-stats-self-secs-in-proc
statprof-stats-calls
statprof-stats-self-secs-per-call
statprof-stats-cum-secs-per-call
statprof-display
statprof-display-anomolies
statprof-fetch-stacks
statprof-fetch-call-tree
statprof
with-statprof
gcprof))
;; This profiler tracks two numbers for every function called while
;; it's active. It tracks the total number of calls, and the number
;; of times the function was active when the sampler fired.
;;
;; Globally the profiler tracks the total time elapsed and the number
;; of times the sampler was fired.
;;
;; Right now, this profiler is not per-thread and is not thread safe.
(define accumulated-time #f) ; total so far.
(define last-start-time #f) ; start-time when timer is active.
(define sample-count #f) ; total count of sampler calls.
(define sampling-frequency #f) ; in (seconds . microseconds)
(define remaining-prof-time #f) ; time remaining when prof suspended.
(define profile-level 0) ; for user start/stop nesting.
(define %count-calls? #t) ; whether to catch apply-frame.
(define gc-time-taken 0) ; gc time between statprof-start and
; statprof-stop.
(define record-full-stacks? #f) ; if #t, stash away the stacks
; for later analysis.
(define stacks '())
;; procedure-data will be a hash where the key is the function object
;; itself and the value is the data. The data will be a vector like
;; this: #(name call-count cum-sample-count self-sample-count)
(define procedure-data #f)
;; If you change the call-data data structure, you need to also change
;; sample-uncount-frame.
(define (make-call-data proc call-count cum-sample-count self-sample-count)
(vector proc call-count cum-sample-count self-sample-count))
(define (call-data-proc cd) (vector-ref cd 0))
(define (call-data-name cd) (procedure-name (call-data-proc cd)))
(define (call-data-printable cd)
(or (call-data-name cd)
(with-output-to-string (lambda () (write (call-data-proc cd))))))
(define (call-data-call-count cd) (vector-ref cd 1))
(define (call-data-cum-sample-count cd) (vector-ref cd 2))
(define (call-data-self-sample-count cd) (vector-ref cd 3))
(define (inc-call-data-call-count! cd)
(vector-set! cd 1 (1+ (vector-ref cd 1))))
(define (inc-call-data-cum-sample-count! cd)
(vector-set! cd 2 (1+ (vector-ref cd 2))))
(define (inc-call-data-self-sample-count! cd)
(vector-set! cd 3 (1+ (vector-ref cd 3))))
(define-macro (accumulate-time stop-time)
`(set! accumulated-time
(+ accumulated-time 0.0 (- ,stop-time last-start-time))))
(define (get-call-data proc)
(let ((k (if (or (not (program? proc))
(zero? (program-num-free-variables proc)))
proc
(program-objcode proc))))
(or (hashq-ref procedure-data k)
(let ((call-data (make-call-data proc 0 0 0)))
(hashq-set! procedure-data k call-data)
call-data))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SIGPROF handler
(define (sample-stack-procs stack)
(let ((stacklen (stack-length stack))
(hit-count-call? #f))
(if record-full-stacks?
(set! stacks (cons stack stacks)))
(set! sample-count (+ sample-count 1))
;; Now accumulate stats for the whole stack.
(let loop ((frame (stack-ref stack 0))
(procs-seen (make-hash-table 13))
(self #f))
(cond
((not frame)
(hash-fold
(lambda (proc val accum)
(inc-call-data-cum-sample-count!
(get-call-data proc)))
#f
procs-seen)
(and=> (and=> self get-call-data)
inc-call-data-self-sample-count!))
((frame-procedure frame)
=> (lambda (proc)
(cond
((eq? proc count-call)
;; We're not supposed to be sampling count-call and
;; its sub-functions, so loop again with a clean
;; slate.
(set! hit-count-call? #t)
(loop (frame-previous frame) (make-hash-table 13) #f))
(else
(hashq-set! procs-seen proc #t)
(loop (frame-previous frame)
procs-seen
(or self proc))))))
(else
(loop (frame-previous frame) procs-seen self))))
hit-count-call?))
(define inside-profiler? #f)
(define (profile-signal-handler sig)
(set! inside-profiler? #t)
;; FIXME: with-statprof should be able to set an outer frame for the
;; stack cut
(if (positive? profile-level)
(let* ((stop-time (get-internal-run-time))
;; cut down to the signal handler. note that this will only
;; work if statprof.scm is compiled; otherwise we get
;; `eval' on the stack instead, because if it's not
;; compiled, profile-signal-handler is a thunk that
;; tail-calls eval. perhaps we should always compile the
;; signal handler instead...
(stack (or (make-stack #t profile-signal-handler)
(pk 'what! (make-stack #t))))
(inside-apply-trap? (sample-stack-procs stack)))
(if (not inside-apply-trap?)
(begin
;; disabling here is just a little more efficient, but
;; not necessary given inside-profiler?. We can't just
;; disable unconditionally at the top of this function
;; and eliminate inside-profiler? because it seems to
;; confuse guile wrt re-enabling the trap when
;; count-call finishes.
(if %count-calls?
(set-vm-trace-level! (the-vm)
(1- (vm-trace-level (the-vm)))))
(accumulate-time stop-time)))
(setitimer ITIMER_PROF
0 0
(car sampling-frequency)
(cdr sampling-frequency))
(if (not inside-apply-trap?)
(begin
(set! last-start-time (get-internal-run-time))
(if %count-calls?
(set-vm-trace-level! (the-vm)
(1+ (vm-trace-level (the-vm)))))))))
(set! inside-profiler? #f))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Count total calls.
(define (count-call frame)
(if (not inside-profiler?)
(begin
(accumulate-time (get-internal-run-time))
(and=> (frame-procedure frame)
(lambda (proc)
(inc-call-data-call-count!
(get-call-data proc))))
(set! last-start-time (get-internal-run-time)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (statprof-active?)
"Returns @code{#t} if @code{statprof-start} has been called more times
than @code{statprof-stop}, @code{#f} otherwise."
(positive? profile-level))
;; Do not call this from statprof internal functions -- user only.
(define (statprof-start)
"Start the profiler.@code{}"
;; After some head-scratching, I don't *think* I need to mask/unmask
;; signals here, but if I'm wrong, please let me know.
(set! profile-level (+ profile-level 1))
(if (= profile-level 1)
(let* ((rpt remaining-prof-time)
(use-rpt? (and rpt
(or (positive? (car rpt))
(positive? (cdr rpt))))))
(set! remaining-prof-time #f)
(set! last-start-time (get-internal-run-time))
(set! gc-time-taken
(cdr (assq 'gc-time-taken (gc-stats))))
(if use-rpt?
(setitimer ITIMER_PROF 0 0 (car rpt) (cdr rpt))
(setitimer ITIMER_PROF
0 0
(car sampling-frequency)
(cdr sampling-frequency)))
(if %count-calls?
(add-hook! (vm-apply-hook (the-vm)) count-call))
(set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
#t)))
;; Do not call this from statprof internal functions -- user only.
(define (statprof-stop)
"Stop the profiler.@code{}"
;; After some head-scratching, I don't *think* I need to mask/unmask
;; signals here, but if I'm wrong, please let me know.
(set! profile-level (- profile-level 1))
(if (zero? profile-level)
(begin
(set! gc-time-taken
(- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
(set-vm-trace-level! (the-vm) (1- (vm-trace-level (the-vm))))
(if %count-calls?
(remove-hook! (vm-apply-hook (the-vm)) count-call))
;; I believe that we need to do this before getting the time
;; (unless we want to make things even more complicated).
(set! remaining-prof-time (setitimer ITIMER_PROF 0 0 0 0))
(accumulate-time (get-internal-run-time))
(set! last-start-time #f))))
(define* (statprof-reset sample-seconds sample-microseconds count-calls?
#\optional full-stacks?)
"Reset the statprof sampler interval to @var{sample-seconds} and
@var{sample-microseconds}. If @var{count-calls?} is true, arrange to
instrument procedure calls as well as collecting statistical profiling
data. If @var{full-stacks?} is true, collect all sampled stacks into a
list for later analysis.
Enables traps and debugging as necessary."
(if (positive? profile-level)
(error "Can't reset profiler while profiler is running."))
(set! %count-calls? count-calls?)
(set! accumulated-time 0)
(set! last-start-time #f)
(set! sample-count 0)
(set! sampling-frequency (cons sample-seconds sample-microseconds))
(set! remaining-prof-time #f)
(set! procedure-data (make-hash-table 131))
(set! record-full-stacks? full-stacks?)
(set! stacks '())
(sigaction SIGPROF profile-signal-handler)
#t)
(define (statprof-fold-call-data proc init)
"Fold @var{proc} over the call-data accumulated by statprof. Cannot be
called while statprof is active. @var{proc} should take two arguments,
@code{(@var{call-data} @var{prior-result})}.
Note that a given proc-name may appear multiple times, but if it does,
it represents different functions with the same name."
(if (positive? profile-level)
(error "Can't call statprof-fold-called while profiler is running."))
(hash-fold
(lambda (key value prior-result)
(proc value prior-result))
init
procedure-data))
(define (statprof-proc-call-data proc)
"Returns the call-data associated with @var{proc}, or @code{#f} if
none is available."
(if (positive? profile-level)
(error "Can't call statprof-fold-called while profiler is running."))
(hashq-ref procedure-data proc))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Stats
(define (statprof-call-data->stats call-data)
"Returns an object of type @code{statprof-stats}."
;; returns (vector proc-name
;; %-time-in-proc
;; cum-seconds-in-proc
;; self-seconds-in-proc
;; num-calls
;; self-secs-per-call
;; total-secs-per-call)
(let* ((proc-name (call-data-printable call-data))
(self-samples (call-data-self-sample-count call-data))
(cum-samples (call-data-cum-sample-count call-data))
(all-samples (statprof-sample-count))
(secs-per-sample (/ (statprof-accumulated-time)
(statprof-sample-count)))
(num-calls (and %count-calls? (statprof-call-data-calls call-data))))
(vector proc-name
(* (/ self-samples all-samples) 100.0)
(* cum-samples secs-per-sample 1.0)
(* self-samples secs-per-sample 1.0)
num-calls
(and num-calls ;; maybe we only sampled in children
(if (zero? self-samples) 0.0
(/ (* self-samples secs-per-sample) 1.0 num-calls)))
(and num-calls ;; cum-samples must be positive
(/ (* cum-samples secs-per-sample)
1.0
;; num-calls might be 0 if we entered statprof during the
;; dynamic extent of the call
(max num-calls 1))))))
(define (statprof-stats-proc-name stats) (vector-ref stats 0))
(define (statprof-stats-%-time-in-proc stats) (vector-ref stats 1))
(define (statprof-stats-cum-secs-in-proc stats) (vector-ref stats 2))
(define (statprof-stats-self-secs-in-proc stats) (vector-ref stats 3))
(define (statprof-stats-calls stats) (vector-ref stats 4))
(define (statprof-stats-self-secs-per-call stats) (vector-ref stats 5))
(define (statprof-stats-cum-secs-per-call stats) (vector-ref stats 6))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define (stats-sorter x y)
(let ((diff (- (statprof-stats-self-secs-in-proc x)
(statprof-stats-self-secs-in-proc y))))
(positive?
(if (= diff 0)
(- (statprof-stats-cum-secs-in-proc x)
(statprof-stats-cum-secs-in-proc y))
diff))))
(define (statprof-display . port)
"Displays a gprof-like summary of the statistics collected. Unless an
optional @var{port} argument is passed, uses the current output port."
(if (null? port) (set! port (current-output-port)))
(cond
((zero? (statprof-sample-count))
(format port "No samples recorded.\n"))
(else
(let* ((stats-list (statprof-fold-call-data
(lambda (data prior-value)
(cons (statprof-call-data->stats data)
prior-value))
'()))
(sorted-stats (sort stats-list stats-sorter)))
(define (display-stats-line stats)
(if %count-calls?
(format port "~6,2f ~9,2f ~9,2f ~7d ~8,2f ~8,2f "
(statprof-stats-%-time-in-proc stats)
(statprof-stats-cum-secs-in-proc stats)
(statprof-stats-self-secs-in-proc stats)
(statprof-stats-calls stats)
(* 1000 (statprof-stats-self-secs-per-call stats))
(* 1000 (statprof-stats-cum-secs-per-call stats)))
(format port "~6,2f ~9,2f ~9,2f "
(statprof-stats-%-time-in-proc stats)
(statprof-stats-cum-secs-in-proc stats)
(statprof-stats-self-secs-in-proc stats)))
(display (statprof-stats-proc-name stats) port)
(newline port))
(if %count-calls?
(begin
(format port "~5a ~10a ~7a ~8a ~8a ~8a ~8@a\n"
"% " "cumulative" "self" "" "self" "total" "")
(format port "~5a ~9a ~8a ~8a ~8a ~8a ~8@a\n"
"time" "seconds" "seconds" "calls" "ms/call" "ms/call" "name"))
(begin
(format port "~5a ~10a ~7a ~8@a\n"
"%" "cumulative" "self" "")
(format port "~5a ~10a ~7a ~8@a\n"
"time" "seconds" "seconds" "name")))
(for-each display-stats-line sorted-stats)
(display "---\n" port)
(simple-format #t "Sample count: ~A\n" (statprof-sample-count))
(simple-format #t "Total time: ~A seconds (~A seconds in GC)\n"
(statprof-accumulated-time)
(/ gc-time-taken 1.0 internal-time-units-per-second))))))
(define (statprof-display-anomolies)
"A sanity check that attempts to detect anomolies in statprof's
statistics.@code{}"
(statprof-fold-call-data
(lambda (data prior-value)
(if (and %count-calls?
(zero? (call-data-call-count data))
(positive? (call-data-cum-sample-count data)))
(simple-format #t
"==[~A ~A ~A]\n"
(call-data-name data)
(call-data-call-count data)
(call-data-cum-sample-count data))))
#f)
(simple-format #t "Total time: ~A\n" (statprof-accumulated-time))
(simple-format #t "Sample count: ~A\n" (statprof-sample-count)))
(define (statprof-accumulated-time)
"Returns the time accumulated during the last statprof run.@code{}"
(if (positive? profile-level)
(error "Can't get accumulated time while profiler is running."))
(/ accumulated-time internal-time-units-per-second))
(define (statprof-sample-count)
"Returns the number of samples taken during the last statprof run.@code{}"
(if (positive? profile-level)
(error "Can't get accumulated time while profiler is running."))
sample-count)
(define statprof-call-data-name call-data-name)
(define statprof-call-data-calls call-data-call-count)
(define statprof-call-data-cum-samples call-data-cum-sample-count)
(define statprof-call-data-self-samples call-data-self-sample-count)
(define (statprof-fetch-stacks)
"Returns a list of stacks, as they were captured since the last call
to @code{statprof-reset}.
Note that stacks are only collected if the @var{full-stacks?} argument
to @code{statprof-reset} is true."
stacks)
(define procedure=?
(lambda (a b)
(cond
((eq? a b))
((and (program? a) (program? b))
(eq? (program-objcode a) (program-objcode b)))
(else
#f))))
;; tree ::= (car n . tree*)
(define (lists->trees lists equal?)
(let lp ((in lists) (n-terminal 0) (tails '()))
(cond
((null? in)
(let ((trees (map (lambda (tail)
(cons (car tail)
(lists->trees (cdr tail) equal?)))
tails)))
(cons (apply + n-terminal (map cadr trees))
(sort trees
(lambda (a b) (> (cadr a) (cadr b)))))))
((null? (car in))
(lp (cdr in) (1+ n-terminal) tails))
((find (lambda (x) (equal? (car x) (caar in)))
tails)
=> (lambda (tail)
(lp (cdr in)
n-terminal
(assq-set! tails
(car tail)
(cons (cdar in) (cdr tail))))))
(else
(lp (cdr in)
n-terminal
(acons (caar in) (list (cdar in)) tails))))))
(define (stack->procedures stack)
(filter identity
(unfold-right (lambda (x) (not x))
frame-procedure
frame-previous
(stack-ref stack 0))))
(define (statprof-fetch-call-tree)
"Return a call tree for the previous statprof run.
The return value is a list of nodes, each of which is of the type:
@code
node ::= (@var{proc} @var{count} . @var{nodes})
@end code"
(cons #t (lists->trees (map stack->procedures stacks) procedure=?)))
(define* (statprof thunk #\key (loop 1) (hz 100) (count-calls? #f)
(full-stacks? #f))
"Profile the execution of @var{thunk}, and return its return values.
The stack will be sampled @var{hz} times per second, and the thunk
itself will be called @var{loop} times.
If @var{count-calls?} is true, all procedure calls will be recorded. This
operation is somewhat expensive.
If @var{full-stacks?} is true, at each sample, statprof will store away the
whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
@code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
(dynamic-wind
(lambda ()
(statprof-reset (inexact->exact (floor (/ 1 hz)))
(inexact->exact (* 1e6 (- (/ 1 hz)
(floor (/ 1 hz)))))
count-calls?
full-stacks?)
(statprof-start))
(lambda ()
(let lp ((i loop)
(result '()))
(if (zero? i)
(apply values result)
(call-with-values thunk
(lambda result
(lp (1- i) result))))))
(lambda ()
(statprof-stop)
(statprof-display)
(set! procedure-data #f))))
(define-macro (with-statprof . args)
"Profile the expressions in the body, and return the body's return values.
Keyword arguments:
@table @code
@item #:loop
Execute the body @var{loop} number of times, or @code{#f} for no looping
default: @code{#f}
@item #:hz
Sampling rate
default: @code{20}
@item #:count-calls?
Whether to instrument each function call (expensive)
default: @code{#f}
@item #:full-stacks?
Whether to collect away all sampled stacks into a list
default: @code{#f}
@end table"
(define (kw-arg-ref kw args def)
(cond
((null? args) (error "Invalid macro body"))
((keyword? (car args))
(if (eq? (car args) kw)
(cadr args)
(kw-arg-ref kw (cddr args) def)))
((eq? kw #f def) ;; asking for the body
args)
(else def))) ;; kw not found
`((@ (statprof) statprof)
(lambda () ,@(kw-arg-ref #f args #f))
#\loop ,(kw-arg-ref #\loop args 1)
#\hz ,(kw-arg-ref #\hz args 100)
#\count-calls? ,(kw-arg-ref #\count-calls? args #f)
#\full-stacks? ,(kw-arg-ref #\full-stacks? args #f)))
(define* (gcprof thunk #\key (loop 1) (full-stacks? #f))
"Do an allocation profile of the execution of @var{thunk}.
The stack will be sampled soon after every garbage collection, yielding
an approximate idea of what is causing allocation in your program.
Since GC does not occur very frequently, you may need to use the
@var{loop} parameter, to cause @var{thunk} to be called @var{loop}
times.
If @var{full-stacks?} is true, at each sample, statprof will store away the
whole call tree, for later analysis. Use @code{statprof-fetch-stacks} or
@code{statprof-fetch-call-tree} to retrieve the last-stored stacks."
(define (reset)
(if (positive? profile-level)
(error "Can't reset profiler while profiler is running."))
(set! accumulated-time 0)
(set! last-start-time #f)
(set! sample-count 0)
(set! %count-calls? #f)
(set! procedure-data (make-hash-table 131))
(set! record-full-stacks? full-stacks?)
(set! stacks '()))
(define (gc-callback)
(cond
(inside-profiler?)
(else
(set! inside-profiler? #t)
;; FIXME: should be able to set an outer frame for the stack cut
(let ((stop-time (get-internal-run-time))
;; Cut down to gc-callback, and then one before (the
;; after-gc async). See the note in profile-signal-handler
;; also.
(stack (or (make-stack #t gc-callback 0 1)
(pk 'what! (make-stack #t)))))
(sample-stack-procs stack)
(accumulate-time stop-time)
(set! last-start-time (get-internal-run-time)))
(set! inside-profiler? #f))))
(define (start)
(set! profile-level (+ profile-level 1))
(if (= profile-level 1)
(begin
(set! remaining-prof-time #f)
(set! last-start-time (get-internal-run-time))
(set! gc-time-taken (cdr (assq 'gc-time-taken (gc-stats))))
(add-hook! after-gc-hook gc-callback)
(set-vm-trace-level! (the-vm) (1+ (vm-trace-level (the-vm))))
#t)))
(define (stop)
(set! profile-level (- profile-level 1))
(if (zero? profile-level)
(begin
(set! gc-time-taken
(- (cdr (assq 'gc-time-taken (gc-stats))) gc-time-taken))
(remove-hook! after-gc-hook gc-callback)
(accumulate-time (get-internal-run-time))
(set! last-start-time #f))))
(dynamic-wind
(lambda ()
(reset)
(start))
(lambda ()
(let lp ((i loop))
(if (not (zero? i))
(begin
(thunk)
(lp (1- i))))))
(lambda ()
(stop)
(statprof-display)
(set! procedure-data #f))))
;;;; (sxml apply-templates) -- xslt-like transformation for sxml
;;;;
;;;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; Copyright 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Written 2003 by Oleg Kiselyov <oleg at pobox dot com> as apply-templates.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;; Pre-order traversal of a tree and creation of a new tree:
;;
;;@smallexample
;; apply-templates:: tree x <templates> -> <new-tree>
;;@end smallexample
;; where
;;@smallexample
;; <templates> ::= (<template> ...)
;; <template> ::= (<node-test> <node-test> ... <node-test> . <handler>)
;; <node-test> ::= an argument to node-typeof? above
;; <handler> ::= <tree> -> <new-tree>
;;@end smallexample
;;
;; This procedure does a @emph{normal}, pre-order traversal of an SXML
;; tree. It walks the tree, checking at each node against the list of
;; matching templates.
;;
;; If the match is found (which must be unique, i.e., unambiguous), the
;; corresponding handler is invoked and given the current node as an
;; argument. The result from the handler, which must be a @code{<tree>},
;; takes place of the current node in the resulting tree.
;;
;; The name of the function is not accidental: it resembles rather
;; closely an @code{apply-templates} function of XSLT.
;;
;;; Code:
(define-module (sxml apply-templates)
#\use-module (sxml ssax)
#\use-module ((sxml xpath) \:hide (filter))
#\export (apply-templates))
(define (apply-templates tree templates)
; Filter the list of templates. If a template does not
; contradict the given node (that is, its head matches
; the type of the node), chop off the head and keep the
; rest as the result. All contradicting templates are removed.
(define (filter-templates node templates)
(cond
((null? templates) templates)
((not (pair? (car templates))) ; A good template must be a list
(filter-templates node (cdr templates)))
(((node-typeof? (caar templates)) node)
(cons (cdar templates) (filter-templates node (cdr templates))))
(else
(filter-templates node (cdr templates)))))
; Here <templates> ::= [<template> | <handler>]
; If there is a <handler> in the above list, it must
; be only one. If found, return it; otherwise, return #f
(define (find-handler templates)
(and (pair? templates)
(cond
((procedure? (car templates))
(if (find-handler (cdr templates))
(error "ambiguous template match"))
(car templates))
(else (find-handler (cdr templates))))))
(let loop ((tree tree) (active-templates '()))
;(cout "active-templates: " active-templates nl "tree: " tree nl)
(if (nodeset? tree)
(map-union (lambda (a-tree) (loop a-tree active-templates)) tree)
(let ((still-active-templates
(append
(filter-templates tree active-templates)
(filter-templates tree templates))))
(cond
;((null? still-active-templates) '())
((find-handler still-active-templates) =>
(lambda (handler) (handler tree)))
((not (pair? tree)) '())
(else
(loop (cdr tree) still-active-templates)))))))
;;; arch-tag: 88cd87de-8825-4ab3-9721-cf99694fb787
;;; templates.scm ends here
;;;; (sxml fold) -- transformation of sxml via fold operations
;;;;
;;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;; Written 2007 by Andy Wingo <wingo at pobox dot com>.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;; @code{(sxml fold)} defines a number of variants of the @dfn{fold}
;; algorithm for use in transforming SXML trees. Additionally it defines
;; the layout operator, @code{fold-layout}, which might be described as
;; a context-passing variant of SSAX's @code{pre-post-order}.
;;
;;; Code:
(define-module (sxml fold)
#\use-module (srfi srfi-1)
#\export (foldt
foldts
foldts*
fold-values
foldts*-values
fold-layout))
(define (atom? x)
(not (pair? x)))
(define (foldt fup fhere tree)
"The standard multithreaded tree fold.
@var{fup} is of type [a] -> a. @var{fhere} is of type object -> a.
"
(if (atom? tree)
(fhere tree)
(fup (map (lambda (kid)
(foldt fup fhere kid))
tree))))
(define (foldts fdown fup fhere seed tree)
"The single-threaded tree fold originally defined in SSAX.
@xref{sxml ssax,,(sxml ssax)}, for more information."
(if (atom? tree)
(fhere seed tree)
(fup seed
(fold (lambda (kid kseed)
(foldts fdown fup fhere kseed kid))
(fdown seed tree)
tree)
tree)))
(define (foldts* fdown fup fhere seed tree)
"A variant of @ref{sxml fold foldts,,foldts} that allows pre-order
tree rewrites. Originally defined in Andy Wingo's 2007 paper,
@emph{Applications of fold to XML transformation}."
(if (atom? tree)
(fhere seed tree)
(call-with-values
(lambda () (fdown seed tree))
(lambda (kseed tree)
(fup seed
(fold (lambda (kid kseed)
(foldts* fdown fup fhere
kseed kid))
kseed
tree)
tree)))))
(define (fold-values proc list . seeds)
"A variant of @ref{SRFI-1 Fold and Map, fold} that allows multi-valued
seeds. Note that the order of the arguments differs from that of
@code{fold}."
(if (null? list)
(apply values seeds)
(call-with-values
(lambda () (apply proc (car list) seeds))
(lambda seeds
(apply fold-values proc (cdr list) seeds)))))
(define (foldts*-values fdown fup fhere tree . seeds)
"A variant of @ref{sxml fold foldts*,,foldts*} that allows
multi-valued seeds. Originally defined in Andy Wingo's 2007 paper,
@emph{Applications of fold to XML transformation}."
(if (atom? tree)
(apply fhere tree seeds)
(call-with-values
(lambda () (apply fdown tree seeds))
(lambda (tree . kseeds)
(call-with-values
(lambda ()
(apply fold-values
(lambda (tree . seeds)
(apply foldts*-values
fdown fup fhere tree seeds))
tree kseeds))
(lambda kseeds
(apply fup tree (append seeds kseeds))))))))
(define (assq-ref alist key default)
(cond ((assq key alist) => cdr)
(else default)))
(define (fold-layout tree bindings params layout stylesheet)
"A traversal combinator in the spirit of SSAX's @ref{sxml transform
pre-post-order,,pre-post-order}.
@code{fold-layout} was originally presented in Andy Wingo's 2007 paper,
@emph{Applications of fold to XML transformation}.
@example
bindings := (<binding>...)
binding := (<tag> <bandler-pair>...)
| (*default* . <post-handler>)
| (*text* . <text-handler>)
tag := <symbol>
handler-pair := (pre-layout . <pre-layout-handler>)
| (post . <post-handler>)
| (bindings . <bindings>)
| (pre . <pre-handler>)
| (macro . <macro-handler>)
@end example
@table @var
@item pre-layout-handler
A function of three arguments:
@table @var
@item kids
the kids of the current node, before traversal
@item params
the params of the current node
@item layout
the layout coming into this node
@end table
@var{pre-layout-handler} is expected to use this information to return a
layout to pass to the kids. The default implementation returns the
layout given in the arguments.
@item post-handler
A function of five arguments:
@table @var
@item tag
the current tag being processed
@item params
the params of the current node
@item layout
the layout coming into the current node, before any kids were processed
@item klayout
the layout after processing all of the children
@item kids
the already-processed child nodes
@end table
@var{post-handler} should return two values, the layout to pass to the
next node and the final tree.
@item text-handler
@var{text-handler} is a function of three arguments:
@table @var
@item text
the string
@item params
the current params
@item layout
the current layout
@end table
@var{text-handler} should return two values, the layout to pass to the
next node and the value to which the string should transform.
@end table
"
(define (err . args)
(error "no binding available" args))
(define (fdown tree bindings pcont params layout ret)
(define (fdown-helper new-bindings new-layout cont)
(let ((cont-with-tag (lambda args
(apply cont (car tree) args)))
(bindings (if new-bindings
(append new-bindings bindings)
bindings))
(style-params (assq-ref stylesheet (car tree) '())))
(cond
((null? (cdr tree))
(values
'() bindings cont-with-tag (cons style-params params) new-layout '()))
((and (pair? (cadr tree)) (eq? (caadr tree) '@))
(let ((params (cons (append (cdadr tree) style-params) params)))
(values
(cddr tree) bindings cont-with-tag params new-layout '())))
(else
(values
(cdr tree) bindings cont-with-tag (cons style-params params) new-layout '())))))
(define (no-bindings)
(fdown-helper #f layout (assq-ref bindings '*default* err)))
(define (macro macro-handler)
(fdown (apply macro-handler tree)
bindings pcont params layout ret))
(define (pre pre-handler)
(values '() bindings
(lambda (params layout old-layout kids)
(values layout (reverse kids)))
params layout (apply pre-handler tree)))
(define (have-bindings tag-bindings)
(fdown-helper
(assq-ref tag-bindings 'bindings #f)
((assq-ref tag-bindings 'pre-layout
(lambda (tag params layout)
layout))
tree params layout)
(assq-ref tag-bindings 'post
(assq-ref bindings '*default* err))))
(let ((tag-bindings (assq-ref bindings (car tree) #f)))
(cond
((not tag-bindings) (no-bindings))
((assq-ref tag-bindings 'macro #f) => macro)
((assq-ref tag-bindings 'pre #f) => pre)
(else (have-bindings tag-bindings)))))
(define (fup tree bindings cont params layout ret
kbindings kcont kparams klayout kret)
(call-with-values
(lambda ()
(kcont kparams layout klayout (reverse kret)))
(lambda (klayout kret)
(values bindings cont params klayout (cons kret ret)))))
(define (fhere tree bindings cont params layout ret)
(call-with-values
(lambda ()
((assq-ref bindings '*text* err) tree params layout))
(lambda (tlayout tret)
(values bindings cont params tlayout (cons tret ret)))))
(call-with-values
(lambda ()
(foldts*-values
fdown fup fhere tree bindings #f (cons params '()) layout '()))
(lambda (bindings cont params layout ret)
(values (car ret) layout))))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2010, 2011 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; This library 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 Lesser
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(define-module (sxml match)
#\export (sxml-match
sxml-match-let
sxml-match-let*)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-11)
#\use-module (ice-9 control))
;;; Commentary:
;;;
;;; This module provides an SXML pattern matcher, written by Jim Bender. This
;;; allows application code to match on SXML nodes and attributes without having
;;; to deal with the details of s-expression matching, without worrying about
;;; the order of attributes, etc.
;;;
;;; It is fully documented in the Guile Reference Manual.
;;;
;;; Code:
;;;
;;; PLT compatibility layer.
;;;
(define-syntax-rule (syntax-object->datum stx)
(syntax->datum stx))
(define-syntax-rule (void)
*unspecified*)
(define (raise-syntax-error x msg obj sub)
(throw 'sxml-match-error x msg obj sub))
(define-syntax module
(syntax-rules (provide require)
((_ name lang (provide p_ ...) (require r_ ...)
body ...)
(begin body ...))))
;;;
;;; Include upstream source file.
;;;
;; This file was taken from
;; <http://planet.plt-scheme.org/package-source/jim/sxml-match.plt/1/1/> on
;; 2010-05-24. It was written by Jim Bender <benderjg2@aol.com> and released
;; under the MIT/X11 license
;; <http://www.gnu.org/licenses/license-list.html#X11License>.
;;
;; Modified the `sxml-match1' macro to allow multiple-value returns (upstream
;; was notified.)
(include-from-path "sxml/sxml-match.ss")
;;; match.scm ends here
;;;; (sxml simple) -- a simple interface to the SSAX parser
;;;;
;;;; Copyright (C) 2009, 2010, 2013 Free Software Foundation, Inc.
;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Originally written by Oleg Kiselyov <oleg at pobox dot com> as SXML-to-HTML.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;;A simple interface to XML parsing and serialization.
;;
;;; Code:
(define-module (sxml simple)
#\use-module (sxml ssax input-parse)
#\use-module (sxml ssax)
#\use-module (sxml transform)
#\use-module (ice-9 match)
#\use-module (srfi srfi-13)
#\export (xml->sxml sxml->xml sxml->string))
;; Helpers from upstream/SSAX.scm.
;;
; ssax:reverse-collect-str LIST-OF-FRAGS -> LIST-OF-FRAGS
; given the list of fragments (some of which are text strings)
; reverse the list and concatenate adjacent text strings.
; We can prove from the general case below that if LIST-OF-FRAGS
; has zero or one element, the result of the procedure is equal?
; to its argument. This fact justifies the shortcut evaluation below.
(define (ssax:reverse-collect-str fragments)
(cond
((null? fragments) '()) ; a shortcut
((null? (cdr fragments)) fragments) ; see the comment above
(else
(let loop ((fragments fragments) (result '()) (strs '()))
(cond
((null? fragments)
(if (null? strs) result
(cons (string-concatenate/shared strs) result)))
((string? (car fragments))
(loop (cdr fragments) result (cons (car fragments) strs)))
(else
(loop (cdr fragments)
(cons
(car fragments)
(if (null? strs) result
(cons (string-concatenate/shared strs) result)))
'())))))))
(define (read-internal-doctype-as-string port)
(string-concatenate/shared
(let loop ()
(let ((fragment
(next-token '() '(#\]) "reading internal DOCTYPE" port)))
(if (eqv? #\> (peek-next-char port))
(begin
(read-char port)
(cons fragment '()))
(cons* fragment "]" (loop)))))))
;; Ideas for the future for this interface:
;;
;; * Allow doctypes to provide parsed entities
;;
;; * Allow validation (the ELEMENTS value from the DOCTYPE handler
;; below)
;;
;; * Parse internal DTDs
;;
;; * Parse external DTDs
;;
(define* (xml->sxml #\optional (string-or-port (current-input-port)) #\key
(namespaces '())
(declare-namespaces? #t)
(trim-whitespace? #f)
(entities '())
(default-entity-handler #f)
(doctype-handler #f))
"Use SSAX to parse an XML document into SXML. Takes one optional
argument, @var{string-or-port}, which defaults to the current input
port."
;; NAMESPACES: alist of PREFIX -> URI. Specifies the symbol prefix
;; that the user wants on elements of a given namespace in the
;; resulting SXML, regardless of the abbreviated namespaces defined in
;; the document by xmlns attributes. If DECLARE-NAMESPACES? is true,
;; these namespaces are treated as if they were declared in the DTD.
;; ENTITIES: alist of SYMBOL -> STRING.
;; NAMESPACES: list of (DOC-PREFIX . (USER-PREFIX . URI)).
;; A DOC-PREFIX of #f indicates that it comes from the user.
;; Otherwise, prefixes are symbols.
(define (munge-namespaces namespaces)
(map (lambda (el)
(match el
((prefix . uri-string)
(cons* (and declare-namespaces? prefix)
prefix
(ssax:uri-string->symbol uri-string)))))
namespaces))
(define (user-namespaces)
(munge-namespaces namespaces))
(define (user-entities)
(if (and default-entity-handler
(not (assq '*DEFAULT* entities)))
(acons '*DEFAULT* default-entity-handler entities)
entities))
(define (name->sxml name)
(match name
((prefix . local-part)
(symbol-append prefix (string->symbol ":") local-part))
(_ name)))
(define (doctype-continuation seed)
(lambda* (#\key (entities '()) (namespaces '()))
(values #f
(append entities (user-entities))
(append (munge-namespaces namespaces) (user-namespaces))
seed)))
;; The SEED in this parser is the SXML: initialized to '() at each new
;; level by the fdown handlers; built in reverse by the fhere parsers;
;; and reverse-collected by the fup handlers.
(define parser
(ssax:make-parser
NEW-LEVEL-SEED ; fdown
(lambda (elem-gi attributes namespaces expected-content seed)
'())
FINISH-ELEMENT ; fup
(lambda (elem-gi attributes namespaces parent-seed seed)
(let ((seed (if trim-whitespace?
(ssax:reverse-collect-str-drop-ws seed)
(ssax:reverse-collect-str seed)))
(attrs (attlist-fold
(lambda (attr accum)
(cons (list (name->sxml (car attr)) (cdr attr))
accum))
'() attributes)))
(acons (name->sxml elem-gi)
(if (null? attrs)
seed
(cons (cons '@ attrs) seed))
parent-seed)))
CHAR-DATA-HANDLER ; fhere
(lambda (string1 string2 seed)
(if (string-null? string2)
(cons string1 seed)
(cons* string2 string1 seed)))
DOCTYPE
;; -> ELEMS ENTITIES NAMESPACES SEED
;;
;; ELEMS is for validation and currently unused.
;;
;; ENTITIES is an alist of parsed entities (symbol -> string).
;;
;; NAMESPACES is as above.
;;
;; SEED builds up the content.
(lambda (port docname systemid internal-subset? seed)
(call-with-values
(lambda ()
(cond
(doctype-handler
(doctype-handler docname systemid
(and internal-subset?
(read-internal-doctype-as-string port))))
(else
(when internal-subset?
(ssax:skip-internal-dtd port))
(values))))
(doctype-continuation seed)))
UNDECL-ROOT
;; This is like the DOCTYPE handler, but for documents that do not
;; have a <!DOCTYPE!> entry.
(lambda (elem-gi seed)
(call-with-values
(lambda ()
(if doctype-handler
(doctype-handler #f #f #f)
(values)))
(doctype-continuation seed)))
PI
((*DEFAULT*
. (lambda (port pi-tag seed)
(cons
(list '*PI* pi-tag (ssax:read-pi-body-as-string port))
seed))))))
(let* ((port (if (string? string-or-port)
(open-input-string string-or-port)
string-or-port))
(elements (reverse (parser port '()))))
`(*TOP* ,@elements)))
(define check-name
(let ((*good-cache* (make-hash-table)))
(lambda (name)
(if (not (hashq-ref *good-cache* name))
(let* ((str (symbol->string name))
(i (string-index str #\:))
(head (or (and i (substring str 0 i)) str))
(tail (and i (substring str (1+ i)))))
(and i (string-index (substring str (1+ i)) #\:)
(error "Invalid QName: more than one colon" name))
(for-each
(lambda (s)
(and s
(or (char-alphabetic? (string-ref s 0))
(eq? (string-ref s 0) #\_)
(error "Invalid name starting character" s name))
(string-for-each
(lambda (c)
(or (char-alphabetic? c) (string-index "0123456789.-_" c)
(error "Invalid name character" c s name)))
s)))
(list head tail))
(hashq-set! *good-cache* name #t))))))
;; The following two functions serialize tags and attributes. They are
;; being used in the node handlers for the post-order function, see
;; below.
(define (attribute-value->xml value port)
(cond
((pair? value)
(attribute-value->xml (car value) port)
(attribute-value->xml (cdr value) port))
((null? value)
*unspecified*)
((string? value)
(string->escaped-xml value port))
((procedure? value)
(with-output-to-port port value))
(else
(string->escaped-xml
(call-with-output-string (lambda (port) (display value port)))
port))))
(define (attribute->xml attr value port)
(check-name attr)
(display attr port)
(display "=\"" port)
(attribute-value->xml value port)
(display #\" port))
(define (element->xml tag attrs body port)
(check-name tag)
(display #\< port)
(display tag port)
(if attrs
(let lp ((attrs attrs))
(if (pair? attrs)
(let ((attr (car attrs)))
(display #\space port)
(if (pair? attr)
(attribute->xml (car attr) (cdr attr) port)
(error "bad attribute" tag attr))
(lp (cdr attrs)))
(if (not (null? attrs))
(error "bad attributes" tag attrs)))))
(if (pair? body)
(begin
(display #\> port)
(let lp ((body body))
(cond
((pair? body)
(sxml->xml (car body) port)
(lp (cdr body)))
((null? body)
(display "</" port)
(display tag port)
(display ">" port))
(else
(error "bad element body" tag body)))))
(display " />" port)))
;; FIXME: ensure name is valid
(define (entity->xml name port)
(display #\& port)
(display name port)
(display #\; port))
;; FIXME: ensure tag and str are valid
(define (pi->xml tag str port)
(display "<?" port)
(display tag port)
(display #\space port)
(display str port)
(display "?>" port))
(define* (sxml->xml tree #\optional (port (current-output-port)))
"Serialize the sxml tree @var{tree} as XML. The output will be written
to the current output port, unless the optional argument @var{port} is
present."
(cond
((pair? tree)
(if (symbol? (car tree))
;; An element.
(let ((tag (car tree)))
(case tag
((*TOP*)
(sxml->xml (cdr tree) port))
((*ENTITY*)
(if (and (list? (cdr tree)) (= (length (cdr tree)) 1))
(entity->xml (cadr tree) port)
(error "bad *ENTITY* args" (cdr tree))))
((*PI*)
(if (and (list? (cdr tree)) (= (length (cdr tree)) 2))
(pi->xml (cadr tree) (caddr tree) port)
(error "bad *PI* args" (cdr tree))))
(else
(let* ((elems (cdr tree))
(attrs (and (pair? elems) (pair? (car elems))
(eq? '@ (caar elems))
(cdar elems))))
(element->xml tag attrs (if attrs (cdr elems) elems) port)))))
;; A nodelist.
(for-each (lambda (x) (sxml->xml x port)) tree)))
((string? tree)
(string->escaped-xml tree port))
((null? tree) *unspecified*)
((not tree) *unspecified*)
((eqv? tree #t) *unspecified*)
((procedure? tree)
(with-output-to-port port tree))
(else
(string->escaped-xml
(call-with-output-string (lambda (port) (display tree port)))
port))))
(define (sxml->string sxml)
"Detag an sxml tree @var{sxml} into a string. Does not perform any
formatting."
(string-concatenate-reverse
(foldts
(lambda (seed tree) ; fdown
'())
(lambda (seed kid-seed tree) ; fup
(append! kid-seed seed))
(lambda (seed tree) ; fhere
(if (string? tree) (cons tree seed) seed))
'()
sxml)))
(define (make-char-quotator char-encoding)
(let ((bad-chars (list->char-set (map car char-encoding))))
;; Check to see if str contains one of the characters in charset,
;; from the position i onward. If so, return that character's index.
;; otherwise, return #f
(define (index-cset str i charset)
(string-index str charset i))
;; The body of the function
(lambda (str port)
(let ((bad-pos (index-cset str 0 bad-chars)))
(if (not bad-pos)
(display str port) ; str had all good chars
(let loop ((from 0) (to bad-pos))
(cond
((>= from (string-length str)) *unspecified*)
((not to)
(display (substring str from (string-length str)) port))
(else
(let ((quoted-char
(cdr (assv (string-ref str to) char-encoding)))
(new-to
(index-cset str (+ 1 to) bad-chars)))
(if (< from to)
(display (substring str from to) port))
(display quoted-char port)
(loop (1+ to) new-to))))))))))
;; Given a string, check to make sure it does not contain characters
;; such as '<' or '&' that require encoding. Return either the original
;; string, or a list of string fragments with special characters
;; replaced by appropriate character entities.
(define string->escaped-xml
(make-char-quotator
'((#\< . "<") (#\> . ">") (#\& . "&") (#\" . """))))
;;; arch-tag: 9c853b25-d82f-42ef-a959-ae26fdc7d1ac
;;; simple.scm ends here
;;;; (sxml ssax) -- the SSAX parser
;;;;
;;;; Copyright (C) 2009, 2010,2012,2013 Free Software Foundation, Inc.
;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Written 2001,2002,2003,2004 by Oleg Kiselyov <oleg at pobox dot com> as SSAX.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;@subheading Functional XML parsing framework
;@subsubheading SAX/DOM and SXML parsers with support for XML Namespaces and validation
;
; This is a package of low-to-high level lexing and parsing procedures
; that can be combined to yield a SAX, a DOM, a validating parser, or
; a parser intended for a particular document type. The procedures in
; the package can be used separately to tokenize or parse various
; pieces of XML documents. The package supports XML Namespaces,
; internal and external parsed entities, user-controlled handling of
; whitespace, and validation. This module therefore is intended to be
; a framework, a set of "Lego blocks" you can use to build a parser
; following any discipline and performing validation to any degree. As
; an example of the parser construction, this file includes a
; semi-validating SXML parser.
; The present XML framework has a "sequential" feel of SAX yet a
; "functional style" of DOM. Like a SAX parser, the framework scans the
; document only once and permits incremental processing. An application
; that handles document elements in order can run as efficiently as
; possible. @emph{Unlike} a SAX parser, the framework does not require
; an application register stateful callbacks and surrender control to
; the parser. Rather, it is the application that can drive the framework
; -- calling its functions to get the current lexical or syntax element.
; These functions do not maintain or mutate any state save the input
; port. Therefore, the framework permits parsing of XML in a pure
; functional style, with the input port being a monad (or a linear,
; read-once parameter).
; Besides the @var{port}, there is another monad -- @var{seed}. Most of
; the middle- and high-level parsers are single-threaded through the
; @var{seed}. The functions of this framework do not process or affect
; the @var{seed} in any way: they simply pass it around as an instance
; of an opaque datatype. User functions, on the other hand, can use the
; seed to maintain user's state, to accumulate parsing results, etc. A
; user can freely mix his own functions with those of the framework. On
; the other hand, the user may wish to instantiate a high-level parser:
; @code{SSAX:make-elem-parser} or @code{SSAX:make-parser}. In the latter
; case, the user must provide functions of specific signatures, which
; are called at predictable moments during the parsing: to handle
; character data, element data, or processing instructions (PI). The
; functions are always given the @var{seed}, among other parameters, and
; must return the new @var{seed}.
; From a functional point of view, XML parsing is a combined
; pre-post-order traversal of a "tree" that is the XML document
; itself. This down-and-up traversal tells the user about an element
; when its start tag is encountered. The user is notified about the
; element once more, after all element's children have been
; handled. The process of XML parsing therefore is a fold over the
; raw XML document. Unlike a fold over trees defined in [1], the
; parser is necessarily single-threaded -- obviously as elements
; in a text XML document are laid down sequentially. The parser
; therefore is a tree fold that has been transformed to accept an
; accumulating parameter [1,2].
; Formally, the denotational semantics of the parser can be expressed
; as
;@smallexample
; parser:: (Start-tag -> Seed -> Seed) ->
; (Start-tag -> Seed -> Seed -> Seed) ->
; (Char-Data -> Seed -> Seed) ->
; XML-text-fragment -> Seed -> Seed
; parser fdown fup fchar "<elem attrs> content </elem>" seed
; = fup "<elem attrs>" seed
; (parser fdown fup fchar "content" (fdown "<elem attrs>" seed))
;
; parser fdown fup fchar "char-data content" seed
; = parser fdown fup fchar "content" (fchar "char-data" seed)
;
; parser fdown fup fchar "elem-content content" seed
; = parser fdown fup fchar "content" (
; parser fdown fup fchar "elem-content" seed)
;@end smallexample
; Compare the last two equations with the left fold
;@smallexample
; fold-left kons elem:list seed = fold-left kons list (kons elem seed)
;@end smallexample
; The real parser created by @code{SSAX:make-parser} is slightly more
; complicated, to account for processing instructions, entity
; references, namespaces, processing of document type declaration, etc.
; The XML standard document referred to in this module is
; @uref{http://www.w3.org/TR/1998/REC-xml-19980210.html}
;
; The present file also defines a procedure that parses the text of an
; XML document or of a separate element into SXML, an S-expression-based
; model of an XML Information Set. SXML is also an Abstract Syntax Tree
; of an XML document. SXML is similar but not identical to DOM; SXML is
; particularly suitable for Scheme-based XML/HTML authoring, SXPath
; queries, and tree transformations. See SXML.html for more details.
; SXML is a term implementation of evaluation of the XML document [3].
; The other implementation is context-passing.
; The present frameworks fully supports the XML Namespaces Recommendation:
; @uref{http://www.w3.org/TR/REC-xml-names/}
; Other links:
;@table @asis
;@item [1]
; Jeremy Gibbons, Geraint Jones, "The Under-appreciated Unfold,"
; Proc. ICFP'98, 1998, pp. 273-279.
;@item [2]
; Richard S. Bird, The promotion and accumulation strategies in
; transformational programming, ACM Trans. Progr. Lang. Systems,
; 6(4):487-504, October 1984.
;@item [3]
; Ralf Hinze, "Deriving Backtracking Monad Transformers,"
; Functional Pearl. Proc ICFP'00, pp. 186-197.
;@end table
;;
;;; Code:
(define-module (sxml ssax)
#\use-module (sxml ssax input-parse)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-13)
#\export (current-ssax-error-port
with-ssax-error-to-port
xml-token? xml-token-kind xml-token-head
make-empty-attlist attlist-add
attlist-null?
attlist-remove-top
attlist->alist attlist-fold
define-parsed-entity!
reset-parsed-entity-definitions!
ssax:uri-string->symbol
ssax:skip-internal-dtd
ssax:read-pi-body-as-string
ssax:reverse-collect-str-drop-ws
ssax:read-markup-token
ssax:read-cdata-body
ssax:read-char-ref
ssax:read-attributes
ssax:complete-start-tag
ssax:read-external-id
ssax:read-char-data
ssax:xml->sxml
ssax:make-parser
ssax:make-pi-parser
ssax:make-elem-parser))
(define (parser-error port message . rest)
(apply throw 'parser-error port message rest))
(define ascii->char integer->char)
(define char->ascii char->integer)
(define current-ssax-error-port
(make-parameter (current-error-port)))
(define *current-ssax-error-port*
(parameter-fluid current-ssax-error-port))
(define (with-ssax-error-to-port port thunk)
(parameterize ((current-ssax-error-port port))
(thunk)))
(define (ssax:warn port . args)
(with-output-to-port (current-ssax-error-port)
(lambda ()
(display ";;; SSAX warning: ")
(for-each display args)
(newline))))
(define (ucscode->string codepoint)
(string (integer->char codepoint)))
(define char-newline #\newline)
(define char-return #\return)
(define char-tab #\tab)
(define nl "\n")
;; This isn't a great API, but a more proper fix will involve hacking
;; SSAX.
(define (reset-parsed-entity-definitions!)
"Restore the set of parsed entity definitions to its initial state."
(set! ssax:predefined-parsed-entities
'((amp . "&")
(lt . "<")
(gt . ">")
(apos . "'")
(quot . "\""))))
(define (define-parsed-entity! entity str)
"Define a new parsed entity. @var{entity} should be a symbol.
Instances of &@var{entity}; in XML text will be replaced with the
string @var{str}, which will then be parsed."
(set! ssax:predefined-parsed-entities
(acons entity str ssax:predefined-parsed-entities)))
;; Execute a sequence of forms and return the result of the _first_ one.
;; Like PROG1 in Lisp. Typically used to evaluate one or more forms with
;; side effects and return a value that must be computed before some or
;; all of the side effects happen.
(define-syntax begin0
(syntax-rules ()
((begin0 form form1 ... )
(let ((val form)) form1 ... val))))
; Like let* but allowing for multiple-value bindings
(define-syntax let*-values
(syntax-rules ()
((let*-values () . bodies) (begin . bodies))
((let*-values (((var) initializer) . rest) . bodies)
(let ((var initializer)) ; a single var optimization
(let*-values rest . bodies)))
((let*-values ((vars initializer) . rest) . bodies)
(call-with-values (lambda () initializer) ; the most generic case
(lambda vars (let*-values rest . bodies))))))
;; needed for some dumb reason
(define inc 1+)
(define dec 1-)
(define-syntax include-from-path/filtered
(lambda (x)
(define (read-filtered accept-list file)
(with-input-from-file (%search-load-path file)
(lambda ()
(let loop ((sexp (read)) (out '()))
(cond
((eof-object? sexp) (reverse out))
((and (pair? sexp) (memq (car sexp) accept-list))
(loop (read) (cons sexp out)))
(else
(loop (read) out)))))))
(syntax-case x ()
((_ accept-list file)
(with-syntax (((exp ...) (datum->syntax
x
(read-filtered
(syntax->datum #'accept-list)
(syntax->datum #'file)))))
#'(begin exp ...))))))
(include-from-path "sxml/upstream/assert.scm")
(include-from-path/filtered
(define define-syntax ssax:define-labeled-arg-macro)
"sxml/upstream/SSAX.scm")
;;;; (sxml ssax input-parse) -- a simple lexer
;;;;
;;;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Written 2003 by Oleg Kiselyov <oleg at pobox dot com> as input-parse.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;; A simple lexer.
;;
;; The procedures in this module surprisingly often suffice to parse an
;; input stream. They either skip, or build and return tokens, according
;; to inclusion or delimiting semantics. The list of characters to
;; expect, include, or to break at may vary from one invocation of a
;; function to another. This allows the functions to easily parse even
;; context-sensitive languages.
;;
;; EOF is generally frowned on, and thrown up upon if encountered.
;; Exceptions are mentioned specifically. The list of expected
;; characters (characters to skip until, or break-characters) may
;; include an EOF "character", which is to be coded as the symbol,
;; @code{*eof*}.
;;
;; The input stream to parse is specified as a @dfn{port}, which is
;; usually the last (and optional) argument. It defaults to the current
;; input port if omitted.
;;
;; If the parser encounters an error, it will throw an exception to the
;; key @code{parser-error}. The arguments will be of the form
;; @code{(@var{port} @var{message} @var{specialising-msg}*)}.
;;
;; The first argument is a port, which typically points to the offending
;; character or its neighborhood. You can then use @code{port-column}
;; and @code{port-line} to query the current position. @var{message} is
;; the description of the error. Other arguments supply more details
;; about the problem.
;;
;;; Code:
(define-module (sxml ssax input-parse)
#\use-module (ice-9 rdelim)
#\export (peek-next-char
assert-curr-char
skip-until
skip-while
next-token
next-token-of
read-text-line
read-string
find-string-from-port?))
(define ascii->char integer->char)
(define char->ascii char->integer)
(define char-newline #\newline)
(define char-return #\return)
(define inc 1+)
(define dec 1-)
;; rewrite oleg's define-opt into define* style
(define-macro (define-opt bindings body . body-rest)
(let* ((rev-bindings (reverse bindings))
(opt-bindings
(and (pair? rev-bindings) (pair? (car rev-bindings))
(eq? 'optional (caar rev-bindings))
(cdar rev-bindings))))
(if opt-bindings
`(define* ,(append (reverse (cons #\optional (cdr rev-bindings)))
opt-bindings)
,body ,@body-rest)
`(define* ,bindings ,body ,@body-rest))))
(define (parser-error port message . rest)
(apply throw 'parser-error port message rest))
(include-from-path "sxml/upstream/input-parse.scm")
;; This version for guile is quite speedy, due to read-delimited (which
;; is implemented in C).
(define-opt (next-token prefix-skipped-chars break-chars
(optional (comment "") (port (current-input-port))) )
(let ((delims (list->string (delete '*eof* break-chars))))
(if (eof-object? (if (null? prefix-skipped-chars)
(peek-char port)
(skip-while prefix-skipped-chars port)))
(if (memq '*eof* break-chars)
""
(parser-error port "EOF while reading a token " comment))
(let ((token (read-delimited delims port 'peek)))
(if (and (eof-object? (peek-char port))
(not (memq '*eof* break-chars)))
(parser-error port "EOF while reading a token " comment)
token)))))
(define-opt (read-text-line (optional (port (current-input-port))) )
(read-line port))
;; Written 1995, 1996 by Oleg Kiselyov (oleg@acm.org)
;; Modified 1996, 1997, 1998, 2001 by A. Jaffer (agj@alum.mit.edu)
;; Modified 2003 by Steve VanDevender (stevev@hexadecimal.uoregon.edu)
;; Modified 2004 Andy Wingo <wingo at pobox dot com>
;; This function is from SLIB's strsrch.scm, and is in the public domain.
(define (find-string-from-port? str <input-port> . max-no-char)
"Looks for @var{str} in @var{<input-port>}, optionally within the
first @var{max-no-char} characters."
(set! max-no-char (if (null? max-no-char) #f (car max-no-char)))
(letrec
((no-chars-read 0)
(peeked? #f)
(my-peek-char ; Return a peeked char or #f
(lambda () (and (or (not (number? max-no-char))
(< no-chars-read max-no-char))
(let ((c (peek-char <input-port>)))
(cond (peeked? c)
((eof-object? c) #f)
((procedure? max-no-char)
(set! peeked? #t)
(if (max-no-char c) #f c))
((eqv? max-no-char c) #f)
(else c))))))
(next-char (lambda () (set! peeked? #f) (read-char <input-port>)
(set! no-chars-read (+ 1 no-chars-read))))
(match-1st-char ; of the string str
(lambda ()
(let ((c (my-peek-char)))
(and c
(begin (next-char)
(if (char=? c (string-ref str 0))
(match-other-chars 1)
(match-1st-char)))))))
;; There has been a partial match, up to the point pos-to-match
;; (for example, str[0] has been found in the stream)
;; Now look to see if str[pos-to-match] for would be found, too
(match-other-chars
(lambda (pos-to-match)
(if (>= pos-to-match (string-length str))
no-chars-read ; the entire string has matched
(let ((c (my-peek-char)))
(and c
(if (not (char=? c (string-ref str pos-to-match)))
(backtrack 1 pos-to-match)
(begin (next-char)
(match-other-chars (+ 1 pos-to-match)))))))))
;; There had been a partial match, but then a wrong char showed up.
;; Before discarding previously read (and matched) characters, we check
;; to see if there was some smaller partial match. Note, characters read
;; so far (which matter) are those of str[0..matched-substr-len - 1]
;; In other words, we will check to see if there is such i>0 that
;; substr(str,0,j) = substr(str,i,matched-substr-len)
;; where j=matched-substr-len - i
(backtrack
(lambda (i matched-substr-len)
(let ((j (- matched-substr-len i)))
(if (<= j 0)
;; backed off completely to the begining of str
(match-1st-char)
(let loop ((k 0))
(if (>= k j)
(match-other-chars j) ; there was indeed a shorter match
(if (char=? (string-ref str k)
(string-ref str (+ i k)))
(loop (+ 1 k))
(backtrack (+ 1 i) matched-substr-len))))))))
)
(match-1st-char)))
;;;; (sxml transform) -- pre- and post-order sxml transformation
;;;;
;;;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Written 2003 by Oleg Kiselyov <oleg at pobox dot com> as SXML-tree-trans.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;;@heading SXML expression tree transformers
;
;@subheading Pre-Post-order traversal of a tree and creation of a new tree
;@smallexample
;pre-post-order:: <tree> x <bindings> -> <new-tree>
;@end smallexample
; where
;@smallexample
; <bindings> ::= (<binding> ...)
; <binding> ::= (<trigger-symbol> *preorder* . <handler>) |
; (<trigger-symbol> *macro* . <handler>) |
; (<trigger-symbol> <new-bindings> . <handler>) |
; (<trigger-symbol> . <handler>)
; <trigger-symbol> ::= XMLname | *text* | *default*
; <handler> :: <trigger-symbol> x [<tree>] -> <new-tree>
;@end smallexample
;
; The pre-post-order function visits the nodes and nodelists
; pre-post-order (depth-first). For each @code{<Node>} of the form
; @code{(@var{name} <Node> ...)}, it looks up an association with the
; given @var{name} among its @var{<bindings>}. If failed,
; @code{pre-post-order} tries to locate a @code{*default*} binding. It's
; an error if the latter attempt fails as well. Having found a binding,
; the @code{pre-post-order} function first checks to see if the binding
; is of the form
;@smallexample
; (<trigger-symbol> *preorder* . <handler>)
;@end smallexample
;
; If it is, the handler is 'applied' to the current node. Otherwise, the
; pre-post-order function first calls itself recursively for each child
; of the current node, with @var{<new-bindings>} prepended to the
; @var{<bindings>} in effect. The result of these calls is passed to the
; @var{<handler>} (along with the head of the current @var{<Node>}). To
; be more precise, the handler is _applied_ to the head of the current
; node and its processed children. The result of the handler, which
; should also be a @code{<tree>}, replaces the current @var{<Node>}. If
; the current @var{<Node>} is a text string or other atom, a special
; binding with a symbol @code{*text*} is looked up.
;
; A binding can also be of a form
;@smallexample
; (<trigger-symbol> *macro* . <handler>)
;@end smallexample
; This is equivalent to @code{*preorder*} described above. However, the
; result is re-processed again, with the current stylesheet.
;;
;;; Code:
(define-module (sxml transform)
#\export (SRV:send-reply
foldts
post-order
pre-post-order
replace-range))
;; Upstream version:
; $Id: SXML-tree-trans.scm,v 1.8 2003/04/24 19:39:53 oleg Exp oleg $
; Like let* but allowing for multiple-value bindings
(define-macro (let*-values bindings . body)
(if (null? bindings) (cons 'begin body)
(apply
(lambda (vars initializer)
(let ((cont
(cons 'let*-values
(cons (cdr bindings) body))))
(cond
((not (pair? vars)) ; regular let case, a single var
`(let ((,vars ,initializer)) ,cont))
((null? (cdr vars)) ; single var, see the prev case
`(let ((,(car vars) ,initializer)) ,cont))
(else ; the most generic case
`(call-with-values (lambda () ,initializer)
(lambda ,vars ,cont))))))
(car bindings))))
(define (SRV:send-reply . fragments)
"Output the @var{fragments} to the current output port.
The fragments are a list of strings, characters, numbers, thunks,
@code{#f}, @code{#t} -- and other fragments. The function traverses the
tree depth-first, writes out strings and characters, executes thunks,
and ignores @code{#f} and @code{'()}. The function returns @code{#t} if
anything was written at all; otherwise the result is @code{#f} If
@code{#t} occurs among the fragments, it is not written out but causes
the result of @code{SRV:send-reply} to be @code{#t}."
(let loop ((fragments fragments) (result #f))
(cond
((null? fragments) result)
((not (car fragments)) (loop (cdr fragments) result))
((null? (car fragments)) (loop (cdr fragments) result))
((eq? #t (car fragments)) (loop (cdr fragments) #t))
((pair? (car fragments))
(loop (cdr fragments) (loop (car fragments) result)))
((procedure? (car fragments))
((car fragments))
(loop (cdr fragments) #t))
(else
(display (car fragments))
(loop (cdr fragments) #t)))))
;------------------------------------------------------------------------
; Traversal of an SXML tree or a grove:
; a <Node> or a <Nodelist>
;
; A <Node> and a <Nodelist> are mutually-recursive datatypes that
; underlie the SXML tree:
; <Node> ::= (name . <Nodelist>) | "text string"
; An (ordered) set of nodes is just a list of the constituent nodes:
; <Nodelist> ::= (<Node> ...)
; Nodelists, and Nodes other than text strings are both lists. A
; <Nodelist> however is either an empty list, or a list whose head is
; not a symbol (an atom in general). A symbol at the head of a node is
; either an XML name (in which case it's a tag of an XML element), or
; an administrative name such as '@'.
; See SXPath.scm and SSAX.scm for more information on SXML.
;; see the commentary for docs
(define (pre-post-order tree bindings)
(let* ((default-binding (assq '*default* bindings))
(text-binding (or (assq '*text* bindings) default-binding))
(text-handler ; Cache default and text bindings
(and text-binding
(if (procedure? (cdr text-binding))
(cdr text-binding) (cddr text-binding)))))
(let loop ((tree tree))
(cond
((null? tree) '())
((not (pair? tree))
(let ((trigger '*text*))
(if text-handler (text-handler trigger tree)
(error "Unknown binding for " trigger " and no default"))))
((not (symbol? (car tree))) (map loop tree)) ; tree is a nodelist
(else ; tree is an SXML node
(let* ((trigger (car tree))
(binding (or (assq trigger bindings) default-binding)))
(cond
((not binding)
(error "Unknown binding for " trigger " and no default"))
((not (pair? (cdr binding))) ; must be a procedure: handler
(apply (cdr binding) trigger (map loop (cdr tree))))
((eq? '*preorder* (cadr binding))
(apply (cddr binding) tree))
((eq? '*macro* (cadr binding))
(loop (apply (cddr binding) tree)))
(else ; (cadr binding) is a local binding
(apply (cddr binding) trigger
(pre-post-order (cdr tree) (append (cadr binding) bindings)))
))))))))
; post-order is a strict subset of pre-post-order without *preorder*
; (let alone *macro*) traversals.
; Now pre-post-order is actually faster than the old post-order.
; The function post-order is deprecated and is aliased below for
; backward compatibility.
(define post-order pre-post-order)
;------------------------------------------------------------------------
; Extended tree fold
; tree = atom | (node-name tree ...)
;
; foldts fdown fup fhere seed (Leaf str) = fhere seed str
; foldts fdown fup fhere seed (Nd kids) =
; fup seed $ foldl (foldts fdown fup fhere) (fdown seed) kids
; procedure fhere: seed -> atom -> seed
; procedure fdown: seed -> node -> seed
; procedure fup: parent-seed -> last-kid-seed -> node -> seed
; foldts returns the final seed
(define (foldts fdown fup fhere seed tree)
(cond
((null? tree) seed)
((not (pair? tree)) ; An atom
(fhere seed tree))
(else
(let loop ((kid-seed (fdown seed tree)) (kids (cdr tree)))
(if (null? kids)
(fup seed kid-seed tree)
(loop (foldts fdown fup fhere kid-seed (car kids))
(cdr kids)))))))
;------------------------------------------------------------------------
; Traverse a forest depth-first and cut/replace ranges of nodes.
;
; The nodes that define a range don't have to have the same immediate
; parent, don't have to be on the same level, and the end node of a
; range doesn't even have to exist. A replace-range procedure removes
; nodes from the beginning node of the range up to (but not including)
; the end node of the range. In addition, the beginning node of the
; range can be replaced by a node or a list of nodes. The range of
; nodes is cut while depth-first traversing the forest. If all
; branches of the node are cut a node is cut as well. The procedure
; can cut several non-overlapping ranges from a forest.
; replace-range:: BEG-PRED x END-PRED x FOREST -> FOREST
; where
; type FOREST = (NODE ...)
; type NODE = Atom | (Name . FOREST) | FOREST
;
; The range of nodes is specified by two predicates, beg-pred and end-pred.
; beg-pred:: NODE -> #f | FOREST
; end-pred:: NODE -> #f | FOREST
; The beg-pred predicate decides on the beginning of the range. The node
; for which the predicate yields non-#f marks the beginning of the range
; The non-#f value of the predicate replaces the node. The value can be a
; list of nodes. The replace-range procedure then traverses the tree and skips
; all the nodes, until the end-pred yields non-#f. The value of the end-pred
; replaces the end-range node. The new end node and its brothers will be
; re-scanned.
; The predicates are evaluated pre-order. We do not descend into a node that
; is marked as the beginning of the range.
(define (replace-range beg-pred end-pred forest)
; loop forest keep? new-forest
; forest is the forest to traverse
; new-forest accumulates the nodes we will keep, in the reverse
; order
; If keep? is #t, keep the curr node if atomic. If the node is not atomic,
; traverse its children and keep those that are not in the skip range.
; If keep? is #f, skip the current node if atomic. Otherwise,
; traverse its children. If all children are skipped, skip the node
; as well.
(define (loop forest keep? new-forest)
(if (null? forest) (values (reverse new-forest) keep?)
(let ((node (car forest)))
(if keep?
(cond ; accumulate mode
((beg-pred node) => ; see if the node starts the skip range
(lambda (repl-branches) ; if so, skip/replace the node
(loop (cdr forest) #f
(append (reverse repl-branches) new-forest))))
((not (pair? node)) ; it's an atom, keep it
(loop (cdr forest) keep? (cons node new-forest)))
(else
(let*-values
(((node?) (symbol? (car node))) ; or is it a nodelist?
((new-kids keep?) ; traverse its children
(loop (if node? (cdr node) node) #t '())))
(loop (cdr forest) keep?
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)))))
; skip mode
(cond
((end-pred node) => ; end the skip range
(lambda (repl-branches) ; repl-branches will be re-scanned
(loop (append repl-branches (cdr forest)) #t
new-forest)))
((not (pair? node)) ; it's an atom, skip it
(loop (cdr forest) keep? new-forest))
(else
(let*-values
(((node?) (symbol? (car node))) ; or is it a nodelist?
((new-kids keep?) ; traverse its children
(loop (if node? (cdr node) node) #f '())))
(loop (cdr forest) keep?
(if (or keep? (pair? new-kids))
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)
new-forest) ; if all kids are skipped
)))))))) ; skip the node too
(let*-values (((new-forest keep?) (loop forest #t '())))
new-forest))
;;; arch-tag: 6c814f4b-38f7-42c1-b8ef-ce3447edefc7
;;; transform.scm ends here
; Functional XML parsing framework: SAX/DOM and SXML parsers
; with support for XML Namespaces and validation
;
; This is a package of low-to-high level lexing and parsing procedures
; that can be combined to yield a SAX, a DOM, a validating parsers, or
; a parser intended for a particular document type. The procedures in
; the package can be used separately to tokenize or parse various
; pieces of XML documents. The package supports XML Namespaces,
; internal and external parsed entities, user-controlled handling of
; whitespace, and validation. This module therefore is intended to be
; a framework, a set of "Lego blocks" you can use to build a parser
; following any discipline and performing validation to any degree. As
; an example of the parser construction, this file includes a
; semi-validating SXML parser.
; The present XML framework has a "sequential" feel of SAX yet a
; "functional style" of DOM. Like a SAX parser, the framework scans
; the document only once and permits incremental processing. An
; application that handles document elements in order can run as
; efficiently as possible. _Unlike_ a SAX parser, the framework does
; not require an application register stateful callbacks and surrender
; control to the parser. Rather, it is the application that can drive
; the framework -- calling its functions to get the current lexical or
; syntax element. These functions do not maintain or mutate any state
; save the input port. Therefore, the framework permits parsing of XML
; in a pure functional style, with the input port being a monad (or a
; linear, read-once parameter).
; Besides the PORT, there is another monad -- SEED. Most of the
; middle- and high-level parsers are single-threaded through the
; seed. The functions of this framework do not process or affect the
; SEED in any way: they simply pass it around as an instance of an
; opaque datatype. User functions, on the other hand, can use the
; seed to maintain user's state, to accumulate parsing results, etc. A
; user can freely mix his own functions with those of the
; framework. On the other hand, the user may wish to instantiate a
; high-level parser: ssax:make-elem-parser or ssax:make-parser. In
; the latter case, the user must provide functions of specific
; signatures, which are called at predictable moments during the
; parsing: to handle character data, element data, or processing
; instructions (PI). The functions are always given the SEED, among
; other parameters, and must return the new SEED.
; From a functional point of view, XML parsing is a combined
; pre-post-order traversal of a "tree" that is the XML document
; itself. This down-and-up traversal tells the user about an element
; when its start tag is encountered. The user is notified about the
; element once more, after all element's children have been
; handled. The process of XML parsing therefore is a fold over the
; raw XML document. Unlike a fold over trees defined in [1], the
; parser is necessarily single-threaded -- obviously as elements
; in a text XML document are laid down sequentially. The parser
; therefore is a tree fold that has been transformed to accept an
; accumulating parameter [1,2].
; Formally, the denotational semantics of the parser can be expressed
; as
; parser:: (Start-tag -> Seed -> Seed) ->
; (Start-tag -> Seed -> Seed -> Seed) ->
; (Char-Data -> Seed -> Seed) ->
; XML-text-fragment -> Seed -> Seed
; parser fdown fup fchar "<elem attrs> content </elem>" seed
; = fup "<elem attrs>" seed
; (parser fdown fup fchar "content" (fdown "<elem attrs>" seed))
;
; parser fdown fup fchar "char-data content" seed
; = parser fdown fup fchar "content" (fchar "char-data" seed)
;
; parser fdown fup fchar "elem-content content" seed
; = parser fdown fup fchar "content" (
; parser fdown fup fchar "elem-content" seed)
; Compare the last two equations with the left fold
; fold-left kons elem:list seed = fold-left kons list (kons elem seed)
; The real parser created my ssax:make-parser is slightly more complicated,
; to account for processing instructions, entity references, namespaces,
; processing of document type declaration, etc.
; The XML standard document referred to in this module is
; http://www.w3.org/TR/1998/REC-xml-19980210.html
;
; The present file also defines a procedure that parses the text of an
; XML document or of a separate element into SXML, an
; S-expression-based model of an XML Information Set. SXML is also an
; Abstract Syntax Tree of an XML document. SXML is similar
; but not identical to DOM; SXML is particularly suitable for
; Scheme-based XML/HTML authoring, SXPath queries, and tree
; transformations. See SXML.html for more details.
; SXML is a term implementation of evaluation of the XML document [3].
; The other implementation is context-passing.
; The present frameworks fully supports the XML Namespaces Recommendation:
; http://www.w3.org/TR/REC-xml-names/
; Other links:
; [1] Jeremy Gibbons, Geraint Jones, "The Under-appreciated Unfold,"
; Proc. ICFP'98, 1998, pp. 273-279.
; [2] Richard S. Bird, The promotion and accumulation strategies in
; transformational programming, ACM Trans. Progr. Lang. Systems,
; 6(4):487-504, October 1984.
; [3] Ralf Hinze, "Deriving Backtracking Monad Transformers,"
; Functional Pearl. Proc ICFP'00, pp. 186-197.
; IMPORT
; parser-error ssax:warn, see Handling of errors, below
; functions declared in files util.scm, input-parse.scm and look-for-str.scm
; char-encoding.scm for various platform-specific character-encoding functions.
; From SRFI-13: string-concatenate/shared and string-concatenate-reverse/shared
; If a particular implementation lacks SRFI-13 support, please
; include the file srfi-13-local.scm
; Handling of errors
; This package relies on a function parser-error, which must be defined
; by a user of the package. The function has the following signature:
; parser-error PORT MESSAGE SPECIALISING-MSG*
; Many procedures of this package call 'parser-error' whenever a
; parsing, well-formedness or validation error is encountered. The
; first argument is a port, which typically points to the offending
; character or its neighborhood. Most of the Scheme systems let the
; user query a PORT for the current position. The MESSAGE argument
; indicates a failed XML production or a failed XML constraint. The
; latter is referred to by its anchor name in the XML Recommendation
; or XML Namespaces Recommendation. The parsing library (e.g.,
; next-token, assert-curr-char) invoke 'parser-error' as well, in
; exactly the same way. See input-parse.scm for more details.
; See
; http://pair.com/lisovsky/download/parse-error.scm
; for an excellent example of such a redefined parser-error function.
;
; In addition, the present code invokes a function ssax:warn
; ssax:warn PORT MESSAGE SPECIALISING-MSG*
; to notify the user about warnings that are NOT errors but still
; may alert the user.
;
; Again, parser-error and ssax:warn are supposed to be defined by the
; user. However, if a run-test macro below is set to include
; self-tests, this present code does provide the definitions for these
; functions to allow tests to run.
; Misc notes
; It seems it is highly desirable to separate tests out in a dedicated
; file.
;
; Jim Bender wrote on Mon, 9 Sep 2002 20:03:42 EDT on the SSAX-SXML
; mailing list (message A fine-grained "lego")
; The task was to record precise source location information, as PLT
; does with its current XML parser. That parser records the start and
; end location (filepos, line#, column#) for pi, elements, attributes,
; chuncks of "pcdata".
; As suggested above, though, in some cases I needed to be able force
; open an interface that did not yet exist. For instance, I added an
; "end-char-data-hook", which would be called at the end of char-data
; fragment. This returns a function of type (seed -> seed) which is
; invoked on the current seed only if read-char-data has indeed reached
; the end of a block of char data (after reading a new token.
; But the deepest interface that I needed to expose was that of reading
; attributes. In the official distribution, this is not even a separate
; function. Instead, it is embedded within SSAX:read-attributes. This
; required some small re-structuring as well.
; This definitely will not be to everyone's taste (nor needed by most).
; Certainly, the existing make-parser interface addresses most custom
; needs. And likely 80-90 lines of a "link specification" to create a
; parser from many tiny little lego blocks may please only a few, while
; appalling others.
; The code is available at http://celtic.benderweb.net/ssax-lego.plt or
; http://celtic.benderweb.net/ssax-lego.tar.gz
; In the examples directory, I provide:
; - a unit version of the make-parser interface,
; - a simple SXML parser using that interface,
; - an SXML parser which directly uses the "new lego",
; - a pseudo-SXML parser, which records source location information
; - and lastly a parser which returns the structures used in PLT's xml
; collection, with source location information
; $Id: SSAX.scm,v 5.1 2004/07/07 16:02:30 sperber Exp $
;^^^^^^^^^
; See the Makefile in the ../tests directory
; (in particular, the rule vSSAX) for an example of how
; to run this code on various Scheme systems.
; See SSAX examples for many samples of using this code,
; again, on a variety of Scheme systems.
; See http://ssax.sf.net/
; The following macro runs built-in test cases -- or does not run,
; depending on which of the two cases below you commented out
; Case 1: no tests:
;(define-macro run-test (lambda body '(begin #f)))
;(define-syntax run-test (syntax-rules () ((run-test . args) (begin #f))))
; Case 2: with tests.
; The following macro could've been defined just as
; (define-macro run-test (lambda body `(begin (display "\n-->Test\n") ,@body)))
;
; Instead, it's more involved, to make up for case-insensitivity of
; symbols on some Scheme systems. In Gambit, symbols are case
; sensitive: (eq? 'A 'a) is #f and (eq? 'Aa (string->symbol "Aa")) is
; #t. On some systems, symbols are case-insensitive and just the
; opposite is true. Therefore, we introduce a notation '"ASymbol" (a
; quoted string) that stands for a case-_sensitive_ ASymbol -- on any
; R5RS Scheme system. This notation is valid only within the body of
; run-test.
; The notation is implemented by scanning the run-test's
; body and replacing every occurrence of (quote "str") with the result
; of (string->symbol "str"). We can do such a replacement at macro-expand
; time (rather than at run time).
; Here's the previous version of run-test, implemented as a low-level
; macro.
; (define-macro run-test
; (lambda body
; (define (re-write body)
; (cond
; ((vector? body)
; (list->vector (re-write (vector->list body))))
; ((not (pair? body)) body)
; ((and (eq? 'quote (car body)) (pair? (cdr body))
; (string? (cadr body)))
; (string->symbol (cadr body)))
; (else (cons (re-write (car body)) (re-write (cdr body))))))
; (cons 'begin (re-write body))))
;
; For portability, it is re-written as syntax-rules. The syntax-rules
; version is less powerful: for example, it can't handle
; (case x (('"Foo") (do-on-Foo))) whereas the low-level macro
; could correctly place a case-sensitive symbol at the right place.
; We also do not scan vectors (because we don't use them here).
; Twice-deep quasiquotes aren't handled either.
; Still, the syntax-rules version satisfies our immediate needs.
; Incidentally, I originally didn't believe that the macro below
; was at all possible.
;
; The macro is written in a continuation-passing style. A continuation
; typically has the following structure: (k-head ! . args)
; When the continuation is invoked, we expand into
; (k-head <computed-result> . arg). That is, the dedicated symbol !
; is the placeholder for the result.
;
; It seems that the most modular way to write the run-test macro would
; be the following
;
; (define-syntax run-test
; (syntax-rules ()
; ((run-test . ?body)
; (letrec-syntax
; ((scan-exp ; (scan-exp body k)
; (syntax-rules (quote quasiquote !)
; ((scan-exp (quote (hd . tl)) k)
; (scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
; ((scan-exp (quote x) (k-head ! . args))
; (k-head
; (if (string? (quote x)) (string->symbol (quote x)) (quote x))
; . args))
; ((scan-exp (hd . tl) k)
; (scan-exp hd (do-tl ! scan-exp tl k)))
; ((scan-exp x (k-head ! . args))
; (k-head x . args))))
; (do-tl
; (syntax-rules (!)
; ((do-tl processed-hd fn () (k-head ! . args))
; (k-head (processed-hd) . args))
; ((do-tl processed-hd fn old-tl k)
; (fn old-tl (do-cons ! processed-hd k)))))
; ...
; (do-finish
; (syntax-rules ()
; ((do-finish (new-body)) new-body)
; ((do-finish new-body) (begin . new-body))))
; ...
; (scan-exp ?body (do-finish !))
; ))))
;
; Alas, that doesn't work on all systems. We hit yet another dark
; corner of the R5RS macros. The reason is that run-test is used in
; the code below to introduce definitions. For example:
; (run-test
; (define (ssax:warn port msg . other-msg)
; (apply cerr (cons* nl "Warning: " msg other-msg)))
; )
; This code expands to
; (begin
; (define (ssax:warn port msg . other-msg) ...))
; so the definition gets spliced in into the top level. Right?
; Well, On Petite Chez Scheme it is so. However, many other systems
; don't like this approach. The reason is that the invocation of
; (run-test (define (ssax:warn port msg . other-msg) ...))
; first expands into
; (letrec-syntax (...)
; (scan-exp ((define (ssax:warn port msg . other-msg) ...)) ...))
; because of the presence of (letrec-syntax ...), the begin form that
; is generated eventually is no longer at the top level! The begin
; form in Scheme is an overloading of two distinct forms: top-level
; begin and the other begin. The forms have different rules: for example,
; (begin (define x 1)) is OK for a top-level begin but not OK for
; the other begin. Some Scheme systems see the that the macro
; (run-test ...) expands into (letrec-syntax ...) and decide right there
; that any further (begin ...) forms are NOT top-level begin forms.
; The only way out is to make sure all our macros are top-level.
; The best approach <sigh> seems to be to make run-test one huge
; top-level macro.
(define-syntax run-test
(syntax-rules (define)
((run-test "scan-exp" (define vars body))
(define vars (run-test "scan-exp" body)))
((run-test "scan-exp" ?body)
(letrec-syntax
((scan-exp ; (scan-exp body k)
(syntax-rules (quote quasiquote !)
((scan-exp '() (k-head ! . args))
(k-head '() . args))
((scan-exp (quote (hd . tl)) k)
(scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
((scan-exp (quasiquote (hd . tl)) k)
(scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
((scan-exp (quote x) (k-head ! . args))
(k-head
(if (string? (quote x)) (string->symbol (quote x)) (quote x))
. args))
((scan-exp (hd . tl) k)
(scan-exp hd (do-tl ! scan-exp tl k)))
((scan-exp x (k-head ! . args))
(k-head x . args))))
(do-tl
(syntax-rules (!)
((do-tl processed-hd fn () (k-head ! . args))
(k-head (processed-hd) . args))
((do-tl processed-hd fn old-tl k)
(fn old-tl (do-cons ! processed-hd k)))))
(do-cons
(syntax-rules (!)
((do-cons processed-tl processed-hd (k-head ! . args))
(k-head (processed-hd . processed-tl) . args))))
(do-wrap
(syntax-rules (!)
((do-wrap val fn (k-head ! . args))
(k-head (fn val) . args))))
(do-finish
(syntax-rules ()
((do-finish new-body) new-body)))
(scan-lit-lst ; scan literal list
(syntax-rules (quote unquote unquote-splicing !)
((scan-lit-lst '() (k-head ! . args))
(k-head '() . args))
((scan-lit-lst (quote (hd . tl)) k)
(do-tl quote scan-lit-lst ((hd . tl)) k))
((scan-lit-lst (unquote x) k)
(scan-exp x (do-wrap ! unquote k)))
((scan-lit-lst (unquote-splicing x) k)
(scan-exp x (do-wrap ! unquote-splicing k)))
((scan-lit-lst (quote x) (k-head ! . args))
(k-head
,(if (string? (quote x)) (string->symbol (quote x)) (quote x))
. args))
((scan-lit-lst (hd . tl) k)
(scan-lit-lst hd (do-tl ! scan-lit-lst tl k)))
((scan-lit-lst x (k-head ! . args))
(k-head x . args))))
)
(scan-exp ?body (do-finish !))))
((run-test body ...)
(begin
(run-test "scan-exp" body) ...))
))
;========================================================================
; Data Types
; TAG-KIND
; a symbol 'START, 'END, 'PI, 'DECL, 'COMMENT, 'CDSECT
; or 'ENTITY-REF that identifies a markup token
; UNRES-NAME
; a name (called GI in the XML Recommendation) as given in an xml
; document for a markup token: start-tag, PI target, attribute name.
; If a GI is an NCName, UNRES-NAME is this NCName converted into
; a Scheme symbol. If a GI is a QName, UNRES-NAME is a pair of
; symbols: (PREFIX . LOCALPART)
; RES-NAME
; An expanded name, a resolved version of an UNRES-NAME.
; For an element or an attribute name with a non-empty namespace URI,
; RES-NAME is a pair of symbols, (URI-SYMB . LOCALPART).
; Otherwise, it's a single symbol.
; ELEM-CONTENT-MODEL
; A symbol:
; ANY - anything goes, expect an END tag.
; EMPTY-TAG - no content, and no END-tag is coming
; EMPTY - no content, expect the END-tag as the next token
; PCDATA - expect character data only, and no children elements
; MIXED
; ELEM-CONTENT
; URI-SYMB
; A symbol representing a namespace URI -- or other symbol chosen
; by the user to represent URI. In the former case,
; URI-SYMB is created by %-quoting of bad URI characters and
; converting the resulting string into a symbol.
; NAMESPACES
; A list representing namespaces in effect. An element of the list
; has one of the following forms:
; (PREFIX URI-SYMB . URI-SYMB) or
; (PREFIX USER-PREFIX . URI-SYMB)
; USER-PREFIX is a symbol chosen by the user
; to represent the URI.
; (#f USER-PREFIX . URI-SYMB)
; Specification of the user-chosen prefix and a URI-SYMBOL.
; (*DEFAULT* USER-PREFIX . URI-SYMB)
; Declaration of the default namespace
; (*DEFAULT* #f . #f)
; Un-declaration of the default namespace. This notation
; represents overriding of the previous declaration
; A NAMESPACES list may contain several elements for the same PREFIX.
; The one closest to the beginning of the list takes effect.
; ATTLIST
; An ordered collection of (NAME . VALUE) pairs, where NAME is
; a RES-NAME or an UNRES-NAME. The collection is an ADT
; STR-HANDLER
; A procedure of three arguments: STRING1 STRING2 SEED
; returning a new SEED
; The procedure is supposed to handle a chunk of character data
; STRING1 followed by a chunk of character data STRING2.
; STRING2 is a short string, often "\n" and even ""
; ENTITIES
; An assoc list of pairs:
; (named-entity-name . named-entity-body)
; where named-entity-name is a symbol under which the entity was
; declared, named-entity-body is either a string, or
; (for an external entity) a thunk that will return an
; input port (from which the entity can be read).
; named-entity-body may also be #f. This is an indication that a
; named-entity-name is currently being expanded. A reference to
; this named-entity-name will be an error: violation of the
; WFC nonrecursion.
;
; As an extension to the original SSAX, Guile allows a
; named-entity-name of *DEFAULT* to indicate a fallback procedure,
; called as (FALLBACK PORT NAME). The procedure should return a
; string.
; XML-TOKEN -- a record
; In Gambit, you can use the following declaration:
; (define-structure xml-token kind head)
; The following declaration is "standard" as it follows SRFI-9:
;;(define-record-type xml-token (make-xml-token kind head) xml-token?
;; (kind xml-token-kind)
;; (head xml-token-head) )
; No field mutators are declared as SSAX is a pure functional parser
;
; But to make the code more portable, we define xml-token simply as
; a pair. It suffices for us. Furthermore, xml-token-kind and xml-token-head
; can be defined as simple procedures. However, they are declared as
; macros below for efficiency.
(define (make-xml-token kind head) (cons kind head))
(define xml-token? pair?)
(define-syntax xml-token-kind
(syntax-rules () ((xml-token-kind token) (car token))))
(define-syntax xml-token-head
(syntax-rules () ((xml-token-head token) (cdr token))))
; (define-macro xml-token-kind (lambda (token) `(car ,token)))
; (define-macro xml-token-head (lambda (token) `(cdr ,token)))
; This record represents a markup, which is, according to the XML
; Recommendation, "takes the form of start-tags, end-tags, empty-element tags,
; entity references, character references, comments, CDATA section delimiters,
; document type declarations, and processing instructions."
;
; kind -- a TAG-KIND
; head -- an UNRES-NAME. For xml-tokens of kinds 'COMMENT and
; 'CDSECT, the head is #f
;
; For example,
; <P> => kind='START, head='P
; </P> => kind='END, head='P
; <BR/> => kind='EMPTY-EL, head='BR
; <!DOCTYPE OMF ...> => kind='DECL, head='DOCTYPE
; <?xml version="1.0"?> => kind='PI, head='xml
; &my-ent; => kind = 'ENTITY-REF, head='my-ent
;
; Character references are not represented by xml-tokens as these references
; are transparently resolved into the corresponding characters.
;
; XML-DECL -- a record
; The following is Gambit-specific, see below for a portable declaration
;(define-structure xml-decl elems entities notations)
; The record represents a datatype of an XML document: the list of
; declared elements and their attributes, declared notations, list of
; replacement strings or loading procedures for parsed general
; entities, etc. Normally an xml-decl record is created from a DTD or
; an XML Schema, although it can be created and filled in in many other
; ways (e.g., loaded from a file).
;
; elems: an (assoc) list of decl-elem or #f. The latter instructs
; the parser to do no validation of elements and attributes.
;
; decl-elem: declaration of one element:
; (elem-name elem-content decl-attrs)
; elem-name is an UNRES-NAME for the element.
; elem-content is an ELEM-CONTENT-MODEL.
; decl-attrs is an ATTLIST, of (ATTR-NAME . VALUE) associations
; !!!This element can declare a user procedure to handle parsing of an
; element (e.g., to do a custom validation, or to build a hash of
; IDs as they're encountered).
;
; decl-attr: an element of an ATTLIST, declaration of one attribute
; (attr-name content-type use-type default-value)
; attr-name is an UNRES-NAME for the declared attribute
; content-type is a symbol: CDATA, NMTOKEN, NMTOKENS, ...
; or a list of strings for the enumerated type.
; use-type is a symbol: REQUIRED, IMPLIED, FIXED
; default-value is a string for the default value, or #f if not given.
;
;
; see a function make-empty-xml-decl to make a XML declaration entry
; suitable for a non-validating parsing.
;-------------------------
; Utilities
; ssax:warn PORT MESSAGE SPECIALISING-MSG*
; to notify the user about warnings that are NOT errors but still
; may alert the user.
; Result is unspecified.
; We need to define the function to allow the self-tests to run.
; Normally the definition of ssax:warn is to be provided by the user.
(run-test
(define (ssax:warn port msg . other-msg)
(apply cerr (cons* nl "Warning: " msg other-msg)))
)
; parser-error PORT MESSAGE SPECIALISING-MSG*
; to let the user know of a syntax error or a violation of a
; well-formedness or validation constraint.
; Result is unspecified.
; We need to define the function to allow the self-tests to run.
; Normally the definition of parser-error is to be provided by the user.
(run-test
(define (parser-error port msg . specializing-msgs)
(apply error (cons msg specializing-msgs)))
)
; The following is a function that is often used in validation tests,
; to make sure that the computed result matches the expected one.
; This function is a standard equal? predicate with one exception.
; On Scheme systems where (string->symbol "A") and a symbol A
; are the same, equal_? is precisely equal?
; On other Scheme systems, we compare symbols disregarding their case.
; Since this function is used only in tests, we don't have to
; strive to make it efficient.
(run-test
(define (equal_? e1 e2)
(if (eq? 'A (string->symbol "A")) (equal? e1 e2)
(cond
((symbol? e1)
(and (symbol? e2)
(string-ci=? (symbol->string e1) (symbol->string e2))))
((pair? e1)
(and (pair? e2)
(equal_? (car e1) (car e2)) (equal_? (cdr e1) (cdr e2))))
((vector? e1)
(and (vector? e2) (equal_? (vector->list e1) (vector->list e2))))
(else
(equal? e1 e2)))))
)
; The following function, which is often used in validation tests,
; lets us conveniently enter newline, CR and tab characters in a character
; string.
; unesc-string: ESC-STRING -> STRING
; where ESC-STRING is a character string that may contain
; %n -- for #\newline
; %r -- for #\return
; %t -- for #\tab
; %% -- for #\%
;
; The result of unesc-string is a character string with all %-combinations
; above replaced with their character equivalents
(run-test
(define (unesc-string str)
(call-with-input-string str
(lambda (port)
(let loop ((frags '()))
(let* ((token (next-token '() '(#\% *eof*) "unesc-string" port))
(cterm (read-char port))
(frags (cons token frags)))
(if (eof-object? cterm) (string-concatenate-reverse/shared frags)
(let ((cchar (read-char port))) ; char after #\%
(if (eof-object? cchar)
(error "unexpected EOF after reading % in unesc-string:" str)
(loop
(cons
(case cchar
((#\n) (string #\newline))
((#\r) (string char-return))
((#\t) (string char-tab))
((#\%) "%")
(else (error "bad %-char in unesc-string:" cchar)))
frags))))))))))
)
; Test if a string is made of only whitespace
; An empty string is considered made of whitespace as well
(define (string-whitespace? str)
(let ((len (string-length str)))
(cond
((zero? len) #t)
((= 1 len) (char-whitespace? (string-ref str 0)))
((= 2 len) (and (char-whitespace? (string-ref str 0))
(char-whitespace? (string-ref str 1))))
(else
(let loop ((i 0))
(or (>= i len)
(and (char-whitespace? (string-ref str i))
(loop (inc i)))))))))
; Find val in alist
; Return (values found-el remaining-alist) or
; (values #f alist)
(define (assq-values val alist)
(let loop ((alist alist) (scanned '()))
(cond
((null? alist) (values #f scanned))
((equal? val (caar alist))
(values (car alist) (append scanned (cdr alist))))
(else
(loop (cdr alist) (cons (car alist) scanned))))))
; From SRFI-1
(define (fold-right kons knil lis1)
(let recur ((lis lis1))
(if (null? lis) knil
(let ((head (car lis)))
(kons head (recur (cdr lis)))))))
; Left fold combinator for a single list
(define (fold kons knil lis1)
(let lp ((lis lis1) (ans knil))
(if (null? lis) ans
(lp (cdr lis) (kons (car lis) ans)))))
;========================================================================
; Lower-level parsers and scanners
;
; They deal with primitive lexical units (Names, whitespaces, tags)
; and with pieces of more generic productions. Most of these parsers
; must be called in appropriate context. For example, ssax:complete-start-tag
; must be called only when the start-tag has been detected and its GI
; has been read.
;------------------------------------------------------------------------
; Low-level parsing code
; Skip the S (whitespace) production as defined by
; [3] S ::= (#x20 | #x9 | #xD | #xA)
; The procedure returns the first not-whitespace character it
; encounters while scanning the PORT. This character is left
; on the input stream.
(define ssax:S-chars (map ascii->char '(32 10 9 13)))
(define (ssax:skip-S port)
(skip-while ssax:S-chars port))
; Read a Name lexem and return it as string
; [4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':'
; | CombiningChar | Extender
; [5] Name ::= (Letter | '_' | ':') (NameChar)*
;
; This code supports the XML Namespace Recommendation REC-xml-names,
; which modifies the above productions as follows:
;
; [4] NCNameChar ::= Letter | Digit | '.' | '-' | '_'
; | CombiningChar | Extender
; [5] NCName ::= (Letter | '_') (NCNameChar)*
; As the Rec-xml-names says,
; "An XML document conforms to this specification if all other tokens
; [other than element types and attribute names] in the document which
; are required, for XML conformance, to match the XML production for
; Name, match this specification's production for NCName."
; Element types and attribute names must match the production QName,
; defined below.
; Check to see if a-char may start a NCName
(define (ssax:ncname-starting-char? a-char)
(and (char? a-char)
(or
(char-alphabetic? a-char)
(char=? #\_ a-char))))
; Read a NCName starting from the current position in the PORT and
; return it as a symbol.
(define (ssax:read-NCName port)
(let ((first-char (peek-char port)))
(or (ssax:ncname-starting-char? first-char)
(parser-error port "XMLNS [4] for '" first-char "'")))
(string->symbol
(next-token-of
(lambda (c)
(cond
((eof-object? c) #f)
((char-alphabetic? c) c)
((string-index "0123456789.-_" c) c)
(else #f)))
port)))
; Read a (namespace-) Qualified Name, QName, from the current
; position in the PORT.
; From REC-xml-names:
; [6] QName ::= (Prefix ':')? LocalPart
; [7] Prefix ::= NCName
; [8] LocalPart ::= NCName
; Return: an UNRES-NAME
(define (ssax:read-QName port)
(let ((prefix-or-localpart (ssax:read-NCName port)))
(case (peek-char port)
((#\:) ; prefix was given after all
(read-char port) ; consume the colon
(cons prefix-or-localpart (ssax:read-NCName port)))
(else prefix-or-localpart) ; Prefix was omitted
)))
; The prefix of the pre-defined XML namespace
(define ssax:Prefix-XML (string->symbol "xml"))
(run-test
(assert (eq? '_
(call-with-input-string "_" ssax:read-NCName)))
(assert (eq? '_
(call-with-input-string "_" ssax:read-QName)))
(assert (eq? (string->symbol "_abc_")
(call-with-input-string "_abc_;" ssax:read-NCName)))
(assert (eq? (string->symbol "_abc_")
(call-with-input-string "_abc_;" ssax:read-QName)))
(assert (eq? (string->symbol "_a.b")
(call-with-input-string "_a.b " ssax:read-QName)))
(assert (equal? (cons (string->symbol "_a.b") (string->symbol "d.1-ef-"))
(call-with-input-string "_a.b:d.1-ef-;" ssax:read-QName)))
(assert (equal? (cons (string->symbol "a") (string->symbol "b"))
(call-with-input-string "a:b:c" ssax:read-QName)))
(assert (failed? (call-with-input-string ":abc" ssax:read-NCName)))
(assert (failed? (call-with-input-string "1:bc" ssax:read-NCName)))
)
; Compare one RES-NAME or an UNRES-NAME with the other.
; Return a symbol '<, '>, or '= depending on the result of
; the comparison.
; Names without PREFIX are always smaller than those with the PREFIX.
(define name-compare
(letrec ((symbol-compare
(lambda (symb1 symb2)
(cond
((eq? symb1 symb2) '=)
((string<? (symbol->string symb1) (symbol->string symb2))
'<)
(else '>)))))
(lambda (name1 name2)
(cond
((symbol? name1) (if (symbol? name2) (symbol-compare name1 name2)
'<))
((symbol? name2) '>)
((eq? name2 ssax:largest-unres-name) '<)
((eq? name1 ssax:largest-unres-name) '>)
((eq? (car name1) (car name2)) ; prefixes the same
(symbol-compare (cdr name1) (cdr name2)))
(else (symbol-compare (car name1) (car name2)))))))
; An UNRES-NAME that is postulated to be larger than anything that can occur in
; a well-formed XML document.
; name-compare enforces this postulate.
(define ssax:largest-unres-name (cons
(string->symbol "#LARGEST-SYMBOL")
(string->symbol "#LARGEST-SYMBOL")))
(run-test
(assert (eq? '= (name-compare 'ABC 'ABC)))
(assert (eq? '< (name-compare 'ABC 'ABCD)))
(assert (eq? '> (name-compare 'XB 'ABCD)))
(assert (eq? '> (name-compare '(HTML . PRE) 'PRE)))
(assert (eq? '< (name-compare 'HTML '(HTML . PRE))))
(assert (eq? '= (name-compare '(HTML . PRE) '(HTML . PRE))))
(assert (eq? '< (name-compare '(HTML . PRE) '(XML . PRE))))
(assert (eq? '> (name-compare '(HTML . PRE) '(HTML . P))))
(assert (eq? '< (name-compare '(HTML . PRE) ssax:largest-unres-name)))
(assert (eq? '< (name-compare '(ZZZZ . ZZZ) ssax:largest-unres-name)))
(assert (eq? '> (name-compare ssax:largest-unres-name '(ZZZZ . ZZZ) )))
)
; procedure: ssax:read-markup-token PORT
; This procedure starts parsing of a markup token. The current position
; in the stream must be #\<. This procedure scans enough of the input stream
; to figure out what kind of a markup token it is seeing. The procedure returns
; an xml-token structure describing the token. Note, generally reading
; of the current markup is not finished! In particular, no attributes of
; the start-tag token are scanned.
;
; Here's a detailed break out of the return values and the position in the PORT
; when that particular value is returned:
; PI-token: only PI-target is read.
; To finish the Processing Instruction and disregard it,
; call ssax:skip-pi. ssax:read-attributes may be useful
; as well (for PIs whose content is attribute-value
; pairs)
; END-token: The end tag is read completely; the current position
; is right after the terminating #\> character.
; COMMENT is read and skipped completely. The current position
; is right after "-->" that terminates the comment.
; CDSECT The current position is right after "<!CDATA["
; Use ssax:read-cdata-body to read the rest.
; DECL We have read the keyword (the one that follows "<!")
; identifying this declaration markup. The current
; position is after the keyword (usually a
; whitespace character)
;
; START-token We have read the keyword (GI) of this start tag.
; No attributes are scanned yet. We don't know if this
; tag has an empty content either.
; Use ssax:complete-start-tag to finish parsing of
; the token.
(define ssax:read-markup-token ; procedure ssax:read-markup-token port
(let ()
; we have read "<!-". Skip through the rest of the comment
; Return the 'COMMENT token as an indication we saw a comment
; and skipped it.
(define (skip-comment port)
(assert-curr-char '(#\-) "XML [15], second dash" port)
(if (not (find-string-from-port? "-->" port))
(parser-error port "XML [15], no -->"))
(make-xml-token 'COMMENT #f))
; we have read "<![" that must begin a CDATA section
(define (read-cdata port)
(assert (string=? "CDATA[" (read-string 6 port)))
(make-xml-token 'CDSECT #f))
(lambda (port)
(assert-curr-char '(#\<) "start of the token" port)
(case (peek-char port)
((#\/) (read-char port)
(begin0 (make-xml-token 'END (ssax:read-QName port))
(ssax:skip-S port)
(assert-curr-char '(#\>) "XML [42]" port)))
((#\?) (read-char port) (make-xml-token 'PI (ssax:read-NCName port)))
((#\!)
(case (peek-next-char port)
((#\-) (read-char port) (skip-comment port))
((#\[) (read-char port) (read-cdata port))
(else (make-xml-token 'DECL (ssax:read-NCName port)))))
(else (make-xml-token 'START (ssax:read-QName port)))))
))
; The current position is inside a PI. Skip till the rest of the PI
(define (ssax:skip-pi port)
(if (not (find-string-from-port? "?>" port))
(parser-error port "Failed to find ?> terminating the PI")))
; The current position is right after reading the PITarget. We read the
; body of PI and return is as a string. The port will point to the
; character right after '?>' combination that terminates PI.
; [16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>'
(define (ssax:read-pi-body-as-string port)
(ssax:skip-S port) ; skip WS after the PI target name
(string-concatenate/shared
(let loop ()
(let ((pi-fragment
(next-token '() '(#\?) "reading PI content" port)))
(if (eqv? #\> (peek-next-char port))
(begin
(read-char port)
(cons pi-fragment '()))
(cons* pi-fragment "?" (loop)))))))
(run-test
(assert (equal? "p1 content "
(call-with-input-string "<?pi1 p1 content ?>"
(lambda (port)
(ssax:read-markup-token port)
(ssax:read-pi-body-as-string port)))))
(assert (equal? "pi2? content? ?"
(call-with-input-string "<?pi2 pi2? content? ??>"
(lambda (port)
(ssax:read-markup-token port)
(ssax:read-pi-body-as-string port)))))
)
;(define (ssax:read-pi-body-as-name-values port)
; The current pos in the port is inside an internal DTD subset
; (e.g., after reading #\[ that begins an internal DTD subset)
; Skip until the "]>" combination that terminates this DTD
(define (ssax:skip-internal-dtd port)
(if (not (find-string-from-port? "]>" port))
(parser-error port
"Failed to find ]> terminating the internal DTD subset")))
; procedure+: ssax:read-cdata-body PORT STR-HANDLER SEED
;
; This procedure must be called after we have read a string "<![CDATA["
; that begins a CDATA section. The current position must be the first
; position of the CDATA body. This function reads _lines_ of the CDATA
; body and passes them to a STR-HANDLER, a character data consumer.
;
; The str-handler is a STR-HANDLER, a procedure STRING1 STRING2 SEED.
; The first STRING1 argument to STR-HANDLER never contains a newline.
; The second STRING2 argument often will. On the first invocation of
; the STR-HANDLER, the seed is the one passed to ssax:read-cdata-body
; as the third argument. The result of this first invocation will be
; passed as the seed argument to the second invocation of the line
; consumer, and so on. The result of the last invocation of the
; STR-HANDLER is returned by the ssax:read-cdata-body. Note a
; similarity to the fundamental 'fold' iterator.
;
; Within a CDATA section all characters are taken at their face value,
; with only three exceptions:
; CR, LF, and CRLF are treated as line delimiters, and passed
; as a single #\newline to the STR-HANDLER
; "]]>" combination is the end of the CDATA section.
; > is treated as an embedded #\> character
; Note, < and & are not specially recognized (and are not expanded)!
(define ssax:read-cdata-body
(let ((cdata-delimiters (list char-return #\newline #\] #\&)))
(lambda (port str-handler seed)
(let loop ((seed seed))
(let ((fragment (next-token '() cdata-delimiters
"reading CDATA" port)))
; that is, we're reading the char after the 'fragment'
(case (read-char port)
((#\newline) (loop (str-handler fragment nl seed)))
((#\])
(if (not (eqv? (peek-char port) #\]))
(loop (str-handler fragment "]" seed))
(let check-after-second-braket
((seed (if (string-null? fragment) seed
(str-handler fragment "" seed))))
(case (peek-next-char port) ; after the second bracket
((#\>) (read-char port) seed) ; we have read "]]>"
((#\]) (check-after-second-braket
(str-handler "]" "" seed)))
(else (loop (str-handler "]]" "" seed)))))))
((#\&) ; Note that #\& within CDATA may stand for itself
(let ((ent-ref ; it does not have to start an entity ref
(next-token-of (lambda (c)
(and (not (eof-object? c)) (char-alphabetic? c) c)) port)))
(cond ; ">" is to be replaced with #\>
((and (string=? "gt" ent-ref) (eqv? (peek-char port) #\;))
(read-char port)
(loop (str-handler fragment ">" seed)))
(else
(loop
(str-handler ent-ref ""
(str-handler fragment "&" seed)))))))
(else ; Must be CR: if the next char is #\newline, skip it
(if (eqv? (peek-char port) #\newline) (read-char port))
(loop (str-handler fragment nl seed)))
))))))
; a few lines of validation code
(run-test (letrec
((consumer (lambda (fragment foll-fragment seed)
(cons* (if (equal? foll-fragment (string #\newline))
" NL" foll-fragment) fragment seed)))
(test (lambda (str expected-result)
(newline) (display "body: ") (write str)
(newline) (display "Result: ")
(let ((result
(reverse
(call-with-input-string (unesc-string str)
(lambda (port) (ssax:read-cdata-body port consumer '()))
))))
(write result)
(assert (equal? result expected-result)))))
)
(test "]]>" '())
(test "abcd]]>" '("abcd" ""))
(test "abcd]]]>" '("abcd" "" "]" ""))
(test "abcd]]]]>" '("abcd" "" "]" "" "]" ""))
(test "abcd]]]]]>" '("abcd" "" "]" "" "]" "" "]" ""))
(test "abcd]]]a]]>" '("abcd" "" "]" "" "]]" "" "a" ""))
(test "abc%r%ndef%n]]>" '("abc" " NL" "def" " NL"))
(test "%r%n%r%n]]>" '("" " NL" "" " NL"))
(test "%r%n%r%na]]>" '("" " NL" "" " NL" "a" ""))
(test "%r%r%r%na]]>" '("" " NL" "" " NL" "" " NL" "a" ""))
(test "abc&!!!]]>" '("abc" "&" "" "" "!!!" ""))
(test "abc]]>>&]]]>and]]>"
'("abc" "" "]]" "" "" ">" "" "&" "gt" "" "" "&" "amp" "" ";" "" "]" ""
"]]" "" "" ">" "and" ""))
))
; procedure+: ssax:read-char-ref PORT
;
; [66] CharRef ::= '&#' [0-9]+ ';'
; | '&#x' [0-9a-fA-F]+ ';'
;
; This procedure must be called after we we have read "&#"
; that introduces a char reference.
; The procedure reads this reference and returns the corresponding char
; The current position in PORT will be after ";" that terminates
; the char reference
; Faults detected:
; WFC: XML-Spec.html#wf-Legalchar
;
; According to Section "4.1 Character and Entity References"
; of the XML Recommendation:
; "[Definition: A character reference refers to a specific character
; in the ISO/IEC 10646 character set, for example one not directly
; accessible from available input devices.]"
; Therefore, we use a ucscode->string function to convert a character
; code into the character -- *regardless* of the current character
; encoding of the input stream.
(define (ssax:read-char-ref port)
(let* ((base
(cond ((eqv? (peek-char port) #\x) (read-char port) 16)
(else 10)))
(name (next-token '() '(#\;) "XML [66]" port))
(char-code (string->number name base)))
(read-char port) ; read the terminating #\; char
(if (integer? char-code) (ucscode->string char-code)
(parser-error port "[wf-Legalchar] broken for '" name "'"))))
; procedure+: ssax:handle-parsed-entity PORT NAME ENTITIES
; CONTENT-HANDLER STR-HANDLER SEED
;
; Expand and handle a parsed-entity reference
; port - a PORT
; name - the name of the parsed entity to expand, a symbol
; entities - see ENTITIES
; content-handler -- procedure PORT ENTITIES SEED
; that is supposed to return a SEED
; str-handler - a STR-HANDLER. It is called if the entity in question
; turns out to be a pre-declared entity
;
; The result is the one returned by CONTENT-HANDLER or STR-HANDLER
; Faults detected:
; WFC: XML-Spec.html#wf-entdeclared
; WFC: XML-Spec.html#norecursion
(define ssax:predefined-parsed-entities
`(
(,(string->symbol "amp") . "&")
(,(string->symbol "lt") . "<")
(,(string->symbol "gt") . ">")
(,(string->symbol "apos") . "'")
(,(string->symbol "quot") . "\"")))
(define (ssax:handle-parsed-entity port name entities
content-handler str-handler seed)
(cond ; First we check the list of the declared entities
((assq name entities) =>
(lambda (decl-entity)
(let ((ent-body (cdr decl-entity)) ; mark the list to prevent recursion
(new-entities (cons (cons name #f) entities)))
(cond
((string? ent-body)
(call-with-input-string ent-body
(lambda (port) (content-handler port new-entities seed))))
((procedure? ent-body)
(let ((port (ent-body)))
(begin0
(content-handler port new-entities seed)
(close-input-port port))))
(else
(parser-error port "[norecursion] broken for " name))))))
((assq name ssax:predefined-parsed-entities)
=> (lambda (decl-entity)
(str-handler (cdr decl-entity) "" seed)))
((assq '*DEFAULT* entities) =>
(lambda (decl-entity)
(let ((fallback (cdr decl-entity))
(new-entities (cons (cons name #f) entities)))
(cond
((procedure? fallback)
(call-with-input-string (fallback port name)
(lambda (port) (content-handler port new-entities seed))))
(else
(parser-error port "[norecursion] broken for " name))))))
(else (parser-error port "[wf-entdeclared] broken for " name))))
; The ATTLIST Abstract Data Type
; Currently is implemented as an assoc list sorted in the ascending
; order of NAMES.
(define (make-empty-attlist) '())
; Add a name-value pair to the existing attlist preserving the order
; Return the new list, in the sorted ascending order.
; Return #f if a pair with the same name already exists in the attlist
(define (attlist-add attlist name-value)
(if (null? attlist) (cons name-value attlist)
(case (name-compare (car name-value) (caar attlist))
((=) #f)
((<) (cons name-value attlist))
(else (cons (car attlist) (attlist-add (cdr attlist) name-value)))
)))
(define attlist-null? null?)
; Given an non-null attlist, return a pair of values: the top and the rest
(define (attlist-remove-top attlist)
(values (car attlist) (cdr attlist)))
(define (attlist->alist attlist) attlist)
(define attlist-fold fold)
; procedure+: ssax:read-attributes PORT ENTITIES
;
; This procedure reads and parses a production Attribute*
; [41] Attribute ::= Name Eq AttValue
; [10] AttValue ::= '"' ([^<&"] | Reference)* '"'
; | "'" ([^<&'] | Reference)* "'"
; [25] Eq ::= S? '=' S?
;
;
; The procedure returns an ATTLIST, of Name (as UNRES-NAME), Value (as string)
; pairs. The current character on the PORT is a non-whitespace character
; that is not an ncname-starting character.
;
; Note the following rules to keep in mind when reading an 'AttValue'
; "Before the value of an attribute is passed to the application
; or checked for validity, the XML processor must normalize it as follows:
; - a character reference is processed by appending the referenced
; character to the attribute value
; - an entity reference is processed by recursively processing the
; replacement text of the entity [see ENTITIES]
; [named entities amp lt gt quot apos are assumed pre-declared]
; - a whitespace character (#x20, #xD, #xA, #x9) is processed by appending #x20
; to the normalized value, except that only a single #x20 is appended for a
; "#xD#xA" sequence that is part of an external parsed entity or the
; literal entity value of an internal parsed entity
; - other characters are processed by appending them to the normalized value "
;
;
; Faults detected:
; WFC: XML-Spec.html#CleanAttrVals
; WFC: XML-Spec.html#uniqattspec
(define ssax:read-attributes ; ssax:read-attributes port entities
(let ((value-delimeters (append ssax:S-chars '(#\< #\&))))
; Read the AttValue from the PORT up to the delimiter
; (which can be a single or double-quote character,
; or even a symbol *eof*)
; 'prev-fragments' is the list of string fragments, accumulated
; so far, in reverse order.
; Return the list of fragments with newly read fragments
; prepended.
(define (read-attrib-value delimiter port entities prev-fragments)
(let* ((new-fragments
(cons (next-token '() (cons delimiter value-delimeters)
"XML [10]" port)
prev-fragments))
(cterm (read-char port)))
(cond
((or (eof-object? cterm) (eqv? cterm delimiter))
new-fragments)
((eqv? cterm char-return) ; treat a CR and CRLF as a LF
(if (eqv? (peek-char port) #\newline) (read-char port))
(read-attrib-value delimiter port entities
(cons " " new-fragments)))
((memv cterm ssax:S-chars)
(read-attrib-value delimiter port entities
(cons " " new-fragments)))
((eqv? cterm #\&)
(cond
((eqv? (peek-char port) #\#)
(read-char port)
(read-attrib-value delimiter port entities
(cons (ssax:read-char-ref port) new-fragments)))
(else
(read-attrib-value delimiter port entities
(read-named-entity port entities new-fragments)))))
(else (parser-error port "[CleanAttrVals] broken")))))
; we have read "&" that introduces a named entity reference.
; read this reference and return the result of
; normalizing of the corresponding string
; (that is, read-attrib-value is applied to the replacement
; text of the entity)
; The current position will be after ";" that terminates
; the entity reference
(define (read-named-entity port entities fragments)
(let ((name (ssax:read-NCName port)))
(assert-curr-char '(#\;) "XML [68]" port)
(ssax:handle-parsed-entity port name entities
(lambda (port entities fragments)
(read-attrib-value '*eof* port entities fragments))
(lambda (str1 str2 fragments)
(if (equal? "" str2) (cons str1 fragments)
(cons* str2 str1 fragments)))
fragments)))
(lambda (port entities)
(let loop ((attr-list (make-empty-attlist)))
(if (not (ssax:ncname-starting-char? (ssax:skip-S port))) attr-list
(let ((name (ssax:read-QName port)))
(ssax:skip-S port)
(assert-curr-char '(#\=) "XML [25]" port)
(ssax:skip-S port)
(let ((delimiter
(assert-curr-char '(#\' #\" ) "XML [10]" port)))
(loop
(or (attlist-add attr-list
(cons name
(string-concatenate-reverse/shared
(read-attrib-value delimiter port entities
'()))))
(parser-error port "[uniqattspec] broken for " name))))))))
))
; a few lines of validation code
(run-test (letrec
((test (lambda (str decl-entities expected-res)
(newline) (display "input: ") (write str)
(newline) (display "Result: ")
(let ((result
(call-with-input-string (unesc-string str)
(lambda (port)
(ssax:read-attributes port decl-entities)))))
(write result) (newline)
(assert (equal? result expected-res))))))
(test "" '() '())
(test "href='http://a%tb%r%n%r%n%nc'" '()
`((,(string->symbol "href") . "http://a b c")))
(test "href='http://a%tb%r%r%n%rc'" '()
`((,(string->symbol "href") . "http://a b c")))
(test "_1 ='12&' _2= \"%r%n%t12 3\">" '()
`((_1 . "12&") (_2 . ,(unesc-string " 12%n3"))))
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<xx>"))
`((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
(,(string->symbol "Next") . "12<xx>34")))
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<xx>"))
`((,(string->symbol "Abc") . ,(unesc-string "<&>%r"))
(,(string->symbol "Next") . "12<xx>34")))
(test "%tAbc='<&>
'%nNext='12&en;34' />"
`((en . ,(lambda () (open-input-string ""xx'"))))
`((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
(,(string->symbol "Next") . "12\"xx'34")))
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<&ent1;T;>") (ent1 . "&"))
`((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
(,(string->symbol "Next") . "12<&T;>34")))
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
`((*DEFAULT* . ,(lambda (port name)
(case name
((ent) "<&ent1;T;>")
((ent1) "&")
(else (error "unrecognized" name))))))
`((,(string->symbol "Abc") . ,(unesc-string "<&>%n"))
(,(string->symbol "Next") . "12<&T;>34")))
(assert (failed?
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<&ent1;T;>") (ent1 . "&")) '())))
(assert (failed?
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<&ent;T;>") (ent1 . "&")) '())))
(assert (failed?
(test "%tAbc='<&>
'%nNext='12&ent;34' />"
'((ent . "<&ent1;T;>") (ent1 . "&ent;")) '())))
(test "html:href='http://a%tb%r%n%r%n%nc'" '()
`(((,(string->symbol "html") . ,(string->symbol "href"))
. "http://a b c")))
(test "html:href='ref1' html:src='ref2'" '()
`(((,(string->symbol "html") . ,(string->symbol "href"))
. "ref1")
((,(string->symbol "html") . ,(string->symbol "src"))
. "ref2")))
(test "html:href='ref1' xml:html='ref2'" '()
`(((,(string->symbol "html") . ,(string->symbol "href"))
. "ref1")
((,ssax:Prefix-XML . ,(string->symbol "html"))
. "ref2")))
(assert (failed? (test "html:href='ref1' html:href='ref2'" '() '())))
(assert (failed? (test "html:href='<' html:href='ref2'" '() '())))
(assert (failed? (test "html:href='ref1' html:href='&ref2;'" '() '())))
))
; ssax:resolve-name PORT UNRES-NAME NAMESPACES apply-default-ns?
;
; Convert an UNRES-NAME to a RES-NAME given the appropriate NAMESPACES
; declarations.
; the last parameter apply-default-ns? determines if the default
; namespace applies (for instance, it does not for attribute names)
;
; Per REC-xml-names/#nsc-NSDeclared, "xml" prefix is considered pre-declared
; and bound to the namespace name "http://www.w3.org/XML/1998/namespace".
;
; This procedure tests for the namespace constraints:
; http://www.w3.org/TR/REC-xml-names/#nsc-NSDeclared
(define (ssax:resolve-name port unres-name namespaces apply-default-ns?)
(cond
((pair? unres-name) ; it's a QNAME
(cons
(cond
((assq (car unres-name) namespaces) => cadr)
((eq? (car unres-name) ssax:Prefix-XML) ssax:Prefix-XML)
(else
(parser-error port "[nsc-NSDeclared] broken; prefix " (car unres-name))))
(cdr unres-name)))
(apply-default-ns? ; Do apply the default namespace, if any
(let ((default-ns (assq '*DEFAULT* namespaces)))
(if (and default-ns (cadr default-ns))
(cons (cadr default-ns) unres-name)
unres-name))) ; no default namespace declared
(else unres-name))) ; no prefix, don't apply the default-ns
(run-test
(let* ((namespaces
'((HTML UHTML . URN-HTML)
(HTML UHTML-1 . URN-HTML)
(A UHTML . URN-HTML)))
(namespaces-def
(cons
'(*DEFAULT* DEF . URN-DEF) namespaces))
(namespaces-undef
(cons
'(*DEFAULT* #f . #f) namespaces-def))
(port (current-input-port)))
(assert (equal? 'ABC
(ssax:resolve-name port 'ABC namespaces #t)))
(assert (equal? '(DEF . ABC)
(ssax:resolve-name port 'ABC namespaces-def #t)))
(assert (equal? 'ABC
(ssax:resolve-name port 'ABC namespaces-def #f)))
(assert (equal? 'ABC
(ssax:resolve-name port 'ABC namespaces-undef #t)))
(assert (equal? '(UHTML . ABC)
(ssax:resolve-name port '(HTML . ABC) namespaces-def #t)))
(assert (equal? '(UHTML . ABC)
(ssax:resolve-name port '(HTML . ABC) namespaces-def #f)))
(assert (equal? `(,ssax:Prefix-XML . space)
(ssax:resolve-name port
`(,(string->symbol "xml") . space) namespaces-def #f)))
(assert (failed?
(ssax:resolve-name port '(XXX . ABC) namespaces-def #f)))
))
; procedure+: ssax:uri-string->symbol URI-STR
; Convert a URI-STR to an appropriate symbol
(define (ssax:uri-string->symbol uri-str)
(string->symbol uri-str))
; procedure+: ssax:complete-start-tag TAG PORT ELEMS ENTITIES NAMESPACES
;
; This procedure is to complete parsing of a start-tag markup. The
; procedure must be called after the start tag token has been
; read. TAG is an UNRES-NAME. ELEMS is an instance of xml-decl::elems;
; it can be #f to tell the function to do _no_ validation of elements
; and their attributes.
;
; This procedure returns several values:
; ELEM-GI: a RES-NAME.
; ATTRIBUTES: element's attributes, an ATTLIST of (RES-NAME . STRING)
; pairs. The list does NOT include xmlns attributes.
; NAMESPACES: the input list of namespaces amended with namespace
; (re-)declarations contained within the start-tag under parsing
; ELEM-CONTENT-MODEL
; On exit, the current position in PORT will be the first character after
; #\> that terminates the start-tag markup.
;
; Faults detected:
; VC: XML-Spec.html#enum
; VC: XML-Spec.html#RequiredAttr
; VC: XML-Spec.html#FixedAttr
; VC: XML-Spec.html#ValueType
; WFC: XML-Spec.html#uniqattspec (after namespaces prefixes are resolved)
; VC: XML-Spec.html#elementvalid
; WFC: REC-xml-names/#dt-NSName
; Note, although XML Recommendation does not explicitly say it,
; xmlns and xmlns: attributes don't have to be declared (although they
; can be declared, to specify their default value)
; Procedure: ssax:complete-start-tag tag-head port elems entities namespaces
(define ssax:complete-start-tag
(let ((xmlns (string->symbol "xmlns"))
(largest-dummy-decl-attr (list ssax:largest-unres-name #f #f #f)))
; Scan through the attlist and validate it, against decl-attrs
; Return an assoc list with added fixed or implied attrs.
; Note that both attlist and decl-attrs are ATTLISTs, and therefore,
; sorted
(define (validate-attrs port attlist decl-attrs)
; Check to see decl-attr is not of use type REQUIRED. Add
; the association with the default value, if any declared
(define (add-default-decl decl-attr result)
(let*-values
(((attr-name content-type use-type default-value)
(apply values decl-attr)))
(and (eq? use-type 'REQUIRED)
(parser-error port "[RequiredAttr] broken for" attr-name))
(if default-value
(cons (cons attr-name default-value) result)
result)))
(let loop ((attlist attlist) (decl-attrs decl-attrs) (result '()))
(if (attlist-null? attlist)
(attlist-fold add-default-decl result decl-attrs)
(let*-values
(((attr attr-others)
(attlist-remove-top attlist))
((decl-attr other-decls)
(if (attlist-null? decl-attrs)
(values largest-dummy-decl-attr decl-attrs)
(attlist-remove-top decl-attrs)))
)
(case (name-compare (car attr) (car decl-attr))
((<)
(if (or (eq? xmlns (car attr))
(and (pair? (car attr)) (eq? xmlns (caar attr))))
(loop attr-others decl-attrs (cons attr result))
(parser-error port "[ValueType] broken for " attr)))
((>)
(loop attlist other-decls
(add-default-decl decl-attr result)))
(else ; matched occurrence of an attr with its declaration
(let*-values
(((attr-name content-type use-type default-value)
(apply values decl-attr)))
; Run some tests on the content of the attribute
(cond
((eq? use-type 'FIXED)
(or (equal? (cdr attr) default-value)
(parser-error port "[FixedAttr] broken for " attr-name)))
((eq? content-type 'CDATA) #t) ; everything goes
((pair? content-type)
(or (member (cdr attr) content-type)
(parser-error port "[enum] broken for " attr-name "="
(cdr attr))))
(else
(ssax:warn port "declared content type " content-type
" not verified yet")))
(loop attr-others other-decls (cons attr result)))))
))))
; Add a new namespace declaration to namespaces.
; First we convert the uri-str to a uri-symbol and search namespaces for
; an association (_ user-prefix . uri-symbol).
; If found, we return the argument namespaces with an association
; (prefix user-prefix . uri-symbol) prepended.
; Otherwise, we prepend (prefix uri-symbol . uri-symbol)
(define (add-ns port prefix uri-str namespaces)
(and (equal? "" uri-str)
(parser-error port "[dt-NSName] broken for " prefix))
(let ((uri-symbol (ssax:uri-string->symbol uri-str)))
(let loop ((nss namespaces))
(cond
((null? nss)
(cons (cons* prefix uri-symbol uri-symbol) namespaces))
((eq? uri-symbol (cddar nss))
(cons (cons* prefix (cadar nss) uri-symbol) namespaces))
(else (loop (cdr nss)))))))
; partition attrs into proper attrs and new namespace declarations
; return two values: proper attrs and the updated namespace declarations
(define (adjust-namespace-decl port attrs namespaces)
(let loop ((attrs attrs) (proper-attrs '()) (namespaces namespaces))
(cond
((null? attrs) (values proper-attrs namespaces))
((eq? xmlns (caar attrs)) ; re-decl of the default namespace
(loop (cdr attrs) proper-attrs
(if (equal? "" (cdar attrs)) ; un-decl of the default ns
(cons (cons* '*DEFAULT* #f #f) namespaces)
(add-ns port '*DEFAULT* (cdar attrs) namespaces))))
((and (pair? (caar attrs)) (eq? xmlns (caaar attrs)))
(loop (cdr attrs) proper-attrs
(add-ns port (cdaar attrs) (cdar attrs) namespaces)))
(else
(loop (cdr attrs) (cons (car attrs) proper-attrs) namespaces)))))
; The body of the function
(lambda (tag-head port elems entities namespaces)
(let*-values
(((attlist) (ssax:read-attributes port entities))
((empty-el-tag?)
(begin
(ssax:skip-S port)
(and
(eqv? #\/
(assert-curr-char '(#\> #\/) "XML [40], XML [44], no '>'" port))
(assert-curr-char '(#\>) "XML [44], no '>'" port))))
((elem-content decl-attrs) ; see xml-decl for their type
(if elems ; elements declared: validate!
(cond
((assoc tag-head elems) =>
(lambda (decl-elem) ; of type xml-decl::decl-elem
(values
(if empty-el-tag? 'EMPTY-TAG (cadr decl-elem))
(caddr decl-elem))))
(else
(parser-error port "[elementvalid] broken, no decl for " tag-head)))
(values ; non-validating parsing
(if empty-el-tag? 'EMPTY-TAG 'ANY)
#f) ; no attributes declared
))
((merged-attrs) (if decl-attrs (validate-attrs port attlist decl-attrs)
(attlist->alist attlist)))
((proper-attrs namespaces)
(adjust-namespace-decl port merged-attrs namespaces))
)
;(cerr "proper attrs: " proper-attrs nl)
; build the return value
(values
(ssax:resolve-name port tag-head namespaces #t)
(fold-right
(lambda (name-value attlist)
(or
(attlist-add attlist
(cons (ssax:resolve-name port (car name-value) namespaces #f)
(cdr name-value)))
(parser-error port "[uniqattspec] after NS expansion broken for "
name-value)))
(make-empty-attlist)
proper-attrs)
namespaces
elem-content)))))
(run-test
(let* ((urn-a (string->symbol "urn:a"))
(urn-b (string->symbol "urn:b"))
(urn-html (string->symbol "http://w3c.org/html"))
(namespaces
`((#f '"UHTML" . ,urn-html)
('"A" '"UA" . ,urn-a)))
(test
(lambda (tag-head-name elems str)
(call-with-input-string str
(lambda (port)
(call-with-values
(lambda ()
(ssax:complete-start-tag
(call-with-input-string tag-head-name
(lambda (port) (ssax:read-QName port)))
port
elems '() namespaces))
list))))))
; First test with no validation of elements
;(test "TAG1" #f "")
(assert (equal? `('"TAG1" () ,namespaces ANY)
(test "TAG1" #f ">")))
(assert (equal? `('"TAG1" () ,namespaces EMPTY-TAG)
(test "TAG1" #f "/>")))
(assert (equal? `('"TAG1" (('"HREF" . "a")) ,namespaces EMPTY-TAG)
(test "TAG1" #f "HREF='a'/>")))
(assert (equal? `(('"UA" . '"TAG1") (('"HREF" . "a"))
,(cons `(*DEFAULT* '"UA" . ,urn-a) namespaces) ANY)
(test "TAG1" #f "HREF='a' xmlns='urn:a'>")))
(assert (equal? `('"TAG1" (('"HREF" . "a"))
,(cons '(*DEFAULT* #f . #f) namespaces) ANY)
(test "TAG1" #f "HREF='a' xmlns=''>")))
(assert (failed? (test "UA:TAG1" #f "HREF='a' xmlns=''/>")))
(assert (equal? `(('"UA" . '"TAG1") ((('"UA" . '"HREF") . "a"))
,(cons '(*DEFAULT* #f . #f) namespaces) ANY)
(test "A:TAG1" #f "A:HREF='a' xmlns=''>")))
(assert (equal? `(('"UA" . '"TAG1") ((('"UA" . '"HREF") . "a"))
,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) ANY)
(test "A:TAG1" #f "A:HREF='a' xmlns='urn:b'>")))
(assert (failed? (test "B:TAG1" #f "A:HREF='a' xmlns:b=''/>")))
(assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
(test "B:TAG1" #f "A:HREF='a' xmlns:B='urn:b'>")))
(assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a")
((,urn-b . '"SRC") . "b"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
(test "B:TAG1" #f
"B:SRC='b' A:HREF='a' xmlns:B='urn:b'>")))
(assert (equal? `((,urn-b . '"TAG1") ((('"UA" . '"HREF") . "a")
((,urn-b . '"HREF") . "b"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) ANY)
(test "B:TAG1" #f
"B:HREF=\"b\" A:HREF='a' xmlns:B='urn:b'>")))
; must be an error! Duplicate attr
(assert (failed? (test "B:TAG1" #f
"HREF=\"b\" HREF='a' xmlns:B='urn:a'/>")))
; must be an error! Duplicate attr after ns expansion
(assert (failed? (test "B:TAG1" #f
"B:HREF=\"b\" A:HREF='a' xmlns:B='urn:a'/>")))
(assert (equal? `(('"UA" . '"TAG1") (('"HREF" . "a")
(('"UA" . '"HREF") . "b"))
,(cons `(*DEFAULT* '"UA" . ,urn-a) namespaces) ANY)
(test "TAG1" #f
"A:HREF=\"b\" HREF='a' xmlns='urn:a'>")))
(assert (equal? `('"TAG1" ((('"UHTML" . '"HREF") . "a")
((,urn-b . '"HREF") . "b"))
,(append `(
('"HTML" '"UHTML" . ,urn-html)
('"B" ,urn-b . ,urn-b))
namespaces) ANY)
(test "TAG1" #f
"B:HREF=\"b\" xmlns:B='urn:b' xmlns:HTML='http://w3c.org/html' HTML:HREF='a' >")))
; Now test the validating parsing
; No decl for tag1
(assert (failed? (test "TAG1" '((TAG2 ANY ()))
"B:HREF='b' xmlns:B='urn:b'>")))
; No decl for HREF elem
;; (cond-expand
;; ((not (or scm mit-scheme)) ; Regretfully, SCM treats '() as #f
;; (assert (failed?
;; (test "TAG1" '(('"TAG1" ANY ()))
;; "B:HREF='b' xmlns:B='urn:b'>"))))
;; (else #t))
; No decl for HREF elem
(assert (failed?
(test "TAG1" '(('"TAG1" ANY (('"HREF1" CDATA IMPLIED #f))))
"B:HREF='b' xmlns:B='urn:b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces EMPTY-TAG)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
"HREF='b'/>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
"HREF='b'>")))
; Req'd attribute not given error
(assert (failed?
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f))))
">")))
; Wrong content-type of the attribute
(assert (failed?
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" ("c") REQUIRED #f))))
"HREF='b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" ("c" "b") IMPLIED #f))))
"HREF='b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED "c"))))
"HREF='b'>")))
; Bad fixed attribute
(assert (failed?
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "c"))))
"HREF='b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "b"))))
"HREF='b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA FIXED "b")))) ">")))
(assert (equal? `('"TAG1" (('"HREF" . "b")) ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED "b")))) ">")))
(assert (equal? `('"TAG1" () ,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA IMPLIED #f)))) ">")))
; Undeclared attr
(assert (failed?
(test "TAG1"
'(('"TAG1" PCDATA ((('"A" . '"HREF") CDATA IMPLIED "c"))))
"HREF='b'>")))
(assert (equal? `('"TAG1" (('"HREF" . "b") (('"UA" . '"HREF") . "c"))
,namespaces PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
(('"A" . '"HREF") CDATA IMPLIED "c"))))
"HREF='b'>")))
(assert (equal? `(('"UA" . '"TAG1")
(('"HREF" . "b") (('"UA" . '"HREF") . "c"))
,namespaces PCDATA)
(test "A:TAG1" '((('"A" . '"TAG1") PCDATA
(('"HREF" NMTOKEN REQUIRED #f)
(('"A" . '"HREF") CDATA IMPLIED "c"))))
"HREF='b'>")))
(assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
(test "B:TAG1" '((('"B" . '"TAG1") PCDATA (('"HREF" CDATA REQUIRED #f)
(('"xmlns" . '"B") CDATA IMPLIED "urn:b"))))
"HREF='b'>")))
(assert (equal? `((,urn-b . '"TAG1") (((,urn-b . '"HREF") . "b"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
(test "B:TAG1" '((('"B" . '"TAG1") PCDATA
((('"B" . '"HREF") CDATA REQUIRED #f)
(('"xmlns" . '"B") CDATA IMPLIED "urn:b"))))
"B:HREF='b'>")))
(assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
('"xmlns" CDATA IMPLIED "urn:b"))))
"HREF='b'>")))
; xmlns not declared
(assert (equal? `((,urn-b . '"TAG1") (('"HREF" . "b"))
,(cons `(*DEFAULT* ,urn-b . ,urn-b) namespaces) PCDATA)
(test "TAG1" '(('"TAG1" PCDATA (('"HREF" CDATA REQUIRED #f)
)))
"HREF='b' xmlns='urn:b'>")))
; xmlns:B not declared
(assert (equal? `((,urn-b . '"TAG1") (((,urn-b . '"HREF") . "b"))
,(cons `('"B" ,urn-b . ,urn-b) namespaces) PCDATA)
(test "B:TAG1" '((('"B" . '"TAG1") PCDATA
((('"B" . '"HREF") CDATA REQUIRED #f)
)))
"B:HREF='b' xmlns:B='urn:b'>")))
))
; procedure+: ssax:read-external-id PORT
;
; This procedure parses an ExternalID production:
; [75] ExternalID ::= 'SYSTEM' S SystemLiteral
; | 'PUBLIC' S PubidLiteral S SystemLiteral
; [11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'")
; [12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'"
; [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9]
; | [-'()+,./:=?;!*#@$_%]
;
; This procedure is supposed to be called when an ExternalID is expected;
; that is, the current character must be either #\S or #\P that start
; correspondingly a SYSTEM or PUBLIC token. This procedure returns the
; SystemLiteral as a string. A PubidLiteral is disregarded if present.
(define (ssax:read-external-id port)
(let ((discriminator (ssax:read-NCName port)))
(assert-curr-char ssax:S-chars "space after SYSTEM or PUBLIC" port)
(ssax:skip-S port)
(let ((delimiter
(assert-curr-char '(#\' #\" ) "XML [11], XML [12]" port)))
(cond
((eq? discriminator (string->symbol "SYSTEM"))
(begin0
(next-token '() (list delimiter) "XML [11]" port)
(read-char port) ; reading the closing delim
))
((eq? discriminator (string->symbol "PUBLIC"))
(skip-until (list delimiter) port)
(assert-curr-char ssax:S-chars "space after PubidLiteral" port)
(ssax:skip-S port)
(let* ((delimiter
(assert-curr-char '(#\' #\" ) "XML [11]" port))
(systemid
(next-token '() (list delimiter) "XML [11]" port)))
(read-char port) ; reading the closing delim
systemid))
(else
(parser-error port "XML [75], " discriminator
" rather than SYSTEM or PUBLIC"))))))
;-----------------------------------------------------------------------------
; Higher-level parsers and scanners
;
; They parse productions corresponding to the whole (document) entity
; or its higher-level pieces (prolog, root element, etc).
; Scan the Misc production in the context
; [1] document ::= prolog element Misc*
; [22] prolog ::= XMLDecl? Misc* (doctypedec l Misc*)?
; [27] Misc ::= Comment | PI | S
;
; The following function should be called in the prolog or epilog contexts.
; In these contexts, whitespaces are completely ignored.
; The return value from ssax:scan-Misc is either a PI-token,
; a DECL-token, a START token, or EOF.
; Comments are ignored and not reported.
(define (ssax:scan-Misc port)
(let loop ((c (ssax:skip-S port)))
(cond
((eof-object? c) c)
((not (char=? c #\<))
(parser-error port "XML [22], char '" c "' unexpected"))
(else
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((COMMENT) (loop (ssax:skip-S port)))
((PI DECL START) token)
(else
(parser-error port "XML [22], unexpected token of kind "
(xml-token-kind token)
))))))))
; procedure+: ssax:read-char-data PORT EXPECT-EOF? STR-HANDLER SEED
;
; This procedure is to read the character content of an XML document
; or an XML element.
; [43] content ::=
; (element | CharData | Reference | CDSect | PI
; | Comment)*
; To be more precise, the procedure reads CharData, expands CDSect
; and character entities, and skips comments. The procedure stops
; at a named reference, EOF, at the beginning of a PI or a start/end tag.
;
; port
; a PORT to read
; expect-eof?
; a boolean indicating if EOF is normal, i.e., the character
; data may be terminated by the EOF. EOF is normal
; while processing a parsed entity.
; str-handler
; a STR-HANDLER
; seed
; an argument passed to the first invocation of STR-HANDLER.
;
; The procedure returns two results: SEED and TOKEN.
; The SEED is the result of the last invocation of STR-HANDLER, or the
; original seed if STR-HANDLER was never called.
;
; TOKEN can be either an eof-object (this can happen only if
; expect-eof? was #t), or:
; - an xml-token describing a START tag or an END-tag;
; For a start token, the caller has to finish reading it.
; - an xml-token describing the beginning of a PI. It's up to an
; application to read or skip through the rest of this PI;
; - an xml-token describing a named entity reference.
;
; CDATA sections and character references are expanded inline and
; never returned. Comments are silently disregarded.
;
; As the XML Recommendation requires, all whitespace in character data
; must be preserved. However, a CR character (#xD) must be disregarded
; if it appears before a LF character (#xA), or replaced by a #xA character
; otherwise. See Secs. 2.10 and 2.11 of the XML Recommendation. See also
; the canonical XML Recommendation.
; ssax:read-char-data port expect-eof? str-handler seed
(define ssax:read-char-data
(let
((terminators-usual (list #\< #\& char-return))
(terminators-usual-eof (list #\< '*eof* #\& char-return))
(handle-fragment
(lambda (fragment str-handler seed)
(if (string-null? fragment) seed
(str-handler fragment "" seed))))
)
(lambda (port expect-eof? str-handler seed)
; Very often, the first character we encounter is #\<
; Therefore, we handle this case in a special, fast path
(if (eqv? #\< (peek-char port))
; The fast path
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((START END) ; The most common case
(values seed token))
((CDSECT)
(let ((seed (ssax:read-cdata-body port str-handler seed)))
(ssax:read-char-data port expect-eof? str-handler seed)))
((COMMENT) (ssax:read-char-data port expect-eof?
str-handler seed))
(else
(values seed token))))
; The slow path
(let ((char-data-terminators
(if expect-eof? terminators-usual-eof terminators-usual)))
(let loop ((seed seed))
(let* ((fragment
(next-token '() char-data-terminators
"reading char data" port))
(term-char (peek-char port)) ; one of char-data-terminators
)
(if (eof-object? term-char)
(values
(handle-fragment fragment str-handler seed)
term-char)
(case term-char
((#\<)
(let ((token (ssax:read-markup-token port)))
(case (xml-token-kind token)
((CDSECT)
(loop
(ssax:read-cdata-body port str-handler
(handle-fragment fragment str-handler seed))))
((COMMENT)
(loop (handle-fragment fragment str-handler seed)))
(else
(values
(handle-fragment fragment str-handler seed)
token)))))
((#\&)
(case (peek-next-char port)
((#\#) (read-char port)
(loop (str-handler fragment
(ssax:read-char-ref port)
seed)))
(else
(let ((name (ssax:read-NCName port)))
(assert-curr-char '(#\;) "XML [68]" port)
(values
(handle-fragment fragment str-handler seed)
(make-xml-token 'ENTITY-REF name))))))
(else ; This must be a CR character
(if (eqv? (peek-next-char port) #\newline)
(read-char port))
(loop (str-handler fragment (string #\newline) seed))))
))))))))
; a few lines of validation code
(run-test (letrec
((a-tag (make-xml-token 'START (string->symbol "BR")))
(a-ref (make-xml-token 'ENTITY-REF (string->symbol "lt")))
(eof-object (lambda () eof-object)) ; a unique value
(str-handler (lambda (fragment foll-fragment seed)
(if (string-null? foll-fragment) (cons fragment seed)
(cons* foll-fragment fragment seed))))
(test (lambda (str expect-eof? expected-data expected-token)
(newline) (display "body: ") (write str)
(newline) (display "Result: ")
(let*-values
(((seed token)
(call-with-input-string (unesc-string str)
(lambda (port)
(ssax:read-char-data port expect-eof? str-handler '()))))
((result) (reverse seed)))
(write result)
(display " ")
(display token)
(assert (equal? result (map unesc-string expected-data))
(if (eq? expected-token eof-object)
(eof-object? token)
(equal? token expected-token))))))
)
(test "" #t '() eof-object)
(assert (failed? (test "" #f '() eof-object)))
(test " " #t '(" ") eof-object)
(test "<BR/>" #f '() a-tag)
(test " <BR />" #f '(" ") a-tag)
(test " <" #f '(" ") a-ref)
(test " a<" #f '(" a") a-ref)
(test " a <" #f '(" a ") a-ref)
(test " <!-- comment--> a a<BR/>" #f '(" " " a a") a-tag)
(test " <!-- comment-->%ra a<BR/>" #f '(" " "" "%n" "a a") a-tag)
(test " <!-- comment-->%r%na a<BR/>" #f '(" " "" "%n" "a a") a-tag)
(test " <!-- comment-->%r%na%t%r%r%na<BR/>" #f
'(" " "" "%n" "a%t" "%n" "" "%n" "a") a-tag)
(test "a<!-- comment--> a a<BR/>" #f '("a" " a a") a-tag)
(test "!<BR/>" #f '("" "!") a-tag)
(test "!%n<BR/>" #f '("" "!" "%n") a-tag)
(test "%t!%n<BR/>" #f '("%t" "!" "%n") a-tag)
(test "%t!%na a<BR/>" #f '("%t" "!" "%na a") a-tag)
(test "%t!%ra a<BR/>" #f '("%t" "!" "" "%n" "a a") a-tag)
(test "%t!%r%na a<BR/>" #f '("%t" "!" "" "%n" "a a") a-tag)
(test " %ta ! b <BR/>" #f '(" %ta " "!" " b ") a-tag)
(test " %ta   b <BR/>" #f '(" %ta " " " " b ") a-tag)
(test "<![CDATA[<]]><BR/>" #f '("<") a-tag)
(test "<![CDATA[]]]><BR/>" #f '("]") a-tag)
(test "%t<![CDATA[<]]><BR/>" #f '("%t" "<") a-tag)
(test "%t<![CDATA[<]]>a b<BR/>" #f '("%t" "<" "a b") a-tag)
(test "%t<![CDATA[<]]> a b<BR/>" #f '("%t" "<" " a b") a-tag)
(test "%td <![CDATA[ <%r%r%n]]> a b<BR/>" #f
'("%td " " <" "%n" "" "%n" " a b") a-tag)
))
; procedure+: ssax:assert-token TOKEN KIND GI
; Make sure that TOKEN is of anticipated KIND and has anticipated GI
; Note GI argument may actually be a pair of two symbols, Namespace
; URI or the prefix, and of the localname.
; If the assertion fails, error-cont is evaluated by passing it
; three arguments: token kind gi. The result of error-cont is returned.
(define (ssax:assert-token token kind gi error-cont)
(or
(and (xml-token? token)
(eq? kind (xml-token-kind token))
(equal? gi (xml-token-head token)))
(error-cont token kind gi)))
;========================================================================
; Highest-level parsers: XML to SXML
; These parsers are a set of syntactic forms to instantiate a SSAX parser.
; A user can instantiate the parser to do the full validation, or
; no validation, or any particular validation. The user specifies
; which PI he wants to be notified about. The user tells what to do
; with the parsed character and element data. The latter handlers
; determine if the parsing follows a SAX or a DOM model.
; syntax: ssax:make-pi-parser my-pi-handlers
; Create a parser to parse and process one Processing Element (PI).
; my-pi-handlers
; An assoc list of pairs (PI-TAG . PI-HANDLER)
; where PI-TAG is an NCName symbol, the PI target, and
; PI-HANDLER is a procedure PORT PI-TAG SEED
; where PORT points to the first symbol after the PI target.
; The handler should read the rest of the PI up to and including
; the combination '?>' that terminates the PI. The handler should
; return a new seed.
; One of the PI-TAGs may be the symbol *DEFAULT*. The corresponding
; handler will handle PIs that no other handler will. If the
; *DEFAULT* PI-TAG is not specified, ssax:make-pi-parser will assume
; the default handler that skips the body of the PI
;
; The output of the ssax:make-pi-parser is a procedure
; PORT PI-TAG SEED
; that will parse the current PI according to the user-specified handlers.
;
; The previous version of ssax:make-pi-parser was a low-level macro:
; (define-macro ssax:make-pi-parser
; (lambda (my-pi-handlers)
; `(lambda (port target seed)
; (case target
; ; Generate the body of the case statement
; ,@(let loop ((pi-handlers my-pi-handlers) (default #f))
; (cond
; ((null? pi-handlers)
; (if default `((else (,default port target seed)))
; '((else
; (ssax:warn port "Skipping PI: " target nl)
; (ssax:skip-pi port)
; seed))))
; ((eq? '*DEFAULT* (caar pi-handlers))
; (loop (cdr pi-handlers) (cdar pi-handlers)))
; (else
; (cons
; `((,(caar pi-handlers)) (,(cdar pi-handlers) port target seed))
; (loop (cdr pi-handlers) default)))))))))
(define-syntax ssax:make-pi-parser
(syntax-rules ()
((ssax:make-pi-parser orig-handlers)
(letrec-syntax
; Generate the clauses of the case statement
((loop
(syntax-rules (*DEFAULT*)
((loop () #f accum port target seed) ; no default
(make-case
((else
(ssax:warn port "Skipping PI: " target nl)
(ssax:skip-pi port)
seed)
. accum)
() target))
((loop () default accum port target seed)
(make-case
((else (default port target seed)) . accum)
() target))
((loop ((*DEFAULT* . default) . handlers) old-def accum
port target seed)
(loop handlers default accum port target seed))
((loop ((tag . handler) . handlers) default accum port target seed)
(loop handlers default
(((tag) (handler port target seed)) . accum)
port target seed))
))
(make-case ; Reverse the clauses, make the 'case'
(syntax-rules ()
((make-case () clauses target)
(case target . clauses))
((make-case (clause . clauses) accum target)
(make-case clauses (clause . accum) target)))
))
(lambda (port target seed)
(loop orig-handlers #f () port target seed))
))))
(run-test
(pp (ssax:make-pi-parser ()))
(pp (ssax:make-pi-parser ((xml . (lambda (port target seed) seed)))))
(pp (ssax:make-pi-parser ((xml . (lambda (port target seed) seed))
(html . list)
(*DEFAULT* . ssax:warn))))
)
; syntax: ssax:make-elem-parser my-new-level-seed my-finish-element
; my-char-data-handler my-pi-handlers
; Create a parser to parse and process one element, including its
; character content or children elements. The parser is typically
; applied to the root element of a document.
; my-new-level-seed
; procedure ELEM-GI ATTRIBUTES NAMESPACES EXPECTED-CONTENT SEED
; where ELEM-GI is a RES-NAME of the element
; about to be processed.
; This procedure is to generate the seed to be passed
; to handlers that process the content of the element.
; This is the function identified as 'fdown' in the denotational
; semantics of the XML parser given in the title comments to this
; file.
;
; my-finish-element
; procedure ELEM-GI ATTRIBUTES NAMESPACES PARENT-SEED SEED
; This procedure is called when parsing of ELEM-GI is finished.
; The SEED is the result from the last content parser (or
; from my-new-level-seed if the element has the empty content).
; PARENT-SEED is the same seed as was passed to my-new-level-seed.
; The procedure is to generate a seed that will be the result
; of the element parser.
; This is the function identified as 'fup' in the denotational
; semantics of the XML parser given in the title comments to this
; file.
;
; my-char-data-handler
; A STR-HANDLER
;
; my-pi-handlers
; See ssax:make-pi-handler above
;
; The generated parser is a
; procedure START-TAG-HEAD PORT ELEMS ENTITIES
; NAMESPACES PRESERVE-WS? SEED
; The procedure must be called after the start tag token has been
; read. START-TAG-HEAD is an UNRES-NAME from the start-element tag.
; ELEMS is an instance of xml-decl::elems.
; See ssax:complete-start-tag::preserve-ws?
; Faults detected:
; VC: XML-Spec.html#elementvalid
; WFC: XML-Spec.html#GIMatch
(define-syntax ssax:make-elem-parser
(syntax-rules ()
((ssax:make-elem-parser my-new-level-seed my-finish-element
my-char-data-handler my-pi-handlers)
(lambda (start-tag-head port elems entities namespaces
preserve-ws? seed)
(define xml-space-gi (cons ssax:Prefix-XML
(string->symbol "space")))
(let handle-start-tag ((start-tag-head start-tag-head)
(port port) (entities entities)
(namespaces namespaces)
(preserve-ws? preserve-ws?) (parent-seed seed))
(let*-values
(((elem-gi attributes namespaces expected-content)
(ssax:complete-start-tag start-tag-head port elems
entities namespaces))
((seed)
(my-new-level-seed elem-gi attributes
namespaces expected-content parent-seed)))
(case expected-content
((EMPTY-TAG)
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
((EMPTY) ; The end tag must immediately follow
(ssax:assert-token
(and (eqv? #\< (ssax:skip-S port)) (ssax:read-markup-token port))
'END start-tag-head
(lambda (token exp-kind exp-head)
(parser-error port "[elementvalid] broken for " token
" while expecting "
exp-kind exp-head)))
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
(else ; reading the content...
(let ((preserve-ws? ; inherit or set the preserve-ws? flag
(cond
((assoc xml-space-gi attributes) =>
(lambda (name-value)
(equal? "preserve" (cdr name-value))))
(else preserve-ws?))))
(let loop ((port port) (entities entities)
(expect-eof? #f) (seed seed))
(let*-values
(((seed term-token)
(ssax:read-char-data port expect-eof?
my-char-data-handler seed)))
(if (eof-object? term-token)
seed
(case (xml-token-kind term-token)
((END)
(ssax:assert-token term-token 'END start-tag-head
(lambda (token exp-kind exp-head)
(parser-error port "[GIMatch] broken for "
term-token " while expecting "
exp-kind exp-head)))
(my-finish-element
elem-gi attributes namespaces parent-seed seed))
((PI)
(let ((seed
((ssax:make-pi-parser my-pi-handlers)
port (xml-token-head term-token) seed)))
(loop port entities expect-eof? seed)))
((ENTITY-REF)
(let ((seed
(ssax:handle-parsed-entity
port (xml-token-head term-token)
entities
(lambda (port entities seed)
(loop port entities #t seed))
my-char-data-handler
seed))) ; keep on reading the content after ent
(loop port entities expect-eof? seed)))
((START) ; Start of a child element
(if (eq? expected-content 'PCDATA)
(parser-error port "[elementvalid] broken for "
elem-gi
" with char content only; unexpected token "
term-token))
; Do other validation of the element content
(let ((seed
(handle-start-tag
(xml-token-head term-token)
port entities namespaces
preserve-ws? seed)))
(loop port entities expect-eof? seed)))
(else
(parser-error port "XML [43] broken for "
term-token))))))))
)))
))))
; syntax: ssax:make-parser user-handler-tag user-handler-proc ...
;
; Create an XML parser, an instance of the XML parsing framework.
; This will be a SAX, a DOM, or a specialized parser depending
; on the supplied user-handlers.
; user-handler-tag is a symbol that identifies a procedural expression
; that follows the tag. Given below are tags and signatures of the
; corresponding procedures. Not all tags have to be specified. If some
; are omitted, reasonable defaults will apply.
;
; tag: DOCTYPE
; handler-procedure: PORT DOCNAME SYSTEMID INTERNAL-SUBSET? SEED
; If internal-subset? is #t, the current position in the port
; is right after we have read #\[ that begins the internal DTD subset.
; We must finish reading of this subset before we return
; (or must call skip-internal-subset if we aren't interested in reading it).
; The port at exit must be at the first symbol after the whole
; DOCTYPE declaration.
; The handler-procedure must generate four values:
; ELEMS ENTITIES NAMESPACES SEED
; See xml-decl::elems for ELEMS. It may be #f to switch off the validation.
; NAMESPACES will typically contain USER-PREFIXes for selected URI-SYMBs.
; The default handler-procedure skips the internal subset,
; if any, and returns (values #f '() '() seed)
; tag: UNDECL-ROOT
; handler-procedure: ELEM-GI SEED
; where ELEM-GI is an UNRES-NAME of the root element. This procedure
; is called when an XML document under parsing contains _no_ DOCTYPE
; declaration.
; The handler-procedure, as a DOCTYPE handler procedure above,
; must generate four values:
; ELEMS ENTITIES NAMESPACES SEED
; The default handler-procedure returns (values #f '() '() seed)
; tag: DECL-ROOT
; handler-procedure: ELEM-GI SEED
; where ELEM-GI is an UNRES-NAME of the root element. This procedure
; is called when an XML document under parsing does contains the DOCTYPE
; declaration.
; The handler-procedure must generate a new SEED (and verify
; that the name of the root element matches the doctype, if the handler
; so wishes).
; The default handler-procedure is the identity function.
; tag: NEW-LEVEL-SEED
; handler-procedure: see ssax:make-elem-parser, my-new-level-seed
; tag: FINISH-ELEMENT
; handler-procedure: see ssax:make-elem-parser, my-finish-element
; tag: CHAR-DATA-HANDLER
; handler-procedure: see ssax:make-elem-parser, my-char-data-handler
; tag: PI
; handler-procedure: see ssax:make-pi-parser
; The default value is '()
; The generated parser is a
; procedure PORT SEED
; This procedure parses the document prolog and then exits to
; an element parser (created by ssax:make-elem-parser) to handle
; the rest.
;
; [1] document ::= prolog element Misc*
; [22] prolog ::= XMLDecl? Misc* (doctypedec | Misc*)?
; [27] Misc ::= Comment | PI | S
;
; [28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S?
; ('[' (markupdecl | PEReference | S)* ']' S?)? '>'
; [29] markupdecl ::= elementdecl | AttlistDecl
; | EntityDecl
; | NotationDecl | PI
; | Comment
;
; This is ssax:make-parser with all the (specialization) handlers given
; as positional arguments. It is called by ssax:make-parser, see below
(define-syntax ssax:make-parser/positional-args
(syntax-rules ()
((ssax:make-parser/positional-args
*handler-DOCTYPE
*handler-UNDECL-ROOT
*handler-DECL-ROOT
*handler-NEW-LEVEL-SEED
*handler-FINISH-ELEMENT
*handler-CHAR-DATA-HANDLER
*handler-PI)
(lambda (port seed)
; We must've just scanned the DOCTYPE token
; Handle the doctype declaration and exit to
; scan-for-significant-prolog-token-2, and eventually, to the
; element parser.
(define (handle-decl port token-head seed)
(or (eq? (string->symbol "DOCTYPE") token-head)
(parser-error port "XML [22], expected DOCTYPE declaration, found "
token-head))
(assert-curr-char ssax:S-chars "XML [28], space after DOCTYPE" port)
(ssax:skip-S port)
(let*-values
(((docname) (ssax:read-QName port))
((systemid)
(and (ssax:ncname-starting-char? (ssax:skip-S port))
(ssax:read-external-id port)))
((internal-subset?)
(begin (ssax:skip-S port)
(eqv? #\[ (assert-curr-char '(#\> #\[)
"XML [28], end-of-DOCTYPE" port))))
((elems entities namespaces seed)
(*handler-DOCTYPE port docname systemid
internal-subset? seed))
)
(scan-for-significant-prolog-token-2 port elems entities namespaces
seed)))
; Scan the leading PIs until we encounter either a doctype declaration
; or a start token (of the root element)
; In the latter two cases, we exit to the appropriate continuation
(define (scan-for-significant-prolog-token-1 port seed)
(let ((token (ssax:scan-Misc port)))
(if (eof-object? token)
(parser-error port "XML [22], unexpected EOF")
(case (xml-token-kind token)
((PI)
(let ((seed
((ssax:make-pi-parser *handler-PI)
port (xml-token-head token) seed)))
(scan-for-significant-prolog-token-1 port seed)))
((DECL) (handle-decl port (xml-token-head token) seed))
((START)
(let*-values
(((elems entities namespaces seed)
(*handler-UNDECL-ROOT (xml-token-head token) seed)))
(element-parser (xml-token-head token) port elems
entities namespaces #f seed)))
(else (parser-error port "XML [22], unexpected markup "
token))))))
; Scan PIs after the doctype declaration, till we encounter
; the start tag of the root element. After that we exit
; to the element parser
(define (scan-for-significant-prolog-token-2 port elems entities
namespaces seed)
(let ((token (ssax:scan-Misc port)))
(if (eof-object? token)
(parser-error port "XML [22], unexpected EOF")
(case (xml-token-kind token)
((PI)
(let ((seed
((ssax:make-pi-parser *handler-PI)
port (xml-token-head token) seed)))
(scan-for-significant-prolog-token-2 port elems entities
namespaces seed)))
((START)
(element-parser (xml-token-head token) port elems
entities namespaces #f
(*handler-DECL-ROOT (xml-token-head token) seed)))
(else (parser-error port "XML [22], unexpected markup "
token))))))
; A procedure start-tag-head port elems entities namespaces
; preserve-ws? seed
(define element-parser
(ssax:make-elem-parser *handler-NEW-LEVEL-SEED
*handler-FINISH-ELEMENT
*handler-CHAR-DATA-HANDLER
*handler-PI))
; Get the ball rolling ...
(scan-for-significant-prolog-token-1 port seed)
))))
; The following meta-macro turns a regular macro (with positional
; arguments) into a form with keyword (labeled) arguments. We later
; use the meta-macro to convert ssax:make-parser/positional-args into
; ssax:make-parser. The latter provides a prettier (with labeled
; arguments and defaults) interface to
; ssax:make-parser/positional-args
;
; ssax:define-labeled-arg-macro LABELED-ARG-MACRO-NAME
; (POS-MACRO-NAME ARG-DESCRIPTOR ...)
; expands into the definition of a macro
; LABELED-ARG-MACRO-NAME KW-NAME KW-VALUE KW-NAME1 KW-VALUE1 ...
; which, in turn, expands into
; POS-MACRO-NAME ARG1 ARG2 ...
; where each ARG1 etc. comes either from KW-VALUE or from
; the deafult part of ARG-DESCRIPTOR. ARG1 corresponds to the first
; ARG-DESCRIPTOR, ARG2 corresponds to the second descriptor, etc.
; Here ARG-DESCRIPTOR describes one argument of the positional macro.
; It has the form
; (ARG-NAME DEFAULT-VALUE)
; or
; (ARG-NAME)
; In the latter form, the default value is not given, so that the invocation of
; LABELED-ARG-MACRO-NAME must mention the corresponding parameter.
; ARG-NAME can be anything: an identifier, a string, or even a number.
(define-syntax ssax:define-labeled-arg-macro
(syntax-rules ()
((ssax:define-labeled-arg-macro
labeled-arg-macro-name
(positional-macro-name
(arg-name . arg-def) ...))
(define-syntax labeled-arg-macro-name
(syntax-rules ()
((labeled-arg-macro-name . kw-val-pairs)
(letrec-syntax
((find
(syntax-rules (arg-name ...)
((find k-args (arg-name . default) arg-name
val . others) ; found arg-name among kw-val-pairs
(next val . k-args)) ...
((find k-args key arg-no-match-name val . others)
(find k-args key . others))
((find k-args (arg-name default)) ; default must be here
(next default . k-args)) ...
))
(next ; pack the continuation to find
(syntax-rules ()
((next val vals key . keys)
(find ((val . vals) . keys) key . kw-val-pairs))
((next val vals) ; processed all arg-descriptors
(rev-apply (val) vals))))
(rev-apply
(syntax-rules ()
((rev-apply form (x . xs))
(rev-apply (x . form) xs))
((rev-apply form ()) form))))
(next positional-macro-name ()
(arg-name . arg-def) ...))))))))
; The definition of ssax:make-parser
(ssax:define-labeled-arg-macro ssax:make-parser
(ssax:make-parser/positional-args
(DOCTYPE
(lambda (port docname systemid internal-subset? seed)
(when internal-subset?
(ssax:warn port "Internal DTD subset is not currently handled ")
(ssax:skip-internal-dtd port))
(ssax:warn port "DOCTYPE DECL " docname " "
systemid " found and skipped")
(values #f '() '() seed)
))
(UNDECL-ROOT
(lambda (elem-gi seed) (values #f '() '() seed)))
(DECL-ROOT
(lambda (elem-gi seed) seed))
(NEW-LEVEL-SEED) ; required
(FINISH-ELEMENT) ; required
(CHAR-DATA-HANDLER) ; required
(PI ())
))
(run-test
(letrec ((simple-parser
(lambda (str doctype-fn)
(call-with-input-string str
(lambda (port)
((ssax:make-parser
NEW-LEVEL-SEED
(lambda (elem-gi attributes namespaces
expected-content seed)
'())
FINISH-ELEMENT
(lambda (elem-gi attributes namespaces parent-seed seed)
(let
((seed (if (null? namespaces) (reverse seed)
(cons (list '*NAMESPACES* namespaces)
(reverse seed)))))
(let ((seed (if (attlist-null? attributes) seed
(cons
(cons '@
(map (lambda (attr)
(list (car attr) (cdr attr)))
(attlist->alist attributes)))
seed))))
(cons (cons elem-gi seed) parent-seed))))
CHAR-DATA-HANDLER
(lambda (string1 string2 seed)
(if (string-null? string2) (cons string1 seed)
(cons* string2 string1 seed)))
DOCTYPE
(lambda (port docname systemid internal-subset? seed)
(when internal-subset?
(ssax:warn port
"Internal DTD subset is not currently handled ")
(ssax:skip-internal-dtd port))
(ssax:warn port "DOCTYPE DECL " docname " "
systemid " found and skipped")
(doctype-fn docname seed))
UNDECL-ROOT
(lambda (elem-gi seed)
(doctype-fn elem-gi seed))
)
port '())))))
(dummy-doctype-fn (lambda (elem-gi seed) (values #f '() '() seed)))
(test
(lambda (str doctype-fn expected)
(cout nl "Parsing: " str nl)
(let ((result (simple-parser (unesc-string str) doctype-fn)))
(write result)
(assert (equal? result expected)))))
)
(test "<BR/>" dummy-doctype-fn '(('"BR")))
(assert (failed? (test "<BR>" dummy-doctype-fn '())))
(test "<BR></BR>" dummy-doctype-fn '(('"BR")))
(assert (failed? (test "<BR></BB>" dummy-doctype-fn '())))
(test " <A HREF='URL'> link <I>itlink </I> &amp;</A>"
dummy-doctype-fn
'(('"A" (@ ('"HREF" "URL")) " link " ('"I" "itlink ")
" " "&" "amp;")))
(test
" <A HREF='URL' xml:space='preserve'> link <I>itlink </I> &amp;</A>" dummy-doctype-fn
'(('"A" (@ ('"HREF" "URL") (('"xml" . '"space") "preserve"))
" link " ('"I" "itlink ") " " "&" "amp;")))
(test " <A HREF='URL' xml:space='preserve'> link <I xml:space='default'>itlink </I> &amp;</A>" dummy-doctype-fn
'(('"A" (@ ('"HREF" "URL") (('"xml" . '"space") "preserve"))
" link "
('"I" (@ (('"xml" . '"space") "default")) "itlink ")
" " "&" "amp;")))
(test "<itemize><item>This is item 1 </item>%n<!-- Just:a comment --><item>Item 2</item>%n </itemize>" dummy-doctype-fn
`(('"itemize" ('"item" "This is item 1 ")
,(unesc-string "%n") ('"item" "Item 2") ,(unesc-string "%n "))))
(test " <P><![CDATA[<BR>%n<![CDATA[<BR>]]>]]></P>"
dummy-doctype-fn `(('"P" "<BR>" ,nl "<![CDATA[<BR>" "]]" "" ">")))
(test " <P><![CDATA[<BR>%r<![CDATA[<BR>]]>]]></P>"
dummy-doctype-fn `(('"P" "<BR>" ,nl "<![CDATA[<BR>" "]]" "" ">")))
(test "<?xml version='1.0'?>%n%n<Reports TStamp='1'></Reports>"
dummy-doctype-fn '(('"Reports" (@ ('"TStamp" "1")))))
(test "%n<?PI xxx?><!-- Comment %n -%r-->%n<?PI1 zzz?><T/>"
dummy-doctype-fn '(('"T")))
(test "<!DOCTYPE T SYSTEM 'system1' ><!-- comment -->%n<T/>"
(lambda (elem-gi seed) (assert (equal? elem-gi ''"T"))
(values #f '() '() seed))
'(('"T")))
(test "<!DOCTYPE T PUBLIC '//EN/T' \"system1\" [ <!ELEMENT a 'aa'> ]>%n<?pi?><T/>"
(lambda (elem-gi seed) (assert (equal? elem-gi ''"T"))
(values #f '() '() seed))
'(('"T")))
(test "<BR/>"
(lambda (elem-gi seed)
(values '(('"BR" EMPTY ())) '() '() seed)) '(('"BR")))
(test "<BR></BR>"
(lambda (elem-gi seed)
(values '(('"BR" EMPTY ())) '() '() seed)) '(('"BR")))
(assert (failed? (test "<BR>aa</BR>"
(lambda (elem-gi seed)
(values '(('"BR" EMPTY ())) '() '() seed)) '())))
(test "<BR>aa</BR>"
(lambda (elem-gi seed)
(values '(('"BR" PCDATA ())) '() '() seed)) '(('"BR" "aa")))
(assert (failed? (test "<BR>a<I>a</I></BR>"
(lambda (elem-gi seed)
(values '(('"BR" PCDATA ())) '() '() seed)) '())))
(test "<BR>a<I>a</I></BR>"
(lambda (elem-gi seed)
(values '(('"BR" ANY ()) ('"I" PCDATA ())) '() '() seed))
'(('"BR" "a" ('"I" "a"))))
(test "<DIV>Example: \"&example;\"</DIV>"
(lambda (elem-gi seed)
(values #f '((example . "<P>An ampersand (&) may be escaped numerically (&#38;) or with a general entity (&amp;).</P>")) '() seed))
'(('"DIV" "Example: \""
('"P" "An ampersand (" "&" ") may be escaped numerically (" "&" "#38;) or with a general entity (" "&" "amp;).") "\"")))
(test "<DIV>Example: \"&example;\" <P/></DIV>"
(lambda (elem-gi seed)
(values #f '(('"quote" . "<I>example:</I> ex")
('"example" . "<Q>"e;!</Q>?")) '() seed))
'(('"DIV" "Example: \"" ('"Q" ('"I" "example:") " ex" "!") "?"
"\" " ('"P"))))
(assert (failed?
(test "<DIV>Example: \"&example;\" <P/></DIV>"
(lambda (elem-gi seed)
(values #f '(('"quote" . "<I>example:")
('"example" . "<Q>"e;</I>!</Q>?")) '() seed))
'())))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values #f '() '() seed))
'((('"URI1" . '"DIV") (@ ('"B" "B") (('"URI1" . '"B") "A"))
(*NAMESPACES* (('"A" '"URI1" . '"URI1")
(*DEFAULT* '"URI1" . '"URI1")))
(('"URI1" . '"P")
(*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"URI1" . '"URI1")
(*DEFAULT* '"URI1" . '"URI1")))
('"BR"
(*NAMESPACES* ((*DEFAULT* #f . #f)
('"A" '"URI1" . '"URI1")
(*DEFAULT* '"URI1" . '"URI1"))))))))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values #f '() '((#f '"UA" . '"URI1")) seed))
'((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A"))
(*NAMESPACES* (('"A" '"UA" . '"URI1")
(*DEFAULT* '"UA" . '"URI1") (#f '"UA" . '"URI1")))
(('"UA" . '"P")
(*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"UA" . '"URI1")
(*DEFAULT* '"UA" . '"URI1") (#f '"UA" . '"URI1")))
('"BR"
(*NAMESPACES* ((*DEFAULT* #f . #f) ('"A" '"UA" . '"URI1")
(*DEFAULT* '"UA" . '"URI1")
(#f '"UA" . '"URI1"))))))))
; uniqattr should fail
(assert (failed?
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values
`(('"DIV" ANY (('"B" CDATA IMPLIED #f)
(('"A" . '"B") CDATA IMPLIED #f)
(('"C" . '"B") CDATA IMPLIED "xx")
(('"xmlns" . '"C") CDATA IMPLIED "URI1")
))
(('"A" . '"P") ANY ()) ('"BR" '"EMPTY" ()))
'() '((#f '"UA" . '"URI1")) seed))
'())))
; prefix C undeclared
(assert (failed?
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values
'(('"DIV" ANY (('"B" CDATA IMPLIED #f)
('"xmlns" CDATA IMPLIED "URI1")
(('"A" . '"B") CDATA IMPLIED #f)
(('"C" . '"B") CDATA IMPLIED "xx")
))
(('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
'() '((#f '"UA" . '"URI1")) seed))
'())))
; contradiction to xmlns declaration
(assert (failed?
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values
'(('"DIV" ANY (('"B" CDATA IMPLIED #f)
('"xmlns" CDATA FIXED "URI2")
(('"A" . '"B") CDATA IMPLIED #f)
))
(('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
'() '((#f '"UA" . '"URI1")) seed))
'())))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values
'(('"DIV" ANY (('"B" CDATA IMPLIED #f)
('"xmlns" CDATA FIXED "URI1")
(('"A" . '"B") CDATA IMPLIED #f)
))
(('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
'() '((#f '"UA" . '"URI1")) seed))
'((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A"))
(*NAMESPACES* ((*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1")))
(('"UA" . '"P")
(*NAMESPACES* ((*DEFAULT* #f . #f)
(*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1")))
('"BR"
(*NAMESPACES* ((*DEFAULT* #f . #f) (*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1") (#f '"UA" . '"URI1"))))))))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>"
(lambda (elem-gi seed)
(values
'(('"DIV" ANY (('"B" CDATA IMPLIED #f)
(('"A" . '"B") CDATA IMPLIED #f)
(('"C" . '"B") CDATA IMPLIED "xx")
(('"xmlns" . '"C") CDATA IMPLIED "URI2")
))
(('"A" . '"P") ANY ()) ('"BR" EMPTY ()))
'() '((#f '"UA" . '"URI1")) seed))
'((('"UA" . '"DIV") (@ ('"B" "B") (('"UA" . '"B") "A")
(('"URI2" . '"B") "xx"))
(*NAMESPACES* ((*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1")
('"C" '"URI2" . '"URI2")
(#f '"UA" . '"URI1")))
(('"UA" . '"P")
(*NAMESPACES* ((*DEFAULT* #f . #f) (*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1")
('"C" '"URI2" . '"URI2") (#f '"UA" . '"URI1")))
('"BR"
(*NAMESPACES* ((*DEFAULT* #f . #f)
(*DEFAULT* '"UA" . '"URI1")
('"A" '"UA" . '"URI1")
('"C" '"URI2" . '"URI2")
(#f '"UA" . '"URI1"))))))))
))
;========================================================================
; Highest-level parsers: XML to SXML
;
; First, a few utility procedures that turned out useful
; ssax:reverse-collect-str LIST-OF-FRAGS -> LIST-OF-FRAGS
; given the list of fragments (some of which are text strings)
; reverse the list and concatenate adjacent text strings.
; We can prove from the general case below that if LIST-OF-FRAGS
; has zero or one element, the result of the procedure is equal?
; to its argument. This fact justifies the shortcut evaluation below.
(define (ssax:reverse-collect-str fragments)
(cond
((null? fragments) '()) ; a shortcut
((null? (cdr fragments)) fragments) ; see the comment above
(else
(let loop ((fragments fragments) (result '()) (strs '()))
(cond
((null? fragments)
(if (null? strs) result
(cons (string-concatenate/shared strs) result)))
((string? (car fragments))
(loop (cdr fragments) result (cons (car fragments) strs)))
(else
(loop (cdr fragments)
(cons
(car fragments)
(if (null? strs) result
(cons (string-concatenate/shared strs) result)))
'())))))))
; ssax:reverse-collect-str-drop-ws LIST-OF-FRAGS -> LIST-OF-FRAGS
; given the list of fragments (some of which are text strings)
; reverse the list and concatenate adjacent text strings.
; We also drop "unsignificant" whitespace, that is, whitespace
; in front, behind and between elements. The whitespace that
; is included in character data is not affected.
; We use this procedure to "intelligently" drop "insignificant"
; whitespace in the parsed SXML. If the strict compliance with
; the XML Recommendation regarding the whitespace is desired, please
; use the ssax:reverse-collect-str procedure instead.
(define (ssax:reverse-collect-str-drop-ws fragments)
(cond
((null? fragments) '()) ; a shortcut
((null? (cdr fragments)) ; another shortcut
(if (and (string? (car fragments)) (string-whitespace? (car fragments)))
'() fragments)) ; remove trailing ws
(else
(let loop ((fragments fragments) (result '()) (strs '())
(all-whitespace? #t))
(cond
((null? fragments)
(if all-whitespace? result ; remove leading ws
(cons (string-concatenate/shared strs) result)))
((string? (car fragments))
(loop (cdr fragments) result (cons (car fragments) strs)
(and all-whitespace?
(string-whitespace? (car fragments)))))
(else
(loop (cdr fragments)
(cons
(car fragments)
(if all-whitespace? result
(cons (string-concatenate/shared strs) result)))
'() #t)))))))
; procedure: ssax:xml->sxml PORT NAMESPACE-PREFIX-ASSIG
;
; This is an instance of a SSAX parser above that returns an SXML
; representation of the XML document to be read from PORT.
; NAMESPACE-PREFIX-ASSIG is a list of (USER-PREFIX . URI-STRING)
; that assigns USER-PREFIXes to certain namespaces identified by
; particular URI-STRINGs. It may be an empty list.
; The procedure returns an SXML tree. The port points out to the
; first character after the root element.
(define (ssax:xml->sxml port namespace-prefix-assig)
(letrec
((namespaces
(map (lambda (el)
(cons* #f (car el) (ssax:uri-string->symbol (cdr el))))
namespace-prefix-assig))
(RES-NAME->SXML
(lambda (res-name)
(string->symbol
(string-append
(symbol->string (car res-name))
":"
(symbol->string (cdr res-name))))))
)
(let ((result
(reverse
((ssax:make-parser
NEW-LEVEL-SEED
(lambda (elem-gi attributes namespaces
expected-content seed)
'())
FINISH-ELEMENT
(lambda (elem-gi attributes namespaces parent-seed seed)
(let ((seed (ssax:reverse-collect-str seed))
(attrs
(attlist-fold
(lambda (attr accum)
(cons (list
(if (symbol? (car attr)) (car attr)
(RES-NAME->SXML (car attr)))
(cdr attr)) accum))
'() attributes)))
(cons
(cons
(if (symbol? elem-gi) elem-gi
(RES-NAME->SXML elem-gi))
(if (null? attrs) seed
(cons (cons '@ attrs) seed)))
parent-seed)))
CHAR-DATA-HANDLER
(lambda (string1 string2 seed)
(if (string-null? string2) (cons string1 seed)
(cons* string2 string1 seed)))
DOCTYPE
(lambda (port docname systemid internal-subset? seed)
(when internal-subset?
(ssax:warn port
"Internal DTD subset is not currently handled ")
(ssax:skip-internal-dtd port))
(ssax:warn port "DOCTYPE DECL " docname " "
systemid " found and skipped")
(values #f '() namespaces seed))
UNDECL-ROOT
(lambda (elem-gi seed)
(values #f '() namespaces seed))
PI
((*DEFAULT* .
(lambda (port pi-tag seed)
(cons
(list '*PI* pi-tag (ssax:read-pi-body-as-string port))
seed))))
)
port '()))))
(cons '*TOP*
(if (null? namespace-prefix-assig) result
(cons
(list '@ (cons '*NAMESPACES*
(map (lambda (ns) (list (car ns) (cdr ns)))
namespace-prefix-assig)))
result)))
)))
; For backwards compatibility
(define SSAX:XML->SXML ssax:xml->sxml)
; a few lines of validation code
(run-test (letrec
((test (lambda (str namespace-assig expected-res)
(newline) (display "input: ")
(write (unesc-string str)) (newline) (display "Result: ")
(let ((result
(call-with-input-string (unesc-string str)
(lambda (port)
(ssax:xml->sxml port namespace-assig)))))
(pp result)
(assert (equal_? result expected-res))))))
(test " <BR/>" '() '(*TOP* (BR)))
(test "<BR></BR>" '() '(*TOP* (BR)))
(test " <BR CLEAR='ALL'%nCLASS='Class1'/>" '()
'(*TOP* (BR (@ (CLEAR "ALL") (CLASS "Class1")))))
(test " <A HREF='URL'> link <I>itlink </I> &amp;</A>" '()
'(*TOP* (A (@ (HREF "URL")) " link " (I "itlink ") " &")))
(test " <A HREF='URL' xml:space='preserve'> link <I>itlink </I> &amp;</A>" '()
'(*TOP* (A (@ (xml:space "preserve") (HREF "URL"))
" link " (I "itlink ") " &")))
(test " <A HREF='URL' xml:space='preserve'> link <I xml:space='default'>itlink </I> &amp;</A>" '()
'(*TOP* (A (@ (xml:space "preserve") (HREF "URL"))
" link " (I (@ (xml:space "default"))
"itlink ") " &")))
(test " <P><?pi1 p1 content ?>?<?pi2 pi2? content? ??></P>" '()
'(*TOP* (P (*PI* pi1 "p1 content ") "?"
(*PI* pi2 "pi2? content? ?"))))
(test " <P>some text <![CDATA[<]]>1%n"<B>strong</B>"%r</P>"
'()
`(*TOP* (P ,(unesc-string "some text <1%n\"")
(B "strong") ,(unesc-string "\"%n"))))
(test " <P><![CDATA[<BR>%n<![CDATA[<BR>]]>]]></P>" '()
`(*TOP* (P ,(unesc-string "<BR>%n<![CDATA[<BR>]]>"))))
; (test "<T1><T2>it's%r%nand that%n</T2>%r%n%r%n%n</T1>" '()
; '(*TOP* (T1 (T2 "it's%nand that%n") "%n%n%n")))
(test "<T1><T2>it's%r%nand that%n</T2>%r%n%r%n%n</T1>" '()
`(*TOP* (T1 (T2 ,(unesc-string "it's%nand that%n")) ,(unesc-string "%n%n%n"))))
(test "<T1><T2>it's%rand that%n</T2>%r%n%r%n%n</T1>" '()
`(*TOP* (T1 (T2 ,(unesc-string "it's%nand that%n")) ,(unesc-string "%n%n%n"))))
(test "<!DOCTYPE T SYSTEM 'system1' ><!-- comment -->%n<T/>" '()
'(*TOP* (T)))
(test "<?xml version='1.0'?>%n<WEIGHT unit=\"pound\">%n<NET certified='certified'> 67 </NET>%n<GROSS> 95 </GROSS>%n</WEIGHT>" '()
`(*TOP* (*PI* xml "version='1.0'") (WEIGHT (@ (unit "pound"))
,nl (NET (@ (certified "certified")) " 67 ") ,nl
(GROSS " 95 ") ,nl)
))
; (test "<?xml version='1.0'?>%n<WEIGHT unit=\"pound\">%n<NET certified='certified'> 67 </NET>%n<GROSS> 95 </GROSS>%n</WEIGHT>" '()
; '(*TOP* (*PI* xml "version='1.0'") (WEIGHT (@ (unit "pound"))
; "%n" (NET (@ (certified "certified")) " 67 ")
; "%n" (GROSS " 95 ") "%n")
; ))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>" '()
'(*TOP* (URI1:DIV (@ (URI1:B "A") (B "B")) (URI1:P (BR)))))
(test "<DIV A:B='A' B='B' xmlns:A='URI1' xmlns='URI1'><A:P xmlns=''><BR/></A:P></DIV>" '((UA . "URI1"))
'(*TOP* (@ (*NAMESPACES* (UA "URI1")))
(UA:DIV (@ (UA:B "A") (B "B")) (UA:P (BR)))))
; A few tests from XML Namespaces Recommendation
(test (string-append
"<x xmlns:edi='http://ecommerce.org/schema'>"
"<!-- the 'taxClass' attribute's ns http://ecommerce.org/schema -->"
"<lineItem edi:taxClass='exempt'>Baby food</lineItem>" nl
"</x>") '()
`(*TOP*
(x (lineItem
(@ (http://ecommerce.org/schema:taxClass "exempt"))
"Baby food") ,nl)))
(test (string-append
"<x xmlns:edi='http://ecommerce.org/schema'>"
"<!-- the 'taxClass' attribute's ns http://ecommerce.org/schema -->"
"<lineItem edi:taxClass='exempt'>Baby food</lineItem>"
"</x>") '((EDI . "http://ecommerce.org/schema"))
'(*TOP*
(@ (*NAMESPACES* (EDI "http://ecommerce.org/schema")))
(x (lineItem
(@ (EDI:taxClass "exempt"))
"Baby food"))))
(test (string-append
"<bk:book xmlns:bk='urn:loc.gov:books' "
"xmlns:isbn='urn:ISBN:0-395-36341-6'>"
"<bk:title>Cheaper by the Dozen</bk:title>"
"<isbn:number>1568491379</isbn:number></bk:book>")
'()
'(*TOP* (urn:loc.gov:books:book
(urn:loc.gov:books:title "Cheaper by the Dozen")
(urn:ISBN:0-395-36341-6:number "1568491379"))))
(test (string-append
"<!-- initially, the default namespace is 'books' -->"
"<book xmlns='urn:loc.gov:books' "
"xmlns:isbn='urn:ISBN:0-395-36341-6'>"
"<title>Cheaper by the Dozen</title>"
"<isbn:number>1568491379</isbn:number>"
"<notes>"
"<!-- make HTML the default namespace for some commentary -->"
"<p xmlns='urn:w3-org-ns:HTML'>"
"This is a <i>funny</i> book!"
"</p>"
"</notes>"
"</book>") '()
'(*TOP* (urn:loc.gov:books:book
(urn:loc.gov:books:title "Cheaper by the Dozen")
(urn:ISBN:0-395-36341-6:number "1568491379")
(urn:loc.gov:books:notes
(urn:w3-org-ns:HTML:p
"This is a " (urn:w3-org-ns:HTML:i "funny")
" book!")))))
(test (string-append
"<Beers>"
"<!-- the default namespace is now that of HTML -->"
"<table xmlns='http://www.w3.org/TR/REC-html40'>"
"<th><td>Name</td><td>Origin</td><td>Description</td></th>"
"<tr>"
"<!-- no default namespace inside table cells -->"
"<td><brandName xmlns=\"\">Huntsman</brandName></td>"
"<td><origin xmlns=''>Bath, UK</origin></td>"
"<td>"
"<details xmlns=''><class>Bitter</class><hop>Fuggles</hop>"
"<pro>Wonderful hop, light alcohol, good summer beer</pro>"
"<con>Fragile; excessive variance pub to pub</con>"
"</details>"
"</td>"
"</tr>"
"</table>"
"</Beers>")
'((html . "http://www.w3.org/TR/REC-html40"))
'(*TOP*
(@ (*NAMESPACES* (html "http://www.w3.org/TR/REC-html40")))
(Beers (html:table
(html:th (html:td "Name")
(html:td "Origin")
(html:td "Description"))
(html:tr (html:td (brandName "Huntsman"))
(html:td (origin "Bath, UK"))
(html:td
(details
(class "Bitter")
(hop "Fuggles")
(pro "Wonderful hop, light alcohol, good summer beer")
(con "Fragile; excessive variance pub to pub"))))))))
(test (string-append
"<!-- 1 --><RESERVATION xmlns:HTML='http://www.w3.org/TR/REC-html40'>"
"<!-- 2 --><NAME HTML:CLASS=\"largeSansSerif\">Layman, A</NAME>"
"<!-- 3 --><SEAT CLASS='Y' HTML:CLASS=\"largeMonotype\">33B</SEAT>"
"<!-- 4 --><HTML:A HREF='/cgi-bin/ResStatus'>Check Status</HTML:A>"
"<!-- 5 --><DEPARTURE>1997-05-24T07:55:00+1</DEPARTURE></RESERVATION>")
'((HTML . "http://www.w3.org/TR/REC-html40"))
'(*TOP*
(@ (*NAMESPACES* (HTML "http://www.w3.org/TR/REC-html40")))
(RESERVATION
(NAME (@ (HTML:CLASS "largeSansSerif")) "Layman, A")
(SEAT (@ (HTML:CLASS "largeMonotype") (CLASS "Y")) "33B")
(HTML:A (@ (HREF "/cgi-bin/ResStatus")) "Check Status")
(DEPARTURE "1997-05-24T07:55:00+1"))))
; Part of RDF from the XML Infoset
(test (string-concatenate/shared '(
"<?xml version='1.0' encoding='utf-8' standalone='yes'?>"
"<!-- this can be decoded as US-ASCII or iso-8859-1 as well,"
" since it contains no characters outside the US-ASCII repertoire -->"
"<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'"
" xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#'"
" xmlns='http://www.w3.org/2001/02/infoset#'>"
"<rdfs:Class ID='Boolean'/>"
"<Boolean ID='Boolean.true'/>"
"<Boolean ID='Boolean.false'/>"
"<!--Info item classes-->"
"<rdfs:Class ID='InfoItem'/>"
"<rdfs:Class ID='Document' rdfs:subClassOf='#InfoItem'/>"
"<rdfs:Class ID='Element' rdfs:subClassOf='#InfoItem'/>"
"<rdfs:Class ID='Attribute' rdfs:subClassOf='#InfoItem'/>"
"<rdfs:Class ID='InfoItemSet'
rdfs:subClassOf='http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag'/>"
"<rdfs:Class ID='AttributeSet' rdfs:subClassOf='#InfoItemSet'/>"
"<!--Info item properties-->"
"<rdfs:Property ID='allDeclarationsProcessed'>"
"<rdfs:domain resource='#Document'/>"
"<rdfs:range resource='#Boolean'/></rdfs:Property>"
"<rdfs:Property ID='attributes'>"
"<rdfs:domain resource='#Element'/>"
"<rdfs:range resource='#AttributeSet'/>"
"</rdfs:Property>"
"</rdf:RDF>"))
'((RDF . "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(RDFS . "http://www.w3.org/2000/01/rdf-schema#")
(ISET . "http://www.w3.org/2001/02/infoset#"))
'(*TOP* (@ (*NAMESPACES*
(RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(RDFS "http://www.w3.org/2000/01/rdf-schema#")
(ISET "http://www.w3.org/2001/02/infoset#")))
(*PI* xml "version='1.0' encoding='utf-8' standalone='yes'")
(RDF:RDF
(RDFS:Class (@ (ID "Boolean")))
(ISET:Boolean (@ (ID "Boolean.true")))
(ISET:Boolean (@ (ID "Boolean.false")))
(RDFS:Class (@ (ID "InfoItem")))
(RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Document")))
(RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Element")))
(RDFS:Class (@ (RDFS:subClassOf "#InfoItem") (ID "Attribute")))
(RDFS:Class
(@ (RDFS:subClassOf
"http://www.w3.org/1999/02/22-rdf-syntax-ns#Bag")
(ID "InfoItemSet")))
(RDFS:Class
(@ (RDFS:subClassOf "#InfoItemSet") (ID "AttributeSet")))
(RDFS:Property
(@ (ID "allDeclarationsProcessed"))
(RDFS:domain (@ (resource "#Document")))
(RDFS:range (@ (resource "#Boolean"))))
(RDFS:Property
(@ (ID "attributes"))
(RDFS:domain (@ (resource "#Element")))
(RDFS:range (@ (resource "#AttributeSet")))))))
; Part of RDF from RSS of the Daemon News Mall
(test (string-concatenate/shared (list-intersperse '(
"<?xml version='1.0'?><rdf:RDF "
"xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' "
"xmlns='http://my.netscape.com/rdf/simple/0.9/'>"
"<channel>"
"<title>Daemon News Mall</title>"
"<link>http://mall.daemonnews.org/</link>"
"<description>Central source for all your BSD needs</description>"
"</channel>"
"<item>"
"<title>Daemon News Jan/Feb Issue NOW Available! Subscribe $24.95</title>"
"<link>http://mall.daemonnews.org/?page=shop/flypage&product_id=880</link>"
"</item>"
"<item>"
"<title>The Design and Implementation of the 4.4BSD Operating System $54.95</title>"
"<link>http://mall.daemonnews.org/?page=shop/flypage&product_id=912&category_id=1761</link>"
"</item>"
"</rdf:RDF>")
(string #\newline)
))
'((RDF . "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(RSS . "http://my.netscape.com/rdf/simple/0.9/")
(ISET . "http://www.w3.org/2001/02/infoset#"))
`(*TOP* (@ (*NAMESPACES*
(RDF "http://www.w3.org/1999/02/22-rdf-syntax-ns#")
(RSS "http://my.netscape.com/rdf/simple/0.9/")
(ISET "http://www.w3.org/2001/02/infoset#")))
(*PI* xml "version='1.0'")
(RDF:RDF ,nl
(RSS:channel ,nl
(RSS:title "Daemon News Mall") ,nl
(RSS:link "http://mall.daemonnews.org/") ,nl
(RSS:description "Central source for all your BSD needs") ,nl) ,nl
(RSS:item ,nl
(RSS:title
"Daemon News Jan/Feb Issue NOW Available! Subscribe $24.95") ,nl
(RSS:link
"http://mall.daemonnews.org/?page=shop/flypage&product_id=880") ,nl) ,nl
(RSS:item ,nl
(RSS:title
"The Design and Implementation of the 4.4BSD Operating System $54.95") ,nl
(RSS:link
"http://mall.daemonnews.org/?page=shop/flypage&product_id=912&category_id=1761") ,nl) ,nl)))
(test (string-concatenate/shared
'("<Forecasts TStamp='958082142'>"
"<TAF TStamp='958066200' LatLon='36.583, -121.850' BId='724915'"
" SName='KMRY, MONTEREY PENINSULA'>"
"<VALID TRange='958068000, 958154400'>111730Z 111818</VALID>"
"<PERIOD TRange='958068000, 958078800'>"
"<PREVAILING>31010KT P6SM FEW030</PREVAILING>"
"</PERIOD>"
"<PERIOD TRange='958078800, 958104000' Title='FM2100'>"
"<PREVAILING>29016KT P6SM FEW040</PREVAILING>"
"</PERIOD>"
"<PERIOD TRange='958104000, 958154400' Title='FM0400'>"
"<PREVAILING>29010KT P6SM SCT200</PREVAILING>"
"<VAR Title='BECMG 0708' TRange='958114800, 958118400'>VRB05KT</VAR>"
"</PERIOD></TAF>"
"</Forecasts>"))
'()
'(*TOP* (Forecasts
(@ (TStamp "958082142"))
(TAF (@ (TStamp "958066200")
(SName "KMRY, MONTEREY PENINSULA")
(LatLon "36.583, -121.850")
(BId "724915"))
(VALID (@ (TRange "958068000, 958154400")) "111730Z 111818")
(PERIOD (@ (TRange "958068000, 958078800"))
(PREVAILING "31010KT P6SM FEW030"))
(PERIOD (@ (Title "FM2100") (TRange "958078800, 958104000"))
(PREVAILING "29016KT P6SM FEW040"))
(PERIOD (@ (Title "FM0400") (TRange "958104000, 958154400"))
(PREVAILING "29010KT P6SM SCT200")
(VAR (@ (Title "BECMG 0708")
(TRange "958114800, 958118400"))
"VRB05KT"))))))
))
(run-test
(newline)
(display "All tests passed")
(newline)
)
; XML/HTML processing in Scheme
; SXML expression tree transformers
;
; IMPORT
; A prelude appropriate for your Scheme system
; (myenv-bigloo.scm, myenv-mit.scm, etc.)
;
; EXPORT
; (provide SRV:send-reply
; post-order pre-post-order replace-range)
;
; See vSXML-tree-trans.scm for the validation code, which also
; serves as usage examples.
;
; $Id: SXML-tree-trans.scm,v 1.6 2003/04/25 19:16:15 oleg Exp $
; Output the 'fragments'
; The fragments are a list of strings, characters,
; numbers, thunks, #f, #t -- and other fragments.
; The function traverses the tree depth-first, writes out
; strings and characters, executes thunks, and ignores
; #f and '().
; The function returns #t if anything was written at all;
; otherwise the result is #f
; If #t occurs among the fragments, it is not written out
; but causes the result of SRV:send-reply to be #t
(define (SRV:send-reply . fragments)
(let loop ((fragments fragments) (result #f))
(cond
((null? fragments) result)
((not (car fragments)) (loop (cdr fragments) result))
((null? (car fragments)) (loop (cdr fragments) result))
((eq? #t (car fragments)) (loop (cdr fragments) #t))
((pair? (car fragments))
(loop (cdr fragments) (loop (car fragments) result)))
((procedure? (car fragments))
((car fragments))
(loop (cdr fragments) #t))
(else
(display (car fragments))
(loop (cdr fragments) #t)))))
;------------------------------------------------------------------------
; Traversal of an SXML tree or a grove:
; a <Node> or a <Nodelist>
;
; A <Node> and a <Nodelist> are mutually-recursive datatypes that
; underlie the SXML tree:
; <Node> ::= (name . <Nodelist>) | "text string"
; An (ordered) set of nodes is just a list of the constituent nodes:
; <Nodelist> ::= (<Node> ...)
; Nodelists, and Nodes other than text strings are both lists. A
; <Nodelist> however is either an empty list, or a list whose head is
; not a symbol (an atom in general). A symbol at the head of a node is
; either an XML name (in which case it's a tag of an XML element), or
; an administrative name such as '@'.
; See SXPath.scm and SSAX.scm for more information on SXML.
; Pre-Post-order traversal of a tree and creation of a new tree:
; pre-post-order:: <tree> x <bindings> -> <new-tree>
; where
; <bindings> ::= (<binding> ...)
; <binding> ::= (<trigger-symbol> *preorder* . <handler>) |
; (<trigger-symbol> *macro* . <handler>) |
; (<trigger-symbol> <new-bindings> . <handler>) |
; (<trigger-symbol> . <handler>)
; <trigger-symbol> ::= XMLname | *text* | *default*
; <handler> :: <trigger-symbol> x [<tree>] -> <new-tree>
;
; The pre-post-order function visits the nodes and nodelists
; pre-post-order (depth-first). For each <Node> of the form (name
; <Node> ...) it looks up an association with the given 'name' among
; its <bindings>. If failed, pre-post-order tries to locate a
; *default* binding. It's an error if the latter attempt fails as
; well. Having found a binding, the pre-post-order function first
; checks to see if the binding is of the form
; (<trigger-symbol> *preorder* . <handler>)
; If it is, the handler is 'applied' to the current node. Otherwise,
; the pre-post-order function first calls itself recursively for each
; child of the current node, with <new-bindings> prepended to the
; <bindings> in effect. The result of these calls is passed to the
; <handler> (along with the head of the current <Node>). To be more
; precise, the handler is _applied_ to the head of the current node
; and its processed children. The result of the handler, which should
; also be a <tree>, replaces the current <Node>. If the current <Node>
; is a text string or other atom, a special binding with a symbol
; *text* is looked up.
;
; A binding can also be of a form
; (<trigger-symbol> *macro* . <handler>)
; This is equivalent to *preorder* described above. However, the result
; is re-processed again, with the current stylesheet.
(define (pre-post-order tree bindings)
(let* ((default-binding (assq '*default* bindings))
(text-binding (or (assq '*text* bindings) default-binding))
(text-handler ; Cache default and text bindings
(and text-binding
(if (procedure? (cdr text-binding))
(cdr text-binding) (cddr text-binding)))))
(let loop ((tree tree))
(cond
((null? tree) '())
((not (pair? tree))
(let ((trigger '*text*))
(if text-handler (text-handler trigger tree)
(error "Unknown binding for " trigger " and no default"))))
((not (symbol? (car tree))) (map loop tree)) ; tree is a nodelist
(else ; tree is an SXML node
(let* ((trigger (car tree))
(binding (or (assq trigger bindings) default-binding)))
(cond
((not binding)
(error "Unknown binding for " trigger " and no default"))
((not (pair? (cdr binding))) ; must be a procedure: handler
(apply (cdr binding) trigger (map loop (cdr tree))))
((eq? '*preorder* (cadr binding))
(apply (cddr binding) tree))
((eq? '*macro* (cadr binding))
(loop (apply (cddr binding) tree)))
(else ; (cadr binding) is a local binding
(apply (cddr binding) trigger
(pre-post-order (cdr tree) (append (cadr binding) bindings)))
))))))))
; post-order is a strict subset of pre-post-order without *preorder*
; (let alone *macro*) traversals.
; Now pre-post-order is actually faster than the old post-order.
; The function post-order is deprecated and is aliased below for
; backward compatibility.
(define post-order pre-post-order)
;------------------------------------------------------------------------
; Extended tree fold
; tree = atom | (node-name tree ...)
;
; foldts fdown fup fhere seed (Leaf str) = fhere seed str
; foldts fdown fup fhere seed (Nd kids) =
; fup seed $ foldl (foldts fdown fup fhere) (fdown seed) kids
; procedure fhere: seed -> atom -> seed
; procedure fdown: seed -> node -> seed
; procedure fup: parent-seed -> last-kid-seed -> node -> seed
; foldts returns the final seed
(define (foldts fdown fup fhere seed tree)
(cond
((null? tree) seed)
((not (pair? tree)) ; An atom
(fhere seed tree))
(else
(let loop ((kid-seed (fdown seed tree)) (kids (cdr tree)))
(if (null? kids)
(fup seed kid-seed tree)
(loop (foldts fdown fup fhere kid-seed (car kids))
(cdr kids)))))))
;------------------------------------------------------------------------
; Traverse a forest depth-first and cut/replace ranges of nodes.
;
; The nodes that define a range don't have to have the same immediate
; parent, don't have to be on the same level, and the end node of a
; range doesn't even have to exist. A replace-range procedure removes
; nodes from the beginning node of the range up to (but not including)
; the end node of the range. In addition, the beginning node of the
; range can be replaced by a node or a list of nodes. The range of
; nodes is cut while depth-first traversing the forest. If all
; branches of the node are cut a node is cut as well. The procedure
; can cut several non-overlapping ranges from a forest.
; replace-range:: BEG-PRED x END-PRED x FOREST -> FOREST
; where
; type FOREST = (NODE ...)
; type NODE = Atom | (Name . FOREST) | FOREST
;
; The range of nodes is specified by two predicates, beg-pred and end-pred.
; beg-pred:: NODE -> #f | FOREST
; end-pred:: NODE -> #f | FOREST
; The beg-pred predicate decides on the beginning of the range. The node
; for which the predicate yields non-#f marks the beginning of the range
; The non-#f value of the predicate replaces the node. The value can be a
; list of nodes. The replace-range procedure then traverses the tree and skips
; all the nodes, until the end-pred yields non-#f. The value of the end-pred
; replaces the end-range node. The new end node and its brothers will be
; re-scanned.
; The predicates are evaluated pre-order. We do not descend into a node that
; is marked as the beginning of the range.
(define (replace-range beg-pred end-pred forest)
; loop forest keep? new-forest
; forest is the forest to traverse
; new-forest accumulates the nodes we will keep, in the reverse
; order
; If keep? is #t, keep the curr node if atomic. If the node is not atomic,
; traverse its children and keep those that are not in the skip range.
; If keep? is #f, skip the current node if atomic. Otherwise,
; traverse its children. If all children are skipped, skip the node
; as well.
(define (loop forest keep? new-forest)
(if (null? forest) (values (reverse new-forest) keep?)
(let ((node (car forest)))
(if keep?
(cond ; accumulate mode
((beg-pred node) => ; see if the node starts the skip range
(lambda (repl-branches) ; if so, skip/replace the node
(loop (cdr forest) #f
(append (reverse repl-branches) new-forest))))
((not (pair? node)) ; it's an atom, keep it
(loop (cdr forest) keep? (cons node new-forest)))
(else
(let*-values
(((node?) (symbol? (car node))) ; or is it a nodelist?
((new-kids keep?) ; traverse its children
(loop (if node? (cdr node) node) #t '())))
(loop (cdr forest) keep?
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)))))
; skip mode
(cond
((end-pred node) => ; end the skip range
(lambda (repl-branches) ; repl-branches will be re-scanned
(loop (append repl-branches (cdr forest)) #t
new-forest)))
((not (pair? node)) ; it's an atom, skip it
(loop (cdr forest) keep? new-forest))
(else
(let*-values
(((node?) (symbol? (car node))) ; or is it a nodelist?
((new-kids keep?) ; traverse its children
(loop (if node? (cdr node) node) #f '())))
(loop (cdr forest) keep?
(if (or keep? (pair? new-kids))
(cons
(if node? (cons (car node) new-kids) new-kids)
new-forest)
new-forest) ; if all kids are skipped
)))))))) ; skip the node too
(let*-values (((new-forest keep?) (loop forest #t '())))
new-forest))
; XML processing in Scheme
; SXPath -- SXML Query Language
;
; SXPath is a query language for SXML, an instance of XML Information
; set (Infoset) in the form of s-expressions. See SSAX.scm for the
; definition of SXML and more details. SXPath is also a translation into
; Scheme of an XML Path Language, XPath:
; http://www.w3.org/TR/xpath
; XPath and SXPath describe means of selecting a set of Infoset's items
; or their properties.
;
; To facilitate queries, XPath maps the XML Infoset into an explicit
; tree, and introduces important notions of a location path and a
; current, context node. A location path denotes a selection of a set of
; nodes relative to a context node. Any XPath tree has a distinguished,
; root node -- which serves as the context node for absolute location
; paths. Location path is recursively defined as a location step joined
; with a location path. A location step is a simple query of the
; database relative to a context node. A step may include expressions
; that further filter the selected set. Each node in the resulting set
; is used as a context node for the adjoining location path. The result
; of the step is a union of the sets returned by the latter location
; paths.
;
; The SXML representation of the XML Infoset (see SSAX.scm) is rather
; suitable for querying as it is. Bowing to the XPath specification,
; we will refer to SXML information items as 'Nodes':
; <Node> ::= <Element> | <attributes-coll> | <attrib>
; | "text string" | <PI>
; This production can also be described as
; <Node> ::= (name . <Nodeset>) | "text string"
; An (ordered) set of nodes is just a list of the constituent nodes:
; <Nodeset> ::= (<Node> ...)
; Nodesets, and Nodes other than text strings are both lists. A
; <Nodeset> however is either an empty list, or a list whose head is not
; a symbol. A symbol at the head of a node is either an XML name (in
; which case it's a tag of an XML element), or an administrative name
; such as '@'. This uniform list representation makes processing rather
; simple and elegant, while avoiding confusion. The multi-branch tree
; structure formed by the mutually-recursive datatypes <Node> and
; <Nodeset> lends itself well to processing by functional languages.
;
; A location path is in fact a composite query over an XPath tree or
; its branch. A singe step is a combination of a projection, selection
; or a transitive closure. Multiple steps are combined via join and
; union operations. This insight allows us to _elegantly_ implement
; XPath as a sequence of projection and filtering primitives --
; converters -- joined by _combinators_. Each converter takes a node
; and returns a nodeset which is the result of the corresponding query
; relative to that node. A converter can also be called on a set of
; nodes. In that case it returns a union of the corresponding queries over
; each node in the set. The union is easily implemented as a list
; append operation as all nodes in a SXML tree are considered
; distinct, by XPath conventions. We also preserve the order of the
; members in the union. Query combinators are high-order functions:
; they take converter(s) (which is a Node|Nodeset -> Nodeset function)
; and compose or otherwise combine them. We will be concerned with
; only relative location paths [XPath]: an absolute location path is a
; relative path applied to the root node.
;
; Similarly to XPath, SXPath defines full and abbreviated notations
; for location paths. In both cases, the abbreviated notation can be
; mechanically expanded into the full form by simple rewriting
; rules. In case of SXPath the corresponding rules are given as
; comments to a sxpath function, below. The regression test suite at
; the end of this file shows a representative sample of SXPaths in
; both notations, juxtaposed with the corresponding XPath
; expressions. Most of the samples are borrowed literally from the
; XPath specification, while the others are adjusted for our running
; example, tree1.
;
; To do:
; Rename filter to node-filter or ns-filter
; Use ;=== for chapters, ;--- for sections, and ;^^^ for end sections
;
; $Id: SXPath-old.scm,v 1.4 2004/07/07 16:02:31 sperber Exp $
; See http://pobox.com/~oleg/ftp/Scheme/myenv.scm
; See http://pobox.com/~oleg/ftp/Scheme/myenv-scm.scm
; See http://pobox.com/~oleg/ftp/Scheme/myenv-bigloo.scm
;(module SXPath
; (include "myenv-bigloo.scm")) ; For use with Bigloo 2.2b
;(load "myenv-scm.scm") ; For use with SCM v5d2
;(include "myenv.scm") ; For use with Gambit-C 3.0
(define (nodeset? x)
(or (and (pair? x) (not (symbol? (car x)))) (null? x)))
;-------------------------
; Basic converters and applicators
; A converter is a function
; type Converter = Node|Nodeset -> Nodeset
; A converter can also play a role of a predicate: in that case, if a
; converter, applied to a node or a nodeset, yields a non-empty
; nodeset, the converter-predicate is deemed satisfied. Throughout
; this file a nil nodeset is equivalent to #f in denoting a failure.
; The following function implements a 'Node test' as defined in
; Sec. 2.3 of XPath document. A node test is one of the components of a
; location step. It is also a converter-predicate in SXPath.
;
; The function node-typeof? takes a type criterion and returns a function,
; which, when applied to a node, will tell if the node satisfies
; the test.
; node-typeof? :: Crit -> Node -> Boolean
;
; The criterion 'crit' is a symbol, one of the following:
; id - tests if the Node has the right name (id)
; @ - tests if the Node is an <attributes-coll>
; * - tests if the Node is an <Element>
; *text* - tests if the Node is a text node
; *PI* - tests if the Node is a PI node
; *any* - #t for any type of Node
(define (node-typeof? crit)
(lambda (node)
(case crit
((*) (and (pair? node) (not (memq (car node) '(@ *PI*)))))
((*any*) #t)
((*text*) (string? node))
(else
(and (pair? node) (eq? crit (car node))))
)))
; Curried equivalence converter-predicates
(define (node-eq? other)
(lambda (node)
(eq? other node)))
(define (node-equal? other)
(lambda (node)
(equal? other node)))
; node-pos:: N -> Nodeset -> Nodeset, or
; node-pos:: N -> Converter
; Select the N'th element of a Nodeset and return as a singular Nodeset;
; Return an empty nodeset if the Nth element does not exist.
; ((node-pos 1) Nodeset) selects the node at the head of the Nodeset,
; if exists; ((node-pos 2) Nodeset) selects the Node after that, if
; exists.
; N can also be a negative number: in that case the node is picked from
; the tail of the list.
; ((node-pos -1) Nodeset) selects the last node of a non-empty nodeset;
; ((node-pos -2) Nodeset) selects the last but one node, if exists.
(define (node-pos n)
(lambda (nodeset)
(cond
((not (nodeset? nodeset)) '())
((null? nodeset) nodeset)
((eqv? n 1) (list (car nodeset)))
((negative? n) ((node-pos (+ n 1 (length nodeset))) nodeset))
(else
(assert (positive? n))
((node-pos (dec n)) (cdr nodeset))))))
; filter:: Converter -> Converter
; A filter applicator, which introduces a filtering context. The argument
; converter is considered a predicate, with either #f or nil result meaning
; failure.
(define (filter pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))) (res '()))
(if (null? lst)
(reverse res)
(let ((pred-result (pred? (car lst))))
(loop (cdr lst)
(if (and pred-result (not (null? pred-result)))
(cons (car lst) res)
res)))))))
; take-until:: Converter -> Converter, or
; take-until:: Pred -> Node|Nodeset -> Nodeset
; Given a converter-predicate and a nodeset, apply the predicate to
; each element of the nodeset, until the predicate yields anything but #f or
; nil. Return the elements of the input nodeset that have been processed
; till that moment (that is, which fail the predicate).
; take-until is a variation of the filter above: take-until passes
; elements of an ordered input set till (but not including) the first
; element that satisfies the predicate.
; The nodeset returned by ((take-until (not pred)) nset) is a subset --
; to be more precise, a prefix -- of the nodeset returned by
; ((filter pred) nset)
(define (take-until pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))))
(if (null? lst) lst
(let ((pred-result (pred? (car lst))))
(if (and pred-result (not (null? pred-result)))
'()
(cons (car lst) (loop (cdr lst)))))
))))
; take-after:: Converter -> Converter, or
; take-after:: Pred -> Node|Nodeset -> Nodeset
; Given a converter-predicate and a nodeset, apply the predicate to
; each element of the nodeset, until the predicate yields anything but #f or
; nil. Return the elements of the input nodeset that have not been processed:
; that is, return the elements of the input nodeset that follow the first
; element that satisfied the predicate.
; take-after along with take-until partition an input nodeset into three
; parts: the first element that satisfies a predicate, all preceding
; elements and all following elements.
(define (take-after pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))))
(if (null? lst) lst
(let ((pred-result (pred? (car lst))))
(if (and pred-result (not (null? pred-result)))
(cdr lst)
(loop (cdr lst))))
))))
; Apply proc to each element of lst and return the list of results.
; if proc returns a nodeset, splice it into the result
;
; From another point of view, map-union is a function Converter->Converter,
; which places an argument-converter in a joining context.
(define (map-union proc lst)
(if (null? lst) lst
(let ((proc-res (proc (car lst))))
((if (nodeset? proc-res) append cons)
proc-res (map-union proc (cdr lst))))))
; node-reverse :: Converter, or
; node-reverse:: Node|Nodeset -> Nodeset
; Reverses the order of nodes in the nodeset
; This basic converter is needed to implement a reverse document order
; (see the XPath Recommendation).
(define node-reverse
(lambda (node-or-nodeset)
(if (not (nodeset? node-or-nodeset)) (list node-or-nodeset)
(reverse node-or-nodeset))))
; node-trace:: String -> Converter
; (node-trace title) is an identity converter. In addition it prints out
; a node or nodeset it is applied to, prefixed with the 'title'.
; This converter is very useful for debugging.
(define (node-trace title)
(lambda (node-or-nodeset)
(cout nl "-->")
(display title)
(display " :")
(pretty-print node-or-nodeset)
node-or-nodeset))
;-------------------------
; Converter combinators
;
; Combinators are higher-order functions that transmogrify a converter
; or glue a sequence of converters into a single, non-trivial
; converter. The goal is to arrive at converters that correspond to
; XPath location paths.
;
; From a different point of view, a combinator is a fixed, named
; _pattern_ of applying converters. Given below is a complete set of
; such patterns that together implement XPath location path
; specification. As it turns out, all these combinators can be built
; from a small number of basic blocks: regular functional composition,
; map-union and filter applicators, and the nodeset union.
; select-kids:: Pred -> Node -> Nodeset
; Given a Node, return an (ordered) subset its children that satisfy
; the Pred (a converter, actually)
; select-kids:: Pred -> Nodeset -> Nodeset
; The same as above, but select among children of all the nodes in
; the Nodeset
;
; More succinctly, the signature of this function is
; select-kids:: Converter -> Converter
(define (select-kids test-pred?)
(lambda (node) ; node or node-set
(cond
((null? node) node)
((not (pair? node)) '()) ; No children
((symbol? (car node))
((filter test-pred?) (cdr node))) ; it's a single node
(else (map-union (select-kids test-pred?) node)))))
; node-self:: Pred -> Node -> Nodeset, or
; node-self:: Converter -> Converter
; Similar to select-kids but apply to the Node itself rather
; than to its children. The resulting Nodeset will contain either one
; component, or will be empty (if the Node failed the Pred).
(define node-self filter)
; node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or
; node-join:: [Converter] -> Converter
; join the sequence of location steps or paths as described
; in the title comments above.
(define (node-join . selectors)
(lambda (nodeset) ; Nodeset or node
(let loop ((nodeset nodeset) (selectors selectors))
(if (null? selectors) nodeset
(loop
(if (nodeset? nodeset)
(map-union (car selectors) nodeset)
((car selectors) nodeset))
(cdr selectors))))))
; node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or
; node-reduce:: [Converter] -> Converter
; A regular functional composition of converters.
; From a different point of view,
; ((apply node-reduce converters) nodeset)
; is equivalent to
; (foldl apply nodeset converters)
; i.e., folding, or reducing, a list of converters with the nodeset
; as a seed.
(define (node-reduce . converters)
(lambda (nodeset) ; Nodeset or node
(let loop ((nodeset nodeset) (converters converters))
(if (null? converters) nodeset
(loop ((car converters) nodeset) (cdr converters))))))
; node-or:: [Converter] -> Converter
; This combinator applies all converters to a given node and
; produces the union of their results.
; This combinator corresponds to a union, '|' operation for XPath
; location paths.
; (define (node-or . converters)
; (lambda (node-or-nodeset)
; (if (null? converters) node-or-nodeset
; (append
; ((car converters) node-or-nodeset)
; ((apply node-or (cdr converters)) node-or-nodeset)))))
; More optimal implementation follows
(define (node-or . converters)
(lambda (node-or-nodeset)
(let loop ((result '()) (converters converters))
(if (null? converters) result
(loop (append result (or ((car converters) node-or-nodeset) '()))
(cdr converters))))))
; node-closure:: Converter -> Converter
; Select all _descendants_ of a node that satisfy a converter-predicate.
; This combinator is similar to select-kids but applies to
; grand... children as well.
; This combinator implements the "descendant::" XPath axis
; Conceptually, this combinator can be expressed as
; (define (node-closure f)
; (node-or
; (select-kids f)
; (node-reduce (select-kids (node-typeof? '*)) (node-closure f))))
; This definition, as written, looks somewhat like a fixpoint, and it
; will run forever. It is obvious however that sooner or later
; (select-kids (node-typeof? '*)) will return an empty nodeset. At
; this point further iterations will no longer affect the result and
; can be stopped.
(define (node-closure test-pred?)
(lambda (node) ; Nodeset or node
(let loop ((parent node) (result '()))
(if (null? parent) result
(loop ((select-kids (node-typeof? '*)) parent)
(append result
((select-kids test-pred?) parent)))
))))
; node-parent:: RootNode -> Converter
; (node-parent rootnode) yields a converter that returns a parent of a
; node it is applied to. If applied to a nodeset, it returns the list
; of parents of nodes in the nodeset. The rootnode does not have
; to be the root node of the whole SXML tree -- it may be a root node
; of a branch of interest.
; Given the notation of Philip Wadler's paper on semantics of XSLT,
; parent(x) = { y | y=subnode*(root), x=subnode(y) }
; Therefore, node-parent is not the fundamental converter: it can be
; expressed through the existing ones. Yet node-parent is a rather
; convenient converter. It corresponds to a parent:: axis of SXPath.
; Note that the parent:: axis can be used with an attribute node as well!
(define (node-parent rootnode)
(lambda (node) ; Nodeset or node
(if (nodeset? node) (map-union (node-parent rootnode) node)
(let ((pred
(node-or
(node-reduce
(node-self (node-typeof? '*))
(select-kids (node-eq? node)))
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-eq? node))))))
((node-or
(node-self pred)
(node-closure pred))
rootnode)))))
;-------------------------
; Evaluate an abbreviated SXPath
; sxpath:: AbbrPath -> Converter, or
; sxpath:: AbbrPath -> Node|Nodeset -> Nodeset
; AbbrPath is a list. It is translated to the full SXPath according
; to the following rewriting rules
; (sxpath '()) -> (node-join)
; (sxpath '(path-component ...)) ->
; (node-join (sxpath1 path-component) (sxpath '(...)))
; (sxpath1 '//) -> (node-or
; (node-self (node-typeof? '*any*))
; (node-closure (node-typeof? '*any*)))
; (sxpath1 '(equal? x)) -> (select-kids (node-equal? x))
; (sxpath1 '(eq? x)) -> (select-kids (node-eq? x))
; (sxpath1 ?symbol) -> (select-kids (node-typeof? ?symbol)
; (sxpath1 procedure) -> procedure
; (sxpath1 '(?symbol ...)) -> (sxpath1 '((?symbol) ...))
; (sxpath1 '(path reducer ...)) ->
; (node-reduce (sxpath path) (sxpathr reducer) ...)
; (sxpathr number) -> (node-pos number)
; (sxpathr path-filter) -> (filter (sxpath path-filter))
(define (sxpath path)
(lambda (nodeset)
(let loop ((nodeset nodeset) (path path))
(cond
((null? path) nodeset)
((nodeset? nodeset)
(map-union (sxpath path) nodeset))
((procedure? (car path))
(loop ((car path) nodeset) (cdr path)))
((eq? '// (car path))
(loop
((if (nodeset? nodeset) append cons) nodeset
((node-closure (node-typeof? '*any*)) nodeset))
(cdr path)))
((symbol? (car path))
(loop ((select-kids (node-typeof? (car path))) nodeset)
(cdr path)))
((and (pair? (car path)) (eq? 'equal? (caar path)))
(loop ((select-kids (apply node-equal? (cdar path))) nodeset)
(cdr path)))
((and (pair? (car path)) (eq? 'eq? (caar path)))
(loop ((select-kids (apply node-eq? (cdar path))) nodeset)
(cdr path)))
((pair? (car path))
(let reducer ((nodeset
(if (symbol? (caar path))
((select-kids (node-typeof? (caar path))) nodeset)
(loop nodeset (caar path))))
(reducing-path (cdar path)))
(cond
((null? reducing-path) (loop nodeset (cdr path)))
((number? (car reducing-path))
(reducer ((node-pos (car reducing-path)) nodeset)
(cdr reducing-path)))
(else
(reducer ((filter (sxpath (car reducing-path))) nodeset)
(cdr reducing-path))))))
(else
(error "Invalid path step: " (car path)))
))))
;------------------------------------------------------------------------
; Sample XPath/SXPath expressions: regression test suite for the
; implementation above.
; A running example
(define tree1
'(html
(head (title "Slides"))
(body
(p (@ (align "center"))
(table (@ (style "font-size: x-large"))
(tr
(td (@ (align "right")) "Talks ")
(td (@ (align "center")) " = ")
(td " slides + transition"))
(tr (td)
(td (@ (align "center")) " = ")
(td " data + control"))
(tr (td)
(td (@ (align "center")) " = ")
(td " programs"))))
(ul
(li (a (@ (href "slides/slide0001.gif")) "Introduction"))
(li (a (@ (href "slides/slide0010.gif")) "Summary")))
)))
; Example from a posting "Re: DrScheme and XML",
; Shriram Krishnamurthi, comp.lang.scheme, Nov. 26. 1999.
; http://www.deja.com/getdoc.xp?AN=553507805
(define tree3
'(poem (@ (title "The Lovesong of J. Alfred Prufrock")
(poet "T. S. Eliot"))
(stanza
(line "Let us go then, you and I,")
(line "When the evening is spread out against the sky")
(line "Like a patient etherized upon a table:"))
(stanza
(line "In the room the women come and go")
(line "Talking of Michaelangelo."))))
; Validation Test harness
(define-syntax run-test
(syntax-rules (define)
((run-test "scan-exp" (define vars body))
(define vars (run-test "scan-exp" body)))
((run-test "scan-exp" ?body)
(letrec-syntax
((scan-exp ; (scan-exp body k)
(syntax-rules (quote quasiquote !)
((scan-exp '() (k-head ! . args))
(k-head '() . args))
((scan-exp (quote (hd . tl)) k)
(scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
((scan-exp (quasiquote (hd . tl)) k)
(scan-lit-lst (hd . tl) (do-wrap ! quasiquote k)))
((scan-exp (quote x) (k-head ! . args))
(k-head
(if (string? (quote x)) (string->symbol (quote x)) (quote x))
. args))
((scan-exp (hd . tl) k)
(scan-exp hd (do-tl ! scan-exp tl k)))
((scan-exp x (k-head ! . args))
(k-head x . args))))
(do-tl
(syntax-rules (!)
((do-tl processed-hd fn () (k-head ! . args))
(k-head (processed-hd) . args))
((do-tl processed-hd fn old-tl k)
(fn old-tl (do-cons ! processed-hd k)))))
(do-cons
(syntax-rules (!)
((do-cons processed-tl processed-hd (k-head ! . args))
(k-head (processed-hd . processed-tl) . args))))
(do-wrap
(syntax-rules (!)
((do-wrap val fn (k-head ! . args))
(k-head (fn val) . args))))
(do-finish
(syntax-rules ()
((do-finish new-body) new-body)))
(scan-lit-lst ; scan literal list
(syntax-rules (quote unquote unquote-splicing !)
((scan-lit-lst '() (k-head ! . args))
(k-head '() . args))
((scan-lit-lst (quote (hd . tl)) k)
(do-tl quote scan-lit-lst ((hd . tl)) k))
((scan-lit-lst (unquote x) k)
(scan-exp x (do-wrap ! unquote k)))
((scan-lit-lst (unquote-splicing x) k)
(scan-exp x (do-wrap ! unquote-splicing k)))
((scan-lit-lst (quote x) (k-head ! . args))
(k-head
,(if (string? (quote x)) (string->symbol (quote x)) (quote x))
. args))
((scan-lit-lst (hd . tl) k)
(scan-lit-lst hd (do-tl ! scan-lit-lst tl k)))
((scan-lit-lst x (k-head ! . args))
(k-head x . args))))
)
(scan-exp ?body (do-finish !))))
((run-test body ...)
(begin
(run-test "scan-exp" body) ...))
))
; Overwrite the above macro to switch the tests off
; (define-macro (run-test selector node expected-result) #f)
; Location path, full form: child::para
; Location path, abbreviated form: para
; selects the para element children of the context node
(let ((tree
'(elem (@) (para (@) "para") (br (@)) "cdata" (para (@) "second par"))
)
(expected '((para (@) "para") (para (@) "second par")))
)
(run-test (select-kids (node-typeof? 'para)) tree expected)
(run-test (sxpath '(para)) tree expected)
)
; Location path, full form: child::*
; Location path, abbreviated form: *
; selects all element children of the context node
(let ((tree
'(elem (@) (para (@) "para") (br (@)) "cdata" (para "second par"))
)
(expected
'((para (@) "para") (br (@)) (para "second par")))
)
(run-test (select-kids (node-typeof? '*)) tree expected)
(run-test (sxpath '(*)) tree expected)
)
; Location path, full form: child::text()
; Location path, abbreviated form: text()
; selects all text node children of the context node
(let ((tree
'(elem (@) (para (@) "para") (br (@)) "cdata" (para "second par"))
)
(expected
'("cdata"))
)
(run-test (select-kids (node-typeof? '*text*)) tree expected)
(run-test (sxpath '(*text*)) tree expected)
)
; Location path, full form: child::node()
; Location path, abbreviated form: node()
; selects all the children of the context node, whatever their node type
(let* ((tree
'(elem (@) (para (@) "para") (br (@)) "cdata" (para "second par"))
)
(expected (cdr tree))
)
(run-test (select-kids (node-typeof? '*any*)) tree expected)
(run-test (sxpath '(*any*)) tree expected)
)
; Location path, full form: child::*/child::para
; Location path, abbreviated form: */para
; selects all para grandchildren of the context node
(let ((tree
'(elem (@) (para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para "third para")))
)
(expected
'((para "third para")))
)
(run-test
(node-join (select-kids (node-typeof? '*))
(select-kids (node-typeof? 'para)))
tree expected)
(run-test (sxpath '(* para)) tree expected)
)
; Location path, full form: attribute::name
; Location path, abbreviated form: @name
; selects the 'name' attribute of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para (@) "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
'((name "elem")))
)
(run-test
(node-join (select-kids (node-typeof? '@))
(select-kids (node-typeof? 'name)))
tree expected)
(run-test (sxpath '(@ name)) tree expected)
)
; Location path, full form: attribute::*
; Location path, abbreviated form: @*
; selects all the attributes of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
'((name "elem") (id "idz")))
)
(run-test
(node-join (select-kids (node-typeof? '@))
(select-kids (node-typeof? '*)))
tree expected)
(run-test (sxpath '(@ *)) tree expected)
)
; Location path, full form: descendant::para
; Location path, abbreviated form: .//para
; selects the para element descendants of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
'((para (@) "para") (para "second par") (para (@) "third para")))
)
(run-test
(node-closure (node-typeof? 'para))
tree expected)
(run-test (sxpath '(// para)) tree expected)
)
; Location path, full form: self::para
; Location path, abbreviated form: _none_
; selects the context node if it is a para element; otherwise selects nothing
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
)
(run-test (node-self (node-typeof? 'para)) tree '())
(run-test (node-self (node-typeof? 'elem)) tree (list tree))
)
; Location path, full form: descendant-or-self::node()
; Location path, abbreviated form: //
; selects the context node, all the children (including attribute nodes)
; of the context node, and all the children of all the (element)
; descendants of the context node.
; This is _almost_ a powerset of the context node.
(let* ((tree
'(para (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
(cons tree
(append (cdr tree)
'((@) "para" (@) "second par"
(@ (name "aa")) (para (@) "third para")
(@) "third para"))))
)
(run-test
(node-or
(node-self (node-typeof? '*any*))
(node-closure (node-typeof? '*any*)))
tree expected)
(run-test (sxpath '(//)) tree expected)
)
; Location path, full form: ancestor::div
; Location path, abbreviated form: _none_
; selects all div ancestors of the context node
; This Location expression is equivalent to the following:
; /descendant-or-self::div[descendant::node() = curr_node]
; This shows that the ancestor:: axis is actually redundant. Still,
; it can be emulated as the following SXPath expression demonstrates.
; The insight behind "ancestor::div" -- selecting all "div" ancestors
; of the current node -- is
; S[ancestor::div] context_node =
; { y | y=subnode*(root), context_node=subnode(subnode*(y)),
; isElement(y), name(y) = "div" }
; We observe that
; { y | y=subnode*(root), pred(y) }
; can be expressed in SXPath as
; ((node-or (node-self pred) (node-closure pred)) root-node)
; The composite predicate 'isElement(y) & name(y) = "div"' corresponds to
; (node-self (node-typeof? 'div)) in SXPath. Finally, filter
; context_node=subnode(subnode*(y)) is tantamount to
; (node-closure (node-eq? context-node)), whereas node-reduce denotes the
; the composition of converters-predicates in the filtering context.
(let*
((root
'(div (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para (@) "second par")
(div (@ (name "aa")) (para (@) "third para"))))
(context-node ; /descendant::any()[child::text() == "third para"]
(car
((node-closure
(select-kids
(node-equal? "third para")))
root)))
(pred
(node-reduce (node-self (node-typeof? 'div))
(node-closure (node-eq? context-node))
))
)
(run-test
(node-or
(node-self pred)
(node-closure pred))
root
(cons root
'((div (@ (name "aa")) (para (@) "third para")))))
)
; Location path, full form: child::div/descendant::para
; Location path, abbreviated form: div//para
; selects the para element descendants of the div element
; children of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")
(div (para "fourth para"))))
)
(expected
'((para (@) "third para") (para "fourth para")))
)
(run-test
(node-join
(select-kids (node-typeof? 'div))
(node-closure (node-typeof? 'para)))
tree expected)
(run-test (sxpath '(div // para)) tree expected)
)
; Location path, full form: /descendant::olist/child::item
; Location path, abbreviated form: //olist/item
; selects all the item elements that have an olist parent (which is not root)
; and that are in the same document as the context node
; See the following test.
; Location path, full form: /descendant::td/attribute::align
; Location path, abbreviated form: //td/@align
; Selects 'align' attributes of all 'td' elements in tree1
(let ((tree tree1)
(expected
'((align "right") (align "center") (align "center") (align "center"))
))
(run-test
(node-join
(node-closure (node-typeof? 'td))
(select-kids (node-typeof? '@))
(select-kids (node-typeof? 'align)))
tree expected)
(run-test (sxpath '(// td @ align)) tree expected)
)
; Location path, full form: /descendant::td[attribute::align]
; Location path, abbreviated form: //td[@align]
; Selects all td elements that have an attribute 'align' in tree1
(let ((tree tree1)
(expected
'((td (@ (align "right")) "Talks ") (td (@ (align "center")) " = ")
(td (@ (align "center")) " = ") (td (@ (align "center")) " = "))
))
(run-test
(node-reduce
(node-closure (node-typeof? 'td))
(filter
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-typeof? 'align)))))
tree expected)
(run-test (sxpath `(// td ,(node-self (sxpath '(@ align))))) tree expected)
(run-test (sxpath '(// (td (@ align)))) tree expected)
(run-test (sxpath '(// ((td) (@ align)))) tree expected)
; note! (sxpath ...) is a converter. Therefore, it can be used
; as any other converter, for example, in the full-form SXPath.
; Thus we can mix the full and abbreviated form SXPath's freely.
(run-test
(node-reduce
(node-closure (node-typeof? 'td))
(filter
(sxpath '(@ align))))
tree expected)
)
; Location path, full form: /descendant::td[attribute::align = "right"]
; Location path, abbreviated form: //td[@align = "right"]
; Selects all td elements that have an attribute align = "right" in tree1
(let ((tree tree1)
(expected
'((td (@ (align "right")) "Talks "))
))
(run-test
(node-reduce
(node-closure (node-typeof? 'td))
(filter
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-equal? '(align "right"))))))
tree expected)
(run-test (sxpath '(// (td (@ (equal? (align "right")))))) tree expected)
)
; Location path, full form: child::para[position()=1]
; Location path, abbreviated form: para[1]
; selects the first para child of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
'((para (@) "para"))
))
(run-test
(node-reduce
(select-kids (node-typeof? 'para))
(node-pos 1))
tree expected)
(run-test (sxpath '((para 1))) tree expected)
)
; Location path, full form: child::para[position()=last()]
; Location path, abbreviated form: para[last()]
; selects the last para child of the context node
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(expected
'((para "second par"))
))
(run-test
(node-reduce
(select-kids (node-typeof? 'para))
(node-pos -1))
tree expected)
(run-test (sxpath '((para -1))) tree expected)
)
; Illustrating the following Note of Sec 2.5 of XPath:
; "NOTE: The location path //para[1] does not mean the same as the
; location path /descendant::para[1]. The latter selects the first
; descendant para element; the former selects all descendant para
; elements that are the first para children of their parents."
(let ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
)
(run-test
(node-reduce ; /descendant::para[1] in SXPath
(node-closure (node-typeof? 'para))
(node-pos 1))
tree '((para (@) "para")))
(run-test (sxpath '(// (para 1))) tree
'((para (@) "para") (para (@) "third para")))
)
; Location path, full form: parent::node()
; Location path, abbreviated form: ..
; selects the parent of the context node. The context node may be
; an attribute node!
; For the last test:
; Location path, full form: parent::*/attribute::name
; Location path, abbreviated form: ../@name
; Selects the name attribute of the parent of the context node
(let* ((tree
'(elem (@ (name "elem") (id "idz"))
(para (@) "para") (br (@)) "cdata" (para "second par")
(div (@ (name "aa")) (para (@) "third para")))
)
(para1 ; the first para node
(car ((sxpath '(para)) tree)))
(para3 ; the third para node
(car ((sxpath '(div para)) tree)))
(div ; div node
(car ((sxpath '(// div)) tree)))
)
(run-test
(node-parent tree)
para1 (list tree))
(run-test
(node-parent tree)
para3 (list div))
(run-test ; checking the parent of an attribute node
(node-parent tree)
((sxpath '(@ name)) div) (list div))
(run-test
(node-join
(node-parent tree)
(select-kids (node-typeof? '@))
(select-kids (node-typeof? 'name)))
para3 '((name "aa")))
(run-test
(sxpath `(,(node-parent tree) @ name))
para3 '((name "aa")))
)
; Location path, full form: following-sibling::chapter[position()=1]
; Location path, abbreviated form: none
; selects the next chapter sibling of the context node
; The path is equivalent to
; let cnode = context-node
; in
; parent::* / child::chapter [take-after node_eq(self::*,cnode)]
; [position()=1]
(let* ((tree
'(document
(preface "preface")
(chapter (@ (id "one")) "Chap 1 text")
(chapter (@ (id "two")) "Chap 2 text")
(chapter (@ (id "three")) "Chap 3 text")
(chapter (@ (id "four")) "Chap 4 text")
(epilogue "Epilogue text")
(appendix (@ (id "A")) "App A text")
(References "References"))
)
(a-node ; to be used as a context node
(car ((sxpath '(// (chapter (@ (equal? (id "two")))))) tree)))
(expected
'((chapter (@ (id "three")) "Chap 3 text")))
)
(run-test
(node-reduce
(node-join
(node-parent tree)
(select-kids (node-typeof? 'chapter)))
(take-after (node-eq? a-node))
(node-pos 1)
)
a-node expected)
)
; preceding-sibling::chapter[position()=1]
; selects the previous chapter sibling of the context node
; The path is equivalent to
; let cnode = context-node
; in
; parent::* / child::chapter [take-until node_eq(self::*,cnode)]
; [position()=-1]
(let* ((tree
'(document
(preface "preface")
(chapter (@ (id "one")) "Chap 1 text")
(chapter (@ (id "two")) "Chap 2 text")
(chapter (@ (id "three")) "Chap 3 text")
(chapter (@ (id "four")) "Chap 4 text")
(epilogue "Epilogue text")
(appendix (@ (id "A")) "App A text")
(References "References"))
)
(a-node ; to be used as a context node
(car ((sxpath '(// (chapter (@ (equal? (id "three")))))) tree)))
(expected
'((chapter (@ (id "two")) "Chap 2 text")))
)
(run-test
(node-reduce
(node-join
(node-parent tree)
(select-kids (node-typeof? 'chapter)))
(take-until (node-eq? a-node))
(node-pos -1)
)
a-node expected)
)
; /descendant::figure[position()=42]
; selects the forty-second figure element in the document
; See the next example, which is more general.
; Location path, full form:
; child::table/child::tr[position()=2]/child::td[position()=3]
; Location path, abbreviated form: table/tr[2]/td[3]
; selects the third td of the second tr of the table
(let ((tree ((node-closure (node-typeof? 'p)) tree1))
(expected
'((td " data + control"))
))
(run-test
(node-join
(select-kids (node-typeof? 'table))
(node-reduce (select-kids (node-typeof? 'tr))
(node-pos 2))
(node-reduce (select-kids (node-typeof? 'td))
(node-pos 3)))
tree expected)
(run-test (sxpath '(table (tr 2) (td 3))) tree expected)
)
; Location path, full form:
; child::para[attribute::type='warning'][position()=5]
; Location path, abbreviated form: para[@type='warning'][5]
; selects the fifth para child of the context node that has a type
; attribute with value warning
(let ((tree
'(chapter
(para "para1")
(para (@ (type "warning")) "para 2")
(para (@ (type "warning")) "para 3")
(para (@ (type "warning")) "para 4")
(para (@ (type "warning")) "para 5")
(para (@ (type "warning")) "para 6"))
)
(expected
'((para (@ (type "warning")) "para 6"))
))
(run-test
(node-reduce
(select-kids (node-typeof? 'para))
(filter
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-equal? '(type "warning")))))
(node-pos 5))
tree expected)
(run-test (sxpath '( (((para (@ (equal? (type "warning"))))) 5 ) ))
tree expected)
(run-test (sxpath '( (para (@ (equal? (type "warning"))) 5 ) ))
tree expected)
)
; Location path, full form:
; child::para[position()=5][attribute::type='warning']
; Location path, abbreviated form: para[5][@type='warning']
; selects the fifth para child of the context node if that child has a 'type'
; attribute with value warning
(let ((tree
'(chapter
(para "para1")
(para (@ (type "warning")) "para 2")
(para (@ (type "warning")) "para 3")
(para (@ (type "warning")) "para 4")
(para (@ (type "warning")) "para 5")
(para (@ (type "warning")) "para 6"))
)
(expected
'((para (@ (type "warning")) "para 5"))
))
(run-test
(node-reduce
(select-kids (node-typeof? 'para))
(node-pos 5)
(filter
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-equal? '(type "warning"))))))
tree expected)
(run-test (sxpath '( (( (para 5)) (@ (equal? (type "warning"))))))
tree expected)
(run-test (sxpath '( (para 5 (@ (equal? (type "warning")))) ))
tree expected)
)
; Location path, full form:
; child::*[self::chapter or self::appendix]
; Location path, semi-abbreviated form: *[self::chapter or self::appendix]
; selects the chapter and appendix children of the context node
(let ((tree
'(document
(preface "preface")
(chapter (@ (id "one")) "Chap 1 text")
(chapter (@ (id "two")) "Chap 2 text")
(chapter (@ (id "three")) "Chap 3 text")
(epilogue "Epilogue text")
(appendix (@ (id "A")) "App A text")
(References "References"))
)
(expected
'((chapter (@ (id "one")) "Chap 1 text")
(chapter (@ (id "two")) "Chap 2 text")
(chapter (@ (id "three")) "Chap 3 text")
(appendix (@ (id "A")) "App A text"))
))
(run-test
(node-join
(select-kids (node-typeof? '*))
(filter
(node-or
(node-self (node-typeof? 'chapter))
(node-self (node-typeof? 'appendix)))))
tree expected)
(run-test (sxpath `(* ,(node-or (node-self (node-typeof? 'chapter))
(node-self (node-typeof? 'appendix)))))
tree expected)
)
; Location path, full form: child::chapter[child::title='Introduction']
; Location path, abbreviated form: chapter[title = 'Introduction']
; selects the chapter children of the context node that have one or more
; title children with string-value equal to Introduction
; See a similar example: //td[@align = "right"] above.
; Location path, full form: child::chapter[child::title]
; Location path, abbreviated form: chapter[title]
; selects the chapter children of the context node that have one or
; more title children
; See a similar example //td[@align] above.
(cerr nl "Example with tree3: extracting the first lines of every stanza" nl)
(let ((tree tree3)
(expected
'("Let us go then, you and I," "In the room the women come and go")
))
(run-test
(node-join
(node-closure (node-typeof? 'stanza))
(node-reduce
(select-kids (node-typeof? 'line)) (node-pos 1))
(select-kids (node-typeof? '*text*)))
tree expected)
(run-test (sxpath '(// stanza (line 1) *text*)) tree expected)
)
;
; syntax: assert ?expr ?expr ... [report: ?r-exp ?r-exp ...]
;
; If (and ?expr ?expr ...) evaluates to anything but #f, the result
; is the value of that expression.
; If (and ?expr ?expr ...) evaluates to #f, an error is reported.
; The error message will show the failed expressions, as well
; as the values of selected variables (or expressions, in general).
; The user may explicitly specify the expressions whose
; values are to be printed upon assertion failure -- as ?r-exp that
; follow the identifier 'report:'
; Typically, ?r-exp is either a variable or a string constant.
; If the user specified no ?r-exp, the values of variables that are
; referenced in ?expr will be printed upon the assertion failure.
(define-syntax assert
(syntax-rules (report\:)
((assert "doit" (expr ...) (r-exp ...))
(cond
((and expr ...) => (lambda (x) x))
(else
(error "assertion failure: ~a" (list '(and expr ...) r-exp ...)))))
((assert "collect" (expr ...))
(assert "doit" (expr ...) ()))
((assert "collect" (expr ...) report\: r-exp ...)
(assert "doit" (expr ...) (r-exp ...)))
((assert "collect" (expr ...) expr1 stuff ...)
(assert "collect" (expr ... expr1) stuff ...))
((assert stuff ...)
(assert "collect" () stuff ...))))
(define-syntax assure
(syntax-rules ()
((assure exp error-msg)
(assert exp report\: error-msg))));****************************************************************************
; Simple Parsing of input
;
; The following simple functions surprisingly often suffice to parse
; an input stream. They either skip, or build and return tokens,
; according to inclusion or delimiting semantics. The list of
; characters to expect, include, or to break at may vary from one
; invocation of a function to another. This allows the functions to
; easily parse even context-sensitive languages.
;
; EOF is generally frowned on, and thrown up upon if encountered.
; Exceptions are mentioned specifically. The list of expected characters
; (characters to skip until, or break-characters) may include an EOF
; "character", which is to be coded as symbol *eof*
;
; The input stream to parse is specified as a PORT, which is usually
; the last (and optional) argument. It defaults to the current input
; port if omitted.
;
; IMPORT
; This package relies on a function parser-error, which must be defined
; by a user of the package. The function has the following signature:
; parser-error PORT MESSAGE SPECIALISING-MSG*
; Many procedures of this package call parser-error to report a parsing
; error. The first argument is a port, which typically points to the
; offending character or its neighborhood. Most of the Scheme systems
; let the user query a PORT for the current position. MESSAGE is the
; description of the error. Other arguments supply more details about
; the problem.
; myenv.scm, myenv-bigloo.scm or a similar prelude is assumed.
; From SRFI-13, string-concatenate-reverse
; If a particular implementation lacks SRFI-13 support, please
; include the file srfi-13-local.scm
;
; $Id: input-parse.scm,v 1.7 2004/07/07 16:02:31 sperber Exp $
;------------------------------------------------------------------------
; -- procedure+: peek-next-char [PORT]
; advances to the next character in the PORT and peeks at it.
; This function is useful when parsing LR(1)-type languages
; (one-char-read-ahead).
; The optional argument PORT defaults to the current input port.
(define-opt (peek-next-char (optional (port (current-input-port))))
(read-char port)
(peek-char port))
;------------------------------------------------------------------------
; -- procedure+: assert-curr-char CHAR-LIST STRING [PORT]
; Reads a character from the PORT and looks it up
; in the CHAR-LIST of expected characters
; If the read character was found among expected, it is returned
; Otherwise, the procedure writes a nasty message using STRING
; as a comment, and quits.
; The optional argument PORT defaults to the current input port.
;
(define-opt (assert-curr-char expected-chars comment
(optional (port (current-input-port))))
(let ((c (read-char port)))
(if (memv c expected-chars) c
(parser-error port "Wrong character " c
" (0x" (if (eof-object? c) "*eof*"
(number->string (char->integer c) 16)) ") "
comment ". " expected-chars " expected"))))
; -- procedure+: skip-until CHAR-LIST [PORT]
; Reads and skips characters from the PORT until one of the break
; characters is encountered. This break character is returned.
; The break characters are specified as the CHAR-LIST. This list
; may include EOF, which is to be coded as a symbol *eof*
;
; -- procedure+: skip-until NUMBER [PORT]
; Skips the specified NUMBER of characters from the PORT and returns #f
;
; The optional argument PORT defaults to the current input port.
(define-opt (skip-until arg (optional (port (current-input-port))) )
(cond
((number? arg) ; skip 'arg' characters
(do ((i arg (dec i)))
((not (positive? i)) #f)
(if (eof-object? (read-char port))
(parser-error port "Unexpected EOF while skipping "
arg " characters"))))
(else ; skip until break-chars (=arg)
(let loop ((c (read-char port)))
(cond
((memv c arg) c)
((eof-object? c)
(if (memq '*eof* arg) c
(parser-error port "Unexpected EOF while skipping until " arg)))
(else (loop (read-char port))))))))
; -- procedure+: skip-while CHAR-LIST [PORT]
; Reads characters from the PORT and disregards them,
; as long as they are mentioned in the CHAR-LIST.
; The first character (which may be EOF) peeked from the stream
; that is NOT a member of the CHAR-LIST is returned. This character
; is left on the stream.
; The optional argument PORT defaults to the current input port.
(define-opt (skip-while skip-chars (optional (port (current-input-port))) )
(do ((c (peek-char port) (peek-char port)))
((not (memv c skip-chars)) c)
(read-char port)))
; whitespace const
;------------------------------------------------------------------------
; Stream tokenizers
; -- procedure+:
; next-token PREFIX-CHAR-LIST BREAK-CHAR-LIST [COMMENT-STRING] [PORT]
; skips any number of the prefix characters (members of the
; PREFIX-CHAR-LIST), if any, and reads the sequence of characters
; up to (but not including) a break character, one of the
; BREAK-CHAR-LIST.
; The string of characters thus read is returned.
; The break character is left on the input stream
; The list of break characters may include EOF, which is to be coded as
; a symbol *eof*. Otherwise, EOF is fatal, generating an error message
; including a specified COMMENT-STRING (if any)
;
; The optional argument PORT defaults to the current input port.
;
; Note: since we can't tell offhand how large the token being read is
; going to be, we make a guess, pre-allocate a string, and grow it by
; quanta if necessary. The quantum is always the length of the string
; before it was extended the last time. Thus the algorithm does
; a Fibonacci-type extension, which has been proven optimal.
; Note, explicit port specification in read-char, peek-char helps.
; Procedure: input-parse:init-buffer
; returns an initial buffer for next-token* procedures.
; The input-parse:init-buffer may allocate a new buffer per each invocation:
; (define (input-parse:init-buffer) (make-string 32))
; Size 32 turns out to be fairly good, on average.
; That policy is good only when a Scheme system is multi-threaded with
; preemptive scheduling, or when a Scheme system supports shared substrings.
; In all the other cases, it's better for input-parse:init-buffer to
; return the same static buffer. next-token* functions return a copy
; (a substring) of accumulated data, so the same buffer can be reused.
; We shouldn't worry about an incoming token being too large:
; next-token will use another chunk automatically. Still,
; the best size for the static buffer is to allow most of the tokens to fit in.
; Using a static buffer _dramatically_ reduces the amount of produced garbage
; (e.g., during XML parsing).
(define input-parse:init-buffer
(let ((buffer (make-string 512)))
(lambda () buffer)))
; See a better version below
(define-opt (next-token-old prefix-skipped-chars break-chars
(optional (comment "") (port (current-input-port))) )
(let* ((buffer (input-parse:init-buffer))
(curr-buf-len (string-length buffer))
(quantum curr-buf-len))
(let loop ((i 0) (c (skip-while prefix-skipped-chars port)))
(cond
((memv c break-chars) (substring buffer 0 i))
((eof-object? c)
(if (memq '*eof* break-chars)
(substring buffer 0 i) ; was EOF expected?
(parser-error port "EOF while reading a token " comment)))
(else
(if (>= i curr-buf-len) ; make space for i-th char in buffer
(begin ; -> grow the buffer by the quantum
(set! buffer (string-append buffer (make-string quantum)))
(set! quantum curr-buf-len)
(set! curr-buf-len (string-length buffer))))
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i) (peek-char port))
)))))
; A better version of next-token, which accumulates the characters
; in chunks, and later on reverse-concatenates them, using
; SRFI-13 if available.
; The overhead of copying characters is only 100% (or even smaller: bulk
; string copying might be well-optimised), compared to the (hypothetical)
; circumstance if we had known the size of the token beforehand.
; For small tokens, the code performs just as above. For large
; tokens, we expect an improvement. Note, the code also has no
; assignments.
; See next-token-comp.scm
(define-opt (next-token prefix-skipped-chars break-chars
(optional (comment "") (port (current-input-port))) )
(let outer ((buffer (input-parse:init-buffer)) (filled-buffer-l '())
(c (skip-while prefix-skipped-chars port)))
(let ((curr-buf-len (string-length buffer)))
(let loop ((i 0) (c c))
(cond
((memv c break-chars)
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))
((eof-object? c)
(if (memq '*eof* break-chars) ; was EOF expected?
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i))
(parser-error port "EOF while reading a token " comment)))
((>= i curr-buf-len)
(outer (make-string curr-buf-len)
(cons buffer filled-buffer-l) c))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i) (peek-char port))))))))
; -- procedure+: next-token-of INC-CHARSET [PORT]
; Reads characters from the PORT that belong to the list of characters
; INC-CHARSET. The reading stops at the first character which is not
; a member of the set. This character is left on the stream.
; All the read characters are returned in a string.
;
; -- procedure+: next-token-of PRED [PORT]
; Reads characters from the PORT for which PRED (a procedure of one
; argument) returns non-#f. The reading stops at the first character
; for which PRED returns #f. That character is left on the stream.
; All the results of evaluating of PRED up to #f are returned in a
; string.
;
; PRED is a procedure that takes one argument (a character
; or the EOF object) and returns a character or #f. The returned
; character does not have to be the same as the input argument
; to the PRED. For example,
; (next-token-of (lambda (c)
; (cond ((eof-object? c) #f)
; ((char-alphabetic? c) (char-downcase c))
; (else #f))))
; will try to read an alphabetic token from the current
; input port, and return it in lower case.
;
; The optional argument PORT defaults to the current input port.
;
; This procedure is similar to next-token but only it implements
; an inclusion rather than delimiting semantics.
(define-opt (next-token-of incl-list/pred
(optional (port (current-input-port))) )
(let* ((buffer (input-parse:init-buffer))
(curr-buf-len (string-length buffer)))
(if (procedure? incl-list/pred)
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (incl-list/pred (peek-char port))))
(if c
(begin
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i)))
; incl-list/pred decided it had had enough
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))))))
; incl-list/pred is a list of allowed characters
(let outer ((buffer buffer) (filled-buffer-l '()))
(let loop ((i 0))
(if (>= i curr-buf-len) ; make sure we have space
(outer (make-string curr-buf-len) (cons buffer filled-buffer-l))
(let ((c (peek-char port)))
(cond
((not (memv c incl-list/pred))
(if (null? filled-buffer-l) (substring buffer 0 i)
(string-concatenate-reverse filled-buffer-l buffer i)))
(else
(string-set! buffer i c)
(read-char port) ; move to the next char
(loop (inc i))))))))
)))
; -- procedure+: read-text-line [PORT]
; Reads one line of text from the PORT, and returns it as a string.
; A line is a (possibly empty) sequence of characters terminated
; by CR, CRLF or LF (or even the end of file).
; The terminating character (or CRLF combination) is removed from
; the input stream. The terminating character(s) is not a part
; of the return string either.
; If EOF is encountered before any character is read, the return
; value is EOF.
;
; The optional argument PORT defaults to the current input port.
(define *read-line-breaks* (list char-newline char-return '*eof*))
(define-opt (read-text-line (optional (port (current-input-port))) )
(if (eof-object? (peek-char port)) (peek-char port)
(let* ((line
(next-token '() *read-line-breaks*
"reading a line" port))
(c (read-char port))) ; must be either \n or \r or EOF
(and (eqv? c char-return) (eqv? (peek-char port) #\newline)
(read-char port)) ; skip \n that follows \r
line)))
; -- procedure+: read-string N [PORT]
; Reads N characters from the PORT, and returns them in a string.
; If EOF is encountered before N characters are read, a shorter string
; will be returned.
; If N is not positive, an empty string will be returned.
; The optional argument PORT defaults to the current input port.
(define-opt (read-string n (optional (port (current-input-port))) )
(if (not (positive? n)) ""
(let ((buffer (make-string n)))
(let loop ((i 0) (c (read-char port)))
(if (eof-object? c) (substring buffer 0 i)
(let ((i1 (inc i)))
(string-set! buffer i c)
(if (= i1 n) buffer
(loop i1 (read-char port)))))))))
;;;; (sxml xpath) -- SXPath
;;;;
;;;; Copyright (C) 2009 Free Software Foundation, Inc.
;;;; Modified 2004 by Andy Wingo <wingo at pobox dot com>.
;;;; Written 2001 by Oleg Kiselyov <oleg at pobox dot com> SXPath.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary:
;;
;;@heading SXPath: SXML Query Language
;;
;; SXPath is a query language for SXML, an instance of XML Information
;; set (Infoset) in the form of s-expressions. See @code{(sxml ssax)}
;; for the definition of SXML and more details. SXPath is also a
;; translation into Scheme of an XML Path Language,
;; @uref{http://www.w3.org/TR/xpath,XPath}. XPath and SXPath describe
;; means of selecting a set of Infoset's items or their properties.
;;
;; To facilitate queries, XPath maps the XML Infoset into an explicit
;; tree, and introduces important notions of a location path and a
;; current, context node. A location path denotes a selection of a set of
;; nodes relative to a context node. Any XPath tree has a distinguished,
;; root node -- which serves as the context node for absolute location
;; paths. Location path is recursively defined as a location step joined
;; with a location path. A location step is a simple query of the
;; database relative to a context node. A step may include expressions
;; that further filter the selected set. Each node in the resulting set
;; is used as a context node for the adjoining location path. The result
;; of the step is a union of the sets returned by the latter location
;; paths.
;;
;; The SXML representation of the XML Infoset (see SSAX.scm) is rather
;; suitable for querying as it is. Bowing to the XPath specification,
;; we will refer to SXML information items as 'Nodes':
;;@example
;; <Node> ::= <Element> | <attributes-coll> | <attrib>
;; | "text string" | <PI>
;;@end example
;; This production can also be described as
;;@example
;; <Node> ::= (name . <Nodeset>) | "text string"
;;@end example
;; An (ordered) set of nodes is just a list of the constituent nodes:
;;@example
;; <Nodeset> ::= (<Node> ...)
;;@end example
;; Nodesets, and Nodes other than text strings are both lists. A
;; <Nodeset> however is either an empty list, or a list whose head is not
;; a symbol. A symbol at the head of a node is either an XML name (in
;; which case it's a tag of an XML element), or an administrative name
;; such as '@@'. This uniform list representation makes processing rather
;; simple and elegant, while avoiding confusion. The multi-branch tree
;; structure formed by the mutually-recursive datatypes <Node> and
;; <Nodeset> lends itself well to processing by functional languages.
;;
;; A location path is in fact a composite query over an XPath tree or
;; its branch. A singe step is a combination of a projection, selection
;; or a transitive closure. Multiple steps are combined via join and
;; union operations. This insight allows us to @emph{elegantly}
;; implement XPath as a sequence of projection and filtering primitives
;; -- converters -- joined by @dfn{combinators}. Each converter takes a
;; node and returns a nodeset which is the result of the corresponding
;; query relative to that node. A converter can also be called on a set
;; of nodes. In that case it returns a union of the corresponding
;; queries over each node in the set. The union is easily implemented as
;; a list append operation as all nodes in a SXML tree are considered
;; distinct, by XPath conventions. We also preserve the order of the
;; members in the union. Query combinators are high-order functions:
;; they take converter(s) (which is a Node|Nodeset -> Nodeset function)
;; and compose or otherwise combine them. We will be concerned with only
;; relative location paths [XPath]: an absolute location path is a
;; relative path applied to the root node.
;;
;; Similarly to XPath, SXPath defines full and abbreviated notations
;; for location paths. In both cases, the abbreviated notation can be
;; mechanically expanded into the full form by simple rewriting
;; rules. In case of SXPath the corresponding rules are given as
;; comments to a sxpath function, below. The regression test suite at
;; the end of this file shows a representative sample of SXPaths in
;; both notations, juxtaposed with the corresponding XPath
;; expressions. Most of the samples are borrowed literally from the
;; XPath specification, while the others are adjusted for our running
;; example, tree1.
;;
;;; Code:
(define-module (sxml xpath)
#\use-module (ice-9 pretty-print)
#\export (nodeset? node-typeof? node-eq? node-equal? node-pos
filter take-until take-after map-union node-reverse
node-trace select-kids node-self node-join node-reduce
node-or node-closure node-parent
sxpath))
;; Upstream version:
; $Id: SXPath.scm,v 3.5 2001/01/12 23:20:35 oleg Exp oleg $
(define (nodeset? x)
(or (and (pair? x) (not (symbol? (car x)))) (null? x)))
;-------------------------
; Basic converters and applicators
; A converter is a function
; type Converter = Node|Nodeset -> Nodeset
; A converter can also play a role of a predicate: in that case, if a
; converter, applied to a node or a nodeset, yields a non-empty
; nodeset, the converter-predicate is deemed satisfied. Throughout
; this file a nil nodeset is equivalent to #f in denoting a failure.
; The following function implements a 'Node test' as defined in
; Sec. 2.3 of XPath document. A node test is one of the components of a
; location step. It is also a converter-predicate in SXPath.
;
; The function node-typeof? takes a type criterion and returns a function,
; which, when applied to a node, will tell if the node satisfies
; the test.
; node-typeof? :: Crit -> Node -> Boolean
;
; The criterion 'crit' is a symbol, one of the following:
; id - tests if the Node has the right name (id)
; @ - tests if the Node is an <attributes-coll>
; * - tests if the Node is an <Element>
; *text* - tests if the Node is a text node
; *PI* - tests if the Node is a PI node
; *any* - #t for any type of Node
(define (node-typeof? crit)
(lambda (node)
(case crit
((*) (and (pair? node) (not (memq (car node) '(@ *PI*)))))
((*any*) #t)
((*text*) (string? node))
(else
(and (pair? node) (eq? crit (car node))))
)))
; Curried equivalence converter-predicates
(define (node-eq? other)
(lambda (node)
(eq? other node)))
(define (node-equal? other)
(lambda (node)
(equal? other node)))
; node-pos:: N -> Nodeset -> Nodeset, or
; node-pos:: N -> Converter
; Select the N'th element of a Nodeset and return as a singular Nodeset;
; Return an empty nodeset if the Nth element does not exist.
; ((node-pos 1) Nodeset) selects the node at the head of the Nodeset,
; if exists; ((node-pos 2) Nodeset) selects the Node after that, if
; exists.
; N can also be a negative number: in that case the node is picked from
; the tail of the list.
; ((node-pos -1) Nodeset) selects the last node of a non-empty nodeset;
; ((node-pos -2) Nodeset) selects the last but one node, if exists.
(define (node-pos n)
(lambda (nodeset)
(cond
((not (nodeset? nodeset)) '())
((null? nodeset) nodeset)
((eqv? n 1) (list (car nodeset)))
((negative? n) ((node-pos (+ n 1 (length nodeset))) nodeset))
(else
(or (positive? n) (error "yikes!"))
((node-pos (1- n)) (cdr nodeset))))))
; filter:: Converter -> Converter
; A filter applicator, which introduces a filtering context. The argument
; converter is considered a predicate, with either #f or nil result meaning
; failure.
(define (filter pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))) (res '()))
(if (null? lst)
(reverse res)
(let ((pred-result (pred? (car lst))))
(loop (cdr lst)
(if (and pred-result (not (null? pred-result)))
(cons (car lst) res)
res)))))))
; take-until:: Converter -> Converter, or
; take-until:: Pred -> Node|Nodeset -> Nodeset
; Given a converter-predicate and a nodeset, apply the predicate to
; each element of the nodeset, until the predicate yields anything but #f or
; nil. Return the elements of the input nodeset that have been processed
; till that moment (that is, which fail the predicate).
; take-until is a variation of the filter above: take-until passes
; elements of an ordered input set till (but not including) the first
; element that satisfies the predicate.
; The nodeset returned by ((take-until (not pred)) nset) is a subset --
; to be more precise, a prefix -- of the nodeset returned by
; ((filter pred) nset)
(define (take-until pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))))
(if (null? lst) lst
(let ((pred-result (pred? (car lst))))
(if (and pred-result (not (null? pred-result)))
'()
(cons (car lst) (loop (cdr lst)))))
))))
; take-after:: Converter -> Converter, or
; take-after:: Pred -> Node|Nodeset -> Nodeset
; Given a converter-predicate and a nodeset, apply the predicate to
; each element of the nodeset, until the predicate yields anything but #f or
; nil. Return the elements of the input nodeset that have not been processed:
; that is, return the elements of the input nodeset that follow the first
; element that satisfied the predicate.
; take-after along with take-until partition an input nodeset into three
; parts: the first element that satisfies a predicate, all preceding
; elements and all following elements.
(define (take-after pred?)
(lambda (lst) ; a nodeset or a node (will be converted to a singleton nset)
(let loop ((lst (if (nodeset? lst) lst (list lst))))
(if (null? lst) lst
(let ((pred-result (pred? (car lst))))
(if (and pred-result (not (null? pred-result)))
(cdr lst)
(loop (cdr lst))))
))))
; Apply proc to each element of lst and return the list of results.
; if proc returns a nodeset, splice it into the result
;
; From another point of view, map-union is a function Converter->Converter,
; which places an argument-converter in a joining context.
(define (map-union proc lst)
(if (null? lst) lst
(let ((proc-res (proc (car lst))))
((if (nodeset? proc-res) append cons)
proc-res (map-union proc (cdr lst))))))
; node-reverse :: Converter, or
; node-reverse:: Node|Nodeset -> Nodeset
; Reverses the order of nodes in the nodeset
; This basic converter is needed to implement a reverse document order
; (see the XPath Recommendation).
(define node-reverse
(lambda (node-or-nodeset)
(if (not (nodeset? node-or-nodeset)) (list node-or-nodeset)
(reverse node-or-nodeset))))
; node-trace:: String -> Converter
; (node-trace title) is an identity converter. In addition it prints out
; a node or nodeset it is applied to, prefixed with the 'title'.
; This converter is very useful for debugging.
(define (node-trace title)
(lambda (node-or-nodeset)
(display "\n-->")
(display title)
(display " :")
(pretty-print node-or-nodeset)
node-or-nodeset))
;-------------------------
; Converter combinators
;
; Combinators are higher-order functions that transmogrify a converter
; or glue a sequence of converters into a single, non-trivial
; converter. The goal is to arrive at converters that correspond to
; XPath location paths.
;
; From a different point of view, a combinator is a fixed, named
; _pattern_ of applying converters. Given below is a complete set of
; such patterns that together implement XPath location path
; specification. As it turns out, all these combinators can be built
; from a small number of basic blocks: regular functional composition,
; map-union and filter applicators, and the nodeset union.
; select-kids:: Pred -> Node -> Nodeset
; Given a Node, return an (ordered) subset its children that satisfy
; the Pred (a converter, actually)
; select-kids:: Pred -> Nodeset -> Nodeset
; The same as above, but select among children of all the nodes in
; the Nodeset
;
; More succinctly, the signature of this function is
; select-kids:: Converter -> Converter
(define (select-kids test-pred?)
(lambda (node) ; node or node-set
(cond
((null? node) node)
((not (pair? node)) '()) ; No children
((symbol? (car node))
((filter test-pred?) (cdr node))) ; it's a single node
(else (map-union (select-kids test-pred?) node)))))
; node-self:: Pred -> Node -> Nodeset, or
; node-self:: Converter -> Converter
; Similar to select-kids but apply to the Node itself rather
; than to its children. The resulting Nodeset will contain either one
; component, or will be empty (if the Node failed the Pred).
(define node-self filter)
; node-join:: [LocPath] -> Node|Nodeset -> Nodeset, or
; node-join:: [Converter] -> Converter
; join the sequence of location steps or paths as described
; in the title comments above.
(define (node-join . selectors)
(lambda (nodeset) ; Nodeset or node
(let loop ((nodeset nodeset) (selectors selectors))
(if (null? selectors) nodeset
(loop
(if (nodeset? nodeset)
(map-union (car selectors) nodeset)
((car selectors) nodeset))
(cdr selectors))))))
; node-reduce:: [LocPath] -> Node|Nodeset -> Nodeset, or
; node-reduce:: [Converter] -> Converter
; A regular functional composition of converters.
; From a different point of view,
; ((apply node-reduce converters) nodeset)
; is equivalent to
; (foldl apply nodeset converters)
; i.e., folding, or reducing, a list of converters with the nodeset
; as a seed.
(define (node-reduce . converters)
(lambda (nodeset) ; Nodeset or node
(let loop ((nodeset nodeset) (converters converters))
(if (null? converters) nodeset
(loop ((car converters) nodeset) (cdr converters))))))
; node-or:: [Converter] -> Converter
; This combinator applies all converters to a given node and
; produces the union of their results.
; This combinator corresponds to a union, '|' operation for XPath
; location paths.
; (define (node-or . converters)
; (lambda (node-or-nodeset)
; (if (null? converters) node-or-nodeset
; (append
; ((car converters) node-or-nodeset)
; ((apply node-or (cdr converters)) node-or-nodeset)))))
; More optimal implementation follows
(define (node-or . converters)
(lambda (node-or-nodeset)
(let loop ((result '()) (converters converters))
(if (null? converters) result
(loop (append result (or ((car converters) node-or-nodeset) '()))
(cdr converters))))))
; node-closure:: Converter -> Converter
; Select all _descendants_ of a node that satisfy a converter-predicate.
; This combinator is similar to select-kids but applies to
; grand... children as well.
; This combinator implements the "descendant::" XPath axis
; Conceptually, this combinator can be expressed as
; (define (node-closure f)
; (node-or
; (select-kids f)
; (node-reduce (select-kids (node-typeof? '*)) (node-closure f))))
; This definition, as written, looks somewhat like a fixpoint, and it
; will run forever. It is obvious however that sooner or later
; (select-kids (node-typeof? '*)) will return an empty nodeset. At
; this point further iterations will no longer affect the result and
; can be stopped.
(define (node-closure test-pred?)
(lambda (node) ; Nodeset or node
(let loop ((parent node) (result '()))
(if (null? parent) result
(loop ((select-kids (node-typeof? '*)) parent)
(append result
((select-kids test-pred?) parent)))
))))
; node-parent:: RootNode -> Converter
; (node-parent rootnode) yields a converter that returns a parent of a
; node it is applied to. If applied to a nodeset, it returns the list
; of parents of nodes in the nodeset. The rootnode does not have
; to be the root node of the whole SXML tree -- it may be a root node
; of a branch of interest.
; Given the notation of Philip Wadler's paper on semantics of XSLT,
; parent(x) = { y | y=subnode*(root), x=subnode(y) }
; Therefore, node-parent is not the fundamental converter: it can be
; expressed through the existing ones. Yet node-parent is a rather
; convenient converter. It corresponds to a parent:: axis of SXPath.
; Note that the parent:: axis can be used with an attribute node as well!
(define (node-parent rootnode)
(lambda (node) ; Nodeset or node
(if (nodeset? node) (map-union (node-parent rootnode) node)
(let ((pred
(node-or
(node-reduce
(node-self (node-typeof? '*))
(select-kids (node-eq? node)))
(node-join
(select-kids (node-typeof? '@))
(select-kids (node-eq? node))))))
((node-or
(node-self pred)
(node-closure pred))
rootnode)))))
;-------------------------
; Evaluate an abbreviated SXPath
; sxpath:: AbbrPath -> Converter, or
; sxpath:: AbbrPath -> Node|Nodeset -> Nodeset
; AbbrPath is a list. It is translated to the full SXPath according
; to the following rewriting rules
; (sxpath '()) -> (node-join)
; (sxpath '(path-component ...)) ->
; (node-join (sxpath1 path-component) (sxpath '(...)))
; (sxpath1 '//) -> (node-or
; (node-self (node-typeof? '*any*))
; (node-closure (node-typeof? '*any*)))
; (sxpath1 '(equal? x)) -> (select-kids (node-equal? x))
; (sxpath1 '(eq? x)) -> (select-kids (node-eq? x))
; (sxpath1 ?symbol) -> (select-kids (node-typeof? ?symbol)
; (sxpath1 procedure) -> procedure
; (sxpath1 '(?symbol ...)) -> (sxpath1 '((?symbol) ...))
; (sxpath1 '(path reducer ...)) ->
; (node-reduce (sxpath path) (sxpathr reducer) ...)
; (sxpathr number) -> (node-pos number)
; (sxpathr path-filter) -> (filter (sxpath path-filter))
(define (sxpath path)
(lambda (nodeset)
(let loop ((nodeset nodeset) (path path))
(cond
((null? path) nodeset)
((nodeset? nodeset)
(map-union (sxpath path) nodeset))
((procedure? (car path))
(loop ((car path) nodeset) (cdr path)))
((eq? '// (car path))
(loop
((if (nodeset? nodeset) append cons) nodeset
((node-closure (node-typeof? '*any*)) nodeset))
(cdr path)))
((symbol? (car path))
(loop ((select-kids (node-typeof? (car path))) nodeset)
(cdr path)))
((and (pair? (car path)) (eq? 'equal? (caar path)))
(loop ((select-kids (apply node-equal? (cdar path))) nodeset)
(cdr path)))
((and (pair? (car path)) (eq? 'eq? (caar path)))
(loop ((select-kids (apply node-eq? (cdar path))) nodeset)
(cdr path)))
((pair? (car path))
(let reducer ((nodeset
(if (symbol? (caar path))
((select-kids (node-typeof? (caar path))) nodeset)
(loop nodeset (caar path))))
(reducing-path (cdar path)))
(cond
((null? reducing-path) (loop nodeset (cdr path)))
((number? (car reducing-path))
(reducer ((node-pos (car reducing-path)) nodeset)
(cdr reducing-path)))
(else
(reducer ((filter (sxpath (car reducing-path))) nodeset)
(cdr reducing-path))))))
(else
(error "Invalid path step: " (car path)))))))
;;; arch-tag: c4e57abf-6b61-4612-a6aa-d1536d440774
;;; xpath.scm ends here
;;; ck, to facilitate applicative-order macro programming
;;; Copyright (C) 2012 Free Software Foundation, Inc
;;; Copyright (C) 2009, 2011 Oleg Kiselyov
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;
;;;
;;; Originally written by Oleg Kiselyov and later contributed to Guile.
;;;
;;; Based on the CK machine introduced in:
;;;
;;; Matthias Felleisen and Daniel P. Friedman: Control operators, the
;;; SECD machine, and the lambda-calculus. In Martin Wirsing, editor,
;;; Formal Description of Programming Concepts III, pages
;;; 193-217. Elsevier, Amsterdam, 1986.
;;;
;;; See http://okmij.org/ftp/Scheme/macros.html#ck-macros for details.
;;;
(define-module (system base ck)
#\export (ck))
(define-syntax ck
(syntax-rules (quote)
((ck () 'v) v) ; yield the value on empty stack
((ck (((op ...) ea ...) . s) 'v) ; re-focus on the other argument, ea
(ck-arg s (op ... 'v) ea ...))
((ck s (op ea ...)) ; Focus: handling an application;
(ck-arg s (op) ea ...)))) ; check if args are values
(define-syntax ck-arg
(syntax-rules (quote)
((ck-arg s (op va ...)) ; all arguments are evaluated,
(op s va ...)) ; do the redex
((ck-arg s (op ...) 'v ea1 ...) ; optimization when the first ea
(ck-arg s (op ... 'v) ea1 ...)) ; was already a value
((ck-arg s (op ...) ea ea1 ...) ; focus on ea, to evaluate it
(ck (((op ...) ea1 ...) . s) ea))))
;;; High-level compiler interface
;; Copyright (C) 2001, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code:
(define-module (system base compile)
#\use-module (system base syntax)
#\use-module (system base language)
#\use-module (system base message)
#\use-module (system vm vm) ;; FIXME: there's a reason for this, can't remember why tho
#\use-module (ice-9 regex)
#\use-module (ice-9 optargs)
#\use-module (ice-9 receive)
#\export (compiled-file-name
compile-file
compile-and-load
read-and-compile
compile
decompile))
;;;
;;; Compiler
;;;
(define (call-once thunk)
(let ((entered #f))
(dynamic-wind
(lambda ()
(if entered
(error "thunk may only be entered once: ~a" thunk))
(set! entered #t))
thunk
(lambda () #t))))
;; emacs: (put 'call-with-output-file/atomic 'scheme-indent-function 1)
(define* (call-with-output-file/atomic filename proc #\optional reference)
(let* ((template (string-append filename ".XXXXXX"))
(tmp (mkstemp! template "wb")))
(call-once
(lambda ()
(with-throw-handler #t
(lambda ()
(proc tmp)
;; Chmodding by name instead of by port allows this chmod to
;; work on systems without fchmod, like MinGW.
(let ((perms (or (false-if-exception (stat:perms (stat reference)))
(lognot (umask)))))
(chmod template (logand #o0666 perms)))
(close-port tmp)
(rename-file template filename))
(lambda args
(close-port tmp)
(delete-file template)))))))
(define (ensure-language x)
(if (language? x)
x
(lookup-language x)))
;; Throws an exception if `dir' is not writable. The mkdir occurs
;; before the check, so that we avoid races (possibly due to parallel
;; compilation).
;;
(define (ensure-directory dir)
(catch 'system-error
(lambda ()
(mkdir dir))
(lambda (k subr fmt args rest)
(let ((errno (and (pair? rest) (car rest))))
(cond
((eqv? errno EEXIST)
;; Assume it's a writable directory, to avoid TOCTOU errors,
;; as well as UID/EUID mismatches that occur with access(2).
#t)
((eqv? errno ENOENT)
(ensure-directory (dirname dir))
(ensure-directory dir))
(else
(throw k subr fmt args rest)))))))
;;; This function is among the trickiest I've ever written. I tried many
;;; variants. In the end, simple is best, of course.
;;;
;;; After turning this around a number of times, it seems that the
;;; desired behavior is that .go files should exist in a path, for
;;; searching. That is orthogonal to this function. For writing .go
;;; files, either you know where they should go, in which case you tell
;;; compile-file explicitly, as in the srcdir != builddir case; or you
;;; don't know, in which case this function is called, and we just put
;;; them in your own ccache dir in ~/.cache/guile/ccache.
;;;
;;; See also boot-9.scm:load.
(define (compiled-file-name file)
;; FIXME: would probably be better just to append SHA1(canon-path)
;; to the %compile-fallback-path, to avoid deep directory stats.
(define (canonical->suffix canon)
(cond
((string-prefix? "/" canon) canon)
((and (> (string-length canon) 2)
(eqv? (string-ref canon 1) #\:))
;; Paths like C:... transform to /C...
(string-append "/" (substring canon 0 1) (substring canon 2)))
(else canon)))
(define (compiled-extension)
(cond ((or (null? %load-compiled-extensions)
(string-null? (car %load-compiled-extensions)))
(warn "invalid %load-compiled-extensions"
%load-compiled-extensions)
".go")
(else (car %load-compiled-extensions))))
(and %compile-fallback-path
(let ((f (string-append
%compile-fallback-path
(canonical->suffix (canonicalize-path file))
(compiled-extension))))
(and (false-if-exception (ensure-directory (dirname f)))
f))))
(define* (compile-file file #\key
(output-file #f)
(from (current-language))
(to 'objcode)
(env (default-environment from))
(opts '())
(canonicalization 'relative))
(with-fluids ((%file-port-name-canonicalization canonicalization))
(let* ((comp (or output-file (compiled-file-name file)
(error "failed to create path for auto-compiled file"
file)))
(in (open-input-file file))
(enc (file-encoding in)))
;; Choose the input encoding deterministically.
(set-port-encoding! in (or enc "UTF-8"))
(ensure-directory (dirname comp))
(call-with-output-file/atomic comp
(lambda (port)
((language-printer (ensure-language to))
(read-and-compile in #\env env #\from from #\to to #\opts opts)
port))
file)
comp)))
(define* (compile-and-load file #\key (from (current-language)) (to 'value)
(env (current-module)) (opts '())
(canonicalization 'relative))
(with-fluids ((%file-port-name-canonicalization canonicalization))
(read-and-compile (open-input-file file)
#\from from #\to to #\opts opts
#\env env)))
;;;
;;; Compiler interface
;;;
(define (compile-passes from to opts)
(map cdr
(or (lookup-compilation-order from to)
(error "no way to compile" from "to" to))))
(define (compile-fold passes exp env opts)
(let lp ((passes passes) (x exp) (e env) (cenv env) (first? #t))
(if (null? passes)
(values x e cenv)
(receive (x e new-cenv) ((car passes) x e opts)
(lp (cdr passes) x e (if first? new-cenv cenv) #f)))))
(define (find-language-joint from to)
(let lp ((in (reverse (or (lookup-compilation-order from to)
(error "no way to compile" from "to" to))))
(lang to))
(cond ((null? in) to)
((language-joiner lang) lang)
(else
(lp (cdr in) (caar in))))))
(define (default-language-joiner lang)
(lambda (exps env)
(if (and (pair? exps) (null? (cdr exps)))
(car exps)
(error
"Multiple expressions read and compiled, but language has no joiner"
lang))))
(define (read-and-parse lang port cenv)
(let ((exp ((language-reader lang) port cenv)))
(cond
((eof-object? exp) exp)
((language-parser lang) => (lambda (parse) (parse exp)))
(else exp))))
(define* (read-and-compile port #\key
(from (current-language))
(to 'objcode)
(env (default-environment from))
(opts '()))
(let ((from (ensure-language from))
(to (ensure-language to)))
(let ((joint (find-language-joint from to)))
(parameterize ((current-language from))
(let lp ((exps '()) (env #f) (cenv env))
(let ((x (read-and-parse (current-language) port cenv)))
(cond
((eof-object? x)
(close-port port)
(compile ((or (language-joiner joint)
(default-language-joiner joint))
(reverse exps)
env)
#\from joint #\to to
;; env can be false if no expressions were read.
#\env (or env (default-environment joint))
#\opts opts))
(else
;; compile-fold instead of compile so we get the env too
(receive (jexp jenv jcenv)
(compile-fold (compile-passes (current-language) joint opts)
x cenv opts)
(lp (cons jexp exps) jenv jcenv))))))))))
(define* (compile x #\key
(from (current-language))
(to 'value)
(env (default-environment from))
(opts '()))
(let ((warnings (memq #\warnings opts)))
(if (pair? warnings)
(let ((warnings (cadr warnings)))
;; Sanity-check the requested warnings.
(for-each (lambda (w)
(or (lookup-warning-type w)
(warning 'unsupported-warning #f w)))
warnings))))
(receive (exp env cenv)
(compile-fold (compile-passes from to opts) x env opts)
exp))
;;;
;;; Decompiler interface
;;;
(define (decompile-passes from to opts)
(map cdr
(or (lookup-decompilation-order from to)
(error "no way to decompile" from "to" to))))
(define (decompile-fold passes exp env opts)
(if (null? passes)
(values exp env)
(receive (exp env) ((car passes) exp env opts)
(decompile-fold (cdr passes) exp env opts))))
(define* (decompile x #\key
(env #f)
(from 'value)
(to 'assembly)
(opts '()))
(decompile-fold (decompile-passes from to opts)
x
env
opts))
;;; -*- mode: scheme; coding: utf-8; -*-
;;;
;;; Copyright (C) 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; This library 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 Lesser
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public License
;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(define-module (system base lalr)
;; XXX: In theory this import is not needed but the evaluator (not the
;; compiler) complains about `lexical-token' being unbound when expanding
;; `(define-record-type lexical-token ...)' if we omit it.
#\use-module (srfi srfi-9)
#\export (lalr-parser print-states
make-lexical-token lexical-token?
lexical-token-category
lexical-token-source
lexical-token-value
make-source-location source-location?
source-location-input
source-location-line
source-location-column
source-location-offset
source-location-length
source-location->source-properties
;; `lalr-parser' is a defmacro, which produces code that refers to
;; these drivers.
lr-driver glr-driver))
;; The LALR parser generator was written by Dominique Boucher. It's available
;; from http://code.google.com/p/lalr-scm/ and released under the LGPLv3+.
(include-from-path "system/base/lalr.upstream.scm")
(define (source-location->source-properties loc)
`((filename . ,(source-location-input loc))
(line . ,(source-location-line loc))
(column . ,(source-location-column loc))))
;;;
;;;; An Efficient and Portable LALR(1) Parser Generator for Scheme
;;;
;; Copyright 2014 Jan Nieuwenhuizen <janneke@gnu.org>
;; Copyright 1993, 2010 Dominique Boucher
;;
;; This program is free software: you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public License
;; as published by the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
(define *lalr-scm-version* "2.5.0")
(cond-expand
;; -- Gambit-C
(gambit
(define-macro (def-macro form . body)
`(define-macro ,form (let () ,@body)))
(def-macro (BITS-PER-WORD) 28)
(def-macro (logical-or x . y) `(bitwise-ior ,x ,@y))
(def-macro (lalr-error msg obj) `(error ,msg ,obj))
(define pprint pretty-print)
(define lalr-keyword? keyword?)
(define (note-source-location lvalue tok) lvalue))
;; --
(bigloo
(define-macro (def-macro form . body)
`(define-macro ,form (let () ,@body)))
(define pprint (lambda (obj) (write obj) (newline)))
(define lalr-keyword? keyword?)
(def-macro (BITS-PER-WORD) 29)
(def-macro (logical-or x . y) `(bit-or ,x ,@y))
(def-macro (lalr-error msg obj) `(error "lalr-parser" ,msg ,obj))
(define (note-source-location lvalue tok) lvalue))
;; -- Chicken
(chicken
(define-macro (def-macro form . body)
`(define-macro ,form (let () ,@body)))
(define pprint pretty-print)
(define lalr-keyword? symbol?)
(def-macro (BITS-PER-WORD) 30)
(def-macro (logical-or x . y) `(bitwise-ior ,x ,@y))
(def-macro (lalr-error msg obj) `(error ,msg ,obj))
(define (note-source-location lvalue tok) lvalue))
;; -- STKlos
(stklos
(require "pp")
(define (pprint form) (pp form \:port (current-output-port)))
(define lalr-keyword? keyword?)
(define-macro (BITS-PER-WORD) 30)
(define-macro (logical-or x . y) `(bit-or ,x ,@y))
(define-macro (lalr-error msg obj) `(error 'lalr-parser ,msg ,obj))
(define (note-source-location lvalue tok) lvalue))
;; -- Guile
(guile
(use-modules (ice-9 pretty-print))
(use-modules (srfi srfi-9))
(define pprint pretty-print)
(define lalr-keyword? symbol?)
(define-macro (BITS-PER-WORD) 30)
(define-macro (logical-or x . y) `(logior ,x ,@y))
(define-macro (lalr-error msg obj) `(error ,msg ,obj))
(define (note-source-location lvalue tok)
(if (and (supports-source-properties? lvalue)
(not (source-property lvalue 'loc))
(lexical-token? tok))
(set-source-property! lvalue 'loc (lexical-token-source tok)))
lvalue))
;; -- Kawa
(kawa
(require 'pretty-print)
(define (BITS-PER-WORD) 30)
(define logical-or logior)
(define (lalr-keyword? obj) (keyword? obj))
(define (pprint obj) (pretty-print obj))
(define (lalr-error msg obj) (error msg obj))
(define (note-source-location lvalue tok) lvalue))
;; -- SISC
(sisc
(import logicops)
(import record)
(define pprint pretty-print)
(define lalr-keyword? symbol?)
(define-macro BITS-PER-WORD (lambda () 32))
(define-macro logical-or (lambda (x . y) `(logor ,x ,@y)))
(define-macro (lalr-error msg obj) `(error "~a ~S:" ,msg ,obj))
(define (note-source-location lvalue tok) lvalue))
(else
(error "Unsupported Scheme system")))
(define-record-type lexical-token
(make-lexical-token category source value)
lexical-token?
(category lexical-token-category)
(source lexical-token-source)
(value lexical-token-value))
(define-record-type source-location
(make-source-location input line column offset length)
source-location?
(input source-location-input)
(line source-location-line)
(column source-location-column)
(offset source-location-offset)
(length source-location-length))
;; - Macros pour la gestion des vecteurs de bits
(define-macro (lalr-parser . arguments)
(define (set-bit v b)
(let ((x (quotient b (BITS-PER-WORD)))
(y (expt 2 (remainder b (BITS-PER-WORD)))))
(vector-set! v x (logical-or (vector-ref v x) y))))
(define (bit-union v1 v2 n)
(do ((i 0 (+ i 1)))
((= i n))
(vector-set! v1 i (logical-or (vector-ref v1 i)
(vector-ref v2 i)))))
;; - Macro pour les structures de donnees
(define (new-core) (make-vector 4 0))
(define (set-core-number! c n) (vector-set! c 0 n))
(define (set-core-acc-sym! c s) (vector-set! c 1 s))
(define (set-core-nitems! c n) (vector-set! c 2 n))
(define (set-core-items! c i) (vector-set! c 3 i))
(define (core-number c) (vector-ref c 0))
(define (core-acc-sym c) (vector-ref c 1))
(define (core-nitems c) (vector-ref c 2))
(define (core-items c) (vector-ref c 3))
(define (new-shift) (make-vector 3 0))
(define (set-shift-number! c x) (vector-set! c 0 x))
(define (set-shift-nshifts! c x) (vector-set! c 1 x))
(define (set-shift-shifts! c x) (vector-set! c 2 x))
(define (shift-number s) (vector-ref s 0))
(define (shift-nshifts s) (vector-ref s 1))
(define (shift-shifts s) (vector-ref s 2))
(define (new-red) (make-vector 3 0))
(define (set-red-number! c x) (vector-set! c 0 x))
(define (set-red-nreds! c x) (vector-set! c 1 x))
(define (set-red-rules! c x) (vector-set! c 2 x))
(define (red-number c) (vector-ref c 0))
(define (red-nreds c) (vector-ref c 1))
(define (red-rules c) (vector-ref c 2))
(define (new-set nelem)
(make-vector nelem 0))
(define (vector-map f v)
(let ((vm-n (- (vector-length v) 1)))
(let loop ((vm-low 0) (vm-high vm-n))
(if (= vm-low vm-high)
(vector-set! v vm-low (f (vector-ref v vm-low) vm-low))
(let ((vm-middle (quotient (+ vm-low vm-high) 2)))
(loop vm-low vm-middle)
(loop (+ vm-middle 1) vm-high))))))
;; - Constantes
(define STATE-TABLE-SIZE 1009)
;; - Tableaux
(define rrhs #f)
(define rlhs #f)
(define ritem #f)
(define nullable #f)
(define derives #f)
(define fderives #f)
(define firsts #f)
(define kernel-base #f)
(define kernel-end #f)
(define shift-symbol #f)
(define shift-set #f)
(define red-set #f)
(define state-table #f)
(define acces-symbol #f)
(define reduction-table #f)
(define shift-table #f)
(define consistent #f)
(define lookaheads #f)
(define LA #f)
(define LAruleno #f)
(define lookback #f)
(define goto-map #f)
(define from-state #f)
(define to-state #f)
(define includes #f)
(define F #f)
(define action-table #f)
;; - Variables
(define nitems #f)
(define nrules #f)
(define nvars #f)
(define nterms #f)
(define nsyms #f)
(define nstates #f)
(define first-state #f)
(define last-state #f)
(define final-state #f)
(define first-shift #f)
(define last-shift #f)
(define first-reduction #f)
(define last-reduction #f)
(define nshifts #f)
(define maxrhs #f)
(define ngotos #f)
(define token-set-size #f)
(define driver-name 'lr-driver)
(define (glr-driver?)
(eq? driver-name 'glr-driver))
(define (lr-driver?)
(eq? driver-name 'lr-driver))
(define (gen-tables! tokens gram )
(initialize-all)
(rewrite-grammar
tokens
gram
(lambda (terms terms/prec vars gram gram/actions)
(set! the-terminals/prec (list->vector terms/prec))
(set! the-terminals (list->vector terms))
(set! the-nonterminals (list->vector vars))
(set! nterms (length terms))
(set! nvars (length vars))
(set! nsyms (+ nterms nvars))
(let ((no-of-rules (length gram/actions))
(no-of-items (let loop ((l gram/actions) (count 0))
(if (null? l)
count
(loop (cdr l) (+ count (length (caar l))))))))
(pack-grammar no-of-rules no-of-items gram)
(set-derives)
(set-nullable)
(generate-states)
(lalr)
(build-tables)
(compact-action-table terms)
gram/actions))))
(define (initialize-all)
(set! rrhs #f)
(set! rlhs #f)
(set! ritem #f)
(set! nullable #f)
(set! derives #f)
(set! fderives #f)
(set! firsts #f)
(set! kernel-base #f)
(set! kernel-end #f)
(set! shift-symbol #f)
(set! shift-set #f)
(set! red-set #f)
(set! state-table (make-vector STATE-TABLE-SIZE '()))
(set! acces-symbol #f)
(set! reduction-table #f)
(set! shift-table #f)
(set! consistent #f)
(set! lookaheads #f)
(set! LA #f)
(set! LAruleno #f)
(set! lookback #f)
(set! goto-map #f)
(set! from-state #f)
(set! to-state #f)
(set! includes #f)
(set! F #f)
(set! action-table #f)
(set! nstates #f)
(set! first-state #f)
(set! last-state #f)
(set! final-state #f)
(set! first-shift #f)
(set! last-shift #f)
(set! first-reduction #f)
(set! last-reduction #f)
(set! nshifts #f)
(set! maxrhs #f)
(set! ngotos #f)
(set! token-set-size #f)
(set! rule-precedences '()))
(define (pack-grammar no-of-rules no-of-items gram)
(set! nrules (+ no-of-rules 1))
(set! nitems no-of-items)
(set! rlhs (make-vector nrules #f))
(set! rrhs (make-vector nrules #f))
(set! ritem (make-vector (+ 1 nitems) #f))
(let loop ((p gram) (item-no 0) (rule-no 1))
(if (not (null? p))
(let ((nt (caar p)))
(let loop2 ((prods (cdar p)) (it-no2 item-no) (rl-no2 rule-no))
(if (null? prods)
(loop (cdr p) it-no2 rl-no2)
(begin
(vector-set! rlhs rl-no2 nt)
(vector-set! rrhs rl-no2 it-no2)
(let loop3 ((rhs (car prods)) (it-no3 it-no2))
(if (null? rhs)
(begin
(vector-set! ritem it-no3 (- rl-no2))
(loop2 (cdr prods) (+ it-no3 1) (+ rl-no2 1)))
(begin
(vector-set! ritem it-no3 (car rhs))
(loop3 (cdr rhs) (+ it-no3 1))))))))))))
(define (set-derives)
(define delts (make-vector (+ nrules 1) 0))
(define dset (make-vector nvars -1))
(let loop ((i 1) (j 0)) ; i = 0
(if (< i nrules)
(let ((lhs (vector-ref rlhs i)))
(if (>= lhs 0)
(begin
(vector-set! delts j (cons i (vector-ref dset lhs)))
(vector-set! dset lhs j)
(loop (+ i 1) (+ j 1)))
(loop (+ i 1) j)))))
(set! derives (make-vector nvars 0))
(let loop ((i 0))
(if (< i nvars)
(let ((q (let loop2 ((j (vector-ref dset i)) (s '()))
(if (< j 0)
s
(let ((x (vector-ref delts j)))
(loop2 (cdr x) (cons (car x) s)))))))
(vector-set! derives i q)
(loop (+ i 1))))))
(define (set-nullable)
(set! nullable (make-vector nvars #f))
(let ((squeue (make-vector nvars #f))
(rcount (make-vector (+ nrules 1) 0))
(rsets (make-vector nvars #f))
(relts (make-vector (+ nitems nvars 1) #f)))
(let loop ((r 0) (s2 0) (p 0))
(let ((*r (vector-ref ritem r)))
(if *r
(if (< *r 0)
(let ((symbol (vector-ref rlhs (- *r))))
(if (and (>= symbol 0)
(not (vector-ref nullable symbol)))
(begin
(vector-set! nullable symbol #t)
(vector-set! squeue s2 symbol)
(loop (+ r 1) (+ s2 1) p))))
(let loop2 ((r1 r) (any-tokens #f))
(let* ((symbol (vector-ref ritem r1)))
(if (> symbol 0)
(loop2 (+ r1 1) (or any-tokens (>= symbol nvars)))
(if (not any-tokens)
(let ((ruleno (- symbol)))
(let loop3 ((r2 r) (p2 p))
(let ((symbol (vector-ref ritem r2)))
(if (> symbol 0)
(begin
(vector-set! rcount ruleno
(+ (vector-ref rcount ruleno) 1))
(vector-set! relts p2
(cons (vector-ref rsets symbol)
ruleno))
(vector-set! rsets symbol p2)
(loop3 (+ r2 1) (+ p2 1)))
(loop (+ r2 1) s2 p2)))))
(loop (+ r1 1) s2 p))))))
(let loop ((s1 0) (s3 s2))
(if (< s1 s3)
(let loop2 ((p (vector-ref rsets (vector-ref squeue s1))) (s4 s3))
(if p
(let* ((x (vector-ref relts p))
(ruleno (cdr x))
(y (- (vector-ref rcount ruleno) 1)))
(vector-set! rcount ruleno y)
(if (= y 0)
(let ((symbol (vector-ref rlhs ruleno)))
(if (and (>= symbol 0)
(not (vector-ref nullable symbol)))
(begin
(vector-set! nullable symbol #t)
(vector-set! squeue s4 symbol)
(loop2 (car x) (+ s4 1)))
(loop2 (car x) s4)))
(loop2 (car x) s4))))
(loop (+ s1 1) s4)))))))))
(define (set-firsts)
(set! firsts (make-vector nvars '()))
;; -- initialization
(let loop ((i 0))
(if (< i nvars)
(let loop2 ((sp (vector-ref derives i)))
(if (null? sp)
(loop (+ i 1))
(let ((sym (vector-ref ritem (vector-ref rrhs (car sp)))))
(if (< -1 sym nvars)
(vector-set! firsts i (sinsert sym (vector-ref firsts i))))
(loop2 (cdr sp)))))))
;; -- reflexive and transitive closure
(let loop ((continue #t))
(if continue
(let loop2 ((i 0) (cont #f))
(if (>= i nvars)
(loop cont)
(let* ((x (vector-ref firsts i))
(y (let loop3 ((l x) (z x))
(if (null? l)
z
(loop3 (cdr l)
(sunion (vector-ref firsts (car l)) z))))))
(if (equal? x y)
(loop2 (+ i 1) cont)
(begin
(vector-set! firsts i y)
(loop2 (+ i 1) #t))))))))
(let loop ((i 0))
(if (< i nvars)
(begin
(vector-set! firsts i (sinsert i (vector-ref firsts i)))
(loop (+ i 1))))))
(define (set-fderives)
(set! fderives (make-vector nvars #f))
(set-firsts)
(let loop ((i 0))
(if (< i nvars)
(let ((x (let loop2 ((l (vector-ref firsts i)) (fd '()))
(if (null? l)
fd
(loop2 (cdr l)
(sunion (vector-ref derives (car l)) fd))))))
(vector-set! fderives i x)
(loop (+ i 1))))))
(define (closure core)
;; Initialization
(define ruleset (make-vector nrules #f))
(let loop ((csp core))
(if (not (null? csp))
(let ((sym (vector-ref ritem (car csp))))
(if (< -1 sym nvars)
(let loop2 ((dsp (vector-ref fderives sym)))
(if (not (null? dsp))
(begin
(vector-set! ruleset (car dsp) #t)
(loop2 (cdr dsp))))))
(loop (cdr csp)))))
(let loop ((ruleno 1) (csp core) (itemsetv '())) ; ruleno = 0
(if (< ruleno nrules)
(if (vector-ref ruleset ruleno)
(let ((itemno (vector-ref rrhs ruleno)))
(let loop2 ((c csp) (itemsetv2 itemsetv))
(if (and (pair? c)
(< (car c) itemno))
(loop2 (cdr c) (cons (car c) itemsetv2))
(loop (+ ruleno 1) c (cons itemno itemsetv2)))))
(loop (+ ruleno 1) csp itemsetv))
(let loop2 ((c csp) (itemsetv2 itemsetv))
(if (pair? c)
(loop2 (cdr c) (cons (car c) itemsetv2))
(reverse itemsetv2))))))
(define (allocate-item-sets)
(set! kernel-base (make-vector nsyms 0))
(set! kernel-end (make-vector nsyms #f)))
(define (allocate-storage)
(allocate-item-sets)
(set! red-set (make-vector (+ nrules 1) 0)))
; --
(define (initialize-states)
(let ((p (new-core)))
(set-core-number! p 0)
(set-core-acc-sym! p #f)
(set-core-nitems! p 1)
(set-core-items! p '(0))
(set! first-state (list p))
(set! last-state first-state)
(set! nstates 1)))
(define (generate-states)
(allocate-storage)
(set-fderives)
(initialize-states)
(let loop ((this-state first-state))
(if (pair? this-state)
(let* ((x (car this-state))
(is (closure (core-items x))))
(save-reductions x is)
(new-itemsets is)
(append-states)
(if (> nshifts 0)
(save-shifts x))
(loop (cdr this-state))))))
(define (new-itemsets itemset)
;; - Initialization
(set! shift-symbol '())
(let loop ((i 0))
(if (< i nsyms)
(begin
(vector-set! kernel-end i '())
(loop (+ i 1)))))
(let loop ((isp itemset))
(if (pair? isp)
(let* ((i (car isp))
(sym (vector-ref ritem i)))
(if (>= sym 0)
(begin
(set! shift-symbol (sinsert sym shift-symbol))
(let ((x (vector-ref kernel-end sym)))
(if (null? x)
(begin
(vector-set! kernel-base sym (cons (+ i 1) x))
(vector-set! kernel-end sym (vector-ref kernel-base sym)))
(begin
(set-cdr! x (list (+ i 1)))
(vector-set! kernel-end sym (cdr x)))))))
(loop (cdr isp)))))
(set! nshifts (length shift-symbol)))
(define (get-state sym)
(let* ((isp (vector-ref kernel-base sym))
(n (length isp))
(key (let loop ((isp1 isp) (k 0))
(if (null? isp1)
(modulo k STATE-TABLE-SIZE)
(loop (cdr isp1) (+ k (car isp1))))))
(sp (vector-ref state-table key)))
(if (null? sp)
(let ((x (new-state sym)))
(vector-set! state-table key (list x))
(core-number x))
(let loop ((sp1 sp))
(if (and (= n (core-nitems (car sp1)))
(let loop2 ((i1 isp) (t (core-items (car sp1))))
(if (and (pair? i1)
(= (car i1)
(car t)))
(loop2 (cdr i1) (cdr t))
(null? i1))))
(core-number (car sp1))
(if (null? (cdr sp1))
(let ((x (new-state sym)))
(set-cdr! sp1 (list x))
(core-number x))
(loop (cdr sp1))))))))
(define (new-state sym)
(let* ((isp (vector-ref kernel-base sym))
(n (length isp))
(p (new-core)))
(set-core-number! p nstates)
(set-core-acc-sym! p sym)
(if (= sym nvars) (set! final-state nstates))
(set-core-nitems! p n)
(set-core-items! p isp)
(set-cdr! last-state (list p))
(set! last-state (cdr last-state))
(set! nstates (+ nstates 1))
p))
; --
(define (append-states)
(set! shift-set
(let loop ((l (reverse shift-symbol)))
(if (null? l)
'()
(cons (get-state (car l)) (loop (cdr l)))))))
; --
(define (save-shifts core)
(let ((p (new-shift)))
(set-shift-number! p (core-number core))
(set-shift-nshifts! p nshifts)
(set-shift-shifts! p shift-set)
(if last-shift
(begin
(set-cdr! last-shift (list p))
(set! last-shift (cdr last-shift)))
(begin
(set! first-shift (list p))
(set! last-shift first-shift)))))
(define (save-reductions core itemset)
(let ((rs (let loop ((l itemset))
(if (null? l)
'()
(let ((item (vector-ref ritem (car l))))
(if (< item 0)
(cons (- item) (loop (cdr l)))
(loop (cdr l))))))))
(if (pair? rs)
(let ((p (new-red)))
(set-red-number! p (core-number core))
(set-red-nreds! p (length rs))
(set-red-rules! p rs)
(if last-reduction
(begin
(set-cdr! last-reduction (list p))
(set! last-reduction (cdr last-reduction)))
(begin
(set! first-reduction (list p))
(set! last-reduction first-reduction)))))))
; --
(define (lalr)
(set! token-set-size (+ 1 (quotient nterms (BITS-PER-WORD))))
(set-accessing-symbol)
(set-shift-table)
(set-reduction-table)
(set-max-rhs)
(initialize-LA)
(set-goto-map)
(initialize-F)
(build-relations)
(digraph includes)
(compute-lookaheads))
(define (set-accessing-symbol)
(set! acces-symbol (make-vector nstates #f))
(let loop ((l first-state))
(if (pair? l)
(let ((x (car l)))
(vector-set! acces-symbol (core-number x) (core-acc-sym x))
(loop (cdr l))))))
(define (set-shift-table)
(set! shift-table (make-vector nstates #f))
(let loop ((l first-shift))
(if (pair? l)
(let ((x (car l)))
(vector-set! shift-table (shift-number x) x)
(loop (cdr l))))))
(define (set-reduction-table)
(set! reduction-table (make-vector nstates #f))
(let loop ((l first-reduction))
(if (pair? l)
(let ((x (car l)))
(vector-set! reduction-table (red-number x) x)
(loop (cdr l))))))
(define (set-max-rhs)
(let loop ((p 0) (curmax 0) (length 0))
(let ((x (vector-ref ritem p)))
(if x
(if (>= x 0)
(loop (+ p 1) curmax (+ length 1))
(loop (+ p 1) (max curmax length) 0))
(set! maxrhs curmax)))))
(define (initialize-LA)
(define (last l)
(if (null? (cdr l))
(car l)
(last (cdr l))))
(set! consistent (make-vector nstates #f))
(set! lookaheads (make-vector (+ nstates 1) #f))
(let loop ((count 0) (i 0))
(if (< i nstates)
(begin
(vector-set! lookaheads i count)
(let ((rp (vector-ref reduction-table i))
(sp (vector-ref shift-table i)))
(if (and rp
(or (> (red-nreds rp) 1)
(and sp
(not
(< (vector-ref acces-symbol
(last (shift-shifts sp)))
nvars)))))
(loop (+ count (red-nreds rp)) (+ i 1))
(begin
(vector-set! consistent i #t)
(loop count (+ i 1))))))
(begin
(vector-set! lookaheads nstates count)
(let ((c (max count 1)))
(set! LA (make-vector c #f))
(do ((j 0 (+ j 1))) ((= j c)) (vector-set! LA j (new-set token-set-size)))
(set! LAruleno (make-vector c -1))
(set! lookback (make-vector c #f)))
(let loop ((i 0) (np 0))
(if (< i nstates)
(if (vector-ref consistent i)
(loop (+ i 1) np)
(let ((rp (vector-ref reduction-table i)))
(if rp
(let loop2 ((j (red-rules rp)) (np2 np))
(if (null? j)
(loop (+ i 1) np2)
(begin
(vector-set! LAruleno np2 (car j))
(loop2 (cdr j) (+ np2 1)))))
(loop (+ i 1) np))))))))))
(define (set-goto-map)
(set! goto-map (make-vector (+ nvars 1) 0))
(let ((temp-map (make-vector (+ nvars 1) 0)))
(let loop ((ng 0) (sp first-shift))
(if (pair? sp)
(let loop2 ((i (reverse (shift-shifts (car sp)))) (ng2 ng))
(if (pair? i)
(let ((symbol (vector-ref acces-symbol (car i))))
(if (< symbol nvars)
(begin
(vector-set! goto-map symbol
(+ 1 (vector-ref goto-map symbol)))
(loop2 (cdr i) (+ ng2 1)))
(loop2 (cdr i) ng2)))
(loop ng2 (cdr sp))))
(let loop ((k 0) (i 0))
(if (< i nvars)
(begin
(vector-set! temp-map i k)
(loop (+ k (vector-ref goto-map i)) (+ i 1)))
(begin
(do ((i 0 (+ i 1)))
((>= i nvars))
(vector-set! goto-map i (vector-ref temp-map i)))
(set! ngotos ng)
(vector-set! goto-map nvars ngotos)
(vector-set! temp-map nvars ngotos)
(set! from-state (make-vector ngotos #f))
(set! to-state (make-vector ngotos #f))
(do ((sp first-shift (cdr sp)))
((null? sp))
(let* ((x (car sp))
(state1 (shift-number x)))
(do ((i (shift-shifts x) (cdr i)))
((null? i))
(let* ((state2 (car i))
(symbol (vector-ref acces-symbol state2)))
(if (< symbol nvars)
(let ((k (vector-ref temp-map symbol)))
(vector-set! temp-map symbol (+ k 1))
(vector-set! from-state k state1)
(vector-set! to-state k state2))))))))))))))
(define (map-goto state symbol)
(let loop ((low (vector-ref goto-map symbol))
(high (- (vector-ref goto-map (+ symbol 1)) 1)))
(if (> low high)
(begin
(display (list "Error in map-goto" state symbol)) (newline)
0)
(let* ((middle (quotient (+ low high) 2))
(s (vector-ref from-state middle)))
(cond
((= s state)
middle)
((< s state)
(loop (+ middle 1) high))
(else
(loop low (- middle 1))))))))
(define (initialize-F)
(set! F (make-vector ngotos #f))
(do ((i 0 (+ i 1))) ((= i ngotos)) (vector-set! F i (new-set token-set-size)))
(let ((reads (make-vector ngotos #f)))
(let loop ((i 0) (rowp 0))
(if (< i ngotos)
(let* ((rowf (vector-ref F rowp))
(stateno (vector-ref to-state i))
(sp (vector-ref shift-table stateno)))
(if sp
(let loop2 ((j (shift-shifts sp)) (edges '()))
(if (pair? j)
(let ((symbol (vector-ref acces-symbol (car j))))
(if (< symbol nvars)
(if (vector-ref nullable symbol)
(loop2 (cdr j) (cons (map-goto stateno symbol)
edges))
(loop2 (cdr j) edges))
(begin
(set-bit rowf (- symbol nvars))
(loop2 (cdr j) edges))))
(if (pair? edges)
(vector-set! reads i (reverse edges))))))
(loop (+ i 1) (+ rowp 1)))))
(digraph reads)))
(define (add-lookback-edge stateno ruleno gotono)
(let ((k (vector-ref lookaheads (+ stateno 1))))
(let loop ((found #f) (i (vector-ref lookaheads stateno)))
(if (and (not found) (< i k))
(if (= (vector-ref LAruleno i) ruleno)
(loop #t i)
(loop found (+ i 1)))
(if (not found)
(begin (display "Error in add-lookback-edge : ")
(display (list stateno ruleno gotono)) (newline))
(vector-set! lookback i
(cons gotono (vector-ref lookback i))))))))
(define (transpose r-arg n)
(let ((new-end (make-vector n #f))
(new-R (make-vector n #f)))
(do ((i 0 (+ i 1)))
((= i n))
(let ((x (list 'bidon)))
(vector-set! new-R i x)
(vector-set! new-end i x)))
(do ((i 0 (+ i 1)))
((= i n))
(let ((sp (vector-ref r-arg i)))
(if (pair? sp)
(let loop ((sp2 sp))
(if (pair? sp2)
(let* ((x (car sp2))
(y (vector-ref new-end x)))
(set-cdr! y (cons i (cdr y)))
(vector-set! new-end x (cdr y))
(loop (cdr sp2))))))))
(do ((i 0 (+ i 1)))
((= i n))
(vector-set! new-R i (cdr (vector-ref new-R i))))
new-R))
(define (build-relations)
(define (get-state stateno symbol)
(let loop ((j (shift-shifts (vector-ref shift-table stateno)))
(stno stateno))
(if (null? j)
stno
(let ((st2 (car j)))
(if (= (vector-ref acces-symbol st2) symbol)
st2
(loop (cdr j) st2))))))
(set! includes (make-vector ngotos #f))
(do ((i 0 (+ i 1)))
((= i ngotos))
(let ((state1 (vector-ref from-state i))
(symbol1 (vector-ref acces-symbol (vector-ref to-state i))))
(let loop ((rulep (vector-ref derives symbol1))
(edges '()))
(if (pair? rulep)
(let ((*rulep (car rulep)))
(let loop2 ((rp (vector-ref rrhs *rulep))
(stateno state1)
(states (list state1)))
(let ((*rp (vector-ref ritem rp)))
(if (> *rp 0)
(let ((st (get-state stateno *rp)))
(loop2 (+ rp 1) st (cons st states)))
(begin
(if (not (vector-ref consistent stateno))
(add-lookback-edge stateno *rulep i))
(let loop2 ((done #f)
(stp (cdr states))
(rp2 (- rp 1))
(edgp edges))
(if (not done)
(let ((*rp (vector-ref ritem rp2)))
(if (< -1 *rp nvars)
(loop2 (not (vector-ref nullable *rp))
(cdr stp)
(- rp2 1)
(cons (map-goto (car stp) *rp) edgp))
(loop2 #t stp rp2 edgp)))
(loop (cdr rulep) edgp))))))))
(vector-set! includes i edges)))))
(set! includes (transpose includes ngotos)))
(define (compute-lookaheads)
(let ((n (vector-ref lookaheads nstates)))
(let loop ((i 0))
(if (< i n)
(let loop2 ((sp (vector-ref lookback i)))
(if (pair? sp)
(let ((LA-i (vector-ref LA i))
(F-j (vector-ref F (car sp))))
(bit-union LA-i F-j token-set-size)
(loop2 (cdr sp)))
(loop (+ i 1))))))))
(define (digraph relation)
(define infinity (+ ngotos 2))
(define INDEX (make-vector (+ ngotos 1) 0))
(define VERTICES (make-vector (+ ngotos 1) 0))
(define top 0)
(define R relation)
(define (traverse i)
(set! top (+ 1 top))
(vector-set! VERTICES top i)
(let ((height top))
(vector-set! INDEX i height)
(let ((rp (vector-ref R i)))
(if (pair? rp)
(let loop ((rp2 rp))
(if (pair? rp2)
(let ((j (car rp2)))
(if (= 0 (vector-ref INDEX j))
(traverse j))
(if (> (vector-ref INDEX i)
(vector-ref INDEX j))
(vector-set! INDEX i (vector-ref INDEX j)))
(let ((F-i (vector-ref F i))
(F-j (vector-ref F j)))
(bit-union F-i F-j token-set-size))
(loop (cdr rp2))))))
(if (= (vector-ref INDEX i) height)
(let loop ()
(let ((j (vector-ref VERTICES top)))
(set! top (- top 1))
(vector-set! INDEX j infinity)
(if (not (= i j))
(begin
(bit-union (vector-ref F i)
(vector-ref F j)
token-set-size)
(loop)))))))))
(let loop ((i 0))
(if (< i ngotos)
(begin
(if (and (= 0 (vector-ref INDEX i))
(pair? (vector-ref R i)))
(traverse i))
(loop (+ i 1))))))
;; ----------------------------------------------------------------------
;; operator precedence management
;; ----------------------------------------------------------------------
;; a vector of precedence descriptors where each element
;; is of the form (terminal type precedence)
(define the-terminals/prec #f) ; terminal symbols with precedence
; the precedence is an integer >= 0
(define (get-symbol-precedence sym)
(caddr (vector-ref the-terminals/prec sym)))
; the operator type is either 'none, 'left, 'right, or 'nonassoc
(define (get-symbol-assoc sym)
(cadr (vector-ref the-terminals/prec sym)))
(define rule-precedences '())
(define (add-rule-precedence! rule sym)
(set! rule-precedences
(cons (cons rule sym) rule-precedences)))
(define (get-rule-precedence ruleno)
(cond
((assq ruleno rule-precedences)
=> (lambda (p)
(get-symbol-precedence (cdr p))))
(else
;; process the rule symbols from left to right
(let loop ((i (vector-ref rrhs ruleno))
(prec 0))
(let ((item (vector-ref ritem i)))
;; end of rule
(if (< item 0)
prec
(let ((i1 (+ i 1)))
(if (>= item nvars)
;; it's a terminal symbol
(loop i1 (get-symbol-precedence (- item nvars)))
(loop i1 prec)))))))))
;; ----------------------------------------------------------------------
;; Build the various tables
;; ----------------------------------------------------------------------
(define expected-conflicts 0)
(define (build-tables)
(define (resolve-conflict sym rule)
(let ((sym-prec (get-symbol-precedence sym))
(sym-assoc (get-symbol-assoc sym))
(rule-prec (get-rule-precedence rule)))
(cond
((> sym-prec rule-prec) 'shift)
((< sym-prec rule-prec) 'reduce)
((eq? sym-assoc 'left) 'reduce)
((eq? sym-assoc 'right) 'shift)
(else 'none))))
(define conflict-messages '())
(define (add-conflict-message . l)
(set! conflict-messages (cons l conflict-messages)))
(define (log-conflicts)
(if (> (length conflict-messages) expected-conflicts)
(for-each
(lambda (message)
(for-each display message)
(newline))
conflict-messages)))
;; --- Add an action to the action table
(define (add-action state symbol new-action)
(let* ((state-actions (vector-ref action-table state))
(actions (assv symbol state-actions)))
(if (pair? actions)
(let ((current-action (cadr actions)))
(if (not (= new-action current-action))
;; -- there is a conflict
(begin
(if (and (<= current-action 0) (<= new-action 0))
;; --- reduce/reduce conflict
(begin
(add-conflict-message
"%% Reduce/Reduce conflict (reduce " (- new-action) ", reduce " (- current-action)
") on '" (get-symbol (+ symbol nvars)) "' in state " state)
(if (glr-driver?)
(set-cdr! (cdr actions) (cons new-action (cddr actions)))
(set-car! (cdr actions) (max current-action new-action))))
;; --- shift/reduce conflict
;; can we resolve the conflict using precedences?
(case (resolve-conflict symbol (- current-action))
;; -- shift
((shift) (if (glr-driver?)
(set-cdr! (cdr actions) (cons new-action (cddr actions)))
(set-car! (cdr actions) new-action)))
;; -- reduce
((reduce) #f) ; well, nothing to do...
;; -- signal a conflict!
(else (add-conflict-message
"%% Shift/Reduce conflict (shift " new-action ", reduce " (- current-action)
") on '" (get-symbol (+ symbol nvars)) "' in state " state)
(if (glr-driver?)
(set-cdr! (cdr actions) (cons new-action (cddr actions)))
(set-car! (cdr actions) new-action))))))))
(vector-set! action-table state (cons (list symbol new-action) state-actions)))
))
(define (add-action-for-all-terminals state action)
(do ((i 1 (+ i 1)))
((= i nterms))
(add-action state i action)))
(set! action-table (make-vector nstates '()))
(do ((i 0 (+ i 1))) ; i = state
((= i nstates))
(let ((red (vector-ref reduction-table i)))
(if (and red (>= (red-nreds red) 1))
(if (and (= (red-nreds red) 1) (vector-ref consistent i))
(if (glr-driver?)
(add-action-for-all-terminals i (- (car (red-rules red))))
(add-action i 'default (- (car (red-rules red)))))
(let ((k (vector-ref lookaheads (+ i 1))))
(let loop ((j (vector-ref lookaheads i)))
(if (< j k)
(let ((rule (- (vector-ref LAruleno j)))
(lav (vector-ref LA j)))
(let loop2 ((token 0) (x (vector-ref lav 0)) (y 1) (z 0))
(if (< token nterms)
(begin
(let ((in-la-set? (modulo x 2)))
(if (= in-la-set? 1)
(add-action i token rule)))
(if (= y (BITS-PER-WORD))
(loop2 (+ token 1)
(vector-ref lav (+ z 1))
1
(+ z 1))
(loop2 (+ token 1) (quotient x 2) (+ y 1) z)))))
(loop (+ j 1)))))))))
(let ((shiftp (vector-ref shift-table i)))
(if shiftp
(let loop ((k (shift-shifts shiftp)))
(if (pair? k)
(let* ((state (car k))
(symbol (vector-ref acces-symbol state)))
(if (>= symbol nvars)
(add-action i (- symbol nvars) state))
(loop (cdr k))))))))
(add-action final-state 0 'accept)
(log-conflicts))
(define (compact-action-table terms)
(define (most-common-action acts)
(let ((accums '()))
(let loop ((l acts))
(if (pair? l)
(let* ((x (cadar l))
(y (assv x accums)))
(if (and (number? x) (< x 0))
(if y
(set-cdr! y (+ 1 (cdr y)))
(set! accums (cons `(,x . 1) accums))))
(loop (cdr l)))))
(let loop ((l accums) (max 0) (sym #f))
(if (null? l)
sym
(let ((x (car l)))
(if (> (cdr x) max)
(loop (cdr l) (cdr x) (car x))
(loop (cdr l) max sym)))))))
(define (translate-terms acts)
(map (lambda (act)
(cons (list-ref terms (car act))
(cdr act)))
acts))
(do ((i 0 (+ i 1)))
((= i nstates))
(let ((acts (vector-ref action-table i)))
(if (vector? (vector-ref reduction-table i))
(let ((act (most-common-action acts)))
(vector-set! action-table i
(cons `(*default* ,(if act act '*error*))
(translate-terms
(lalr-filter (lambda (x)
(not (and (= (length x) 2)
(eq? (cadr x) act))))
acts)))))
(vector-set! action-table i
(cons `(*default* *error*)
(translate-terms acts)))))))
;; --
(define (rewrite-grammar tokens grammar k)
(define eoi '*eoi*)
(define (check-terminal term terms)
(cond
((not (valid-terminal? term))
(lalr-error "invalid terminal: " term))
((member term terms)
(lalr-error "duplicate definition of terminal: " term))))
(define (prec->type prec)
(cdr (assq prec '((left_ . left)
(right_ . right)
(nonassoc_ . nonassoc)))))
(cond
;; --- a few error conditions
((not (list? tokens))
(lalr-error "Invalid token list_ " tokens))
((not (pair? grammar))
(lalr-error "Grammar definition must have a non-empty list of productions" '()))
(else
;; --- check the terminals
(let loop1 ((lst tokens)
(rev-terms '())
(rev-terms/prec '())
(prec-level 0))
(if (pair? lst)
(let ((term (car lst)))
(cond
((pair? term)
(if (and (memq (car term) '(left_ right_ nonassoc_))
(not (null? (cdr term))))
(let ((prec (+ prec-level 1))
(optype (prec->type (car term))))
(let loop-toks ((l (cdr term))
(rev-terms rev-terms)
(rev-terms/prec rev-terms/prec))
(if (null? l)
(loop1 (cdr lst) rev-terms rev-terms/prec prec)
(let ((term (car l)))
(check-terminal term rev-terms)
(loop-toks
(cdr l)
(cons term rev-terms)
(cons (list term optype prec) rev-terms/prec))))))
(lalr-error "invalid operator precedence specification_ " term)))
(else
(check-terminal term rev-terms)
(loop1 (cdr lst)
(cons term rev-terms)
(cons (list term 'none 0) rev-terms/prec)
prec-level))))
;; --- check the grammar rules
(let loop2 ((lst grammar) (rev-nonterm-defs '()))
(if (pair? lst)
(let ((def (car lst)))
(if (not (pair? def))
(lalr-error "Nonterminal definition must be a non-empty list" '())
(let ((nonterm (car def)))
(cond ((not (valid-nonterminal? nonterm))
(lalr-error "Invalid nonterminal_" nonterm))
((or (member nonterm rev-terms)
(assoc nonterm rev-nonterm-defs))
(lalr-error "Nonterminal previously defined_" nonterm))
(else
(loop2 (cdr lst)
(cons def rev-nonterm-defs)))))))
(let* ((terms (cons eoi (cons 'error (reverse rev-terms))))
(terms/prec (cons '(eoi none 0) (cons '(error none 0) (reverse rev-terms/prec))))
(nonterm-defs (reverse rev-nonterm-defs))
(nonterms (cons '*start* (map car nonterm-defs))))
(if (= (length nonterms) 1)
(lalr-error "Grammar must contain at least one nonterminal" '())
(let loop-defs ((defs (cons `(*start* (,(cadr nonterms) ,eoi) \_ $1)
nonterm-defs))
(ruleno 0)
(comp-defs '()))
(if (pair? defs)
(let* ((nonterm-def (car defs))
(compiled-def (rewrite-nonterm-def
nonterm-def
ruleno
terms nonterms)))
(loop-defs (cdr defs)
(+ ruleno (length compiled-def))
(cons compiled-def comp-defs)))
(let ((compiled-nonterm-defs (reverse comp-defs)))
(k terms
terms/prec
nonterms
(map (lambda (x) (cons (caaar x) (map cdar x)))
compiled-nonterm-defs)
(apply append compiled-nonterm-defs))))))))))))))
(define (rewrite-nonterm-def nonterm-def ruleno terms nonterms)
(define No-NT (length nonterms))
(define (encode x)
(let ((PosInNT (pos-in-list x nonterms)))
(if PosInNT
PosInNT
(let ((PosInT (pos-in-list x terms)))
(if PosInT
(+ No-NT PosInT)
(lalr-error "undefined symbol _ " x))))))
(define (process-prec-directive rhs ruleno)
(let loop ((l rhs))
(if (null? l)
'()
(let ((first (car l))
(rest (cdr l)))
(cond
((or (member first terms) (member first nonterms))
(cons first (loop rest)))
((and (pair? first)
(eq? (car first) 'prec_))
(if (and (pair? (cdr first))
(null? (cddr first))
(member (cadr first) terms))
(if (null? rest)
(begin
(add-rule-precedence! ruleno (pos-in-list (cadr first) terms))
(loop rest))
(lalr-error "prec_ directive should be at end of rule_ " rhs))
(lalr-error "Invalid prec_ directive_ " first)))
(else
(lalr-error "Invalid terminal or nonterminal_ " first)))))))
(define (check-error-production rhs)
(let loop ((rhs rhs))
(if (pair? rhs)
(begin
(if (and (eq? (car rhs) 'error)
(or (null? (cdr rhs))
(not (member (cadr rhs) terms))
(not (null? (cddr rhs)))))
(lalr-error "Invalid 'error' production. A single terminal symbol must follow the 'error' token._" rhs))
(loop (cdr rhs))))))
(if (not (pair? (cdr nonterm-def)))
(lalr-error "At least one production needed for nonterminal_" (car nonterm-def))
(let ((name (symbol->string (car nonterm-def))))
(let loop1 ((lst (cdr nonterm-def))
(i 1)
(rev-productions-and-actions '()))
(if (not (pair? lst))
(reverse rev-productions-and-actions)
(let* ((rhs (process-prec-directive (car lst) (+ ruleno i -1)))
(rest (cdr lst))
(prod (map encode (cons (car nonterm-def) rhs))))
;; -- check for undefined tokens
(for-each (lambda (x)
(if (not (or (member x terms) (member x nonterms)))
(lalr-error "Invalid terminal or nonterminal_" x)))
rhs)
;; -- check 'error' productions
(check-error-production rhs)
(if (and (pair? rest)
(eq? (car rest) '_)
(pair? (cdr rest)))
(loop1 (cddr rest)
(+ i 1)
(cons (cons prod (cadr rest))
rev-productions-and-actions))
(let* ((rhs-length (length rhs))
(action
(cons 'vector
(cons (list 'quote (string->symbol
(string-append
name
"-"
(number->string i))))
(let loop-j ((j 1))
(if (> j rhs-length)
'()
(cons (string->symbol
(string-append
"$"
(number->string j)))
(loop-j (+ j 1)))))))))
(loop1 rest
(+ i 1)
(cons (cons prod action)
rev-productions-and-actions))))))))))
(define (valid-nonterminal? x)
(symbol? x))
(define (valid-terminal? x)
(symbol? x)) ; DB
;; ----------------------------------------------------------------------
;; Miscellaneous
;; ----------------------------------------------------------------------
(define (pos-in-list x lst)
(let loop ((lst lst) (i 0))
(cond ((not (pair? lst)) #f)
((equal? (car lst) x) i)
(else (loop (cdr lst) (+ i 1))))))
(define (sunion lst1 lst2) ; union of sorted lists
(let loop ((L1 lst1)
(L2 lst2))
(cond ((null? L1) L2)
((null? L2) L1)
(else
(let ((x (car L1)) (y (car L2)))
(cond
((> x y)
(cons y (loop L1 (cdr L2))))
((< x y)
(cons x (loop (cdr L1) L2)))
(else
(loop (cdr L1) L2))
))))))
(define (sinsert elem lst)
(let loop ((l1 lst))
(if (null? l1)
(cons elem l1)
(let ((x (car l1)))
(cond ((< elem x)
(cons elem l1))
((> elem x)
(cons x (loop (cdr l1))))
(else
l1))))))
(define (lalr-filter p lst)
(let loop ((l lst))
(if (null? l)
'()
(let ((x (car l)) (y (cdr l)))
(if (p x)
(cons x (loop y))
(loop y))))))
;; ----------------------------------------------------------------------
;; Debugging tools ...
;; ----------------------------------------------------------------------
(define the-terminals #f) ; names of terminal symbols
(define the-nonterminals #f) ; non-terminals
(define (print-item item-no)
(let loop ((i item-no))
(let ((v (vector-ref ritem i)))
(if (>= v 0)
(loop (+ i 1))
(let* ((rlno (- v))
(nt (vector-ref rlhs rlno)))
(display (vector-ref the-nonterminals nt)) (display " --> ")
(let loop ((i (vector-ref rrhs rlno)))
(let ((v (vector-ref ritem i)))
(if (= i item-no)
(display ". "))
(if (>= v 0)
(begin
(display (get-symbol v))
(display " ")
(loop (+ i 1)))
(begin
(display " (rule ")
(display (- v))
(display ")")
(newline))))))))))
(define (get-symbol n)
(if (>= n nvars)
(vector-ref the-terminals (- n nvars))
(vector-ref the-nonterminals n)))
(define (print-states)
(define (print-action act)
(cond
((eq? act '*error*)
(display " _ Error"))
((eq? act 'accept)
(display " _ Accept input"))
((< act 0)
(display " _ reduce using rule ")
(display (- act)))
(else
(display " _ shift and goto state ")
(display act)))
(newline)
#t)
(define (print-actions acts)
(let loop ((l acts))
(if (null? l)
#t
(let ((sym (caar l))
(act (cadar l)))
(display " ")
(cond
((eq? sym 'default)
(display "default action"))
(else
(if (number? sym)
(display (get-symbol (+ sym nvars)))
(display sym))))
(print-action act)
(loop (cdr l))))))
(if (not action-table)
(begin
(display "No generated parser available!")
(newline)
#f)
(begin
(display "State table") (newline)
(display "-----------") (newline) (newline)
(let loop ((l first-state))
(if (null? l)
#t
(let* ((core (car l))
(i (core-number core))
(items (core-items core))
(actions (vector-ref action-table i)))
(display "state ") (display i) (newline)
(newline)
(for-each (lambda (x) (display " ") (print-item x))
items)
(newline)
(print-actions actions)
(newline)
(loop (cdr l))))))))
;; ----------------------------------------------------------------------
(define build-goto-table
(lambda ()
`(vector
,@(map
(lambda (shifts)
(list 'quote
(if shifts
(let loop ((l (shift-shifts shifts)))
(if (null? l)
'()
(let* ((state (car l))
(symbol (vector-ref acces-symbol state)))
(if (< symbol nvars)
(cons `(,symbol . ,state)
(loop (cdr l)))
(loop (cdr l))))))
'())))
(vector->list shift-table)))))
(define build-reduction-table
(lambda (gram/actions)
`(vector
'()
,@(map
(lambda (p)
(let ((act (cdr p)))
`(lambda ,(if (eq? driver-name 'lr-driver)
'(___stack ___sp ___goto-table ___push yypushback)
'(___sp ___goto-table ___push))
,(let* ((nt (caar p)) (rhs (cdar p)) (n (length rhs)))
`(let* (,@(if act
(let loop ((i 1) (l rhs))
(if (pair? l)
(let ((rest (cdr l))
(ns (number->string (+ (- n i) 1))))
(cons
`(tok ,(if (eq? driver-name 'lr-driver)
`(vector-ref ___stack (- ___sp ,(- (* i 2) 1)))
`(list-ref ___sp ,(+ (* (- i 1) 2) 1))))
(cons
`(,(string->symbol (string-append "$" ns))
(if (lexical-token? tok) (lexical-token-value tok) tok))
(cons
`(,(string->symbol (string-append "@" ns))
(if (lexical-token? tok) (lexical-token-source tok) tok))
(loop (+ i 1) rest)))))
'()))
'()))
,(if (= nt 0)
'$1
`(___push ,n ,nt ,(cdr p) ,@(if (eq? driver-name 'lr-driver) '() '(___sp))
,(if (eq? driver-name 'lr-driver)
`(vector-ref ___stack (- ___sp ,(length rhs)))
`(list-ref ___sp ,(length rhs))))))))))
gram/actions))))
;; Options
(define *valid-options*
(list
(cons 'out-table_
(lambda (option)
(and (list? option)
(= (length option) 2)
(string? (cadr option)))))
(cons 'output_
(lambda (option)
(and (list? option)
(= (length option) 3)
(symbol? (cadr option))
(string? (caddr option)))))
(cons 'expect_
(lambda (option)
(and (list? option)
(= (length option) 2)
(integer? (cadr option))
(>= (cadr option) 0))))
(cons 'driver_
(lambda (option)
(and (list? option)
(= (length option) 2)
(symbol? (cadr option))
(memq (cadr option) '(lr glr)))))))
(define (validate-options options)
(for-each
(lambda (option)
(let ((p (assoc (car option) *valid-options*)))
(if (or (not p)
(not ((cdr p) option)))
(lalr-error "Invalid option_" option))))
options))
(define (output-parser! options code)
(let ((option (assq 'output_ options)))
(if option
(let ((parser-name (cadr option))
(file-name (caddr option)))
(with-output-to-file file-name
(lambda ()
(pprint `(define ,parser-name ,code))
(newline)))))))
(define (output-table! options)
(let ((option (assq 'out-table_ options)))
(if option
(let ((file-name (cadr option)))
(with-output-to-file file-name print-states)))))
(define (set-expected-conflicts! options)
(let ((option (assq 'expect_ options)))
(set! expected-conflicts (if option (cadr option) 0))))
(define (set-driver-name! options)
(let ((option (assq 'driver_ options)))
(if option
(let ((driver-type (cadr option)))
(set! driver-name (if (eq? driver-type 'glr) 'glr-driver 'lr-driver))))))
;; -- arguments
(define (extract-arguments lst proc)
(let loop ((options '())
(tokens '())
(rules '())
(lst lst))
(if (pair? lst)
(let ((p (car lst)))
(cond
((and (pair? p)
(lalr-keyword? (car p))
(assq (car p) *valid-options*))
(loop (cons p options) tokens rules (cdr lst)))
(else
(proc options p (cdr lst)))))
(lalr-error "Malformed lalr-parser form" lst))))
(define (build-driver options tokens rules)
(validate-options options)
(set-expected-conflicts! options)
(set-driver-name! options)
(let* ((gram/actions (gen-tables! tokens rules))
(code `(,driver-name ',action-table ,(build-goto-table) ,(build-reduction-table gram/actions))))
(output-table! options)
(output-parser! options code)
code))
(extract-arguments arguments build-driver))
;;;
;;;; --
;;;; Implementation of the lr-driver
;;;
(cond-expand
(gambit
(declare
(standard-bindings)
(fixnum)
(block)
(not safe)))
(chicken
(declare
(uses extras)
(usual-integrations)
(fixnum)
(not safe)))
(else))
;;;
;;;; Source location utilities
;;;
;; This function assumes that src-location-1 and src-location-2 are source-locations
;; Returns #f if they are not locations for the same input
(define (combine-locations src-location-1 src-location-2)
(let ((offset-1 (source-location-offset src-location-1))
(offset-2 (source-location-offset src-location-2))
(length-1 (source-location-length src-location-1))
(length-2 (source-location-length src-location-2)))
(cond ((not (equal? (source-location-input src-location-1)
(source-location-input src-location-2)))
#f)
((or (not (number? offset-1)) (not (number? offset-2))
(not (number? length-1)) (not (number? length-2))
(< offset-1 0) (< offset-2 0)
(< length-1 0) (< length-2 0))
(make-source-location (source-location-input src-location-1)
(source-location-line src-location-1)
(source-location-column src-location-1)
-1 -1))
((<= offset-1 offset-2)
(make-source-location (source-location-input src-location-1)
(source-location-line src-location-1)
(source-location-column src-location-1)
offset-1
(- (+ offset-2 length-2) offset-1)))
(else
(make-source-location (source-location-input src-location-1)
(source-location-line src-location-1)
(source-location-column src-location-1)
offset-2
(- (+ offset-1 length-1) offset-2))))))
;;;
;;;; LR-driver
;;;
(define *max-stack-size* 500)
(define (lr-driver action-table goto-table reduction-table)
(define ___atable action-table)
(define ___gtable goto-table)
(define ___rtable reduction-table)
(define ___lexerp #f)
(define ___errorp #f)
(define ___stack #f)
(define ___sp 0)
(define ___curr-input #f)
(define ___reuse-input #f)
(define ___input #f)
(define (___consume)
(set! ___input (if ___reuse-input ___curr-input (___lexerp)))
(set! ___reuse-input #f)
(set! ___curr-input ___input))
(define (___pushback)
(set! ___reuse-input #t))
(define (___initstack)
(set! ___stack (make-vector *max-stack-size* 0))
(set! ___sp 0))
(define (___growstack)
(let ((new-stack (make-vector (* 2 (vector-length ___stack)) 0)))
(let loop ((i (- (vector-length ___stack) 1)))
(if (>= i 0)
(begin
(vector-set! new-stack i (vector-ref ___stack i))
(loop (- i 1)))))
(set! ___stack new-stack)))
(define (___checkstack)
(if (>= ___sp (vector-length ___stack))
(___growstack)))
(define (___push delta new-category lvalue tok)
(set! ___sp (- ___sp (* delta 2)))
(let* ((state (vector-ref ___stack ___sp))
(new-state (cdr (assoc new-category (vector-ref ___gtable state)))))
(set! ___sp (+ ___sp 2))
(___checkstack)
(vector-set! ___stack ___sp new-state)
(vector-set! ___stack (- ___sp 1) (note-source-location lvalue tok))))
(define (___reduce st)
((vector-ref ___rtable st) ___stack ___sp ___gtable ___push ___pushback))
(define (___shift token attribute)
(set! ___sp (+ ___sp 2))
(___checkstack)
(vector-set! ___stack (- ___sp 1) attribute)
(vector-set! ___stack ___sp token))
(define (___action x l)
(let ((y (assoc x l)))
(if y (cadr y) (cadar l))))
(define (___recover tok)
(let find-state ((sp ___sp))
(if (< sp 0)
(set! ___sp sp)
(let* ((state (vector-ref ___stack sp))
(act (assoc 'error (vector-ref ___atable state))))
(if act
(begin
(set! ___sp sp)
(___sync (cadr act) tok))
(find-state (- sp 2)))))))
(define (___sync state tok)
(let ((sync-set (map car (cdr (vector-ref ___atable state)))))
(set! ___sp (+ ___sp 4))
(___checkstack)
(vector-set! ___stack (- ___sp 3) #f)
(vector-set! ___stack (- ___sp 2) state)
(let skip ()
(let ((i (___category ___input)))
(if (eq? i '*eoi*)
(set! ___sp -1)
(if (memq i sync-set)
(let ((act (assoc i (vector-ref ___atable state))))
(vector-set! ___stack (- ___sp 1) #f)
(vector-set! ___stack ___sp (cadr act)))
(begin
(___consume)
(skip))))))))
(define (___category tok)
(if (lexical-token? tok)
(lexical-token-category tok)
tok))
(define (___run)
(let loop ()
(if ___input
(let* ((state (vector-ref ___stack ___sp))
(i (___category ___input))
(act (___action i (vector-ref ___atable state))))
(cond ((not (symbol? i))
(___errorp "Syntax error_ invalid token_ " ___input)
#f)
;; Input succesfully parsed
((eq? act 'accept)
(vector-ref ___stack 1))
;; Syntax error in input
((eq? act '*error*)
(if (eq? i '*eoi*)
(begin
(___errorp "Syntax error_ unexpected end of input")
#f)
(begin
(___errorp "Syntax error_ unexpected token _ " ___input)
(___recover i)
(if (>= ___sp 0)
(set! ___input #f)
(begin
(set! ___sp 0)
(set! ___input '*eoi*)))
(loop))))
;; Shift current token on top of the stack
((>= act 0)
(___shift act ___input)
(set! ___input (if (eq? i '*eoi*) '*eoi* #f))
(loop))
;; Reduce by rule (- act)
(else
(___reduce (- act))
(loop))))
;; no lookahead, so check if there is a default action
;; that does not require the lookahead
(let* ((state (vector-ref ___stack ___sp))
(acts (vector-ref ___atable state))
(defact (if (pair? acts) (cadar acts) #f)))
(if (and (= 1 (length acts)) (< defact 0))
(___reduce (- defact))
(___consume))
(loop)))))
(lambda (lexerp errorp)
(set! ___errorp errorp)
(set! ___lexerp lexerp)
(___initstack)
(___run)))
;;;
;;;; Simple-minded GLR-driver
;;;
(define (glr-driver action-table goto-table reduction-table)
(define ___atable action-table)
(define ___gtable goto-table)
(define ___rtable reduction-table)
(define ___lexerp #f)
(define ___errorp #f)
;; -- Input handling
(define *input* #f)
(define (initialize-lexer lexer)
(set! ___lexerp lexer)
(set! *input* #f))
(define (consume)
(set! *input* (___lexerp)))
(define (token-category tok)
(if (lexical-token? tok)
(lexical-token-category tok)
tok))
(define (token-attribute tok)
(if (lexical-token? tok)
(lexical-token-value tok)
tok))
;; -- Processes (stacks) handling
(define *processes* '())
(define (initialize-processes)
(set! *processes* '()))
(define (add-process process)
(set! *processes* (cons process *processes*)))
(define (get-processes)
(reverse *processes*))
(define (for-all-processes proc)
(let ((processes (get-processes)))
(initialize-processes)
(for-each proc processes)))
;; -- parses
(define *parses* '())
(define (get-parses)
*parses*)
(define (initialize-parses)
(set! *parses* '()))
(define (add-parse parse)
(set! *parses* (cons parse *parses*)))
(define (push delta new-category lvalue stack tok)
(let* ((stack (drop stack (* delta 2)))
(state (car stack))
(new-state (cdr (assv new-category (vector-ref ___gtable state)))))
(cons new-state (cons (note-source-location lvalue tok) stack))))
(define (reduce state stack)
((vector-ref ___rtable state) stack ___gtable push))
(define (shift state symbol stack)
(cons state (cons symbol stack)))
(define (get-actions token action-list)
(let ((pair (assoc token action-list)))
(if pair
(cdr pair)
(cdar action-list)))) ;; get the default action
(define (run)
(let loop-tokens ()
(consume)
(let ((symbol (token-category *input*)))
(for-all-processes
(lambda (process)
(let loop ((stacks (list process)) (active-stacks '()))
(cond ((pair? stacks)
(let* ((stack (car stacks))
(state (car stack)))
(let actions-loop ((actions (get-actions symbol (vector-ref ___atable state)))
(active-stacks active-stacks))
(if (pair? actions)
(let ((action (car actions))
(other-actions (cdr actions)))
(cond ((eq? action '*error*)
(actions-loop other-actions active-stacks))
((eq? action 'accept)
(add-parse (car (take-right stack 2)))
(actions-loop other-actions active-stacks))
((>= action 0)
(let ((new-stack (shift action *input* stack)))
(add-process new-stack))
(actions-loop other-actions active-stacks))
(else
(let ((new-stack (reduce (- action) stack)))
(actions-loop other-actions (cons new-stack active-stacks))))))
(loop (cdr stacks) active-stacks)))))
((pair? active-stacks)
(loop (reverse active-stacks) '())))))))
(if (pair? (get-processes))
(loop-tokens))))
(lambda (lexerp errorp)
(set! ___errorp errorp)
(initialize-lexer lexerp)
(initialize-processes)
(initialize-parses)
(add-process '(0))
(run)
(get-parses)))
(define (drop l n)
(cond ((and (> n 0) (pair? l))
(drop (cdr l) (- n 1)))
(else
l)))
(define (take-right l n)
(drop l (- (length l) n)));;; Multi-language support
;; Copyright (C) 2001, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system base language)
#\use-module (system base syntax)
#\export (define-language language? lookup-language make-language
language-name language-title language-reader
language-printer language-parser
language-compilers language-decompilers language-evaluator
language-joiner language-for-humans?
language-make-default-environment
lookup-compilation-order lookup-decompilation-order
invalidate-compilation-cache! default-environment
*current-language*)
#\re-export (current-language))
;;;
;;; Language class
;;;
(define-record/keywords <language>
name
title
reader
printer
(parser #f)
(compilers '())
(decompilers '())
(evaluator #f)
(joiner #f)
(for-humans? #t)
(make-default-environment make-fresh-user-module))
(define-macro (define-language name . spec)
`(begin
(invalidate-compilation-cache!)
(define ,name (make-language #\name ',name ,@spec))))
(define (lookup-language name)
(let ((m (resolve-module `(language ,name spec))))
(if (module-bound? m name)
(module-ref m name)
(error "no such language" name))))
(define *compilation-cache* '())
(define *decompilation-cache* '())
(define (invalidate-compilation-cache!)
(set! *decompilation-cache* '())
(set! *compilation-cache* '()))
(define (compute-translation-order from to language-translators)
(cond
((not (language? to))
(compute-translation-order from (lookup-language to) language-translators))
(else
(let lp ((from from) (seen '()))
(cond
((not (language? from))
(lp (lookup-language from) seen))
((eq? from to) (reverse! seen))
((memq from seen) #f)
(else (or-map (lambda (pair)
(lp (car pair) (acons from (cdr pair) seen)))
(language-translators from))))))))
(define (lookup-compilation-order from to)
(let ((key (cons from to)))
(or (assoc-ref *compilation-cache* key)
(let ((order (compute-translation-order from to language-compilers)))
(set! *compilation-cache*
(acons key order *compilation-cache*))
order))))
(define (lookup-decompilation-order from to)
(let ((key (cons from to)))
(or (assoc-ref *decompilation-cache* key)
;; trickery!
(let ((order (and=>
(compute-translation-order to from language-decompilers)
reverse!)))
(set! *decompilation-cache* (acons key order *decompilation-cache*))
order))))
(define (default-environment lang)
"Return the default compilation environment for source language LANG."
((language-make-default-environment
(if (language? lang) lang (lookup-language lang)))))
;;;
;;; Current language
;;;
;; Deprecated; use current-language instead.
(define *current-language* (parameter-fluid current-language))
;;; User interface messages
;; Copyright (C) 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary_
;;;
;;; This module provide a simple interface to send messages to the user.
;;; TODO_ Internationalize messages.
;;;
;;; Code_
(define-module (system base message)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (ice-9 match)
#\export (*current-warning-port*
*current-warning-prefix*
warning
warning-type? warning-type-name warning-type-description
warning-type-printer lookup-warning-type
%warning-types))
;;;
;;; Source location
;;;
(define (location-string loc)
(if (pair? loc)
(format #f "~a_~a_~a"
(or (assoc-ref loc 'filename) "<stdin>")
(1+ (assoc-ref loc 'line))
(assoc-ref loc 'column))
"<unknown-location>"))
;;;
;;; Warnings
;;;
;; This name existed before %current-warning-port was introduced, but
;; otherwise it is a deprecated binding.
(define *current-warning-port*
;; Can't play the identifier-syntax deprecation game in Guile 2.0, as
;; other modules might depend on this being a normal binding and not a
;; syntax binding.
(parameter-fluid current-warning-port))
(define *current-warning-prefix*
;; Prefix string when emitting a warning.
(make-fluid ";;; "))
(define-record-type <warning-type>
(make-warning-type name description printer)
warning-type?
(name warning-type-name)
(description warning-type-description)
(printer warning-type-printer))
(define %warning-types
;; List of known warning types.
(map (lambda (args)
(apply make-warning-type args))
(let-syntax ((emit
(lambda (s)
(syntax-case s ()
((_ port fmt args ...)
(string? (syntax->datum #'fmt))
(with-syntax ((fmt
(string-append "~a"
(syntax->datum
#'fmt))))
#'(format port fmt
(fluid-ref *current-warning-prefix*)
args ...)))))))
`((unsupported-warning ;; a "meta warning"
"warn about unknown warning types"
,(lambda (port unused name)
(emit port "warning_ unknown warning type `~A'~%"
name)))
(unused-variable
"report unused variables"
,(lambda (port loc name)
(emit port "~A_ warning_ unused variable `~A'~%"
loc name)))
(unused-toplevel
"report unused local top-level variables"
,(lambda (port loc name)
(emit port "~A_ warning_ possibly unused local top-level variable `~A'~%"
loc name)))
(unbound-variable
"report possibly unbound variables"
,(lambda (port loc name)
(emit port "~A_ warning_ possibly unbound variable `~A'~%"
loc name)))
(arity-mismatch
"report procedure arity mismatches (wrong number of arguments)"
,(lambda (port loc name certain?)
(if certain?
(emit port
"~A_ warning_ wrong number of arguments to `~A'~%"
loc name)
(emit port
"~A_ warning_ possibly wrong number of arguments to `~A'~%"
loc name))))
(duplicate-case-datum
"report a duplicate datum in a case expression"
,(lambda (port loc datum clause case-expr)
(emit port
"~A_ warning_ duplicate datum ~S in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(bad-case-datum
"report a case datum that cannot be meaningfully compared using `eqv?'"
,(lambda (port loc datum clause case-expr)
(emit port
"~A_ warning_ datum ~S cannot be meaningfully compared using `eqv?' in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(format
"report wrong number of arguments to `format'"
,(lambda (port loc . rest)
(define (escape-newlines str)
(list->string
(string-fold-right (lambda (c r)
(if (eq? c #\newline)
(append '(#\\ #\n) r)
(cons c r)))
'()
str)))
(define (range min max)
(cond ((eq? min 'any)
(if (eq? max 'any)
"any number" ;; can't happen
(emit #f "up to ~a" max)))
((eq? max 'any)
(emit #f "at least ~a" min))
((= min max) (number->string min))
(else
(emit #f "~a to ~a" min max))))
(match rest
(('simple-format fmt opt)
(emit port
"~A_ warning_ ~S_ unsupported format option ~~~A, use (ice-9 format) instead~%"
loc (escape-newlines fmt) opt))
(('wrong-format-arg-count fmt min max actual)
(emit port
"~A_ warning_ ~S_ wrong number of `format' arguments_ expected ~A, got ~A~%"
loc (escape-newlines fmt)
(range min max) actual))
(('syntax-error 'unterminated-iteration fmt)
(emit port "~A_ warning_ ~S_ unterminated iteration~%"
loc (escape-newlines fmt)))
(('syntax-error 'unterminated-conditional fmt)
(emit port "~A_ warning_ ~S_ unterminated conditional~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-semicolon fmt)
(emit port "~A_ warning_ ~S_ unexpected `~~;'~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-conditional-termination fmt)
(emit port "~A_ warning_ ~S_ unexpected `~~]'~%"
loc (escape-newlines fmt)))
(('wrong-port wrong-port)
(emit port
"~A_ warning_ ~S_ wrong port argument~%"
loc wrong-port))
(('wrong-format-string fmt)
(emit port
"~A_ warning_ ~S_ wrong format string~%"
loc fmt))
(('non-literal-format-string)
(emit port
"~A_ warning_ non-literal format string~%"
loc))
(('wrong-num-args count)
(emit port
"~A_ warning_ wrong number of arguments to `format'~%"
loc))
(else
(emit port "~A_ `format' warning~%" loc)))))))))
(define (lookup-warning-type name)
"Return the warning type NAME or `#f' if not found."
(find (lambda (wt)
(eq? name (warning-type-name wt)))
%warning-types))
(define (warning type location . args)
"Emit a warning of type TYPE for source location LOCATION (a source
property alist) using the data in ARGS."
(let ((wt (lookup-warning-type type))
(port (current-warning-port)))
(if (warning-type? wt)
(apply (warning-type-printer wt)
port (location-string location)
args)
(format port "~A_ unknown warning type `~A'_ ~A~%"
(location-string location) type args))))
;;; message.scm ends here
;;; pmatch, a simple matcher
;;; Copyright (C) 2009, 2010, 2012 Free Software Foundation, Inc
;;; Copyright (C) 2005,2006,2007 Oleg Kiselyov
;;; Copyright (C) 2007 Daniel P. Friedman
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Originally written by Oleg Kiselyov for LeanTAP in Kanren, which is
;;; available under the MIT license.
;;;
;;; http_//kanren.cvs.sourceforge.net/viewvc/kanren/kanren/mini/leanTAP.scm?view=log
;;;
;;; This version taken from_
;;; αKanren_ A Fresh Name in Nominal Logic Programming
;;; by William E. Byrd and Daniel P. Friedman
;;; Proceedings of the 2007 Workshop on Scheme and Functional Programming
;;; Université Laval Technical Report DIUL-RT-0701
;;; To be clear_ the original code is MIT-licensed, and the modifications
;;; made to it by Guile are under Guile's license (currently LGPL v3+).
;;; Code_
(define-module (system base pmatch)
#\export-syntax (pmatch))
(define-syntax-rule (pmatch e cs ...)
(let ((v e)) (pmatch1 v cs ...)))
(define-syntax pmatch1
(syntax-rules (else guard)
((_ v) (if #f #f))
((_ v (else e0 e ...)) (let () e0 e ...))
((_ v (pat (guard g ...) e0 e ...) cs ...)
(let ((fk (lambda () (pmatch1 v cs ...))))
(ppat v pat
(if (and g ...) (let () e0 e ...) (fk))
(fk))))
((_ v (pat e0 e ...) cs ...)
(let ((fk (lambda () (pmatch1 v cs ...))))
(ppat v pat (let () e0 e ...) (fk))))))
(define-syntax ppat
(syntax-rules (_ quote unquote)
((_ v _ kt kf) kt)
((_ v () kt kf) (if (null? v) kt kf))
((_ v (quote lit) kt kf)
(if (equal? v (quote lit)) kt kf))
((_ v (unquote var) kt kf) (let ((var v)) kt))
((_ v (x . y) kt kf)
(if (pair? v)
(let ((vx (car v)) (vy (cdr v)))
(ppat vx x (ppat vy y kt kf) kf))
kf))
((_ v lit kt kf) (if (eq? v (quote lit)) kt kf))))
;;; Guile VM specific syntaxes and utilities
;; Copyright (C) 2001, 2009, 2016 Free Software Foundation, Inc
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system base syntax)
#\export (%compute-initargs)
#\export-syntax (define-type define-record define-record/keywords
record-case transform-record))
(define (symbol-trim-both sym pred)
(string->symbol (string-trim-both (symbol->string sym) pred)))
(define (trim-brackets sym)
(symbol-trim-both sym (list->char-set '(#\< #\>))))
;;;
;;; Type
;;;
(define-macro (define-type name . rest)
(let ((name (if (pair? name) (car name) name))
(opts (if (pair? name) (cdr name) '())))
(let ((printer (kw-arg-ref opts #\printer))
(common-slots (or (kw-arg-ref opts #\common-slots) '())))
`(begin ,@(map (lambda (def)
`(define-record ,(if printer
`(,(car def) ,printer)
(car def))
,@common-slots
,@(cdr def)))
rest)
,@(map (lambda (common-slot i)
`(define ,(symbol-append (trim-brackets name)
'- common-slot)
(make-procedure-with-setter
(lambda (x) (struct-ref x ,i))
(lambda (x v) (struct-set! x ,i v)))))
common-slots (iota (length common-slots)))))))
;;;
;;; Record
;;;
(define-macro (define-record name-form . slots)
(let* ((name (if (pair? name-form) (car name-form) name-form))
(printer (and (pair? name-form) (cadr name-form)))
(slot-names (map (lambda (slot) (if (pair? slot) (car slot) slot))
slots))
(stem (trim-brackets name)))
`(begin
(define ,name (make-record-type ,(symbol->string name) ',slot-names
,@(if printer (list printer) '())))
,(let* ((reqs (let lp ((slots slots))
(if (or (null? slots) (not (symbol? (car slots))))
'()
(cons (car slots) (lp (cdr slots))))))
(opts (list-tail slots (length reqs)))
(tail (module-gensym "defrec")))
`(define (,(symbol-append 'make- stem) ,@reqs . ,tail)
(let ,(map (lambda (o)
`(,(car o) (cond ((null? ,tail) ,(cadr o))
(else (let ((_x (car ,tail)))
(set! ,tail (cdr ,tail))
_x)))))
opts)
(make-struct ,name 0 ,@slot-names))))
(define ,(symbol-append stem '?) (record-predicate ,name))
,@(map (lambda (sname)
`(define ,(symbol-append stem '- sname)
(make-procedure-with-setter
(record-accessor ,name ',sname)
(record-modifier ,name ',sname))))
slot-names))))
;; like the former, but accepting keyword arguments in addition to
;; optional arguments
(define-macro (define-record/keywords name-form . slots)
(let* ((name (if (pair? name-form) (car name-form) name-form))
(printer (and (pair? name-form) (cadr name-form)))
(slot-names (map (lambda (slot) (if (pair? slot) (car slot) slot))
slots))
(stem (trim-brackets name)))
`(begin
(define ,name (make-record-type ,(symbol->string name) ',slot-names
,@(if printer (list printer) '())))
(define ,(symbol-append 'make- stem)
(let ((slots (list ,@(map (lambda (slot)
(if (pair? slot)
`(cons ',(car slot) ,(cadr slot))
`',slot))
slots)))
(constructor (record-constructor ,name)))
(lambda args
(apply constructor (%compute-initargs args slots)))))
(define ,(symbol-append stem '?) (record-predicate ,name))
,@(map (lambda (sname)
`(define ,(symbol-append stem '- sname)
(make-procedure-with-setter
(record-accessor ,name ',sname)
(record-modifier ,name ',sname))))
slot-names))))
(define (%compute-initargs args slots)
(define (finish out)
(map (lambda (slot)
(let ((name (if (pair? slot) (car slot) slot)))
(cond ((assq name out) => cdr)
((pair? slot) (cdr slot))
(else (error "unbound slot" args slots name)))))
slots))
(let lp ((in args) (positional slots) (out '()))
(cond
((null? in)
(finish out))
((keyword? (car in))
(let ((sym (keyword->symbol (car in))))
(cond
((and (not (memq sym slots))
(not (assq sym (filter pair? slots))))
(error "unknown slot" sym))
((assq sym out) (error "slot already set" sym out))
(else (lp (cddr in) '() (acons sym (cadr in) out))))))
((null? positional)
(error "too many initargs" args slots))
(else
(lp (cdr in) (cdr positional)
(let ((slot (car positional)))
(acons (if (pair? slot) (car slot) slot)
(car in)
out)))))))
;; So, dear reader. It is pleasant indeed around this fire or at this
;; cafe or in this room, is it not? I think so too.
;;
;; This macro used to generate code that looked like this_
;;
;; `(((record-predicate ,record-type) ,r)
;; (let ,(map (lambda (slot)
;; (if (pair? slot)
;; `(,(car slot) ((record-accessor ,record-type ',(cadr slot)) ,r))
;; `(,slot ((record-accessor ,record-type ',slot) ,r))))
;; slots)
;; ,@body)))))
;;
;; But this was a hot spot, so computing all those predicates and
;; accessors all the time was getting expensive, so we did a terrible
;; thing_ we decided that since above we're already defining accessors
;; and predicates with computed names, we might as well just rely on that fact here.
;;
;; It's a bit nasty, I agree. But it is fast.
;;
;;scheme@(guile-user)> (with-statprof #\hz 1000 #\full-stacks? #t (resolve-module '(oop goops)))% cumulative self
;; time seconds seconds name
;; 8.82 0.03 0.01 glil->assembly
;; 8.82 0.01 0.01 record-type-fields
;; 5.88 0.01 0.01 %compute-initargs
;; 5.88 0.01 0.01 list-index
;;; So ugly... but I am too ignorant to know how to make it better.
(define-syntax record-case
(lambda (x)
(syntax-case x ()
((_ record clause ...)
(let ((r (syntax r))
(rtd (syntax rtd)))
(define (process-clause tag fields exprs)
(let ((infix (trim-brackets (syntax->datum tag))))
(with-syntax ((tag tag)
(((f . accessor) ...)
(let lp ((fields fields))
(syntax-case fields ()
(() (syntax ()))
(((v0 f0) f1 ...)
(acons (syntax v0)
(datum->syntax x
(symbol-append infix '- (syntax->datum
(syntax f0))))
(lp (syntax (f1 ...)))))
((f0 f1 ...)
(acons (syntax f0)
(datum->syntax x
(symbol-append infix '- (syntax->datum
(syntax f0))))
(lp (syntax (f1 ...))))))))
((e0 e1 ...)
(syntax-case exprs ()
(() (syntax (#t)))
((e0 e1 ...) (syntax (e0 e1 ...))))))
(syntax
((eq? rtd tag)
(let ((f (accessor r))
...)
e0 e1 ...))))))
(with-syntax
((r r)
(rtd rtd)
((processed ...)
(let lp ((clauses (syntax (clause ...)))
(out '()))
(syntax-case clauses (else)
(()
(reverse! (cons (syntax
(else (error "unhandled record" r)))
out)))
(((else e0 e1 ...))
(reverse! (cons (syntax (else e0 e1 ...)) out)))
(((else e0 e1 ...) . rest)
(syntax-violation 'record-case
"bad else clause placement"
(syntax x)
(syntax (else e0 e1 ...))))
((((<foo> f0 ...) e0 ...) . rest)
(lp (syntax rest)
(cons (process-clause (syntax <foo>)
(syntax (f0 ...))
(syntax (e0 ...)))
out)))))))
(syntax
(let* ((r record)
(rtd (struct-vtable r)))
(cond processed ...)))))))))
;; Here we take the terrorism to another level. Nasty, but the client
;; code looks good.
(define-macro (transform-record type-and-common record . clauses)
(let ((r (module-gensym "rec"))
(rtd (module-gensym "rtd"))
(type-stem (trim-brackets (car type-and-common))))
(define (make-stem s)
(symbol-append type-stem '- s))
(define (further-predicates x record-stem slots)
(define (access slot)
`(,(symbol-append (make-stem record-stem) '- slot) ,x))
(let lp ((in slots) (out '()))
(cond ((null? in) out)
((pair? (car in))
(let ((slot (caar in))
(arg (cadar in)))
(cond ((symbol? arg)
(lp (cdr in) out))
((pair? arg)
(lp (cdr in)
(append (further-predicates (access slot)
(car arg)
(cdr arg))
out)))
(else (lp (cdr in) (cons `(eq? ,(access slot) ',arg)
out))))))
(else (lp (cdr in) out)))))
(define (let-clauses x record-stem slots)
(define (access slot)
`(,(symbol-append (make-stem record-stem) '- slot) ,x))
(let lp ((in slots) (out '()))
(cond ((null? in) out)
((pair? (car in))
(let ((slot (caar in))
(arg (cadar in)))
(cond ((symbol? arg)
(lp (cdr in)
(cons `(,arg ,(access slot)) out)))
((pair? arg)
(lp (cdr in)
(append (let-clauses (access slot)
(car arg)
(cdr arg))
out)))
(else
(lp (cdr in) out)))))
(else
(lp (cdr in)
(cons `(,(car in) ,(access (car in))) out))))))
(define (transform-expr x)
(cond ((not (pair? x)) x)
((eq? (car x) '->)
(if (= (length x) 2)
(let ((form (cadr x)))
`(,(symbol-append 'make- (make-stem (car form)))
,@(cdr type-and-common)
,@(map (lambda (y)
(if (and (pair? y) (eq? (car y) 'unquote))
(transform-expr (cadr y))
y))
(cdr form))))
(error "bad -> form" x)))
(else (cons (car x) (map transform-expr (cdr x))))))
(define (process-clause clause)
(if (eq? (car clause) 'else)
clause
(let ((stem (caar clause))
(slots (cdar clause))
(body (cdr clause)))
(let ((record-type (symbol-append '< (make-stem stem) '>)))
`((and (eq? ,rtd ,record-type)
,@(reverse (further-predicates r stem slots)))
(let ,(reverse (let-clauses r stem slots))
,@(if (pair? body)
(map transform-expr body)
'((if #f #f)))))))))
`(let* ((,r ,record)
(,rtd (struct-vtable ,r))
,@(map (lambda (slot)
`(,slot (,(make-stem slot) ,r)))
(cdr type-and-common)))
(cond ,@(let ((clauses (map process-clause clauses)))
(if (assq 'else clauses)
clauses
(append clauses `((else (error "unhandled record" ,r))))))))))
;;; Compilation targets
;; Copyright (C) 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system base target)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 regex)
#\export (target-type with-target
target-cpu target-vendor target-os
target-endianness target-word-size))
;;;
;;; Target types
;;;
(define %native-word-size
;; The native word size. Note_ don't use `word-size' from
;; (system vm objcode) to avoid a circular dependency.
((@ (system foreign) sizeof) '*))
(define %target-type (make-fluid %host-type))
(define %target-endianness (make-fluid (native-endianness)))
(define %target-word-size (make-fluid %native-word-size))
(define (validate-target target)
(if (or (not (string? target))
(let ((parts (string-split target #\-)))
(or (< (length parts) 3)
(or-map string-null? parts))))
(error "invalid target" target)))
(define (with-target target thunk)
(validate-target target)
(let ((cpu (triplet-cpu target)))
(with-fluids ((%target-type target)
(%target-endianness (cpu-endianness cpu))
(%target-word-size (triplet-pointer-size target)))
(thunk))))
(define (cpu-endianness cpu)
"Return the endianness for CPU."
(if (string=? cpu (triplet-cpu %host-type))
(native-endianness)
(cond ((string-match "^i[0-9]86$" cpu)
(endianness little))
((member cpu '("x86_64" "ia64"
"powerpcle" "powerpc64le" "mipsel" "mips64el" "nios2" "sh3" "sh4" "alpha"))
(endianness little))
((member cpu '("sparc" "sparc64" "powerpc" "powerpc64" "spu"
"mips" "mips64" "m68k" "s390x"))
(endianness big))
((string-match "^arm.*el" cpu)
(endianness little))
((string-match "^arm.*eb" cpu)
(endianness big))
((string-prefix? "arm" cpu) ;ARMs are LE by default
(endianness little))
((string-match "^aarch64.*be" cpu)
(endianness big))
((string=? "aarch64" cpu)
(endianness little))
(else
(error "unknown CPU endianness" cpu)))))
(define (triplet-pointer-size triplet)
"Return the size of pointers in bytes for TRIPLET."
(let ((cpu (triplet-cpu triplet)))
(cond ((and (string=? cpu (triplet-cpu %host-type))
(string=? (triplet-os triplet) (triplet-os %host-type)))
%native-word-size)
((string-match "^i[0-9]86$" cpu) 4)
;; Although GNU config.guess doesn't yet recognize them,
;; Debian (ab)uses the OS part to denote the specific ABI
;; being used_ <http_//wiki.debian.org/Multiarch/Tuples>.
;; See <http_//www.linux-mips.org/wiki/WhatsWrongWithO32N32N64>
;; for details on the MIPS ABIs.
((string-match "^mips64.*-gnuabi64" triplet) 8) ; n64 ABI
((string-match "^mips64" cpu) 4) ; n32 or o32
((string-match "^x86_64-.*-gnux32" triplet) 4) ; x32
((string-match "64$" cpu) 8)
((string-match "64_?[lbe][lbe]$" cpu) 8)
((member cpu '("sparc" "powerpc" "mips" "mipsel" "nios2" "m68k" "sh3" "sh4")) 4)
((member cpu '("s390x" "alpha")) 8)
((string-match "^arm.*" cpu) 4)
(else (error "unknown CPU word size" cpu)))))
(define (triplet-cpu t)
(substring t 0 (string-index t #\-)))
(define (triplet-vendor t)
(let ((start (1+ (string-index t #\-))))
(substring t start (string-index t #\- start))))
(define (triplet-os t)
(let ((start (1+ (string-index t #\- (1+ (string-index t #\-))))))
(substring t start)))
(define (target-type)
"Return the GNU configuration triplet of the target platform."
(fluid-ref %target-type))
(define (target-cpu)
"Return the CPU name of the target platform."
(triplet-cpu (target-type)))
(define (target-vendor)
"Return the vendor name of the target platform."
(triplet-vendor (target-type)))
(define (target-os)
"Return the operating system name of the target platform."
(triplet-os (target-type)))
(define (target-endianness)
"Return the endianness object of the target platform."
(fluid-ref %target-endianness))
(define (target-word-size)
"Return the word size, in bytes, of the target platform."
(fluid-ref %target-word-size))
;;; 'SCM' type tag decoding.
;;; Copyright (C) 2014, 2015 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU Lesser General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; This library 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 Lesser
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public License
;;; along with this program. If not, see <http_//www.gnu.org/licenses/>.
(define-module (system base types)
#\use-module (rnrs bytevectors)
#\use-module (rnrs io ports)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\use-module (srfi srfi-60)
#\use-module (ice-9 match)
#\use-module (ice-9 iconv)
#\use-module (ice-9 format)
#\use-module (ice-9 vlist)
#\use-module (system foreign)
#\export (%word-size
memory-backend
memory-backend?
%ffi-memory-backend
dereference-word
memory-port
type-number->name
inferior-object?
inferior-object-kind
inferior-object-sub-kind
inferior-object-address
inferior-fluid?
inferior-fluid-number
inferior-struct?
inferior-struct-name
inferior-struct-fields
scm->object))
;;; Commentary_
;;;
;;; 'SCM' type tag decoding, primarily to support Guile debugging in GDB.
;;;
;;; Code_
;;;
;;; Memory back-ends.
;;;
(define %word-size
;; The pointer size.
(sizeof '*))
(define-record-type <memory-backend>
(memory-backend peek open type-name)
memory-backend?
(peek memory-backend-peek)
(open memory-backend-open)
(type-name memory-backend-type-name)) ; for SMOBs and ports
(define %ffi-memory-backend
;; The FFI back-end to access the current process's memory. The main
;; purpose of this back-end is to allow testing.
(let ()
(define (dereference-word address)
(let* ((ptr (make-pointer address))
(bv (pointer->bytevector ptr %word-size)))
(bytevector-uint-ref bv 0 (native-endianness) %word-size)))
(define (open address size)
(define current-address address)
(define (read-memory! bv index count)
(let* ((ptr (make-pointer current-address))
(mem (pointer->bytevector ptr count)))
(bytevector-copy! mem 0 bv index count)
(set! current-address (+ current-address count))
count))
(if size
(let* ((ptr (make-pointer address))
(bv (pointer->bytevector ptr size)))
(open-bytevector-input-port bv))
(let ((port (make-custom-binary-input-port "ffi-memory"
read-memory!
#f #f #f)))
(setvbuf port _IONBF)
port)))
(memory-backend dereference-word open #f)))
(define-inlinable (dereference-word backend address)
"Return the word at ADDRESS, using BACKEND."
(let ((peek (memory-backend-peek backend)))
(peek address)))
(define-syntax memory-port
(syntax-rules ()
"Return an input port to the SIZE bytes at ADDRESS, using BACKEND. When
SIZE is omitted, return an unbounded port to the memory at ADDRESS."
((_ backend address)
(let ((open (memory-backend-open backend)))
(open address #f)))
((_ backend address size)
(if (zero? size)
;; GDB's 'open-memory' raises an error when size
;; is zero, so we must handle that case specially.
(open-bytevector-input-port '#vu8())
(let ((open (memory-backend-open backend)))
(open address size))))))
(define (get-word port)
"Read a word from PORT and return it as an integer."
(let ((bv (get-bytevector-n port %word-size)))
(bytevector-uint-ref bv 0 (native-endianness) %word-size)))
(define-inlinable (type-number->name backend kind number)
"Return the name of the type NUMBER of KIND, where KIND is one of
'smob or 'port, or #f if the information is unavailable."
(let ((proc (memory-backend-type-name backend)))
(and proc (proc kind number))))
;;;
;;; Matching bit patterns and cells.
;;;
(define-syntax match-cell-words
(syntax-rules (bytevector)
((_ port ((bytevector name len) rest ...) body)
(let ((name (get-bytevector-n port len))
(remainder (modulo len %word-size)))
(unless (zero? remainder)
(get-bytevector-n port (- %word-size remainder)))
(match-cell-words port (rest ...) body)))
((_ port (name rest ...) body)
(let ((name (get-word port)))
(match-cell-words port (rest ...) body)))
((_ port () body)
body)))
(define-syntax match-bit-pattern
(syntax-rules (& !! = _)
((match-bit-pattern bits ((a !! b) & n = c) consequent alternate)
(let ((tag (logand bits n)))
(if (= tag c)
(let ((b tag)
(a (logand bits (bitwise-not n))))
consequent)
alternate)))
((match-bit-pattern bits (x & n = c) consequent alternate)
(let ((tag (logand bits n)))
(if (= tag c)
(let ((x bits))
consequent)
alternate)))
((match-bit-pattern bits (_ & n = c) consequent alternate)
(let ((tag (logand bits n)))
(if (= tag c)
consequent
alternate)))
((match-bit-pattern bits ((a << n) !! c) consequent alternate)
(let ((tag (bitwise-and bits (- (expt 2 n) 1))))
(if (= tag c)
(let ((a (arithmetic-shift bits (- n))))
consequent)
alternate)))))
(define-syntax match-cell-clauses
(syntax-rules ()
((_ port tag (((tag-pattern thing ...) body) rest ...))
(match-bit-pattern tag tag-pattern
(match-cell-words port (thing ...) body)
(match-cell-clauses port tag (rest ...))))
((_ port tag ())
(inferior-object 'unmatched-tag tag))))
(define-syntax match-cell
(syntax-rules ()
"Match a cell---i.e., a non-immediate value other than a pair. The
cell's contents are read from PORT."
((_ port (pattern body ...) ...)
(let ((port* port)
(tag (get-word port)))
(match-cell-clauses port* tag
((pattern (begin body ...))
...))))))
(define-syntax match-scm-clauses
(syntax-rules ()
((_ bits
(bit-pattern body ...)
rest ...)
(match-bit-pattern bits bit-pattern
(begin body ...)
(match-scm-clauses bits rest ...)))
((_ bits)
'unmatched-scm)))
(define-syntax match-scm
(syntax-rules ()
"Match BITS, an integer representation of an 'SCM' value, against
CLAUSES. Each clause must have the form_
(PATTERN BODY ...)
PATTERN is a bit pattern that may specify bitwise operations on BITS to
determine if it matches. TEMPLATE specify the name of the variable to bind
the matching bits, possibly with bitwise operations to extract it from BITS."
((_ bits clauses ...)
(let ((bits* bits))
(match-scm-clauses bits* clauses ...)))))
;;;
;;; Tags---keep in sync with libguile/tags.h!
;;;
;; Immediate values.
(define %tc2-int 2)
(define %tc3-imm24 4)
(define %tc3-cons 0)
(define %tc3-int1 %tc2-int)
(define %tc3-int2 (+ %tc2-int 4))
(define %tc8-char (+ 8 %tc3-imm24))
(define %tc8-flag (+ %tc3-imm24 0))
;; Cell types.
(define %tc3-struct 1)
(define %tc7-symbol 5)
(define %tc7-variable 7)
(define %tc7-vector 13)
(define %tc7-wvect 15)
(define %tc7-string 21)
(define %tc7-number 23)
(define %tc7-hashtable 29)
(define %tc7-pointer 31)
(define %tc7-fluid 37)
(define %tc7-stringbuf 39)
(define %tc7-dynamic-state 45)
(define %tc7-frame 47)
(define %tc7-objcode 53)
(define %tc7-vm 55)
(define %tc7-vm-continuation 71)
(define %tc7-bytevector 77)
(define %tc7-program 79)
(define %tc7-array 85)
(define %tc7-bitvector 87)
(define %tc7-port 125)
(define %tc7-smob 127)
(define %tc16-bignum (+ %tc7-number (* 1 256)))
(define %tc16-real (+ %tc7-number (* 2 256)))
(define %tc16-complex (+ %tc7-number (* 3 256)))
(define %tc16-fraction (+ %tc7-number (* 4 256)))
;; "Stringbufs".
(define-record-type <stringbuf>
(stringbuf string)
stringbuf?
(string stringbuf-contents))
(set-record-type-printer! <stringbuf>
(lambda (stringbuf port)
(display "#<stringbuf " port)
(write (stringbuf-contents stringbuf) port)
(display "#>" port)))
;; Structs.
(define-record-type <inferior-struct>
(inferior-struct name fields)
inferior-struct?
(name inferior-struct-name)
(fields inferior-struct-fields set-inferior-struct-fields!))
(define print-inferior-struct
(let ((%printed-struct (make-parameter vlist-null)))
(lambda (struct port)
(if (vhash-assq struct (%printed-struct))
(format port "#-1#")
(begin
(format port "#<struct ~a"
(inferior-struct-name struct))
(parameterize ((%printed-struct
(vhash-consq struct #t (%printed-struct))))
(for-each (lambda (field)
(if (eq? field struct)
(display " #0#" port)
(format port " ~s" field)))
(inferior-struct-fields struct)))
(format port " ~x>" (object-address struct)))))))
(set-record-type-printer! <inferior-struct> print-inferior-struct)
;; Fluids.
(define-record-type <inferior-fluid>
(inferior-fluid number value)
inferior-fluid?
(number inferior-fluid-number)
(value inferior-fluid-value))
(set-record-type-printer! <inferior-fluid>
(lambda (fluid port)
(match fluid
(($ <inferior-fluid> number)
(format port "#<fluid ~a ~x>"
number
(object-address fluid))))))
;; Object type to represent complex objects from the inferior process that
;; cannot be really converted to usable Scheme objects in the current
;; process.
(define-record-type <inferior-object>
(%inferior-object kind sub-kind address)
inferior-object?
(kind inferior-object-kind)
(sub-kind inferior-object-sub-kind)
(address inferior-object-address))
(define inferior-object
(case-lambda
"Return an object representing an inferior object at ADDRESS, of type
KIND/SUB-KIND."
((kind address)
(%inferior-object kind #f address))
((kind sub-kind address)
(%inferior-object kind sub-kind address))))
(set-record-type-printer! <inferior-object>
(lambda (io port)
(match io
(($ <inferior-object> kind sub-kind address)
(format port "#<~a ~_[~*~;~a ~]~x>"
kind sub-kind sub-kind
address)))))
(define (inferior-smob backend type-number address)
"Return an object representing the SMOB at ADDRESS whose type is
TYPE-NUMBER."
(inferior-object 'smob
(or (type-number->name backend 'smob type-number)
type-number)
address))
(define (inferior-port backend type-number address)
"Return an object representing the port at ADDRESS whose type is
TYPE-NUMBER."
(inferior-object 'port
(or (type-number->name backend 'port type-number)
type-number)
address))
(define %visited-cells
;; Vhash of mapping addresses of already visited cells to the
;; corresponding inferior object. This is used to detect and represent
;; cycles.
(make-parameter vlist-null))
(define-syntax visited
(syntax-rules (->)
((_ (address -> object) body ...)
(parameterize ((%visited-cells (vhash-consv address object
(%visited-cells))))
body ...))))
(define (address->inferior-struct address vtable-data-address backend)
"Read the struct at ADDRESS using BACKEND. Return an 'inferior-struct'
object representing it."
(define %vtable-layout-index 0)
(define %vtable-name-index 5)
(let* ((layout-address (+ vtable-data-address
(* %vtable-layout-index %word-size)))
(layout-bits (dereference-word backend layout-address))
(layout (scm->object layout-bits backend))
(name-address (+ vtable-data-address
(* %vtable-name-index %word-size)))
(name-bits (dereference-word backend name-address))
(name (scm->object name-bits backend)))
(if (symbol? layout)
(let* ((layout (symbol->string layout))
(len (/ (string-length layout) 2))
(slots (dereference-word backend (+ address %word-size)))
(port (memory-port backend slots (* len %word-size)))
(fields (get-bytevector-n port (* len %word-size)))
(result (inferior-struct name #f)))
;; Keep track of RESULT so callees can refer to it if we are
;; decoding a circular struct.
(visited (address -> result)
(let ((values (map (cut scm->object <> backend)
(bytevector->uint-list fields
(native-endianness)
%word-size))))
(set-inferior-struct-fields! result values)
result)))
(inferior-object 'invalid-struct address))))
(define* (cell->object address #\optional (backend %ffi-memory-backend))
"Return an object representing the object at ADDRESS, reading from memory
using BACKEND."
(or (and=> (vhash-assv address (%visited-cells)) cdr) ; circular object
(let ((port (memory-port backend address)))
(match-cell port
(((vtable-data-address & 7 = %tc3-struct))
(address->inferior-struct address
(- vtable-data-address %tc3-struct)
backend))
(((_ & #x7f = %tc7-symbol) buf hash props)
(match (cell->object buf backend)
(($ <stringbuf> string)
(string->symbol string))))
(((_ & #x7f = %tc7-variable) obj)
(inferior-object 'variable address))
(((_ & #x7f = %tc7-string) buf start len)
(match (cell->object buf backend)
(($ <stringbuf> string)
(substring string start (+ start len)))))
(((_ & #x047f = %tc7-stringbuf) len (bytevector buf len))
(stringbuf (bytevector->string buf "ISO-8859-1")))
(((_ & #x047f = (bitwise-ior #x400 %tc7-stringbuf))
len (bytevector buf (* 4 len)))
(stringbuf (bytevector->string buf (match (native-endianness)
('little "UTF-32LE")
('big "UTF-32BE")))))
(((_ & #x7f = %tc7-bytevector) len address)
(let ((bv-port (memory-port backend address len)))
(get-bytevector-n bv-port len)))
((((len << 7) !! %tc7-vector) weakv-data)
(let* ((len (arithmetic-shift len -1))
(words (get-bytevector-n port (* len %word-size)))
(vector (make-vector len)))
(visited (address -> vector)
(fold (lambda (element index)
(vector-set! vector index element)
(+ 1 index))
0
(map (cut scm->object <> backend)
(bytevector->uint-list words (native-endianness)
%word-size)))
vector)))
(((_ & #x7f = %tc7-wvect))
(inferior-object 'weak-vector address)) ; TODO_ show elements
((((n << 8) !! %tc7-fluid) init-value)
(inferior-fluid n #f)) ; TODO_ show current value
(((_ & #x7f = %tc7-dynamic-state))
(inferior-object 'dynamic-state address))
((((flags+type << 8) !! %tc7-port))
(inferior-port backend (logand flags+type #xff) address))
(((_ & #x7f = %tc7-program))
(inferior-object 'program address))
(((_ & #xffff = %tc16-bignum))
(inferior-object 'bignum address))
(((_ & #xffff = %tc16-real) pad)
(let* ((address (+ address (* 2 %word-size)))
(port (memory-port backend address (sizeof double)))
(words (get-bytevector-n port (sizeof double))))
(bytevector-ieee-double-ref words 0 (native-endianness))))
(((_ & #x7f = %tc7-number) mpi)
(inferior-object 'number address))
(((_ & #x7f = %tc7-hashtable) buckets meta-data unused)
(inferior-object 'hash-table address))
(((_ & #x7f = %tc7-pointer) address)
(make-pointer address))
(((_ & #x7f = %tc7-objcode))
(inferior-object 'objcode address))
(((_ & #x7f = %tc7-vm))
(inferior-object 'vm address))
(((_ & #x7f = %tc7-vm-continuation))
(inferior-object 'vm-continuation address))
(((_ & #x7f = %tc7-array))
(inferior-object 'array address))
(((_ & #x7f = %tc7-bitvector))
(inferior-object 'bitvector address))
((((smob-type << 8) !! %tc7-smob) word1)
(inferior-smob backend smob-type address))))))
(define* (scm->object bits #\optional (backend %ffi-memory-backend))
"Return the Scheme object corresponding to BITS, the bits of an 'SCM'
object."
(match-scm bits
(((integer << 2) !! %tc2-int)
integer)
((address & 6 = %tc3-cons)
(let* ((type (dereference-word backend address))
(pair? (not (bit-set? 0 type))))
(if pair?
(or (and=> (vhash-assv address (%visited-cells)) cdr)
(let ((car type)
(cdrloc (+ address %word-size))
(pair (cons *unspecified* *unspecified*)))
(visited (address -> pair)
(set-car! pair (scm->object car backend))
(set-cdr! pair
(scm->object (dereference-word backend cdrloc)
backend))
pair)))
(cell->object address backend))))
(((char << 8) !! %tc8-char)
(integer->char char))
(((flag << 8) !! %tc8-flag)
(case flag
((0) #f)
((1) #nil)
((3) '())
((4) #t)
((8) (if #f #f))
((9) (inferior-object 'undefined bits))
((10) (eof-object))
((11) (inferior-object 'unbound bits))))))
;;; Local Variables_
;;; eval_ (put 'match-scm 'scheme-indent-function 1)
;;; eval_ (put 'match-cell 'scheme-indent-function 1)
;;; eval_ (put 'visited 'scheme-indent-function 1)
;;; End_
;;; types.scm ends here
;;;; Copyright (C) 2010, 2011, 2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2.1 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (system foreign)
#\use-module (rnrs bytevectors)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\export (void
float double
short
unsigned-short
int unsigned-int long unsigned-long size_t ssize_t ptrdiff_t
int8 uint8
uint16 int16
uint32 int32
uint64 int64
sizeof alignof
%null-pointer
null-pointer?
pointer?
make-pointer
pointer->scm
scm->pointer
pointer-address
pointer->bytevector
bytevector->pointer
set-pointer-finalizer!
dereference-pointer
string->pointer
pointer->string
pointer->procedure
;; procedure->pointer (see below)
make-c-struct parse-c-struct
define-wrapped-pointer-type))
(eval-when (expand load eval)
(load-extension (string-append "libguile-" (effective-version))
"scm_init_foreign"))
;;;
;;; Pointers.
;;;
(define (null-pointer? pointer)
"Return true if POINTER is the null pointer."
(= (pointer-address pointer) 0))
(if (defined? 'procedure->pointer)
(export procedure->pointer))
;;;
;;; Structures.
;;;
(define bytevector-pointer-ref
(case (sizeof '*)
((8) (lambda (bv offset)
(make-pointer (bytevector-u64-native-ref bv offset))))
((4) (lambda (bv offset)
(make-pointer (bytevector-u32-native-ref bv offset))))
(else (error "what machine is this?"))))
(define bytevector-pointer-set!
(case (sizeof '*)
((8) (lambda (bv offset ptr)
(bytevector-u64-native-set! bv offset (pointer-address ptr))))
((4) (lambda (bv offset ptr)
(bytevector-u32-native-set! bv offset (pointer-address ptr))))
(else (error "what machine is this?"))))
(define *writers*
`((,float . ,bytevector-ieee-single-native-set!)
(,double . ,bytevector-ieee-double-native-set!)
(,int8 . ,bytevector-s8-set!)
(,uint8 . ,bytevector-u8-set!)
(,int16 . ,bytevector-s16-native-set!)
(,uint16 . ,bytevector-u16-native-set!)
(,int32 . ,bytevector-s32-native-set!)
(,uint32 . ,bytevector-u32-native-set!)
(,int64 . ,bytevector-s64-native-set!)
(,uint64 . ,bytevector-u64-native-set!)
(* . ,bytevector-pointer-set!)))
(define *readers*
`((,float . ,bytevector-ieee-single-native-ref)
(,double . ,bytevector-ieee-double-native-ref)
(,int8 . ,bytevector-s8-ref)
(,uint8 . ,bytevector-u8-ref)
(,int16 . ,bytevector-s16-native-ref)
(,uint16 . ,bytevector-u16-native-ref)
(,int32 . ,bytevector-s32-native-ref)
(,uint32 . ,bytevector-u32-native-ref)
(,int64 . ,bytevector-s64-native-ref)
(,uint64 . ,bytevector-u64-native-ref)
(* . ,bytevector-pointer-ref)))
(define (align off alignment)
(1+ (logior (1- off) (1- alignment))))
(define (write-c-struct bv offset types vals)
(let lp ((offset offset) (types types) (vals vals))
(cond
((not (pair? types))
(or (null? vals)
(error "too many values" vals)))
((not (pair? vals))
(error "too few values" types))
(else
;; alignof will error-check
(let* ((type (car types))
(offset (align offset (alignof type))))
(if (pair? type)
(write-c-struct bv offset (car types) (car vals))
((assv-ref *writers* type) bv offset (car vals)))
(lp (+ offset (sizeof type)) (cdr types) (cdr vals)))))))
(define (read-c-struct bv offset types)
(let lp ((offset offset) (types types) (vals '()))
(cond
((not (pair? types))
(reverse vals))
(else
;; alignof will error-check
(let* ((type (car types))
(offset (align offset (alignof type))))
(lp (+ offset (sizeof type)) (cdr types)
(cons (if (pair? type)
(read-c-struct bv offset (car types))
((assv-ref *readers* type) bv offset))
vals)))))))
(define (make-c-struct types vals)
(let ((bv (make-bytevector (sizeof types) 0)))
(write-c-struct bv 0 types vals)
(bytevector->pointer bv)))
(define (parse-c-struct foreign types)
(let ((size (fold (lambda (type total)
(+ (sizeof type)
(align total (alignof type))))
0
types)))
(read-c-struct (pointer->bytevector foreign size) 0 types)))
;;;
;;; Wrapped pointer types.
;;;
(define-syntax define-wrapped-pointer-type
(lambda (stx)
"Define helper procedures to wrap pointer objects into Scheme
objects with a disjoint type. Specifically, this macro defines PRED, a
predicate for the new Scheme type, WRAP, a procedure that takes a
pointer object and returns an object that satisfies PRED, and UNWRAP
which does the reverse. PRINT must name a user-defined object printer."
(syntax-case stx ()
((_ type-name pred wrap unwrap print)
(with-syntax ((%wrap (datum->syntax #'wrap (gensym "wrap"))))
#'(begin
(define-record-type type-name
(%wrap pointer)
pred
(pointer unwrap))
(define wrap
;; Use a weak hash table to preserve pointer identity, i.e.,
;; PTR1 == PTR2 <-> (eq? (wrap PTR1) (wrap PTR2)).
(let ((ptr->obj (make-weak-value-hash-table 3000)))
(lambda (ptr)
;; XXX_ We can't use `hash-create-handle!' +
;; `set-cdr!' here because the former would create a
;; weak-cdr pair but the latter wouldn't register a
;; disappearing link (see `scm_hash_fn_set_x'.)
(or (hash-ref ptr->obj ptr)
(let ((o (%wrap ptr)))
(hash-set! ptr->obj ptr o)
o)))))
(set-record-type-printer! type-name print)))))))
;;; Repl commands
;; Copyright (C) 2001, 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system repl command)
#\use-module (system base syntax)
#\use-module (system base pmatch)
#\use-module (system base compile)
#\use-module (system repl common)
#\use-module (system repl debug)
#\use-module (system vm objcode)
#\use-module (system vm program)
#\use-module (system vm trap-state)
#\use-module (system vm vm)
#\use-module ((system vm frame) #\select (frame-return-values))
#\autoload (system base language) (lookup-language language-reader)
#\autoload (system vm trace) (call-with-trace)
#\use-module (ice-9 format)
#\use-module (ice-9 session)
#\use-module (ice-9 documentation)
#\use-module (ice-9 and-let-star)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 control)
#\use-module ((ice-9 pretty-print) #\select ((pretty-print . pp)))
#\use-module ((system vm inspect) #\select ((inspect . %inspect)))
#\use-module (statprof)
#\export (meta-command define-meta-command))
;;;
;;; Meta command interface
;;;
(define *command-table*
'((help (help h) (show) (apropos a) (describe d))
(module (module m) (import use) (load l) (reload re) (binding b) (in))
(language (language L))
(compile (compile c) (compile-file cc)
(expand exp) (optimize opt)
(disassemble x) (disassemble-file xx))
(profile (time t) (profile pr) (trace tr))
(debug (backtrace bt) (up) (down) (frame fr)
(procedure proc) (locals) (error-message error)
(break br bp) (break-at-source break-at bs)
(step s) (step-instruction si)
(next n) (next-instruction ni)
(finish)
(tracepoint tp)
(traps) (delete del) (disable) (enable)
(registers regs))
(inspect (inspect i) (pretty-print pp))
(system (gc) (statistics stat) (option o)
(quit q continue cont))))
(define *show-table*
'((show (warranty w) (copying c) (version v))))
(define (group-name g) (car g))
(define (group-commands g) (cdr g))
(define *command-infos* (make-hash-table))
(define (command-name c) (car c))
(define (command-abbrevs c) (cdr c))
(define (command-info c) (hashq-ref *command-infos* (command-name c)))
(define (command-procedure c) (command-info-procedure (command-info c)))
(define (command-doc c) (procedure-documentation (command-procedure c)))
(define (make-command-info proc arguments-reader)
(cons proc arguments-reader))
(define (command-info-procedure info)
(car info))
(define (command-info-arguments-reader info)
(cdr info))
(define (command-usage c)
(let ((doc (command-doc c)))
(substring doc 0 (string-index doc #\newline))))
(define (command-summary c)
(let* ((doc (command-doc c))
(start (1+ (string-index doc #\newline))))
(cond ((string-index doc #\newline start)
=> (lambda (end) (substring doc start end)))
(else (substring doc start)))))
(define (lookup-group name)
(assq name *command-table*))
(define* (lookup-command key #\optional (table *command-table*))
(let loop ((groups table) (commands '()))
(cond ((and (null? groups) (null? commands)) #f)
((null? commands)
(loop (cdr groups) (cdar groups)))
((memq key (car commands)) (car commands))
(else (loop groups (cdr commands))))))
(define* (display-group group #\optional (abbrev? #t))
(format #t "~_(~A~) Commands~_[~; [abbrev]~]_~2%" (group-name group) abbrev?)
(for-each (lambda (c)
(display-summary (command-usage c)
(if abbrev? (command-abbrevs c) '())
(command-summary c)))
(group-commands group))
(newline))
(define (display-command command)
(display "Usage_ ")
(display (command-doc command))
(newline))
(define (display-summary usage abbrevs summary)
(let* ((usage-len (string-length usage))
(abbrevs (if (pair? abbrevs)
(format #f "[,~A~{ ,~A~}]" (car abbrevs) (cdr abbrevs))
""))
(abbrevs-len (string-length abbrevs)))
(format #t " ,~A~A~A - ~A\n"
usage
(cond
((> abbrevs-len 32)
(error "abbrevs too long" abbrevs))
((> (+ usage-len abbrevs-len) 32)
(format #f "~%~v_" (+ 2 (- 32 abbrevs-len))))
(else
(format #f "~v_" (- 32 abbrevs-len usage-len))))
abbrevs
summary)))
(define (read-command repl)
(catch #t
(lambda () (read))
(lambda (key . args)
(pmatch args
((,subr ,msg ,args . ,rest)
(format #t "Throw to key `~a' while reading command_\n" key)
(display-error #f (current-output-port) subr msg args rest))
(else
(format #t "Throw to key `~a' with args `~s' while reading command.\n"
key args)))
(force-output)
*unspecified*)))
(define (read-command-arguments c repl)
((command-info-arguments-reader (command-info c)) repl))
(define (meta-command repl)
(let ((command (read-command repl)))
(cond
((eq? command *unspecified*)) ; read error, already signalled; pass.
((not (symbol? command))
(format #t "Meta-command not a symbol_ ~s~%" command))
((lookup-command command)
=> (lambda (c)
(and=> (read-command-arguments c repl)
(lambda (args) (apply (command-procedure c) repl args)))))
(else
(format #t "Unknown meta command_ ~A~%" command)))))
(define (add-meta-command! name category proc argument-reader)
(hashq-set! *command-infos* name (make-command-info proc argument-reader))
(if category
(let ((entry (assq category *command-table*)))
(if entry
(set-cdr! entry (append (cdr entry) (list (list name))))
(set! *command-table*
(append *command-table*
(list (list category (list name)))))))))
(define-syntax define-meta-command
(syntax-rules ()
((_ ((name category) repl (expression0 ...) . datums) docstring b0 b1 ...)
(add-meta-command!
'name
'category
(lambda* (repl expression0 ... . datums)
docstring
b0 b1 ...)
(lambda (repl)
(define (handle-read-error form-name key args)
(pmatch args
((,subr ,msg ,args . ,rest)
(format #t "Throw to key `~a' while reading ~@[argument `~A' of ~]command `~A'_\n"
key form-name 'name)
(display-error #f (current-output-port) subr msg args rest))
(else
(format #t "Throw to key `~a' with args `~s' while reading ~@[ argument `~A' of ~]command `~A'.\n"
key args form-name 'name)))
(abort))
(% (let* ((expression0
(catch #t
(lambda ()
(repl-reader
""
(lambda* (#\optional (port (current-input-port)))
((language-reader (repl-language repl))
port (current-module)))))
(lambda (k . args)
(handle-read-error 'expression0 k args))))
...)
(append
(list expression0 ...)
(catch #t
(lambda ()
(let ((port (open-input-string (read-line))))
(let lp ((out '()))
(let ((x (read port)))
(if (eof-object? x)
(reverse out)
(lp (cons x out)))))))
(lambda (k . args)
(handle-read-error #f k args)))))
(lambda (k) #f))))) ; the abort handler
((_ ((name category) repl . datums) docstring b0 b1 ...)
(define-meta-command ((name category) repl () . datums)
docstring b0 b1 ...))
((_ (name repl (expression0 ...) . datums) docstring b0 b1 ...)
(define-meta-command ((name #f) repl (expression0 ...) . datums)
docstring b0 b1 ...))
((_ (name repl . datums) docstring b0 b1 ...)
(define-meta-command ((name #f) repl () . datums)
docstring b0 b1 ...))))
;;;
;;; Help commands
;;;
(define-meta-command (help repl . args)
"help [all | GROUP | [-c] COMMAND]
Show help.
With one argument, tries to look up the argument as a group name, giving
help on that group if successful. Otherwise tries to look up the
argument as a command, giving help on the command.
If there is a command whose name is also a group name, use the ,help
-c COMMAND form to give help on the command instead of the group.
Without any argument, a list of help commands and command groups
are displayed."
(pmatch args
(()
(display-group (lookup-group 'help))
(display "Command Groups_\n\n")
(display-summary "help all" #f "List all commands")
(for-each (lambda (g)
(let* ((name (symbol->string (group-name g)))
(usage (string-append "help " name))
(header (string-append "List " name " commands")))
(display-summary usage #f header)))
(cdr *command-table*))
(newline)
(display
"Type `,help -c COMMAND' to show documentation of a particular command.")
(newline))
((all)
(for-each display-group *command-table*))
((,group) (guard (lookup-group group))
(display-group (lookup-group group)))
((,command) (guard (lookup-command command))
(display-command (lookup-command command)))
((-c ,command) (guard (lookup-command command))
(display-command (lookup-command command)))
((,command)
(format #t "Unknown command or group_ ~A~%" command))
((-c ,command)
(format #t "Unknown command_ ~A~%" command))
(else
(format #t "Bad arguments_ ~A~%" args))))
(define-meta-command (show repl . args)
"show [TOPIC]
Gives information about Guile.
With one argument, tries to show a particular piece of information;
currently supported topics are `warranty' (or `w'), `copying' (or `c'),
and `version' (or `v').
Without any argument, a list of topics is displayed."
(pmatch args
(()
(display-group (car *show-table*) #f)
(newline))
((,topic) (guard (lookup-command topic *show-table*))
((command-procedure (lookup-command topic *show-table*)) repl))
((,command)
(format #t "Unknown topic_ ~A~%" command))
(else
(format #t "Bad arguments_ ~A~%" args))))
;;; `warranty', `copying' and `version' are "hidden" meta-commands, only
;;; accessible via `show'. They have an entry in *command-infos* but not
;;; in *command-table*.
(define-meta-command (warranty repl)
"show warranty
Details on the lack of warranty."
(display *warranty*)
(newline))
(define-meta-command (copying repl)
"show copying
Show the LGPLv3."
(display *copying*)
(newline))
(define-meta-command (version repl)
"show version
Version information."
(display *version*)
(newline))
(define-meta-command (apropos repl regexp)
"apropos REGEXP
Find bindings/modules/packages."
(apropos (->string regexp)))
(define-meta-command (describe repl (form))
"describe OBJ
Show description/documentation."
(display
(object-documentation
(let ((input (repl-parse repl form)))
(if (symbol? input)
(module-ref (current-module) input)
(repl-eval repl input)))))
(newline))
(define-meta-command (option repl . args)
"option [NAME] [EXP]
List/show/set options."
(pmatch args
(()
(for-each (lambda (spec)
(format #t " ~A~24t~A\n" (car spec) (cadr spec)))
(repl-options repl)))
((,name)
(display (repl-option-ref repl name))
(newline))
((,name ,exp)
;; Would be nice to evaluate in the current language, but the REPL
;; option parser doesn't permit that, currently.
(repl-option-set! repl name (eval exp (current-module))))))
(define-meta-command (quit repl)
"quit
Quit this session."
(throw 'quit))
;;;
;;; Module commands
;;;
(define-meta-command (module repl . args)
"module [MODULE]
Change modules / Show current module."
(pmatch args
(() (puts (module-name (current-module))))
((,mod-name) (guard (list? mod-name))
(set-current-module (resolve-module mod-name)))
(,mod-name (set-current-module (resolve-module mod-name)))))
(define-meta-command (import repl . args)
"import [MODULE ...]
Import modules / List those imported."
(let ()
(define (use name)
(let ((mod (resolve-interface name)))
(if mod
(module-use! (current-module) mod)
(format #t "No such module_ ~A~%" name))))
(if (null? args)
(for-each puts (map module-name (module-uses (current-module))))
(for-each use args))))
(define-meta-command (load repl file)
"load FILE
Load a file in the current module."
(load (->string file)))
(define-meta-command (reload repl . args)
"reload [MODULE]
Reload the given module, or the current module if none was given."
(pmatch args
(() (reload-module (current-module)))
((,mod-name) (guard (list? mod-name))
(reload-module (resolve-module mod-name)))
(,mod-name (reload-module (resolve-module mod-name)))))
(define-meta-command (binding repl)
"binding
List current bindings."
(module-for-each (lambda (k v) (format #t "~23A ~A\n" k v))
(current-module)))
(define-meta-command (in repl module command-or-expression . args)
"in MODULE COMMAND-OR-EXPRESSION
Evaluate an expression or command in the context of module."
(let ((m (resolve-module module #\ensure #f)))
(if m
(pmatch command-or-expression
(('unquote ,command) (guard (lookup-command command))
(save-module-excursion
(lambda ()
(set-current-module m)
(apply (command-procedure (lookup-command command)) repl args))))
(,expression
(guard (null? args))
(repl-print repl (eval expression m)))
(else
(format #t "Invalid arguments to `in'_ expected a single expression or a command.\n")))
(format #t "No such module_ ~s\n" module))))
;;;
;;; Language commands
;;;
(define-meta-command (language repl name)
"language LANGUAGE
Change languages."
(let ((lang (lookup-language name))
(cur (repl-language repl)))
(format #t "Happy hacking with ~a! To switch back, type `,L ~a'.\n"
(language-title lang) (language-name cur))
(current-language lang)
(set! (repl-language repl) lang)))
;;;
;;; Compile commands
;;;
(define-meta-command (compile repl (form))
"compile EXP
Generate compiled code."
(let ((x (repl-compile repl (repl-parse repl form))))
(cond ((objcode? x) (guile_disassemble x))
(else (repl-print repl x)))))
(define-meta-command (compile-file repl file . opts)
"compile-file FILE
Compile a file."
(compile-file (->string file) #\opts opts))
(define-meta-command (expand repl (form))
"expand EXP
Expand any macros in a form."
(let ((x (repl-expand repl (repl-parse repl form))))
(run-hook before-print-hook x)
(pp x)))
(define-meta-command (optimize repl (form))
"optimize EXP
Run the optimizer on a piece of code and print the result."
(let ((x (repl-optimize repl (repl-parse repl form))))
(run-hook before-print-hook x)
(pp x)))
(define (guile_disassemble x)
((@ (language assembly disassemble) disassemble) x))
(define-meta-command (disassemble repl (form))
"disassemble EXP
Disassemble a compiled procedure."
(let ((obj (repl-eval repl (repl-parse repl form))))
(if (or (program? obj) (objcode? obj))
(guile_disassemble obj)
(format #t "Argument to ,disassemble not a procedure or objcode_ ~a~%"
obj))))
(define-meta-command (disassemble-file repl file)
"disassemble-file FILE
Disassemble a file."
(guile_disassemble (load-objcode (->string file))))
;;;
;;; Profile commands
;;;
(define-meta-command (time repl (form))
"time EXP
Time execution."
(let* ((gc-start (gc-run-time))
(real-start (get-internal-real-time))
(run-start (get-internal-run-time))
(result (repl-eval repl (repl-parse repl form)))
(run-end (get-internal-run-time))
(real-end (get-internal-real-time))
(gc-end (gc-run-time)))
(define (diff start end)
(/ (- end start) 1.0 internal-time-units-per-second))
(repl-print repl result)
(format #t ";; ~,6Fs real time, ~,6Fs run time. ~,6Fs spent in GC.\n"
(diff real-start real-end)
(diff run-start run-end)
(diff gc-start gc-end))
result))
(define-meta-command (profile repl (form) . opts)
"profile EXP
Profile execution."
;; FIXME opts
(apply statprof
(repl-prepare-eval-thunk repl (repl-parse repl form))
opts))
(define-meta-command (trace repl (form) . opts)
"trace EXP
Trace execution."
;; FIXME_ doc options, or somehow deal with them better
(apply call-with-trace
(repl-prepare-eval-thunk repl (repl-parse repl form))
(cons* #\width (terminal-width) opts)))
;;;
;;; Debug commands
;;;
(define-syntax define-stack-command
(lambda (x)
(syntax-case x ()
((_ (name repl . args) docstring body body* ...)
#`(define-meta-command (name repl . args)
docstring
(let ((debug (repl-debug repl)))
(if debug
(letrec-syntax
((#,(datum->syntax #'repl 'frames)
(identifier-syntax (debug-frames debug)))
(#,(datum->syntax #'repl 'message)
(identifier-syntax (debug-error-message debug)))
(#,(datum->syntax #'repl 'for-trap?)
(identifier-syntax (debug-for-trap? debug)))
(#,(datum->syntax #'repl 'index)
(identifier-syntax
(id (debug-index debug))
((set! id exp) (set! (debug-index debug) exp))))
(#,(datum->syntax #'repl 'cur)
(identifier-syntax
(vector-ref #,(datum->syntax #'repl 'frames)
#,(datum->syntax #'repl 'index)))))
body body* ...)
(format #t "Nothing to debug.~%"))))))))
(define-stack-command (backtrace repl #\optional count
#\key (width (terminal-width)) full?)
"backtrace [COUNT] [#:width W] [#full? F]
Print a backtrace.
Print a backtrace of all stack frames, or innermost COUNT frames.
If COUNT is negative, the last COUNT frames will be shown."
(print-frames frames
#\count count
#\width width
#\full? full?
#\for-trap? for-trap?))
(define-stack-command (up repl #\optional (count 1))
"up [COUNT]
Select a calling stack frame.
Select and print stack frames that called this one.
An argument says how many frames up to go."
(cond
((or (not (integer? count)) (<= count 0))
(format #t "Invalid argument to `up'_ expected a positive integer for COUNT.~%"))
((>= (+ count index) (vector-length frames))
(cond
((= index (1- (vector-length frames)))
(format #t "Already at outermost frame.\n"))
(else
(set! index (1- (vector-length frames)))
(print-frame cur #\index index
#\next-source? (and (zero? index) for-trap?)))))
(else
(set! index (+ count index))
(print-frame cur #\index index
#\next-source? (and (zero? index) for-trap?)))))
(define-stack-command (down repl #\optional (count 1))
"down [COUNT]
Select a called stack frame.
Select and print stack frames called by this one.
An argument says how many frames down to go."
(cond
((or (not (integer? count)) (<= count 0))
(format #t "Invalid argument to `down'_ expected a positive integer for COUNT.~%"))
((< (- index count) 0)
(cond
((zero? index)
(format #t "Already at innermost frame.\n"))
(else
(set! index 0)
(print-frame cur #\index index #\next-source? for-trap?))))
(else
(set! index (- index count))
(print-frame cur #\index index
#\next-source? (and (zero? index) for-trap?)))))
(define-stack-command (frame repl #\optional idx)
"frame [IDX]
Show a frame.
Show the selected frame.
With an argument, select a frame by index, then show it."
(cond
(idx
(cond
((or (not (integer? idx)) (< idx 0))
(format #t "Invalid argument to `frame'_ expected a non-negative integer for IDX.~%"))
((< idx (vector-length frames))
(set! index idx)
(print-frame cur #\index index
#\next-source? (and (zero? index) for-trap?)))
(else
(format #t "No such frame.~%"))))
(else (print-frame cur #\index index
#\next-source? (and (zero? index) for-trap?)))))
(define-stack-command (procedure repl)
"procedure
Print the procedure for the selected frame."
(repl-print repl (frame-procedure cur)))
(define-stack-command (locals repl #\key (width (terminal-width)))
"locals
Show local variables.
Show locally-bound variables in the selected frame."
(print-locals cur #\width width))
(define-stack-command (error-message repl)
"error-message
Show error message.
Display the message associated with the error that started the current
debugging REPL."
(format #t "~a~%" (if (string? message) message "No error message")))
(define-meta-command (break repl (form))
"break PROCEDURE
Break on calls to PROCEDURE.
Starts a recursive prompt when PROCEDURE is called."
(let ((proc (repl-eval repl (repl-parse repl form))))
(if (not (procedure? proc))
(error "Not a procedure_ ~a" proc)
(let ((idx (add-trap-at-procedure-call! proc)))
(format #t "Trap ~a_ ~a.~%" idx (trap-name idx))))))
(define-meta-command (break-at-source repl file line)
"break-at-source FILE LINE
Break when control reaches the given source location.
Starts a recursive prompt when control reaches line LINE of file FILE.
Note that the given source location must be inside a procedure."
(let ((file (if (symbol? file) (symbol->string file) file)))
(let ((idx (add-trap-at-source-location! file line)))
(format #t "Trap ~a_ ~a.~%" idx (trap-name idx)))))
(define (repl-pop-continuation-resumer repl msg)
;; Capture the dynamic environment with this prompt thing. The
;; result is a procedure that takes a frame.
(% (call-with-values
(lambda ()
(abort
(lambda (k)
;; Call frame->stack-vector before reinstating the
;; continuation, so that we catch the %stacks fluid at
;; the time of capture.
(lambda (frame)
(k frame
(frame->stack-vector
(frame-previous frame)))))))
(lambda (from stack)
(format #t "~a~%" msg)
(let ((vals (frame-return-values from)))
(if (null? vals)
(format #t "No return values.~%")
(begin
(format #t "Return values_~%")
(for-each (lambda (x) (repl-print repl x)) vals))))
((module-ref (resolve-interface '(system repl repl)) 'start-repl)
#\debug (make-debug stack 0 msg #t))))))
(define-stack-command (finish repl)
"finish
Run until the current frame finishes.
Resume execution, breaking when the current frame finishes."
(let ((handler (repl-pop-continuation-resumer
repl (format #f "Return from ~a" cur))))
(add-ephemeral-trap-at-frame-finish! cur handler)
(throw 'quit)))
(define (repl-next-resumer msg)
;; Capture the dynamic environment with this prompt thing. The
;; result is a procedure that takes a frame.
(% (let ((stack (abort
(lambda (k)
;; Call frame->stack-vector before reinstating the
;; continuation, so that we catch the %stacks fluid
;; at the time of capture.
(lambda (frame)
(k (frame->stack-vector frame)))))))
(format #t "~a~%" msg)
((module-ref (resolve-interface '(system repl repl)) 'start-repl)
#\debug (make-debug stack 0 msg #t)))))
(define-stack-command (step repl)
"step
Step until control reaches a different source location.
Step until control reaches a different source location."
(let ((msg (format #f "Step into ~a" cur)))
(add-ephemeral-stepping-trap! cur (repl-next-resumer msg)
#\into? #t #\instruction? #f)
(throw 'quit)))
(define-stack-command (step-instruction repl)
"step-instruction
Step until control reaches a different instruction.
Step until control reaches a different VM instruction."
(let ((msg (format #f "Step into ~a" cur)))
(add-ephemeral-stepping-trap! cur (repl-next-resumer msg)
#\into? #t #\instruction? #t)
(throw 'quit)))
(define-stack-command (next repl)
"next
Step until control reaches a different source location in the current frame.
Step until control reaches a different source location in the current frame."
(let ((msg (format #f "Step into ~a" cur)))
(add-ephemeral-stepping-trap! cur (repl-next-resumer msg)
#\into? #f #\instruction? #f)
(throw 'quit)))
(define-stack-command (next-instruction repl)
"next-instruction
Step until control reaches a different instruction in the current frame.
Step until control reaches a different VM instruction in the current frame."
(let ((msg (format #f "Step into ~a" cur)))
(add-ephemeral-stepping-trap! cur (repl-next-resumer msg)
#\into? #f #\instruction? #t)
(throw 'quit)))
(define-meta-command (tracepoint repl (form))
"tracepoint PROCEDURE
Add a tracepoint to PROCEDURE.
A tracepoint will print out the procedure and its arguments, when it is
called, and its return value(s) when it returns."
(let ((proc (repl-eval repl (repl-parse repl form))))
(if (not (procedure? proc))
(error "Not a procedure_ ~a" proc)
(let ((idx (add-trace-at-procedure-call! proc)))
(format #t "Trap ~a_ ~a.~%" idx (trap-name idx))))))
(define-meta-command (traps repl)
"traps
Show the set of currently attached traps.
Show the set of currently attached traps (breakpoints and tracepoints)."
(let ((traps (list-traps)))
(if (null? traps)
(format #t "No traps set.~%")
(for-each (lambda (idx)
(format #t " ~a_ ~a~a~%"
idx (trap-name idx)
(if (trap-enabled? idx) "" " (disabled)")))
traps))))
(define-meta-command (delete repl idx)
"delete IDX
Delete a trap.
Delete a trap."
(if (not (integer? idx))
(error "expected a trap index (a non-negative integer)" idx)
(delete-trap! idx)))
(define-meta-command (disable repl idx)
"disable IDX
Disable a trap.
Disable a trap."
(if (not (integer? idx))
(error "expected a trap index (a non-negative integer)" idx)
(disable-trap! idx)))
(define-meta-command (enable repl idx)
"enable IDX
Enable a trap.
Enable a trap."
(if (not (integer? idx))
(error "expected a trap index (a non-negative integer)" idx)
(enable-trap! idx)))
(define-stack-command (registers repl)
"registers
Print registers.
Print the registers of the current frame."
(print-registers cur))
(define-meta-command (width repl #\optional x)
"width [X]
Set debug output width.
Set the number of screen columns in the output from `backtrace' and
`locals'."
(terminal-width x)
(format #t "Set screen width to ~a columns.~%" (terminal-width)))
;;;
;;; Inspection commands
;;;
(define-meta-command (inspect repl (form))
"inspect EXP
Inspect the result(s) of evaluating EXP."
(call-with-values (repl-prepare-eval-thunk repl (repl-parse repl form))
(lambda args
(for-each %inspect args))))
(define-meta-command (pretty-print repl (form))
"pretty-print EXP
Pretty-print the result(s) of evaluating EXP."
(call-with-values (repl-prepare-eval-thunk repl (repl-parse repl form))
(lambda args
(for-each
(lambda (x)
(run-hook before-print-hook x)
(pp x))
args))))
;;;
;;; System commands
;;;
(define-meta-command (gc repl)
"gc
Garbage collection."
(gc))
(define-meta-command (statistics repl)
"statistics
Display statistics."
(let ((this-tms (times))
(this-gcs (gc-stats))
(last-tms (repl-tm-stats repl))
(last-gcs (repl-gc-stats repl)))
;; GC times
(let ((this-times (assq-ref this-gcs 'gc-times))
(last-times (assq-ref last-gcs 'gc-times)))
(display-diff-stat "GC times_" #t this-times last-times "times")
(newline))
;; Memory size
(let ((this-heap (assq-ref this-gcs 'heap-size))
(this-free (assq-ref this-gcs 'heap-free-size)))
(display-stat-title "Memory size_" "current" "limit")
(display-stat "heap" #f (- this-heap this-free) this-heap "bytes")
(newline))
;; Cells collected
(let ((this-alloc (assq-ref this-gcs 'heap-total-allocated))
(last-alloc (assq-ref last-gcs 'heap-total-allocated)))
(display-stat-title "Bytes allocated_" "diff" "total")
(display-diff-stat "allocated" #f this-alloc last-alloc "bytes")
(newline))
;; GC time taken
(let ((this-total (assq-ref this-gcs 'gc-time-taken))
(last-total (assq-ref last-gcs 'gc-time-taken)))
(display-stat-title "GC time taken_" "diff" "total")
(display-time-stat "total" this-total last-total)
(newline))
;; Process time spent
(let ((this-utime (tms_utime this-tms))
(last-utime (tms_utime last-tms))
(this-stime (tms_stime this-tms))
(last-stime (tms_stime last-tms))
(this-cutime (tms_cutime this-tms))
(last-cutime (tms_cutime last-tms))
(this-cstime (tms_cstime this-tms))
(last-cstime (tms_cstime last-tms)))
(display-stat-title "Process time spent_" "diff" "total")
(display-time-stat "user" this-utime last-utime)
(display-time-stat "system" this-stime last-stime)
(display-time-stat "child user" this-cutime last-cutime)
(display-time-stat "child system" this-cstime last-cstime)
(newline))
;; Save statistics
;; Save statistics
(set! (repl-tm-stats repl) this-tms)
(set! (repl-gc-stats repl) this-gcs)))
(define (display-stat title flag field1 field2 unit)
(let ((fmt (format #f "~~20~AA ~~10@A /~~10@A ~~A~~%" (if flag "" "@"))))
(format #t fmt title field1 field2 unit)))
(define (display-stat-title title field1 field2)
(display-stat title #t field1 field2 ""))
(define (display-diff-stat title flag this last unit)
(display-stat title flag (- this last) this unit))
(define (display-time-stat title this last)
(define (conv num)
(format #f "~10,2F" (exact->inexact (/ num internal-time-units-per-second))))
(display-stat title #f (conv (- this last)) (conv this) "s"))
(define (display-mips-stat title this-time this-clock last-time last-clock)
(define (mips time clock)
(if (= time 0) "----" (format #f "~10,2F" (/ clock time 1000000.0))))
(display-stat title #f
(mips (- this-time last-time) (- this-clock last-clock))
(mips this-time this-clock) "mips"))
;;; Repl common routines
;; Copyright (C) 2001, 2008-2016 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system repl common)
#\use-module (system base syntax)
#\use-module (system base compile)
#\use-module (system base language)
#\use-module (system base message)
#\use-module (system vm program)
#\autoload (language tree-il optimize) (optimize!)
#\use-module (ice-9 control)
#\use-module (ice-9 history)
#\export (<repl> make-repl repl-language repl-options
repl-tm-stats repl-gc-stats repl-debug
repl-welcome repl-prompt
repl-read repl-compile repl-prepare-eval-thunk repl-eval
repl-expand repl-optimize
repl-parse repl-print repl-option-ref repl-option-set!
repl-default-option-set! repl-default-prompt-set!
puts ->string user-error
*warranty* *copying* *version*))
(define *version*
(format #f "GNU Guile ~A
Copyright (C) 1995-2016 Free Software Foundation, Inc.
Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'.
This program is free software, and you are welcome to redistribute it
under certain conditions; type `,show c' for details." (version)))
(define *copying*
"Guile is free software_ you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Guile 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program. If not, see
<http_//www.gnu.org/licenses/lgpl.html>.")
(define *warranty*
"Guile is distributed WITHOUT ANY WARRANTY. The following
sections from the GNU General Public License, version 3, should
make that clear.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
See <http_//www.gnu.org/licenses/lgpl.html>, for more details.")
;;;
;;; Repl type
;;;
(define-record/keywords <repl>
language options tm-stats gc-stats debug)
(define repl-default-options
(copy-tree
`((compile-options ,%auto-compilation-options #f)
(trace #f #f)
(interp #f #f)
(prompt #f ,(lambda (prompt)
(cond
((not prompt) #f)
((string? prompt) (lambda (repl) prompt))
((thunk? prompt) (lambda (repl) (prompt)))
((procedure? prompt) prompt)
(else (error "Invalid prompt" prompt)))))
(print #f ,(lambda (print)
(cond
((not print) #f)
((procedure? print) print)
(else (error "Invalid print procedure" print)))))
(value-history
,(value-history-enabled?)
,(lambda (x)
(if x (enable-value-history!) (disable-value-history!))
(->bool x)))
(on-error
debug
,(let ((vals '(debug backtrace report pass)))
(lambda (x)
(if (memq x vals)
x
(error "Bad on-error value ~a; expected one of ~a" x vals))))))))
(define %make-repl make-repl)
(define* (make-repl lang #\optional debug)
(%make-repl #\language (if (language? lang)
lang
(lookup-language lang))
#\options (copy-tree repl-default-options)
#\tm-stats (times)
#\gc-stats (gc-stats)
#\debug debug))
(define (repl-welcome repl)
(display *version*)
(newline)
(newline)
(display "Enter `,help' for help.\n"))
(define (repl-prompt repl)
(cond
((repl-option-ref repl 'prompt)
=> (lambda (prompt) (prompt repl)))
(else
(format #f "~A@~A~A> " (language-name (repl-language repl))
(module-name (current-module))
(let ((level (length (cond
((fluid-ref *repl-stack*) => cdr)
(else '())))))
(if (zero? level) "" (format #f " [~a]" level)))))))
(define (repl-read repl)
(let ((reader (language-reader (repl-language repl))))
(reader (current-input-port) (current-module))))
(define (repl-compile-options repl)
(repl-option-ref repl 'compile-options))
(define (repl-compile repl form)
(let ((from (repl-language repl))
(opts (repl-compile-options repl)))
(compile form #\from from #\to 'objcode #\opts opts
#\env (current-module))))
(define (repl-expand repl form)
(let ((from (repl-language repl))
(opts (repl-compile-options repl)))
(decompile (compile form #\from from #\to 'tree-il #\opts opts
#\env (current-module))
#\from 'tree-il #\to from)))
(define (repl-optimize repl form)
(let ((from (repl-language repl))
(opts (repl-compile-options repl)))
(decompile (optimize! (compile form #\from from #\to 'tree-il #\opts opts
#\env (current-module))
(current-module)
opts)
#\from 'tree-il #\to from)))
(define (repl-parse repl form)
(let ((parser (language-parser (repl-language repl))))
(if parser (parser form) form)))
(define (repl-prepare-eval-thunk repl form)
(let* ((eval (language-evaluator (repl-language repl))))
(if (and eval
(or (null? (language-compilers (repl-language repl)))
(repl-option-ref repl 'interp)))
(lambda () (eval form (current-module)))
(make-program (repl-compile repl form)))))
(define (repl-eval repl form)
(let ((thunk (repl-prepare-eval-thunk repl form)))
(% (thunk))))
(define (repl-print repl val)
(if (not (eq? val *unspecified*))
(begin
(run-hook before-print-hook val)
(cond
((repl-option-ref repl 'print)
=> (lambda (print) (print repl val)))
(else
;; The result of an evaluation is representable in scheme, and
;; should be printed with the generic printer, `write'. The
;; language-printer is something else_ it prints expressions of
;; a given language, not the result of evaluation.
(write val)
(newline))))))
(define (repl-option-ref repl key)
(cadr (or (assq key (repl-options repl))
(error "unknown repl option" key))))
(define (repl-option-set! repl key val)
(let ((spec (or (assq key (repl-options repl))
(error "unknown repl option" key))))
(set-car! (cdr spec)
(if (procedure? (caddr spec))
((caddr spec) val)
val))))
(define (repl-default-option-set! key val)
(let ((spec (or (assq key repl-default-options)
(error "unknown repl option" key))))
(set-car! (cdr spec)
(if (procedure? (caddr spec))
((caddr spec) val)
val))))
(define (repl-default-prompt-set! prompt)
(repl-default-option-set! 'prompt prompt))
;;;
;;; Utilities
;;;
(define (puts x) (display x) (newline))
(define (->string x)
(object->string x display))
(define (user-error msg . args)
(throw 'user-error #f msg args #f))
;;; Cooperative REPL server
;; Copyright (C) 2014, 2016 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system repl coop-server)
#\use-module (ice-9 match)
#\use-module (ice-9 receive)
#\use-module (ice-9 threads)
#\use-module (ice-9 q)
#\use-module (srfi srfi-9)
#\use-module ((system repl repl)
#\select (start-repl* prompting-meta-read))
#\use-module ((system repl server)
#\select (run-server* make-tcp-server-socket
add-open-socket! close-socket!
guard-against-http-request))
#\export (spawn-coop-repl-server
poll-coop-repl-server))
(define-record-type <coop-repl-server>
(%make-coop-repl-server mutex queue)
coop-repl-server?
(mutex coop-repl-server-mutex)
(queue coop-repl-server-queue))
(define (make-coop-repl-server)
(%make-coop-repl-server (make-mutex) (make-q)))
(define (coop-repl-server-eval coop-server opcode . args)
"Queue a new instruction with the symbolic name OPCODE and an arbitrary
number of arguments, to be processed the next time COOP-SERVER is polled."
(with-mutex (coop-repl-server-mutex coop-server)
(enq! (coop-repl-server-queue coop-server)
(cons opcode args))))
(define-record-type <coop-repl>
(%make-coop-repl mutex condvar thunk cont)
coop-repl?
(mutex coop-repl-mutex)
(condvar coop-repl-condvar) ; signaled when thunk becomes non-#f
(thunk coop-repl-read-thunk set-coop-repl-read-thunk!)
(cont coop-repl-cont set-coop-repl-cont!))
(define (make-coop-repl)
(%make-coop-repl (make-mutex) (make-condition-variable) #f #f))
(define (coop-repl-read coop-repl)
"Read an expression via the thunk stored in COOP-REPL."
(let ((thunk
(with-mutex (coop-repl-mutex coop-repl)
(unless (coop-repl-read-thunk coop-repl)
(wait-condition-variable (coop-repl-condvar coop-repl)
(coop-repl-mutex coop-repl)))
(let ((thunk (coop-repl-read-thunk coop-repl)))
(unless thunk
(error "coop-repl-read_ condvar signaled, but thunk is #f!"))
(set-coop-repl-read-thunk! coop-repl #f)
thunk))))
(thunk)))
(define (store-repl-cont cont coop-repl)
"Save the partial continuation CONT within COOP-REPL."
(set-coop-repl-cont! coop-repl
(lambda (exp)
(coop-repl-prompt
(lambda () (cont exp))))))
(define (coop-repl-prompt thunk)
"Apply THUNK within a prompt for cooperative REPLs."
(call-with-prompt 'coop-repl-prompt thunk store-repl-cont))
(define (make-coop-reader coop-repl)
"Return a new procedure for reading user input from COOP-REPL. The
generated procedure passes the responsibility of reading input to
another thread and aborts the cooperative REPL prompt."
(lambda (repl)
(let ((read-thunk
;; Need to preserve the REPL stack and current module across
;; threads.
(let ((stack (fluid-ref *repl-stack*))
(module (current-module)))
(lambda ()
(with-fluids ((*repl-stack* stack))
(set-current-module module)
(prompting-meta-read repl))))))
(with-mutex (coop-repl-mutex coop-repl)
(when (coop-repl-read-thunk coop-repl)
(error "coop-reader_ read-thunk is not #f!"))
(set-coop-repl-read-thunk! coop-repl read-thunk)
(signal-condition-variable (coop-repl-condvar coop-repl))))
(abort-to-prompt 'coop-repl-prompt coop-repl)))
(define (reader-loop coop-server coop-repl)
"Run an unbounded loop that reads an expression for COOP-REPL and
stores the expression within COOP-SERVER for later evaluation."
(coop-repl-server-eval coop-server 'eval coop-repl
(coop-repl-read coop-repl))
(reader-loop coop-server coop-repl))
(define (poll-coop-repl-server coop-server)
"Poll the cooperative REPL server COOP-SERVER and apply a pending
operation if there is one, such as evaluating an expression typed at the
REPL prompt. This procedure must be called from the same thread that
called spawn-coop-repl-server."
(let ((op (with-mutex (coop-repl-server-mutex coop-server)
(let ((queue (coop-repl-server-queue coop-server)))
(and (not (q-empty? queue))
(deq! queue))))))
(when op
(match op
(('new-repl client)
(start-repl-client coop-server client))
(('eval coop-repl exp)
((coop-repl-cont coop-repl) exp))))
*unspecified*))
(define (start-coop-repl coop-server)
"Start a new cooperative REPL process for COOP-SERVER."
;; Calling stop-server-and-clients! from a REPL will cause an
;; exception to be thrown when trying to read from the socket that has
;; been closed, so we catch that here.
(false-if-exception
(let ((coop-repl (make-coop-repl)))
(make-thread reader-loop coop-server coop-repl)
(start-repl* (current-language) #f (make-coop-reader coop-repl)))))
(define (run-coop-repl-server coop-server server-socket)
"Start the cooperative REPL server for COOP-SERVER using the socket
SERVER-SOCKET."
(run-server* server-socket (make-coop-client-proc coop-server)))
(define* (spawn-coop-repl-server
#\optional (server-socket (make-tcp-server-socket)))
"Create and return a new cooperative REPL server object, and spawn a
new thread to listen for connections on SERVER-SOCKET. Proper
functioning of the REPL server requires that poll-coop-repl-server be
called periodically on the returned server object."
(let ((coop-server (make-coop-repl-server)))
(make-thread run-coop-repl-server
coop-server
server-socket)
coop-server))
(define (make-coop-client-proc coop-server)
"Return a new procedure that is used to schedule the creation of a new
cooperative REPL for COOP-SERVER."
(lambda (client addr)
(coop-repl-server-eval coop-server 'new-repl client)))
(define (start-repl-client coop-server client)
"Run a cooperative REPL for COOP-SERVER within a prompt. All input
and output is sent over the socket CLIENT."
;; Add the client to the list of open sockets, with a 'force-close'
;; procedure that closes the underlying file descriptor. We do it
;; this way because we cannot close the port itself safely from
;; another thread.
(add-open-socket! client (lambda () (close-fdes (fileno client))))
(guard-against-http-request client)
(with-continuation-barrier
(lambda ()
(coop-repl-prompt
(lambda ()
(parameterize ((current-input-port client)
(current-output-port client)
(current-error-port client)
(current-warning-port client))
(with-fluids ((*repl-stack* '()))
(save-module-excursion
(lambda ()
(start-coop-repl coop-server)))))
;; This may fail if 'stop-server-and-clients!' is called,
;; because the 'force-close' procedure above closes the
;; underlying file descriptor instead of the port itself.
(false-if-exception
(close-socket! client)))))))
;;; Guile VM debugging facilities
;;; Copyright (C) 2001, 2009, 2010, 2011 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system repl debug)
#\use-module (system base pmatch)
#\use-module (system base syntax)
#\use-module (system base language)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 pretty-print)
#\use-module (ice-9 format)
#\use-module ((system vm inspect) #\select ((inspect . %inspect)))
#\use-module (system vm program)
#\export (<debug>
make-debug debug?
debug-frames debug-index debug-error-message debug-for-trap?
terminal-width
print-registers print-locals print-frame print-frames frame->module
stack->vector narrow-stack->vector
frame->stack-vector))
;; TODO_
;;
;; eval expression in context of frame
;; set local variable in frame
;; step until greater source line
;; watch expression
;; set printing width
;; disassemble the current function
;; inspect any object
;;;
;;; Debugger
;;;
;;; The actual interaction loop of the debugger is run by the repl. This module
;;; simply exports a data structure to hold the debugger state, along with its
;;; accessors, and provides some helper functions.
;;;
(define-record <debug> frames index error-message for-trap?)
;; A fluid, because terminals are usually implicitly associated with
;; threads.
;;
(define terminal-width
(let ((set-width (make-fluid)))
(case-lambda
(()
(or (fluid-ref set-width)
(let ((w (false-if-exception (string->number (getenv "COLUMNS")))))
(and (integer? w) (exact? w) (> w 0) w))
72))
((w)
(if (or (not w) (and (integer? w) (exact? w) (> w 0)))
(fluid-set! set-width w)
(error "Expected a column number (a positive integer)" w))))))
(define (reverse-hashq h)
(let ((ret (make-hash-table)))
(hash-for-each
(lambda (k v)
(hashq-set! ret v (cons k (hashq-ref ret v '()))))
h)
ret))
(define* (print-registers frame #\optional (port (current-output-port))
#\key (per-line-prefix " "))
(define (print fmt val)
(display per-line-prefix port)
(run-hook before-print-hook val)
(format port fmt val))
(format port "~aRegisters_~%" per-line-prefix)
(print "ip = ~d\n" (frame-instruction-pointer frame))
(print "sp = #x~x\n" (frame-stack-pointer frame))
(print "fp = #x~x\n" (frame-address frame)))
(define* (print-locals frame #\optional (port (current-output-port))
#\key (width (terminal-width)) (per-line-prefix " "))
(let ((bindings (frame-bindings frame)))
(cond
((null? bindings)
(format port "~aNo local variables.~%" per-line-prefix))
(else
(format port "~aLocal variables_~%" per-line-prefix)
(for-each
(lambda (binding)
(let ((v (let ((x (frame-local-ref frame (binding_index binding))))
(if (binding_boxed? binding)
(variable-ref x)
x))))
(display per-line-prefix port)
(run-hook before-print-hook v)
(format port "~a~_[~; (boxed)~] = ~v_@y\n"
(binding_name binding) (binding_boxed? binding) width v)))
(frame-bindings frame))))))
(define* (print-frame frame #\optional (port (current-output-port))
#\key index (width (terminal-width)) (full? #f)
(last-source #f) next-source?)
(define (source_pretty-file source)
(if source
(or (source_file source) "current input")
"unknown file"))
(let* ((source ((if next-source? frame-next-source frame-source) frame))
(file (source_pretty-file source))
(line (and=> source source_line-for-user))
(col (and=> source source_column)))
(if (and file (not (equal? file (source_pretty-file last-source))))
(format port "~&In ~a_~&" file))
(format port "~9@a~_[~*~3_~;~3d~] ~v_@y~%"
(if line (format #f "~a_~a" line col) "")
index index width (frame-call-representation frame))
(if full?
(print-locals frame #\width width
#\per-line-prefix " "))))
(define* (print-frames frames
#\optional (port (current-output-port))
#\key (width (terminal-width)) (full? #f)
(forward? #f) count for-trap?)
(let* ((len (vector-length frames))
(lower-idx (if (or (not count) (positive? count))
0
(max 0 (+ len count))))
(upper-idx (if (and count (negative? count))
(1- len)
(1- (if count (min count len) len))))
(inc (if forward? 1 -1)))
(let lp ((i (if forward? lower-idx upper-idx))
(last-source #f))
(if (<= lower-idx i upper-idx)
(let* ((frame (vector-ref frames i)))
(print-frame frame port #\index i #\width width #\full? full?
#\last-source last-source
#\next-source? (and (zero? i) for-trap?))
(lp (+ i inc)
(if (and (zero? i) for-trap?)
(frame-next-source frame)
(frame-source frame))))))))
;; Ideally here we would have something much more syntactic, in that a set! to a
;; local var that is not settable would raise an error, and export etc forms
;; would modify the module in question_ but alack, this is what we have now.
;; Patches welcome!
(define (frame->module frame)
(let ((proc (frame-procedure frame)))
(if (program? proc)
(let* ((mod (or (program-module proc) (current-module)))
(mod* (make-module)))
(module-use! mod* mod)
(for-each
(lambda (binding)
(let* ((x (frame-local-ref frame (binding_index binding)))
(var (if (binding_boxed? binding) x (make-variable x))))
(format #t
"~_[Read-only~;Mutable~] local variable ~a = ~70_@y\n"
(binding_boxed? binding)
(binding_name binding)
(if (variable-bound? var) (variable-ref var) var))
(module-add! mod* (binding_name binding) var)))
(frame-bindings frame))
mod*)
(current-module))))
(define (stack->vector stack)
(let* ((len (stack-length stack))
(v (make-vector len)))
(if (positive? len)
(let lp ((i 0) (frame (stack-ref stack 0)))
(if (< i len)
(begin
(vector-set! v i frame)
(lp (1+ i) (frame-previous frame))))))
v))
(define (narrow-stack->vector stack . args)
(let ((narrowed (apply make-stack (stack-ref stack 0) args)))
(if narrowed
(stack->vector narrowed)
#()))) ; ? Can be the case for a tail-call to `throw' tho
(define (frame->stack-vector frame)
(let ((tag (and (pair? (fluid-ref %stacks))
(cdar (fluid-ref %stacks)))))
(narrow-stack->vector
(make-stack frame)
;; Take the stack from the given frame, cutting 0
;; frames.
0
;; Narrow the end of the stack to the most recent
;; start-stack.
tag
;; And one more frame, because %start-stack
;; invoking the start-stack thunk has its own frame
;; too.
0 (and tag 1))))
;; (define (debug)
;; (run-debugger
;; (narrow-stack->vector
;; (make-stack #t)
;; ;; Narrow the `make-stack' frame and the `debug' frame
;; 2
;; ;; Narrow the end of the stack to the most recent start-stack.
;; (and (pair? (fluid-ref %stacks))
;; (cdar (fluid-ref %stacks))))))
;;; Describe objects
;; Copyright (C) 2001, 2009, 2011 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system repl describe)
#\use-module (oop goops)
#\use-module (ice-9 regex)
#\use-module (ice-9 format)
#\use-module (ice-9 and-let-star)
#\export (describe))
(define-method (describe (symbol <symbol>))
(format #t "`~s' is " symbol)
(if (not (defined? symbol))
(display "not defined in the current module.\n")
(describe-object (module-ref (current-module) symbol))))
;;;
;;; Display functions
;;;
(define (safe-class-name class)
(if (slot-bound? class 'name)
(class-name class)
class))
(define-method (display-class class . args)
(let* ((name (safe-class-name class))
(desc (if (pair? args) (car args) name)))
(if (eq? *describe-format* 'tag)
(format #t "@class{~a}{~a}" name desc)
(format #t "~a" desc))))
(define (display-list title list)
(if title (begin (display title) (display "_\n\n")))
(if (null? list)
(display "(not defined)\n")
(for-each display-summary list)))
(define (display-slot-list title instance list)
(if title (begin (display title) (display "_\n\n")))
(if (null? list)
(display "(not defined)\n")
(for-each (lambda (slot)
(let ((name (slot-definition-name slot)))
(display "Slot_ ")
(display name)
(if (and instance (slot-bound? instance name))
(begin
(display " = ")
(display (slot-ref instance name))))
(newline)))
list)))
(define (display-file location)
(display "Defined in ")
(if (eq? *describe-format* 'tag)
(format #t "@location{~a}.\n" location)
(format #t "`~a'.\n" location)))
(define (format-documentation doc)
(with-current-buffer (make-buffer #\text doc)
(lambda ()
(let ((regexp (make-regexp "@([a-z]*)(\\{([^}]*)\\})?")))
(do-while (match (re-search-forward regexp))
(let ((key (string->symbol (match_substring match 1)))
(value (match_substring match 3)))
(case key
((deffnx)
(delete-region! (match_start match)
(begin (forward-line) (point))))
((var)
(replace-match! match 0 (string-upcase value)))
((code)
(replace-match! match 0 (string-append "`" value "'")))))))
(display (string (current-buffer)))
(newline))))
;;;
;;; Top
;;;
(define description-table
(list
(cons <boolean> "a boolean")
(cons <null> "an empty list")
(cons <integer> "an integer")
(cons <real> "a real number")
(cons <complex> "a complex number")
(cons <char> "a character")
(cons <symbol> "a symbol")
(cons <keyword> "a keyword")
(cons <promise> "a promise")
(cons <hook> "a hook")
(cons <fluid> "a fluid")
(cons <stack> "a stack")
(cons <variable> "a variable")
(cons <regexp> "a regexp object")
(cons <module> "a module object")
(cons <unknown> "an unknown object")))
(define-generic describe-object)
(export describe-object)
(define-method (describe-object (obj <top>))
(display-type obj)
(display-location obj)
(newline)
(display-value obj)
(newline)
(display-documentation obj))
(define-generic display-object)
(define-generic display-summary)
(define-generic display-type)
(define-generic display-value)
(define-generic display-location)
(define-generic display-description)
(define-generic display-documentation)
(export display-object display-summary display-type display-value
display-location display-description display-documentation)
(define-method (display-object (obj <top>))
(write obj))
(define-method (display-summary (obj <top>))
(display "Value_ ")
(display-object obj)
(newline))
(define-method (display-type (obj <top>))
(cond
((eof-object? obj) (display "the end-of-file object"))
((unspecified? obj) (display "unspecified"))
(else (let ((class (class-of obj)))
(display-class class (or (assq-ref description-table class)
(safe-class-name class))))))
(display ".\n"))
(define-method (display-value (obj <top>))
(if (not (unspecified? obj))
(begin (display-object obj) (newline))))
(define-method (display-location (obj <top>))
*unspecified*)
(define-method (display-description (obj <top>))
(let* ((doc (with-output-to-string (lambda () (display-documentation obj))))
(index (string-index doc #\newline)))
(display (substring doc 0 (1+ index)))))
(define-method (display-documentation (obj <top>))
(display "Not documented.\n"))
;;;
;;; Pairs
;;;
(define-method (display-type (obj <pair>))
(cond
((list? obj) (display-class <list> "a list"))
((pair? (cdr obj)) (display "an improper list"))
(else (display-class <pair> "a pair")))
(display ".\n"))
;;;
;;; Strings
;;;
(define-method (display-type (obj <string>))
(if (read-only-string? 'obj)
(display "a read-only string")
(display-class <string> "a string"))
(display ".\n"))
;;;
;;; Procedures
;;;
(define-method (display-object (obj <procedure>))
(cond
;; FIXME_ VM programs, ...
(else
;; Primitive procedure. Let's lookup the dictionary.
(and-let* ((entry (lookup-procedure obj)))
(let ((name (entry-property entry 'name))
(print-arg (lambda (arg)
(display " ")
(display (string-upcase (symbol->string arg))))))
(display "(")
(display name)
(and-let* ((args (entry-property entry 'args)))
(for-each print-arg args))
(and-let* ((opts (entry-property entry 'opts)))
(display " &optional")
(for-each print-arg opts))
(and-let* ((rest (entry-property entry 'rest)))
(display " &rest")
(print-arg rest))
(display ")"))))))
(define-method (display-summary (obj <procedure>))
(display "Procedure_ ")
(display-object obj)
(newline)
(display " ")
(display-description obj))
(define-method (display-type (obj <procedure>))
(cond
((and (thunk? obj) (not (procedure-name obj))) (display "a thunk"))
((procedure-with-setter? obj)
(display-class <procedure-with-setter> "a procedure with setter"))
(else (display-class <procedure> "a procedure")))
(display ".\n"))
(define-method (display-location (obj <procedure>))
(and-let* ((entry (lookup-procedure obj)))
(display-file (entry-file entry))))
(define-method (display-documentation (obj <procedure>))
(cond ((or (procedure-documentation obj)
(and=> (lookup-procedure obj) entry-text))
=> format-documentation)
(else (next-method))))
;;;
;;; Classes
;;;
(define-method (describe-object (obj <class>))
(display-type obj)
(display-location obj)
(newline)
(display-documentation obj)
(newline)
(display-value obj))
(define-method (display-summary (obj <class>))
(display "Class_ ")
(display-class obj)
(newline)
(display " ")
(display-description obj))
(define-method (display-type (obj <class>))
(display-class <class> "a class")
(if (not (eq? (class-of obj) <class>))
(begin (display " of ") (display-class (class-of obj))))
(display ".\n"))
(define-method (display-value (obj <class>))
(display-list "Class precedence list" (class-precedence-list obj))
(newline)
(display-list "Direct superclasses" (class-direct-supers obj))
(newline)
(display-list "Direct subclasses" (class-direct-subclasses obj))
(newline)
(display-slot-list "Direct slots" #f (class-direct-slots obj))
(newline)
(display-list "Direct methods" (class-direct-methods obj)))
;;;
;;; Instances
;;;
(define-method (display-type (obj <object>))
(display-class <object> "an instance")
(display " of class ")
(display-class (class-of obj))
(display ".\n"))
(define-method (display-value (obj <object>))
(display-slot-list #f obj (class-slots (class-of obj))))
;;;
;;; Generic functions
;;;
(define-method (display-type (obj <generic>))
(display-class <generic> "a generic function")
(display " of class ")
(display-class (class-of obj))
(display ".\n"))
(define-method (display-value (obj <generic>))
(display-list #f (generic-function-methods obj)))
;;;
;;; Methods
;;;
(define-method (display-object (obj <method>))
(display "(")
(let ((gf (method-generic-function obj)))
(display (if gf (generic-function-name gf) "#<anonymous>")))
(let loop ((args (method-specializers obj)))
(cond
((null? args))
((pair? args)
(display " ")
(display-class (car args))
(loop (cdr args)))
(else (display " . ") (display-class args))))
(display ")"))
(define-method (display-summary (obj <method>))
(display "Method_ ")
(display-object obj)
(newline)
(display " ")
(display-description obj))
(define-method (display-type (obj <method>))
(display-class <method> "a method")
(display " of class ")
(display-class (class-of obj))
(display ".\n"))
(define-method (display-documentation (obj <method>))
(let ((doc (procedure-documentation (method-procedure obj))))
(if doc (format-documentation doc) (next-method))))
;;; Error handling in the REPL
;; Copyright (C) 2001, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system repl error-handling)
#\use-module (system base pmatch)
#\use-module (system vm trap-state)
#\use-module (system repl debug)
#\use-module (ice-9 format)
#\export (call-with-error-handling
with-error-handling))
;;;
;;; Error handling via repl debugging
;;;
(define (error-string stack key args)
(call-with-output-string
(lambda (port)
(let ((frame (and (< 0 (vector-length stack)) (vector-ref stack 0))))
(print-exception port frame key args)))))
(define* (call-with-error-handling thunk #\key
(on-error 'debug) (post-error 'catch)
(pass-keys '(quit)) (trap-handler 'debug))
(let ((in (current-input-port))
(out (current-output-port))
(err (current-error-port)))
(define (with-saved-ports thunk)
(with-input-from-port in
(lambda ()
(with-output-to-port out
(lambda ()
(with-error-to-port err
thunk))))))
(define (debug-trap-handler frame trap-idx trap-name)
(let* ((tag (and (pair? (fluid-ref %stacks))
(cdar (fluid-ref %stacks))))
(stack (narrow-stack->vector
(make-stack frame)
;; Take the stack from the given frame, cutting 0
;; frames.
0
;; Narrow the end of the stack to the most recent
;; start-stack.
tag
;; And one more frame, because %start-stack
;; invoking the start-stack thunk has its own frame
;; too.
0 (and tag 1)))
(error-msg (if trap-idx
(format #f "Trap ~d_ ~a" trap-idx trap-name)
trap-name))
(debug (make-debug stack 0 error-msg #t)))
(with-saved-ports
(lambda ()
(if trap-idx
(begin
(format #t "~a~%" error-msg)
(format #t "Entering a new prompt. ")
(format #t "Type `,bt' for a backtrace or `,q' to continue.\n")))
((@ (system repl repl) start-repl) #\debug debug)))))
(define (null-trap-handler frame trap-idx trap-name)
#t)
(define le-trap-handler
(case trap-handler
((debug) debug-trap-handler)
((pass) null-trap-handler)
((disabled) #f)
(else (error "Unknown trap-handler strategy" trap-handler))))
(catch #t
(lambda ()
(with-default-trap-handler le-trap-handler
(lambda () (%start-stack #t thunk))))
(case post-error
((report)
(lambda (key . args)
(if (memq key pass-keys)
(apply throw key args)
(begin
(with-saved-ports
(lambda ()
(run-hook before-error-hook)
(print-exception err #f key args)
(run-hook after-error-hook)
(force-output err)))
(if #f #f)))))
((catch)
(lambda (key . args)
(if (memq key pass-keys)
(apply throw key args))))
(else
(if (procedure? post-error)
(lambda (k . args)
(apply (if (memq k pass-keys) throw post-error) k args))
(error "Unknown post-error strategy" post-error))))
(case on-error
((debug)
(lambda (key . args)
(if (not (memq key pass-keys))
(let* ((tag (and (pair? (fluid-ref %stacks))
(cdar (fluid-ref %stacks))))
(stack (narrow-stack->vector
(make-stack #t)
;; Cut three frames from the top of the stack_
;; make-stack, this one, and the throw handler.
3
;; Narrow the end of the stack to the most recent
;; start-stack.
tag
;; And one more frame, because %start-stack invoking
;; the start-stack thunk has its own frame too.
0 (and tag 1)))
(error-msg (error-string stack key args))
(debug (make-debug stack 0 error-msg #f)))
(with-saved-ports
(lambda ()
(format #t "~a~%" error-msg)
(format #t "Entering a new prompt. ")
(format #t "Type `,bt' for a backtrace or `,q' to continue.\n")
((@ (system repl repl) start-repl) #\debug debug)))))))
((report)
(lambda (key . args)
(if (not (memq key pass-keys))
(begin
(with-saved-ports
(lambda ()
(run-hook before-error-hook)
(print-exception err #f key args)
(run-hook after-error-hook)
(force-output err)))
(if #f #f)))))
((backtrace)
(lambda (key . args)
(if (not (memq key pass-keys))
(let* ((tag (and (pair? (fluid-ref %stacks))
(cdar (fluid-ref %stacks))))
(frames (narrow-stack->vector
(make-stack #t)
;; Narrow as above, for the debugging case.
3 tag 0 (and tag 1))))
(with-saved-ports
(lambda ()
(print-frames frames)
(run-hook before-error-hook)
(print-exception err #f key args)
(run-hook after-error-hook)
(force-output err)))
(if #f #f)))))
((pass)
(lambda (key . args)
;; fall through to rethrow
#t))
(else
(if (procedure? on-error)
(lambda (k . args)
(apply (if (memq k pass-keys) throw on-error) k args))
(error "Unknown on-error strategy" on-error)))))))
(define-syntax-rule (with-error-handling form)
(call-with-error-handling (lambda () form)))
;;; Read-Eval-Print Loop
;; Copyright (C) 2001, 2009, 2010, 2011, 2013,
;; 2014 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system repl repl)
#\use-module (system base syntax)
#\use-module (system base pmatch)
#\use-module (system base compile)
#\use-module (system base language)
#\use-module (system vm vm)
#\use-module (system repl error-handling)
#\use-module (system repl common)
#\use-module (system repl command)
#\use-module (ice-9 control)
#\export (start-repl run-repl))
;;;
;;; Comments
;;;
;;; (You don't want a comment to force a continuation line.)
;;;
(define (read-scheme-line-comment port)
(let lp ()
(let ((ch (read-char port)))
(or (eof-object? ch)
(eqv? ch #\newline)
(lp)))))
(define (read-scheme-datum-comment port)
(read port))
;; ch is a peeked char
(define (read-comment lang port ch)
(and (eq? (language-name lang) 'scheme)
(case ch
((#\;)
(read-char port)
(read-scheme-line-comment port)
#t)
((#\#)
(read-char port)
(case (peek-char port)
((#\;)
(read-char port)
(read-scheme-datum-comment port)
#t)
;; Not doing R6RS block comments because of the possibility
;; of read-hash extensions. Lame excuse. Not doing scsh
;; block comments either, because I don't feel like handling
;; .
(else
(unread-char #\# port)
#f)))
(else
#f))))
;;;
;;; Meta commands
;;;
(define meta-command-token (cons 'meta 'command))
(define (meta-reader lang env)
(lambda* (#\optional (port (current-input-port)))
(with-input-from-port port
(lambda ()
(let ((ch (flush-leading-whitespace)))
(cond ((eof-object? ch)
(read-char)) ; consume the EOF and return it
((eqv? ch #\,)
(read-char)
meta-command-token)
((read-comment lang port ch)
*unspecified*)
(else ((language-reader lang) port env))))))))
(define (flush-all-input)
(if (and (char-ready?)
(not (eof-object? (peek-char))))
(begin
(read-char)
(flush-all-input))))
;; repl-reader is a function defined in boot-9.scm, and is replaced by
;; something else if readline has been activated. much of this hoopla is
;; to be able to re-use the existing readline machinery.
;;
;; Catches read errors, returning *unspecified* in that case.
;;
;; Note_ although not exported, this is used by (system repl coop-server)
(define (prompting-meta-read repl)
(catch #t
(lambda ()
(repl-reader (lambda () (repl-prompt repl))
(meta-reader (repl-language repl) (current-module))))
(lambda (key . args)
(case key
((quit)
(apply throw key args))
(else
(format (current-output-port) "While reading expression_\n")
(print-exception (current-output-port) #f key args)
(flush-all-input)
*unspecified*)))))
;;;
;;; The repl
;;;
(define* (start-repl #\optional (lang (current-language)) #\key debug)
(start-repl* lang debug prompting-meta-read))
;; Note_ although not exported, this is used by (system repl coop-server)
(define (start-repl* lang debug prompting-meta-read)
;; ,language at the REPL will update the current-language. Make
;; sure that it does so in a new dynamic scope.
(parameterize ((current-language lang))
(run-repl* (make-repl lang debug) prompting-meta-read)))
;; (put 'abort-on-error 'scheme-indent-function 1)
(define-syntax-rule (abort-on-error string exp)
(catch #t
(lambda () exp)
(lambda (key . args)
(format #t "While ~A_~%" string)
(print-exception (current-output-port) #f key args)
(abort))))
(define (run-repl repl)
(run-repl* repl prompting-meta-read))
(define (run-repl* repl prompting-meta-read)
(define (with-stack-and-prompt thunk)
(call-with-prompt (default-prompt-tag)
(lambda () (start-stack #t (thunk)))
(lambda (k proc)
(with-stack-and-prompt (lambda () (proc k))))))
(% (with-fluids ((*repl-stack*
(cons repl (or (fluid-ref *repl-stack*) '()))))
(if (null? (cdr (fluid-ref *repl-stack*)))
(repl-welcome repl))
(let prompt-loop ()
(let ((exp (prompting-meta-read repl)))
(cond
((eqv? exp *unspecified*)) ; read error or comment, pass
((eq? exp meta-command-token)
(catch #t
(lambda ()
(meta-command repl))
(lambda (k . args)
(if (eq? k 'quit)
(abort args)
(begin
(format #t "While executing meta-command_~%")
(print-exception (current-output-port) #f k args))))))
((eof-object? exp)
(newline)
(abort '()))
(else
;; since the input port is line-buffered, consume up to the
;; newline
(flush-to-newline)
(call-with-error-handling
(lambda ()
(catch 'quit
(lambda ()
(call-with-values
(lambda ()
(% (let ((thunk
(abort-on-error "compiling expression"
(repl-prepare-eval-thunk
repl
(abort-on-error "parsing expression"
(repl-parse repl exp))))))
(run-hook before-eval-hook exp)
(call-with-error-handling
(lambda ()
(with-stack-and-prompt thunk))
#\on-error (repl-option-ref repl 'on-error)))
(lambda (k) (values))))
(lambda l
(for-each (lambda (v)
(repl-print repl v))
l))))
(lambda (k . args)
(abort args))))
#\on-error (repl-option-ref repl 'on-error)
#\trap-handler 'disabled)))
(flush-to-newline) ;; consume trailing whitespace
(prompt-loop))))
(lambda (k status)
status)))
;; Returns first non-whitespace char.
(define (flush-leading-whitespace)
(let ((ch (peek-char)))
(cond ((eof-object? ch) ch)
((char-whitespace? ch) (read-char) (flush-leading-whitespace))
(else ch))))
(define (flush-to-newline)
(if (char-ready?)
(let ((ch (peek-char)))
(if (and (not (eof-object? ch)) (char-whitespace? ch))
(begin
(read-char)
(if (not (char=? ch #\newline))
(flush-to-newline)))))))
;;; Repl server
;; Copyright (C) 2003, 2010, 2011, 2014, 2016 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (system repl server)
#\use-module (system repl repl)
#\use-module (ice-9 threads)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 match)
#\use-module (ice-9 iconv)
#\use-module (rnrs bytevectors)
#\use-module (rnrs io ports)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-26) ; cut
#\export (make-tcp-server-socket
make-unix-domain-server-socket
run-server
spawn-server
stop-server-and-clients!))
;; List of pairs of the form (SOCKET . FORCE-CLOSE), where SOCKET is a
;; socket port, and FORCE-CLOSE is a thunk that forcefully shuts down
;; the socket.
(define *open-sockets* '())
(define sockets-lock (make-mutex))
;; WARNING_ it is unsafe to call 'close-socket!' from another thread.
;; Note_ although not exported, this is used by (system repl coop-server)
(define (close-socket! s)
(with-mutex sockets-lock
(set! *open-sockets* (assq-remove! *open-sockets* s)))
;; Close-port could block or raise an exception flushing buffered
;; output. Hmm.
(close-port s))
;; Note_ although not exported, this is used by (system repl coop-server)
(define (add-open-socket! s force-close)
(with-mutex sockets-lock
(set! *open-sockets* (acons s force-close *open-sockets*))))
(define (stop-server-and-clients!)
(cond
((with-mutex sockets-lock
(match *open-sockets*
(() #f)
(((s . force-close) . rest)
(set! *open-sockets* rest)
force-close)))
=> (lambda (force-close)
(force-close)
(stop-server-and-clients!)))))
(define* (make-tcp-server-socket #\key
(host #f)
(addr (if host (inet-aton host) INADDR_LOOPBACK))
(port 37146))
(let ((sock (socket PF_INET SOCK_STREAM 0)))
(setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
(bind sock AF_INET addr port)
sock))
(define* (make-unix-domain-server-socket #\key (path "/tmp/guile-socket"))
(let ((sock (socket PF_UNIX SOCK_STREAM 0)))
(setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
(bind sock AF_UNIX path)
sock))
;; List of errno values from 'select' or 'accept' that should lead to a
;; retry in 'run-server'.
(define errs-to-retry
(delete-duplicates
(filter-map (lambda (name)
(and=> (module-variable the-root-module name)
variable-ref))
'(EINTR EAGAIN EWOULDBLOCK))))
(define* (run-server #\optional (server-socket (make-tcp-server-socket)))
(run-server* server-socket serve-client))
;; Note_ although not exported, this is used by (system repl coop-server)
(define (run-server* server-socket serve-client)
;; We use a pipe to notify the server when it should shut down.
(define shutdown-pipes (pipe))
(define shutdown-read-pipe (car shutdown-pipes))
(define shutdown-write-pipe (cdr shutdown-pipes))
;; 'shutdown-server' is called by 'stop-server-and-clients!'.
(define (shutdown-server)
(display #\! shutdown-write-pipe)
(force-output shutdown-write-pipe))
(define monitored-ports
(list server-socket
shutdown-read-pipe))
(define (accept-new-client)
(catch #t
(lambda ()
(let ((ready-ports (car (select monitored-ports '() '()))))
;; If we've been asked to shut down, return #f.
(and (not (memq shutdown-read-pipe ready-ports))
(accept server-socket))))
(lambda k-args
(let ((err (system-error-errno k-args)))
(cond
((memv err errs-to-retry)
(accept-new-client))
(else
(warn "Error accepting client" k-args)
;; Retry after a timeout.
(sleep 1)
(accept-new-client)))))))
;; Put the socket into non-blocking mode.
(fcntl server-socket F_SETFL
(logior O_NONBLOCK
(fcntl server-socket F_GETFL)))
(sigaction SIGPIPE SIG_IGN)
(add-open-socket! server-socket shutdown-server)
(listen server-socket 5)
(let lp ((client (accept-new-client)))
;; If client is false, we are shutting down.
(if client
(let ((client-socket (car client))
(client-addr (cdr client)))
(make-thread serve-client client-socket client-addr)
(lp (accept-new-client)))
(begin (close shutdown-write-pipe)
(close shutdown-read-pipe)
(close server-socket)))))
(define* (spawn-server #\optional (server-socket (make-tcp-server-socket)))
(make-thread run-server server-socket))
(define (serve-client client addr)
(let ((thread (current-thread)))
;; Close the socket when this thread exits, even if canceled.
(set-thread-cleanup! thread (lambda () (close-socket! client)))
;; Arrange to cancel this thread to forcefully shut down the socket.
(add-open-socket! client (lambda () (cancel-thread thread))))
(guard-against-http-request client)
(with-continuation-barrier
(lambda ()
(parameterize ((current-input-port client)
(current-output-port client)
(current-error-port client)
(current-warning-port client))
(with-fluids ((*repl-stack* '()))
(start-repl))))))
;;;
;;; The following code adds protection to Guile's REPL servers against
;;; HTTP inter-protocol exploitation attacks, a scenario whereby an
;;; attacker can, via an HTML page, cause a web browser to send data to
;;; TCP servers listening on a loopback interface or private network.
;;; See <https_//en.wikipedia.org/wiki/Inter-protocol_exploitation> and
;;; <https_//www.jochentopf.com/hfpa/hfpa.pdf>, The HTML Form Protocol
;;; Attack (2001) by Tochen Topf <jochen@remote.org>.
;;;
;;; Here we add a procedure to 'before-read-hook' that looks for a possible
;;; HTTP request-line in the first line of input from the client socket. If
;;; present, the socket is drained and closed, and a loud warning is written
;;; to stderr (POSIX file descriptor 2).
;;;
(define (with-temporary-port-encoding port encoding thunk)
"Call THUNK in a dynamic environment in which the encoding of PORT is
temporarily set to ENCODING."
(let ((saved-encoding #f))
(dynamic-wind
(lambda ()
(unless (port-closed? port)
(set! saved-encoding (port-encoding port))
(set-port-encoding! port encoding)))
thunk
(lambda ()
(unless (port-closed? port)
(set! encoding (port-encoding port))
(set-port-encoding! port saved-encoding))))))
(define (with-saved-port-line+column port thunk)
"Save the line and column of PORT before entering THUNK, and restore
their previous values upon normal or non-local exit from THUNK."
(let ((saved-line #f) (saved-column #f))
(dynamic-wind
(lambda ()
(unless (port-closed? port)
(set! saved-line (port-line port))
(set! saved-column (port-column port))))
thunk
(lambda ()
(unless (port-closed? port)
(set-port-line! port saved-line)
(set-port-column! port saved-column))))))
(define (drain-input-and-close socket)
"Drain input from SOCKET using ISO-8859-1 encoding until it would block,
and then close it. Return the drained input as a string."
(dynamic-wind
(lambda ()
;; Enable full buffering mode on the socket to allow
;; 'get-bytevector-some' to return non-trivial chunks.
(setvbuf socket _IOFBF))
(lambda ()
(let loop ((chunks '()))
(let ((result (and (char-ready? socket)
(get-bytevector-some socket))))
(if (bytevector? result)
(loop (cons (bytevector->string result "ISO-8859-1")
chunks))
(string-concatenate-reverse chunks)))))
(lambda ()
;; Close the socket even in case of an exception.
(close-port socket))))
(define permissive-http-request-line?
;; This predicate is deliberately permissive
;; when checking the Request-URI component.
(let ((cs (ucs-range->char-set #x20 #x7E))
(rx (make-regexp
(string-append
"^(OPTIONS|GET|HEAD|POST|PUT|DELETE|TRACE|CONNECT) "
"[^ ]+ "
"HTTP/[0-9]+.[0-9]+$"))))
(lambda (line)
"Return true if LINE might plausibly be an HTTP request-line,
otherwise return #f."
;; We cannot simplify this to a simple 'regexp-exec', because
;; 'regexp-exec' cannot cope with NUL bytes.
(and (string-every cs line)
(regexp-exec rx line)))))
(define (check-for-http-request socket)
"Check for a possible HTTP request in the initial input from SOCKET.
If one is found, close the socket and print a report to STDERR (fdes 2).
Otherwise, put back the bytes."
;; Temporarily set the port encoding to ISO-8859-1 to allow lossless
;; reading and unreading of the first line, regardless of what bytes
;; are present. Note that a valid HTTP request-line contains only
;; ASCII characters.
(with-temporary-port-encoding socket "ISO-8859-1"
(lambda ()
;; Save the port 'line' and 'column' counters and later restore
;; them, since unreading what we read is not sufficient to do so.
(with-saved-port-line+column socket
(lambda ()
;; Read up to (but not including) the first CR or LF.
;; Although HTTP mandates CRLF line endings, we are permissive
;; here to guard against the possibility that in some
;; environments CRLF might be converted to LF before it
;; reaches us.
(match (read-delimited "\r\n" socket 'peek)
((? eof-object?)
;; We found EOF before any input. Nothing to do.
'done)
((? permissive-http-request-line? request-line)
;; The input from the socket began with a plausible HTTP
;; request-line, which is unlikely to be legitimate and may
;; indicate an possible break-in attempt.
;; First, set the current port parameters to a void-port,
;; to avoid sending any more data over the socket, to cause
;; the REPL reader to see EOF, and to swallow any remaining
;; output gracefully.
(let ((void-port (%make-void-port "rw")))
(current-input-port void-port)
(current-output-port void-port)
(current-error-port void-port)
(current-warning-port void-port))
;; Read from the socket until we would block,
;; and then close it.
(let ((drained-input (drain-input-and-close socket)))
;; Print a report to STDERR (POSIX file descriptor 2).
;; XXX Can we do better here?
(call-with-port (dup->port 2 "w")
(cut format <> "
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@ POSSIBLE BREAK-IN ATTEMPT ON THE REPL SERVER @@
@@ BY AN HTTP INTER-PROTOCOL EXPLOITATION ATTACK. See_ @@
@@ <https_//en.wikipedia.org/wiki/Inter-protocol_exploitation> @@
@@ Possible HTTP request received_ ~S
@@ The associated socket has been closed. @@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n"
(string-append request-line
drained-input)))))
(start-line
;; The HTTP request-line was not found, so
;; 'unread' the characters that we have read.
(unread-string start-line socket))))))))
(define (guard-against-http-request socket)
"Arrange for the Guile REPL to check for an HTTP request in the
initial input from SOCKET, in which case the socket will be closed.
This guards against HTTP inter-protocol exploitation attacks, a scenario
whereby an attacker can, via an HTML page, cause a web browser to send
data to TCP servers listening on a loopback interface or private
network."
(%set-port-property! socket 'guard-against-http-request? #t))
(define* (maybe-check-for-http-request
#\optional (socket (current-input-port)))
"Apply check-for-http-request to SOCKET if previously requested by
guard-against-http-request. This procedure is intended to be added to
before-read-hook."
(when (%port-property socket 'guard-against-http-request?)
(check-for-http-request socket)
(unless (port-closed? socket)
(%set-port-property! socket 'guard-against-http-request? #f))))
;; Install the hook.
(add-hook! before-read-hook
maybe-check-for-http-request)
;;; Local Variables_
;;; eval_ (put 'with-temporary-port-encoding 'scheme-indent-function 2)
;;; eval_ (put 'with-saved-port-line+column 'scheme-indent-function 1)
;;; End_
;;; -*- mode_ scheme; coding_ utf-8; -*-
;;;
;;; Copyright (C) 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (system vm coverage)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module (system vm program)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-26)
#\export (with-code-coverage
coverage-data?
instrumented-source-files
instrumented/executed-lines
line-execution-counts
procedure-execution-count
coverage-data->lcov))
;;; Author_ Ludovic Courtès
;;;
;;; Commentary_
;;;
;;; This module provides support to gather code coverage data by instrumenting
;;; the VM.
;;;
;;; Code_
;;;
;;; Gathering coverage data.
;;;
(define (hashq-proc proc n)
;; Return the hash of PROC's objcode.
(hashq (program-objcode proc) n))
(define (assq-proc proc alist)
;; Instead of really looking for PROC in ALIST, look for the objcode of PROC.
;; IOW the alist is indexed by procedures, not objcodes, but those procedures
;; are taken as an arbitrary representative of all the procedures (closures)
;; sharing that objcode. This can significantly reduce memory consumption.
(let ((code (program-objcode proc)))
(find (lambda (pair)
(eq? code (program-objcode (car pair))))
alist)))
(define (with-code-coverage vm thunk)
"Run THUNK, a zero-argument procedure, using VM; instrument VM to collect code
coverage data. Return code coverage data and the values returned by THUNK."
(define procedure->ip-counts
;; Mapping from procedures to hash tables; said hash tables map instruction
;; pointers to the number of times they were executed.
(make-hash-table 500))
(define (collect! frame)
;; Update PROCEDURE->IP-COUNTS with info from FRAME.
(let* ((proc (frame-procedure frame))
(ip (frame-instruction-pointer frame))
(proc-entry (hashx-create-handle! hashq-proc assq-proc
procedure->ip-counts proc #f)))
(let loop ()
(define ip-counts (cdr proc-entry))
(if ip-counts
(let ((ip-entry (hashv-create-handle! ip-counts ip 0)))
(set-cdr! ip-entry (+ (cdr ip-entry) 1)))
(begin
(set-cdr! proc-entry (make-hash-table))
(loop))))))
;; FIXME_ It's unclear what the dynamic-wind is for, given that if the
;; VM is different from the current one, continuations will not be
;; resumable.
(call-with-values (lambda ()
(let ((level (vm-trace-level vm))
(hook (vm-next-hook vm)))
(dynamic-wind
(lambda ()
(set-vm-trace-level! vm (+ level 1))
(add-hook! hook collect!))
(lambda ()
(call-with-vm vm thunk))
(lambda ()
(set-vm-trace-level! vm level)
(remove-hook! hook collect!)))))
(lambda args
(apply values (make-coverage-data procedure->ip-counts) args))))
;;;
;;; Coverage data summary.
;;;
(define-record-type <coverage-data>
(%make-coverage-data procedure->ip-counts
procedure->sources
file->procedures
file->line-counts)
coverage-data?
;; Mapping from procedures to hash tables; said hash tables map instruction
;; pointers to the number of times they were executed.
(procedure->ip-counts data-procedure->ip-counts)
;; Mapping from procedures to the result of `program-sources'.
(procedure->sources data-procedure->sources)
;; Mapping from source file names to lists of procedures defined in the file.
(file->procedures data-file->procedures)
;; Mapping from file names to hash tables, which in turn map from line numbers
;; to execution counts.
(file->line-counts data-file->line-counts))
(define (make-coverage-data procedure->ip-counts)
;; Return a `coverage-data' object based on the coverage data available in
;; PROCEDURE->IP-COUNTS. Precompute the other hash tables that make up
;; `coverage-data' objects.
(let* ((procedure->sources (make-hash-table 500))
(file->procedures (make-hash-table 100))
(file->line-counts (make-hash-table 100))
(data (%make-coverage-data procedure->ip-counts
procedure->sources
file->procedures
file->line-counts)))
(define (increment-execution-count! file line count)
;; Make the execution count of FILE_LINE the maximum of its current value
;; and COUNT. This is so that LINE's execution count is correct when
;; several instruction pointers map to LINE.
(let ((file-entry (hash-create-handle! file->line-counts file #f)))
(if (not (cdr file-entry))
(set-cdr! file-entry (make-hash-table 500)))
(let ((line-entry (hashv-create-handle! (cdr file-entry) line 0)))
(set-cdr! line-entry (max (cdr line-entry) count)))))
;; Update execution counts for procs that were executed.
(hash-for-each (lambda (proc ip-counts)
(let* ((sources (program-sources* data proc))
(file (and (pair? sources)
(source_file (car sources)))))
(and file
(begin
;; Add a zero count for all IPs in SOURCES and in
;; the sources of procedures closed over by PROC.
(for-each
(lambda (source)
(let ((file (source_file source))
(line (source_line source)))
(increment-execution-count! file line 0)))
(append-map (cut program-sources* data <>)
(closed-over-procedures proc)))
;; Add the actual execution count collected.
(hash-for-each
(lambda (ip count)
(let ((line (closest-source-line sources ip)))
(increment-execution-count! file line count)))
ip-counts)))))
procedure->ip-counts)
;; Set the execution count to zero for procedures loaded and not executed.
;; FIXME_ Traversing thousands of procedures here is inefficient.
(for-each (lambda (proc)
(and (not (hashq-ref procedure->sources proc))
(for-each (lambda (proc)
(let* ((sources (program-sources* data proc))
(file (and (pair? sources)
(source_file (car sources)))))
(and file
(for-each
(lambda (ip)
(let ((line (closest-source-line sources ip)))
(increment-execution-count! file line 0)))
(map source_addr sources)))))
(closed-over-procedures proc))))
(append-map module-procedures (loaded-modules)))
data))
(define (procedure-execution-count data proc)
"Return the number of times PROC's code was executed, according to DATA, or #f
if PROC was not executed. When PROC is a closure, the number of times its code
was executed is returned, not the number of times this code associated with this
particular closure was executed."
(let ((sources (program-sources* data proc)))
(and (pair? sources)
(and=> (hashx-ref hashq-proc assq-proc
(data-procedure->ip-counts data) proc)
(lambda (ip-counts)
;; FIXME_ broken with lambda*
(let ((entry-ip (source_addr (car sources))))
(hashv-ref ip-counts entry-ip 0)))))))
(define (program-sources* data proc)
;; A memoizing version of `program-sources'.
(or (hashq-ref (data-procedure->sources data) proc)
(and (program? proc)
(let ((sources (program-sources proc))
(p->s (data-procedure->sources data))
(f->p (data-file->procedures data)))
(if (pair? sources)
(let* ((file (source_file (car sources)))
(entry (hash-create-handle! f->p file '())))
(hashq-set! p->s proc sources)
(set-cdr! entry (cons proc (cdr entry)))
sources)
sources)))))
(define (file-procedures data file)
;; Return the list of globally bound procedures defined in FILE.
(hash-ref (data-file->procedures data) file '()))
(define (instrumented/executed-lines data file)
"Return the number of instrumented and the number of executed source lines in
FILE according to DATA."
(define instr+exec
(and=> (hash-ref (data-file->line-counts data) file)
(lambda (line-counts)
(hash-fold (lambda (line count instr+exec)
(let ((instr (car instr+exec))
(exec (cdr instr+exec)))
(cons (+ 1 instr)
(if (> count 0)
(+ 1 exec)
exec))))
'(0 . 0)
line-counts))))
(values (car instr+exec) (cdr instr+exec)))
(define (line-execution-counts data file)
"Return a list of line number/execution count pairs for FILE, or #f if FILE
is not among the files covered by DATA."
(and=> (hash-ref (data-file->line-counts data) file)
(lambda (line-counts)
(hash-fold alist-cons '() line-counts))))
(define (instrumented-source-files data)
"Return the list of `instrumented' source files, i.e., source files whose code
was loaded at the time DATA was collected."
(hash-fold (lambda (file counts files)
(cons file files))
'()
(data-file->line-counts data)))
;;;
;;; Helpers.
;;;
(define (loaded-modules)
;; Return the list of all the modules currently loaded.
(define seen (make-hash-table))
(let loop ((modules (module-submodules (resolve-module '() #f)))
(result '()))
(hash-fold (lambda (name module result)
(if (hashq-ref seen module)
result
(begin
(hashq-set! seen module #t)
(loop (module-submodules module)
(cons module result)))))
result
modules)))
(define (module-procedures module)
;; Return the list of procedures bound globally in MODULE.
(hash-fold (lambda (binding var result)
(if (variable-bound? var)
(let ((value (variable-ref var)))
(if (procedure? value)
(cons value result)
result))
result))
'()
(module-obarray module)))
(define (closest-source-line sources ip)
;; Given SOURCES, as returned by `program-sources' for a given procedure,
;; return the source line of code that is the closest to IP. This is similar
;; to what `program-source' does.
(let loop ((sources sources)
(line (and (pair? sources) (source_line (car sources)))))
(if (null? sources)
line
(let ((source (car sources)))
(if (> (source_addr source) ip)
line
(loop (cdr sources) (source_line source)))))))
(define (closed-over-procedures proc)
;; Return the list of procedures PROC closes over, PROC included.
(let loop ((proc proc)
(result '()))
(if (and (program? proc) (not (memq proc result)))
(fold loop (cons proc result)
(append (vector->list (or (program-objects proc) #()))
(program-free-variables proc)))
result)))
;;;
;;; LCOV output.
;;;
(define* (coverage-data->lcov data port)
"Traverse code coverage information DATA, as obtained with
`with-code-coverage', and write coverage information in the LCOV format to PORT.
The report will include all the modules loaded at the time coverage data was
gathered, even if their code was not executed."
(define (dump-function proc)
;; Dump source location and basic coverage data for PROC.
(and (program? proc)
(let ((sources (program-sources* data proc)))
(and (pair? sources)
(let* ((line (source_line-for-user (car sources)))
(name (or (procedure-name proc)
(format #f "anonymous-l~a" line))))
(format port "FN_~A,~A~%" line name)
(and=> (procedure-execution-count data proc)
(lambda (count)
(format port "FNDA_~A,~A~%" count name))))))))
;; Output per-file coverage data.
(format port "TN_~%")
(for-each (lambda (file)
(let ((procs (file-procedures data file))
(path (search-path %load-path file)))
(if (string? path)
(begin
(format port "SF_~A~%" path)
(for-each dump-function procs)
(for-each (lambda (line+count)
(let ((line (car line+count))
(count (cdr line+count)))
(format port "DA_~A,~A~%"
(+ 1 line) count)))
(line-execution-counts data file))
(let-values (((instr exec)
(instrumented/executed-lines data file)))
(format port "LH_ ~A~%" exec)
(format port "LF_ ~A~%" instr))
(format port "end_of_record~%"))
(begin
(format (current-error-port)
"skipping unknown source file_ ~a~%"
file)))))
(instrumented-source-files data)))
;;; Guile VM frame functions
;;; Copyright (C) 2001, 2005, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm frame)
#\use-module (system base pmatch)
#\use-module (system vm program)
#\use-module (system vm instruction)
#\use-module (system vm objcode)
#\export (frame-bindings
frame-lookup-binding
frame-binding-ref frame-binding-set!
frame-next-source frame-call-representation
frame-environment
frame-object-binding frame-object-name
frame-return-values))
(define (frame-bindings frame)
(let ((p (frame-procedure frame)))
(if (program? p)
(program-bindings-for-ip p (frame-instruction-pointer frame))
'())))
(define (frame-lookup-binding frame var)
(let lp ((bindings (frame-bindings frame)))
(cond ((null? bindings)
#f)
((eq? (binding_name (car bindings)) var)
(car bindings))
(else
(lp (cdr bindings))))))
(define (frame-binding-set! frame var val)
(frame-local-set! frame
(binding_index
(or (frame-lookup-binding frame var)
(error "variable not bound in frame" var frame)))
val))
(define (frame-binding-ref frame var)
(frame-local-ref frame
(binding_index
(or (frame-lookup-binding frame var)
(error "variable not bound in frame" var frame)))))
;; This function is always called to get some sort of representation of the
;; frame to present to the user, so let's do the logical thing and dispatch to
;; frame-call-representation.
(define (frame-arguments frame)
(cdr (frame-call-representation frame)))
;;;
;;; Pretty printing
;;;
(define (frame-next-source frame)
(let ((proc (frame-procedure frame)))
(if (program? proc)
(program-source proc
(frame-instruction-pointer frame)
(program-sources-pre-retire proc))
'())))
;; Basically there are two cases to deal with here_
;;
;; 1. We've already parsed the arguments, and bound them to local
;; variables. In a standard (lambda (a b c) ...) call, this doesn't
;; involve any argument shuffling; but with rest, optional, or
;; keyword arguments, the arguments as given to the procedure may
;; not correspond to what's on the stack. We reconstruct the
;; arguments using e.g. for the case above_ `(,a ,b ,c). This works
;; for rest arguments too_ (a b . c) => `(,a ,b . ,c)
;;
;; 2. We have failed to parse the arguments. Perhaps it's the wrong
;; number of arguments, or perhaps we're doing a typed dispatch and
;; the types don't match. In that case the arguments are all on the
;; stack, and nothing else is on the stack.
(define (frame-call-representation frame)
(let ((p (frame-procedure frame)))
(cons
(or (false-if-exception (procedure-name p)) p)
(cond
((and (program? p)
(program-arguments-alist p (frame-instruction-pointer frame)))
;; case 1
=> (lambda (arguments)
(define (binding-ref sym i)
(cond
((frame-lookup-binding frame sym)
=> (lambda (b) (frame-local-ref frame (binding_index b))))
((< i (frame-num-locals frame))
(frame-local-ref frame i))
(else
;; let's not error here, as we are called during backtraces...
'???)))
(let lp ((req (or (assq-ref arguments 'required) '()))
(opt (or (assq-ref arguments 'optional) '()))
(key (or (assq-ref arguments 'keyword) '()))
(rest (or (assq-ref arguments 'rest) #f))
(i 0))
(cond
((pair? req)
(cons (binding-ref (car req) i)
(lp (cdr req) opt key rest (1+ i))))
((pair? opt)
(cons (binding-ref (car opt) i)
(lp req (cdr opt) key rest (1+ i))))
((pair? key)
(cons* (caar key)
(frame-local-ref frame (cdar key))
(lp req opt (cdr key) rest (1+ i))))
(rest
(binding-ref rest i))
(else
'())))))
(else
;; case 2
(map (lambda (i)
(frame-local-ref frame i))
(iota (frame-num-locals frame))))))))
;;; Misc
;;;
(define (frame-environment frame)
(map (lambda (binding)
(cons (binding_name binding) (frame-binding-ref frame binding)))
(frame-bindings frame)))
(define (frame-object-binding frame obj)
(do ((bs (frame-bindings frame) (cdr bs)))
((or (null? bs) (eq? obj (frame-binding-ref frame (car bs))))
(and (pair? bs) (car bs)))))
(define (frame-object-name frame obj)
(cond ((frame-object-binding frame obj) => binding_name)
(else #f)))
;; Nota bene, only if frame is in a return context (i.e. in a
;; pop-continuation hook dispatch).
(define (frame-return-values frame)
(let* ((len (frame-num-locals frame))
(nvalues (frame-local-ref frame (1- len))))
(map (lambda (i)
(frame-local-ref frame (+ (- len nvalues 1) i)))
(iota nvalues))))
;;; Guile VM debugging facilities
;;; Copyright (C) 2001, 2009, 2010, 2011 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm inspect)
#\use-module (system base pmatch)
#\use-module (system base syntax)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module ((language assembly disassemble)
#\select ((disassemble . %disassemble)))
#\use-module (ice-9 rdelim)
#\use-module (ice-9 pretty-print)
#\use-module (ice-9 format)
#\use-module (system vm program)
#\export (inspect))
(define (reverse-hashq h)
(let ((ret (make-hash-table)))
(hash-for-each
(lambda (k v)
(hashq-set! ret v (cons k (hashq-ref ret v '()))))
h)
ret))
(define (catch-bad-arguments thunk bad-args-thunk)
(catch 'wrong-number-of-args
(lambda ()
(catch 'keyword-argument-error
thunk
(lambda (k . args)
(bad-args-thunk))))
(lambda (k . args)
(bad-args-thunk))))
(define (read-args prompt)
(define (read* reader)
(repl-reader prompt reader))
(define (next)
(read* read-char))
(define (cmd chr)
(cond
((eof-object? chr) (list chr))
((char=? chr #\newline) (cmd (next)))
((char-whitespace? chr) (cmd (next)))
(else
(unread-char chr)
(let ((tok (read* read)))
(args (list tok) (next))))))
(define (args out chr)
(cond
((eof-object? chr) (reverse out))
((char=? chr #\newline) (reverse out))
((char-whitespace? chr) (args out (next)))
(else
(unread-char chr)
(let ((tok (read* read)))
(args (cons tok out) (next))))))
(cmd (next)))
;;;
;;; Inspector
;;;
(define (inspect x)
(define-syntax-rule (define-command ((mod cname alias ...) . args)
body ...)
(define cname
(let ((c (lambda* args body ...)))
(set-procedure-property! c 'name 'cname)
(module-define! mod 'cname c)
(module-add! mod 'alias (module-local-variable mod 'cname))
...
c)))
(let ((commands (make-module)))
(define (prompt)
(format #f "~20@y inspect> " x))
(define-command ((commands quit q continue cont c))
"Quit the inspector."
(throw 'quit))
(define-command ((commands print p))
"Print the current object using `pretty-print'."
(pretty-print x))
(define-command ((commands write w))
"Print the current object using `write'."
(write x))
(define-command ((commands display d))
"Print the current object using `display'."
(display x))
(define-command ((commands disassemble x))
"Disassemble the current object, which should be objcode or a procedure."
(catch #t
(lambda ()
(%disassemble x))
(lambda args
(format #t "Error disassembling object_ ~a\n" args))))
(define-command ((commands help h ?) #\optional cmd)
"Show this help message."
(let ((rhash (reverse-hashq (module-obarray commands))))
(define (help-cmd cmd)
(let* ((v (module-local-variable commands cmd))
(p (variable-ref v))
(canonical-name (procedure-name p)))
;; la la la
(format #t "~a~{ ~_@(~a~)~}~?~%~a~&~%"
canonical-name (program-lambda-list p)
"~#[~_;~40t(aliases_ ~@{~a~^, ~})~]"
(delq canonical-name (hashq-ref rhash v))
(procedure-documentation p))))
(cond
(cmd
(cond
((and (symbol? cmd) (module-local-variable commands cmd))
(help-cmd cmd))
(else
(format #t "Invalid command ~s.~%" cmd)
(format #t "Try `help' for a list of commands~%"))))
(else
(let ((names (sort
(hash-map->list
(lambda (k v)
(procedure-name (variable-ref k)))
rhash)
(lambda (x y)
(string<? (symbol->string x)
(symbol->string y))))))
(format #t "Available commands_~%~%")
(for-each help-cmd names))))))
(define (handle cmd . args)
(cond
((and (symbol? cmd)
(module-local-variable commands cmd))
=> (lambda (var)
(let ((proc (variable-ref var)))
(catch-bad-arguments
(lambda ()
(apply (variable-ref var) args))
(lambda ()
(format (current-error-port)
"Invalid arguments to ~a. Try `help ~a'.~%"
(procedure-name proc) (procedure-name proc)))))))
; ((and (integer? cmd) (exact? cmd))
; (nth cmd))
((eof-object? cmd)
(newline)
(throw 'quit))
(else
(format (current-error-port)
"~&Unknown command_ ~a. Try `help'.~%" cmd)
*unspecified*)))
(catch 'quit
(lambda ()
(let loop ()
(apply
handle
(save-module-excursion
(lambda ()
(set-current-module commands)
(read-args prompt))))
(loop)))
(lambda (k . args)
(apply values args)))))
;;; Guile VM instructions
;; Copyright (C) 2001, 2010 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm instruction)
#\export (instruction-list
instruction? instruction-length
instruction-pops instruction-pushes
instruction->opcode opcode->instruction))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_instructions")
;;; Guile VM object code
;; Copyright (C) 2001, 2010 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm objcode)
#\export (objcode? objcode-meta
bytecode->objcode objcode->bytecode
load-objcode write-objcode
word-size byte-order))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_objcodes")
;;; Guile VM program functions
;;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm program)
#\use-module (system base pmatch)
#\use-module (system vm instruction)
#\use-module (system vm objcode)
#\use-module (rnrs bytevectors)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-26)
#\export (make-program
make-binding binding_name binding_boxed? binding_index
binding_start binding_end
source_addr source_line source_column source_file
source_line-for-user
program-sources program-sources-pre-retire program-source
program-bindings program-bindings-by-index program-bindings-for-ip
program-arities program-arity arity_start arity_end
arity_nreq arity_nopt arity_rest? arity_kw arity_allow-other-keys?
program-arguments-alist program-lambda-list
program-meta
program-objcode program? program-objects
program-module program-base
program-free-variables
program-num-free-variables
program-free-variable-ref program-free-variable-set!))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_programs")
(define (make-binding name boxed? index start end)
(list name boxed? index start end))
(define (binding_name b) (list-ref b 0))
(define (binding_boxed? b) (list-ref b 1))
(define (binding_index b) (list-ref b 2))
(define (binding_start b) (list-ref b 3))
(define (binding_end b) (list-ref b 4))
(define (source_addr source)
(car source))
(define (source_file source)
(cadr source))
(define (source_line source)
(caddr source))
(define (source_column source)
(cdddr source))
;; Lines are zero-indexed inside Guile, but users expect them to be
;; one-indexed. Columns, on the other hand, are zero-indexed to both. Go
;; figure.
(define (source_line-for-user source)
(1+ (source_line source)))
;; FIXME_ pull this definition from elsewhere.
(define *bytecode-header-len* 8)
;; We could decompile the program to get this, but that seems like a
;; waste.
(define (bytecode-instruction-length bytecode ip)
(let* ((idx (+ ip *bytecode-header-len*))
(inst (opcode->instruction (bytevector-u8-ref bytecode idx))))
;; 1+ for the instruction itself.
(1+ (cond
((eq? inst 'load-program)
(+ (bytevector-u32-native-ref bytecode (+ idx 1))
(bytevector-u32-native-ref bytecode (+ idx 5))))
((< (instruction-length inst) 0)
;; variable length instruction -- the length is encoded in the
;; instruction stream.
(+ (ash (bytevector-u8-ref bytecode (+ idx 1)) 16)
(ash (bytevector-u8-ref bytecode (+ idx 2)) 8)
(bytevector-u8-ref bytecode (+ idx 3))))
(else
;; fixed length
(instruction-length inst))))))
;; Source information could in theory be correlated with the ip of the
;; instruction, or the ip just after the instruction is retired. Guile
;; does the latter, to make backtraces easy -- an error produced while
;; running an opcode always happens after it has retired its arguments.
;;
;; But for breakpoints and such, we need the ip before the instruction
;; is retired -- before it has had a chance to do anything. So here we
;; change from the post-retire addresses given by program-sources to
;; pre-retire addresses.
;;
(define (program-sources-pre-retire proc)
(let ((bv (objcode->bytecode (program-objcode proc))))
(let lp ((in (program-sources proc))
(out '())
(ip 0))
(cond
((null? in)
(reverse out))
(else
(pmatch (car in)
((,post-ip . ,source)
(let lp2 ((ip ip)
(next ip))
(if (< next post-ip)
(lp2 next (+ next (bytecode-instruction-length bv next)))
(lp (cdr in)
(acons ip source out)
next))))
(else
(error "unexpected"))))))))
(define (collapse-locals locs)
(let lp ((ret '()) (locs locs))
(if (null? locs)
(map cdr (sort! ret
(lambda (x y) (< (car x) (car y)))))
(let ((b (car locs)))
(cond
((assv-ref ret (binding_index b))
=> (lambda (bindings)
(append! bindings (list b))
(lp ret (cdr locs))))
(else
(lp (acons (binding_index b) (list b) ret)
(cdr locs))))))))
;; returns list of list of bindings
;; (list-ref ret N) == bindings bound to the Nth local slot
(define (program-bindings-by-index prog)
(cond ((program-bindings prog) => collapse-locals)
(else '())))
(define (program-bindings-for-ip prog ip)
(let lp ((in (program-bindings-by-index prog)) (out '()))
(if (null? in)
(reverse out)
(lp (cdr in)
(let inner ((binds (car in)))
(cond ((null? binds) out)
((<= (binding_start (car binds))
ip
(binding_end (car binds)))
(cons (car binds) out))
(else (inner (cdr binds)))))))))
(define (arity_start a)
(pmatch a ((,start ,end . _) start) (else (error "bad arity" a))))
(define (arity_end a)
(pmatch a ((,start ,end . _) end) (else (error "bad arity" a))))
(define (arity_nreq a)
(pmatch a ((_ _ ,nreq . _) nreq) (else 0)))
(define (arity_nopt a)
(pmatch a ((_ _ ,nreq ,nopt . _) nopt) (else 0)))
(define (arity_rest? a)
(pmatch a ((_ _ ,nreq ,nopt ,rest? . _) rest?) (else #f)))
(define (arity_kw a)
(pmatch a ((_ _ ,nreq ,nopt ,rest? (_ . ,kw)) kw) (else '())))
(define (arity_allow-other-keys? a)
(pmatch a ((_ _ ,nreq ,nopt ,rest? (,aok . ,kw)) aok) (else #f)))
(define (program-arity prog ip)
(let ((arities (program-arities prog)))
(and arities
(let lp ((arities arities))
(cond ((null? arities) #f)
((not ip) (car arities)) ; take the first one
((and (< (arity_start (car arities)) ip)
(<= ip (arity_end (car arities))))
(car arities))
(else (lp (cdr arities))))))))
(define (arglist->arguments-alist arglist)
(pmatch arglist
((,req ,opt ,keyword ,allow-other-keys? ,rest . ,extents)
`((required . ,req)
(optional . ,opt)
(keyword . ,keyword)
(allow-other-keys? . ,allow-other-keys?)
(rest . ,rest)
(extents . ,extents)))
(else #f)))
(define* (arity->arguments-alist prog arity
#\optional
(make-placeholder
(lambda (i) (string->symbol "_"))))
(define var-by-index
(let ((rbinds (map (lambda (x)
(cons (binding_index x) (binding_name x)))
(program-bindings-for-ip prog
(arity_start arity)))))
(lambda (i)
(or (assv-ref rbinds i)
;; if we don't know the name, return a placeholder
(make-placeholder i)))))
(let lp ((nreq (arity_nreq arity)) (req '())
(nopt (arity_nopt arity)) (opt '())
(rest? (arity_rest? arity)) (rest #f)
(n 0))
(cond
((< 0 nreq)
(lp (1- nreq) (cons (var-by-index n) req)
nopt opt rest? rest (1+ n)))
((< 0 nopt)
(lp nreq req
(1- nopt) (cons (var-by-index n) opt)
rest? rest (1+ n)))
(rest?
(lp nreq req nopt opt
#f (var-by-index (+ n (length (arity_kw arity))))
(1+ n)))
(else
`((required . ,(reverse req))
(optional . ,(reverse opt))
(keyword . ,(arity_kw arity))
(allow-other-keys? . ,(arity_allow-other-keys? arity))
(rest . ,rest))))))
;; the name "program-arguments" is taken by features.c...
(define* (program-arguments-alist prog #\optional ip)
"Returns the signature of the given procedure in the form of an association list."
(let ((arity (program-arity prog ip)))
(and arity
(arity->arguments-alist prog arity))))
(define* (program-lambda-list prog #\optional ip)
"Returns the signature of the given procedure in the form of an argument list."
(and=> (program-arguments-alist prog ip) arguments-alist->lambda-list))
(define (arguments-alist->lambda-list arguments-alist)
(let ((req (or (assq-ref arguments-alist 'required) '()))
(opt (or (assq-ref arguments-alist 'optional) '()))
(key (map keyword->symbol
(map car (or (assq-ref arguments-alist 'keyword) '()))))
(rest (or (assq-ref arguments-alist 'rest) '())))
`(,@req
,@(if (pair? opt) (cons #\optional opt) '())
,@(if (pair? key) (cons #\key key) '())
. ,rest)))
(define (program-free-variables prog)
"Return the list of free variables of PROG."
(let ((count (program-num-free-variables prog)))
(unfold (lambda (i) (>= i count))
(cut program-free-variable-ref prog <>)
1+
0)))
(define (write-program prog port)
(format port "#<procedure ~a~a>"
(or (procedure-name prog)
(and=> (program-source prog 0)
(lambda (s)
(format #f "~a at ~a_~a_~a"
(number->string (object-address prog) 16)
(or (source_file s)
(if s "<current input>" "<unknown port>"))
(source_line-for-user s) (source_column s))))
(number->string (object-address prog) 16))
(let ((arities (program-arities prog)))
(if (or (not arities) (null? arities))
""
(string-append
" " (string-join (map (lambda (a)
(object->string
(arguments-alist->lambda-list
(arity->arguments-alist prog a))))
arities)
" | "))))))
;;; Guile VM tracer
;; Copyright (C) 2001, 2009, 2010, 2013 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm trace)
#\use-module (system base syntax)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module (system vm program)
#\use-module (system vm objcode)
#\use-module (system vm traps)
#\use-module (rnrs bytevectors)
#\use-module (system vm instruction)
#\use-module (ice-9 format)
#\export (trace-calls-in-procedure
trace-calls-to-procedure
trace-instructions-in-procedure
call-with-trace))
;; FIXME_ this constant needs to go in system vm objcode
(define *objcode-header-len* 8)
(define (build-prefix prefix depth infix numeric-format max-indent)
(let lp ((indent "") (n 0))
(cond
((= n depth)
(string-append prefix indent))
((< (+ (string-length indent) (string-length infix)) max-indent)
(lp (string-append indent infix) (1+ n)))
(else
(string-append prefix indent (format #f numeric-format depth))))))
(define (print-application frame depth width prefix max-indent)
(let ((prefix (build-prefix prefix depth "| " "~d> " max-indent)))
(format (current-error-port) "~a~v_@y\n"
prefix
width
(frame-call-representation frame))))
(define* (print-return frame depth width prefix max-indent)
(let* ((len (frame-num-locals frame))
(nvalues (frame-local-ref frame (1- len)))
(prefix (build-prefix prefix depth "| " "~d< "max-indent)))
(case nvalues
((0)
(format (current-error-port) "~ano values\n" prefix))
((1)
(format (current-error-port) "~a~v_@y\n"
prefix
width
(frame-local-ref frame (- len 2))))
(else
;; this should work, but there appears to be a bug
;; "~a~d values_~_{ ~v_@y~}\n"
(format (current-error-port) "~a~d values_~{ ~a~}\n"
prefix nvalues
(map (lambda (val)
(format #f "~v_@y" width val))
(frame-return-values frame)))))))
(define* (trace-calls-to-procedure proc #\key (width 80) (vm (the-vm))
(prefix "trace_ ")
(max-indent (- width 40)))
(define (apply-handler frame depth)
(print-application frame depth width prefix max-indent))
(define (return-handler frame depth)
(print-return frame depth width prefix max-indent))
(trap-calls-to-procedure proc apply-handler return-handler
#\vm vm))
(define* (trace-calls-in-procedure proc #\key (width 80) (vm (the-vm))
(prefix "trace_ ")
(max-indent (- width 40)))
(define (apply-handler frame depth)
(print-application frame depth width prefix max-indent))
(define (return-handler frame depth)
(print-return frame depth width prefix max-indent))
(trap-calls-in-dynamic-extent proc apply-handler return-handler
#\vm vm))
(define* (trace-instructions-in-procedure proc #\key (width 80) (vm (the-vm))
(max-indent (- width 40)))
(define (trace-next frame)
(let* ((ip (frame-instruction-pointer frame))
(objcode (program-objcode (frame-procedure frame)))
(opcode (bytevector-u8-ref (objcode->bytecode objcode)
(+ ip *objcode-header-len*))))
(format #t "~8d_ ~a\n" ip (opcode->instruction opcode))))
(trap-instructions-in-dynamic-extent proc trace-next
#\vm vm))
;; Note that because this procedure manipulates the VM trace level
;; directly, it doesn't compose well with traps at the REPL.
;;
(define* (call-with-trace thunk #\key (calls? #t) (instructions? #f)
(width 80) (vm (the-vm)) (max-indent (- width 40)))
(let ((call-trap #f)
(inst-trap #f))
(dynamic-wind
(lambda ()
(if calls?
(set! call-trap
(trace-calls-in-procedure thunk #\vm vm #\width width
#\max-indent max-indent)))
(if instructions?
(set! inst-trap
(trace-instructions-in-procedure thunk #\vm vm #\width width
#\max-indent max-indent)))
(set-vm-trace-level! vm (1+ (vm-trace-level vm))))
thunk
(lambda ()
(set-vm-trace-level! vm (1- (vm-trace-level vm)))
(if call-trap (call-trap))
(if inst-trap (inst-trap))
(set! call-trap #f)
(set! inst-trap #f)))))
;;; trap-state.scm_ a set of traps
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary_
;;;
;;; Code_
(define-module (system vm trap-state)
#\use-module (system base syntax)
#\use-module ((srfi srfi-1) #\select (fold))
#\use-module (system vm vm)
#\use-module (system vm traps)
#\use-module (system vm trace)
#\use-module (system vm frame)
#\use-module (system vm program)
#\export (add-trap!
list-traps
trap-enabled?
trap-name
enable-trap!
disable-trap!
delete-trap!
with-default-trap-handler
install-trap-handler!
add-trap-at-procedure-call!
add-trace-at-procedure-call!
add-trap-at-source-location!
add-ephemeral-trap-at-frame-finish!
add-ephemeral-stepping-trap!))
(define %default-trap-handler (make-fluid))
(define (default-trap-handler frame idx trap-name)
(let ((default-handler (fluid-ref %default-trap-handler)))
(if default-handler
(default-handler frame idx trap-name)
(warn "Trap with no handler installed" frame idx trap-name))))
(define-record <trap-wrapper>
index
enabled?
trap
name)
(define-record <trap-state>
(handler default-trap-handler)
(next-idx 0)
(next-ephemeral-idx -1)
(wrappers '()))
(define (trap-wrapper<? t1 t2)
(< (trap-wrapper-index t1) (trap-wrapper-index t2)))
;; The interface that a trap provides to the outside world is that of a
;; procedure, which when called disables the trap, and returns a
;; procedure to enable the trap. Perhaps this is a bit too odd and we
;; should fix this.
(define (enable-trap-wrapper! wrapper)
(if (trap-wrapper-enabled? wrapper)
(error "Trap already enabled" (trap-wrapper-index wrapper))
(let ((trap (trap-wrapper-trap wrapper)))
(set! (trap-wrapper-trap wrapper) (trap))
(set! (trap-wrapper-enabled? wrapper) #t))))
(define (disable-trap-wrapper! wrapper)
(if (not (trap-wrapper-enabled? wrapper))
(error "Trap already disabled" (trap-wrapper-index wrapper))
(let ((trap (trap-wrapper-trap wrapper)))
(set! (trap-wrapper-trap wrapper) (trap))
(set! (trap-wrapper-enabled? wrapper) #f))))
(define (add-trap-wrapper! trap-state wrapper)
(set! (trap-state-wrappers trap-state)
(append (trap-state-wrappers trap-state) (list wrapper)))
(trap-wrapper-index wrapper))
(define (remove-trap-wrapper! trap-state wrapper)
(set! (trap-state-wrappers trap-state)
(delq wrapper (trap-state-wrappers trap-state))))
(define (trap-state->trace-level trap-state)
(fold (lambda (wrapper level)
(if (trap-wrapper-enabled? wrapper)
(1+ level)
level))
0
(trap-state-wrappers trap-state)))
(define (wrapper-at-index trap-state idx)
(let lp ((wrappers (trap-state-wrappers trap-state)))
(cond
((null? wrappers)
(warn "no wrapper found with index in trap-state" idx)
#f)
((eqv? (trap-wrapper-index (car wrappers)) idx)
(car wrappers))
(else
(lp (cdr wrappers))))))
(define (next-index! trap-state)
(let ((idx (trap-state-next-idx trap-state)))
(set! (trap-state-next-idx trap-state) (1+ idx))
idx))
(define (next-ephemeral-index! trap-state)
(let ((idx (trap-state-next-ephemeral-idx trap-state)))
(set! (trap-state-next-ephemeral-idx trap-state) (1- idx))
idx))
(define (handler-for-index trap-state idx)
(lambda (frame)
(let ((wrapper (wrapper-at-index trap-state idx))
(handler (trap-state-handler trap-state)))
(if wrapper
(handler frame
(trap-wrapper-index wrapper)
(trap-wrapper-name wrapper))))))
(define (ephemeral-handler-for-index trap-state idx handler)
(lambda (frame)
(let ((wrapper (wrapper-at-index trap-state idx)))
(if wrapper
(begin
(if (trap-wrapper-enabled? wrapper)
(disable-trap-wrapper! wrapper))
(remove-trap-wrapper! trap-state wrapper)
(handler frame))))))
;;;
;;; VM-local trap states
;;;
(define *trap-states* (make-weak-key-hash-table))
(define (trap-state-for-vm vm)
(or (hashq-ref *trap-states* vm)
(let ((ts (make-trap-state)))
(hashq-set! *trap-states* vm ts)
(trap-state-for-vm vm))))
(define (the-trap-state)
(trap-state-for-vm (the-vm)))
;;;
;;; API
;;;
(define* (with-default-trap-handler handler thunk
#\optional (trap-state (the-trap-state)))
(with-fluids ((%default-trap-handler handler))
(dynamic-wind
(lambda ()
;; Don't enable hooks if the handler is #f.
(if handler
(set-vm-trace-level! (the-vm) (trap-state->trace-level trap-state))))
thunk
(lambda ()
(if handler
(set-vm-trace-level! (the-vm) 0))))))
(define* (list-traps #\optional (trap-state (the-trap-state)))
(map trap-wrapper-index (trap-state-wrappers trap-state)))
(define* (trap-name idx #\optional (trap-state (the-trap-state)))
(and=> (wrapper-at-index trap-state idx)
trap-wrapper-name))
(define* (trap-enabled? idx #\optional (trap-state (the-trap-state)))
(and=> (wrapper-at-index trap-state idx)
trap-wrapper-enabled?))
(define* (enable-trap! idx #\optional (trap-state (the-trap-state)))
(and=> (wrapper-at-index trap-state idx)
enable-trap-wrapper!))
(define* (disable-trap! idx #\optional (trap-state (the-trap-state)))
(and=> (wrapper-at-index trap-state idx)
disable-trap-wrapper!))
(define* (delete-trap! idx #\optional (trap-state (the-trap-state)))
(and=> (wrapper-at-index trap-state idx)
(lambda (wrapper)
(if (trap-wrapper-enabled? wrapper)
(disable-trap-wrapper! wrapper))
(remove-trap-wrapper! trap-state wrapper))))
(define* (install-trap-handler! handler #\optional (trap-state (the-trap-state)))
(set! (trap-state-handler trap-state) handler))
(define* (add-trap-at-procedure-call! proc #\optional (trap-state (the-trap-state)))
(let* ((idx (next-index! trap-state))
(trap (trap-at-procedure-call
proc
(handler-for-index trap-state idx))))
(add-trap-wrapper!
trap-state
(make-trap-wrapper
idx #t trap
(format #f "Breakpoint at ~a" proc)))))
(define* (add-trace-at-procedure-call! proc
#\optional (trap-state (the-trap-state)))
(let* ((idx (next-index! trap-state))
(trap (trace-calls-to-procedure
proc
#\prefix (format #f "Trap ~a_ " idx))))
(add-trap-wrapper!
trap-state
(make-trap-wrapper
idx #t trap
(format #f "Tracepoint at ~a" proc)))))
(define* (add-trap-at-source-location! file user-line
#\optional (trap-state (the-trap-state)))
(let* ((idx (next-index! trap-state))
(trap (trap-at-source-location file user-line
(handler-for-index trap-state idx))))
(add-trap-wrapper!
trap-state
(make-trap-wrapper
idx #t trap
(format #f "Breakpoint at ~a_~a" file user-line)))))
;; handler _= frame -> nothing
(define* (add-ephemeral-trap-at-frame-finish! frame handler
#\optional (trap-state
(the-trap-state)))
(let* ((idx (next-ephemeral-index! trap-state))
(trap (trap-frame-finish
frame
(ephemeral-handler-for-index trap-state idx handler)
(lambda (frame) (delete-trap! idx trap-state)))))
(add-trap-wrapper!
trap-state
(make-trap-wrapper
idx #t trap
(format #f "Return from ~a" frame)))))
(define (source-string source)
(if source
(format #f "~a_~a_~a" (or (source_file source) "unknown file")
(source_line-for-user source) (source_column source))
"unknown source location"))
(define* (add-ephemeral-stepping-trap! frame handler
#\optional (trap-state
(the-trap-state))
#\key (into? #t) (instruction? #f))
(define (wrap-predicate-according-to-into predicate)
(if into?
predicate
(let ((fp (frame-address frame)))
(lambda (f)
(and (<= (frame-address f) fp)
(predicate f))))))
(let* ((source (frame-next-source frame))
(idx (next-ephemeral-index! trap-state))
(trap (trap-matching-instructions
(wrap-predicate-according-to-into
(if instruction?
(lambda (f) #t)
(lambda (f) (not (equal? (frame-next-source f) source)))))
(ephemeral-handler-for-index trap-state idx handler))))
(add-trap-wrapper!
trap-state
(make-trap-wrapper
idx #t trap
(if instruction?
(if into?
"Step to different instruction"
(format #f "Step to different instruction in ~a" frame))
(if into?
(format #f "Step into ~a" (source-string source))
(format #f "Step out of ~a" (source-string source))))))))
(define* (add-trap! trap name #\optional (trap-state (the-trap-state)))
(let* ((idx (next-index! trap-state)))
(add-trap-wrapper!
trap-state
(make-trap-wrapper idx #t trap name))))
;;; Traps_ stepping, breakpoints, and such.
;; Copyright (C) 2010 Free Software Foundation, Inc.
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary_
;;;
;;; Guile's debugging capabilities come from the hooks that its VM
;;; provides. For example, there is a hook that is fired when a function
;;; is called, and even a hook that gets fired at every retired
;;; instruction.
;;;
;;; But as the firing of these hooks is interleaved with the program
;;; execution, if we want to debug a program, we have to write an
;;; imperative program that mutates the state of these hooks, and to
;;; dispatch the hooks to a more semantic context.
;;;
;;; For example if we have placed a breakpoint at foo.scm_38, and
;;; determined that that location maps to the 18th instruction in
;;; procedure `bar', then we will need per-instruction hooks within
;;; `bar' -- but when running other procedures, we can have the
;;; per-instruction hooks off.
;;;
;;; Our approach is to define "traps". The behavior of a trap is
;;; specified when the trap is created. After creation, traps expose a
;;; limited, uniform interface_ they are either on or off.
;;;
;;; To take our foo.scm_38 example again, we can define a trap that
;;; calls a function when control transfers to that source line --
;;; trap-at-source-location below. Calling the trap-at-source-location
;;; function adds to the VM hooks in such at way that it can do its job.
;;; The result of calling the function is a "disable-hook" closure that,
;;; when called, will turn off that trap.
;;;
;;; The result of calling the "disable-hook" closure, in turn, is an
;;; "enable-hook" closure, which when called turns the hook back on, and
;;; returns a "disable-hook" closure.
;;;
;;; It's a little confusing. The summary is, call these functions to add
;;; a trap; and call their return value to disable the trap.
;;;
;;; Code_
(define-module (system vm traps)
#\use-module (system base pmatch)
#\use-module (system vm vm)
#\use-module (system vm frame)
#\use-module (system vm program)
#\use-module (system vm objcode)
#\use-module (system vm instruction)
#\use-module (system xref)
#\use-module (rnrs bytevectors)
#\export (trap-at-procedure-call
trap-in-procedure
trap-instructions-in-procedure
trap-at-procedure-ip-in-range
trap-at-source-location
trap-frame-finish
trap-in-dynamic-extent
trap-calls-in-dynamic-extent
trap-instructions-in-dynamic-extent
trap-calls-to-procedure
trap-matching-instructions))
(define-syntax arg-check
(syntax-rules ()
((_ arg predicate? message)
(if (not (predicate? arg))
(error "bad argument ~a_ ~a" 'arg message)))
((_ arg predicate?)
(if (not (predicate? arg))
(error "bad argument ~a_ expected ~a" 'arg 'predicate?)))))
(define (new-disabled-trap vm enable disable)
(let ((enabled? #f))
(define-syntax disabled?
(identifier-syntax
(disabled? (not enabled?))
((set! disabled? val) (set! enabled? (not val)))))
(define* (enable-trap #\optional frame)
(if enabled? (error "trap already enabled"))
(enable frame)
(set! enabled? #t)
disable-trap)
(define* (disable-trap #\optional frame)
(if disabled? (error "trap already disabled"))
(disable frame)
(set! disabled? #t)
enable-trap)
enable-trap))
(define (new-enabled-trap vm frame enable disable)
((new-disabled-trap vm enable disable) frame))
(define (frame-matcher proc match-objcode?)
(let ((proc (if (struct? proc)
(procedure proc)
proc)))
(if match-objcode?
(lambda (frame)
(let ((frame-proc (frame-procedure frame)))
(or (eq? frame-proc proc)
(and (program? frame-proc)
(eq? (program-objcode frame-proc)
(program-objcode proc))))))
(lambda (frame)
(eq? (frame-procedure frame) proc)))))
;; A basic trap, fires when a procedure is called.
;;
(define* (trap-at-procedure-call proc handler #\key (vm (the-vm))
(closure? #f)
(our-frame? (frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check handler procedure?)
(let ()
(define (apply-hook frame)
(if (our-frame? frame)
(handler frame)))
(new-enabled-trap
vm #f
(lambda (frame)
(add-hook! (vm-apply-hook vm) apply-hook))
(lambda (frame)
(remove-hook! (vm-apply-hook vm) apply-hook)))))
;; A more complicated trap, traps when control enters a procedure.
;;
;; Control can enter a procedure via_
;; * A procedure call.
;; * A return to a procedure's frame on the stack.
;; * A continuation returning directly to an application of this
;; procedure.
;;
;; Control can leave a procedure via_
;; * A normal return from the procedure.
;; * An application of another procedure.
;; * An invocation of a continuation.
;; * An abort.
;;
(define* (trap-in-procedure proc enter-handler exit-handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame? (frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check enter-handler procedure?)
(arg-check exit-handler procedure?)
(let ((in-proc? #f))
(define (enter-proc frame)
(if in-proc?
(warn "already in proc" frame)
(begin
(enter-handler frame)
(set! in-proc? #t))))
(define (exit-proc frame)
(if in-proc?
(begin
(exit-handler frame)
(set! in-proc? #f))
(warn "not in proc" frame)))
(define (apply-hook frame)
(if in-proc?
(exit-proc frame))
(if (our-frame? frame)
(enter-proc frame)))
(define (push-cont-hook frame)
(if in-proc?
(exit-proc frame)))
(define (pop-cont-hook frame)
(if in-proc?
(exit-proc frame))
(if (our-frame? (frame-previous frame))
(enter-proc (frame-previous frame))))
(define (abort-hook frame)
(if in-proc?
(exit-proc frame))
(if (our-frame? frame)
(enter-proc frame)))
(define (restore-hook frame)
(if in-proc?
(exit-proc frame))
(if (our-frame? frame)
(enter-proc frame)))
(new-enabled-trap
vm current-frame
(lambda (frame)
(add-hook! (vm-apply-hook vm) apply-hook)
(add-hook! (vm-push-continuation-hook vm) push-cont-hook)
(add-hook! (vm-pop-continuation-hook vm) pop-cont-hook)
(add-hook! (vm-abort-continuation-hook vm) abort-hook)
(add-hook! (vm-restore-continuation-hook vm) restore-hook)
(if (and frame (our-frame? frame))
(enter-proc frame)))
(lambda (frame)
(if in-proc?
(exit-proc frame))
(remove-hook! (vm-apply-hook vm) apply-hook)
(remove-hook! (vm-push-continuation-hook vm) push-cont-hook)
(remove-hook! (vm-pop-continuation-hook vm) pop-cont-hook)
(remove-hook! (vm-abort-continuation-hook vm) abort-hook)
(remove-hook! (vm-restore-continuation-hook vm) restore-hook)))))
;; Building on trap-in-procedure, we have trap-instructions-in-procedure
;;
(define* (trap-instructions-in-procedure proc next-handler exit-handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame?
(frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check next-handler procedure?)
(arg-check exit-handler procedure?)
(let ()
(define (next-hook frame)
(if (our-frame? frame)
(next-handler frame)))
(define (enter frame)
(add-hook! (vm-next-hook vm) next-hook)
(if frame (next-hook frame)))
(define (exit frame)
(exit-handler frame)
(remove-hook! (vm-next-hook vm) next-hook))
(trap-in-procedure proc enter exit
#\current-frame current-frame #\vm vm
#\our-frame? our-frame?)))
(define (non-negative-integer? x)
(and (number? x) (integer? x) (exact? x) (not (negative? x))))
(define (positive-integer? x)
(and (number? x) (integer? x) (exact? x) (positive? x)))
(define (range? x)
(and (list? x)
(and-map (lambda (x)
(and (pair? x)
(non-negative-integer? (car x))
(non-negative-integer? (cdr x))))
x)))
(define (in-range? range i)
(or-map (lambda (bounds)
(and (<= (car bounds) i)
(< i (cdr bounds))))
range))
;; Building on trap-instructions-in-procedure, we have
;; trap-at-procedure-ip-in-range.
;;
(define* (trap-at-procedure-ip-in-range proc range handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame?
(frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check range range?)
(arg-check handler procedure?)
(let ((fp-stack '()))
(define (cull-frames! fp)
(let lp ((frames fp-stack))
(if (and (pair? frames) (< (car frames) fp))
(lp (cdr frames))
(set! fp-stack frames))))
(define (next-handler frame)
(let ((fp (frame-address frame))
(ip (frame-instruction-pointer frame)))
(cull-frames! fp)
(let ((now-in-range? (in-range? range ip))
(was-in-range? (and (pair? fp-stack) (= (car fp-stack) fp))))
(cond
(was-in-range?
(if (not now-in-range?)
(set! fp-stack (cdr fp-stack))))
(now-in-range?
(set! fp-stack (cons fp fp-stack))
(handler frame))))))
(define (exit-handler frame)
(if (and (pair? fp-stack)
(= (car fp-stack) (frame-address frame)))
(set! fp-stack (cdr fp-stack))))
(trap-instructions-in-procedure proc next-handler exit-handler
#\current-frame current-frame #\vm vm
#\our-frame? our-frame?)))
;; FIXME_ define this in objcode somehow. We are reffing the first
;; uint32 in the objcode, which is the length of the program (without
;; the meta).
(define (program-last-ip prog)
(bytevector-u32-native-ref (objcode->bytecode (program-objcode prog)) 0))
(define (program-sources-by-line proc file)
(let lp ((sources (program-sources-pre-retire proc))
(out '()))
(if (pair? sources)
(lp (cdr sources)
(pmatch (car sources)
((,start-ip ,start-file ,start-line . ,start-col)
(if (equal? start-file file)
(cons (cons start-line
(if (pair? (cdr sources))
(pmatch (cadr sources)
((,end-ip . _)
(cons start-ip end-ip))
(else (error "unexpected")))
(cons start-ip (program-last-ip proc))))
out)
out))
(else (error "unexpected"))))
(let ((alist '()))
(for-each
(lambda (pair)
(set! alist
(assv-set! alist (car pair)
(cons (cdr pair)
(or (assv-ref alist (car pair))
'())))))
out)
(sort! alist (lambda (x y) (< (car x) (car y))))
alist))))
(define (source->ip-range proc file line)
(or (or-map (lambda (line-and-ranges)
(cond
((= (car line-and-ranges) line)
(cdr line-and-ranges))
((> (car line-and-ranges) line)
(warn "no instructions found at" file "_" line
"; using line" (car line-and-ranges) "instead")
(cdr line-and-ranges))
(else #f)))
(program-sources-by-line proc file))
(begin
(warn "no instructions found for" file "_" line)
'())))
(define (source-closures-or-procedures file line)
(let ((closures (source-closures file line)))
(if (pair? closures)
(values closures #t)
(values (source-procedures file line) #f))))
;; Building on trap-on-instructions-in-procedure, we have
;; trap-at-source-location. The parameter `user-line' is one-indexed, as
;; a user counts lines, instead of zero-indexed, as Guile counts lines.
;;
(define* (trap-at-source-location file user-line handler
#\key current-frame (vm (the-vm)))
(arg-check file string?)
(arg-check user-line positive-integer?)
(arg-check handler procedure?)
(let ((traps #f))
(call-with-values
(lambda () (source-closures-or-procedures file (1- user-line)))
(lambda (procs closures?)
(new-enabled-trap
vm current-frame
(lambda (frame)
(set! traps
(map
(lambda (proc)
(let ((range (source->ip-range proc file (1- user-line))))
(trap-at-procedure-ip-in-range proc range handler
#\current-frame current-frame
#\vm vm
#\closure? closures?)))
procs))
(if (null? traps)
(error "No procedures found at ~a_~a." file user-line)))
(lambda (frame)
(for-each (lambda (trap) (trap frame)) traps)
(set! traps #f)))))))
;; On a different tack, now we're going to build up a set of traps that
;; do useful things during the dynamic extent of a procedure's
;; application. First, a trap for when a frame returns.
;;
(define* (trap-frame-finish frame return-handler abort-handler
#\key (vm (the-vm)))
(arg-check frame frame?)
(arg-check return-handler procedure?)
(arg-check abort-handler procedure?)
(let ((fp (frame-address frame)))
(define (pop-cont-hook frame)
(if (and fp (eq? (frame-address frame) fp))
(begin
(set! fp #f)
(return-handler frame))))
(define (abort-hook frame)
(if (and fp (< (frame-address frame) fp))
(begin
(set! fp #f)
(abort-handler frame))))
(new-enabled-trap
vm frame
(lambda (frame)
(if (not fp)
(error "return-or-abort traps may only be enabled once"))
(add-hook! (vm-pop-continuation-hook vm) pop-cont-hook)
(add-hook! (vm-abort-continuation-hook vm) abort-hook)
(add-hook! (vm-restore-continuation-hook vm) abort-hook))
(lambda (frame)
(set! fp #f)
(remove-hook! (vm-pop-continuation-hook vm) pop-cont-hook)
(remove-hook! (vm-abort-continuation-hook vm) abort-hook)
(remove-hook! (vm-restore-continuation-hook vm) abort-hook)))))
;; A more traditional dynamic-wind trap. Perhaps this should not be
;; based on the above trap-frame-finish?
;;
(define* (trap-in-dynamic-extent proc enter-handler return-handler abort-handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame? (frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check enter-handler procedure?)
(arg-check return-handler procedure?)
(arg-check abort-handler procedure?)
(let ((exit-trap #f))
(define (return-hook frame)
(exit-trap frame) ; disable the return/abort trap.
(set! exit-trap #f)
(return-handler frame))
(define (abort-hook frame)
(exit-trap frame) ; disable the return/abort trap.
(set! exit-trap #f)
(abort-handler frame))
(define (apply-hook frame)
(if (and (not exit-trap) (our-frame? frame))
(begin
(enter-handler frame)
(set! exit-trap
(trap-frame-finish frame return-hook abort-hook
#\vm vm)))))
(new-enabled-trap
vm current-frame
(lambda (frame)
(add-hook! (vm-apply-hook vm) apply-hook))
(lambda (frame)
(if exit-trap
(abort-hook frame))
(set! exit-trap #f)
(remove-hook! (vm-apply-hook vm) apply-hook)))))
;; Trapping all procedure calls within a dynamic extent, recording the
;; depth of the call stack relative to the original procedure.
;;
(define* (trap-calls-in-dynamic-extent proc apply-handler return-handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame?
(frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check apply-handler procedure?)
(arg-check return-handler procedure?)
(let ((*call-depth* 0))
(define (trace-push frame)
(set! *call-depth* (1+ *call-depth*)))
(define (trace-pop frame)
(return-handler frame *call-depth*)
(set! *call-depth* (1- *call-depth*)))
(define (trace-apply frame)
(apply-handler frame *call-depth*))
;; FIXME_ recalc depth on abort
(define (enter frame)
(add-hook! (vm-push-continuation-hook vm) trace-push)
(add-hook! (vm-pop-continuation-hook vm) trace-pop)
(add-hook! (vm-apply-hook vm) trace-apply))
(define (leave frame)
(remove-hook! (vm-push-continuation-hook vm) trace-push)
(remove-hook! (vm-pop-continuation-hook vm) trace-pop)
(remove-hook! (vm-apply-hook vm) trace-apply))
(define (return frame)
(leave frame))
(define (abort frame)
(leave frame))
(trap-in-dynamic-extent proc enter return abort
#\current-frame current-frame #\vm vm
#\our-frame? our-frame?)))
;; Trapping all retired intructions within a dynamic extent.
;;
(define* (trap-instructions-in-dynamic-extent proc next-handler
#\key current-frame (vm (the-vm))
(closure? #f)
(our-frame?
(frame-matcher proc closure?)))
(arg-check proc procedure?)
(arg-check next-handler procedure?)
(let ()
(define (trace-next frame)
(next-handler frame))
(define (enter frame)
(add-hook! (vm-next-hook vm) trace-next))
(define (leave frame)
(remove-hook! (vm-next-hook vm) trace-next))
(define (return frame)
(leave frame))
(define (abort frame)
(leave frame))
(trap-in-dynamic-extent proc enter return abort
#\current-frame current-frame #\vm vm
#\our-frame? our-frame?)))
;; Traps calls and returns for a given procedure, keeping track of the call depth.
;;
(define* (trap-calls-to-procedure proc apply-handler return-handler
#\key (vm (the-vm)))
(arg-check proc procedure?)
(arg-check apply-handler procedure?)
(arg-check return-handler procedure?)
(let ((pending-finish-traps '())
(last-fp #f))
(define (apply-hook frame)
(let ((depth (length pending-finish-traps)))
(apply-handler frame depth)
(if (not (eq? (frame-address frame) last-fp))
(let ((finish-trap #f))
(define (frame-finished frame)
(finish-trap frame) ;; disables the trap.
(set! pending-finish-traps
(delq finish-trap pending-finish-traps))
(set! finish-trap #f))
(define (return-hook frame)
(frame-finished frame)
(return-handler frame depth))
;; FIXME_ abort handler?
(define (abort-hook frame)
(frame-finished frame))
(set! finish-trap
(trap-frame-finish frame return-hook abort-hook #\vm vm))
(set! pending-finish-traps
(cons finish-trap pending-finish-traps))))))
;; The basic idea is that we install one trap that fires for calls,
;; but that each call installs its own finish trap. Those finish
;; traps remove themselves as their frames finish or abort.
;;
;; However since to the outside world we present the interface of
;; just being one trap, disabling this calls-to-procedure trap
;; should take care of disabling all of the pending finish traps. We
;; keep track of pending traps through the pending-finish-traps
;; list.
;;
;; So since we know that the trap-at-procedure will be enabled, and
;; thus returning a disable closure, we make sure to wrap that
;; closure in something that will disable pending finish traps.
(define (with-pending-finish-disablers trap)
(define (with-pending-finish-enablers trap)
(lambda* (#\optional frame)
(with-pending-finish-disablers (trap frame))))
(lambda* (#\optional frame)
(for-each (lambda (disable) (disable frame))
pending-finish-traps)
(set! pending-finish-traps '())
(with-pending-finish-enablers (trap frame))))
(with-pending-finish-disablers
(trap-at-procedure-call proc apply-hook #\vm vm))))
;; Trap when the source location changes.
;;
(define* (trap-matching-instructions frame-pred handler
#\key (vm (the-vm)))
(arg-check frame-pred procedure?)
(arg-check handler procedure?)
(let ()
(define (next-hook frame)
(if (frame-pred frame)
(handler frame)))
(new-enabled-trap
vm #f
(lambda (frame)
(add-hook! (vm-next-hook vm) next-hook))
(lambda (frame)
(remove-hook! (vm-next-hook vm) next-hook)))))
;;; Guile VM core
;;; Copyright (C) 2001, 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This library is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public
;;; License as published by the Free Software Foundation; either
;;; version 3 of the License, or (at your option) any later version.
;;;
;;; This library 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
;;; Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public
;;; License along with this library; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Code_
(define-module (system vm vm)
#\export (vm?
make-vm the-vm call-with-vm
vm_ip vm_sp vm_fp
vm-trace-level set-vm-trace-level!
vm-engine set-vm-engine! set-default-vm-engine!
vm-push-continuation-hook vm-pop-continuation-hook
vm-apply-hook
vm-next-hook
vm-abort-continuation-hook vm-restore-continuation-hook))
(load-extension (string-append "libguile-" (effective-version))
"scm_init_vm")
;;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2.1 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
(define-module (system xref)
#\use-module (system base pmatch)
#\use-module (system base compile)
#\use-module (system vm program)
#\use-module (srfi srfi-1)
#\export (*xref-ignored-modules*
procedure-callees
procedure-callers
source-closures
source-procedures))
;;;
;;; The cross-reference database_ who calls whom.
;;;
(define (program-callee-rev-vars prog)
(define (cons-uniq x y)
(if (memq x y) y (cons x y)))
(cond
((program-objects prog)
=> (lambda (objects)
(let ((n (vector-length objects))
(progv (make-vector (vector-length objects) #f))
(asm (decompile (program-objcode prog) #\to 'assembly)))
(pmatch asm
((load-program ,labels ,len . ,body)
(for-each
(lambda (x)
(pmatch x
((toplevel-ref ,n) (vector-set! progv n #t))
((toplevel-set ,n) (vector-set! progv n #t))))
body)))
(let lp ((i 0) (out '()))
(cond
((= i n) out)
((program? (vector-ref objects i))
(lp (1+ i)
(fold cons-uniq out
(program-callee-rev-vars (vector-ref objects i)))))
((vector-ref progv i)
(let ((obj (vector-ref objects i)))
(if (variable? obj)
(lp (1+ i) (cons-uniq obj out))
;; otherwise it's an unmemoized binding
(pmatch obj
(,sym (guard (symbol? sym))
(let ((v (module-variable (or (program-module prog)
the-root-module)
sym)))
(lp (1+ i) (if v (cons-uniq v out) out))))
((,mod ,sym ,public?)
;; hm, hacky.
(let* ((m (nested-ref-module (resolve-module '() #f)
mod))
(v (and m
(module-variable
(if public?
(module-public-interface m)
m)
sym))))
(lp (1+ i)
(if v (cons-uniq v out) out))))))))
(else (lp (1+ i) out)))))))
(else '())))
(define (procedure-callee-rev-vars proc)
(cond
((program? proc) (program-callee-rev-vars proc))
(else '())))
(define (procedure-callees prog)
"Evaluates to a list of the given program callees."
(let lp ((in (procedure-callee-rev-vars prog)) (out '()))
(cond ((null? in) out)
((variable-bound? (car in))
(lp (cdr in) (cons (variable-ref (car in)) out)))
(else (lp (cdr in) out)))))
;; var -> ((module-name caller ...) ...)
(define *callers-db* #f)
;; module-name -> (callee ...)
(define *module-callees-db* (make-hash-table))
;; (module-name ...)
(define *tainted-modules* '())
(define *xref-ignored-modules* '((value-history)))
(define (on-module-modified m)
(let ((name (module-name m)))
(if (and (not (member name *xref-ignored-modules*))
(not (member name *tainted-modules*))
(pair? name))
(set! *tainted-modules* (cons name *tainted-modules*)))))
(define (add-caller callee caller mod-name)
(let ((all-callers (hashq-ref *callers-db* callee)))
(if (not all-callers)
(hashq-set! *callers-db* callee `((,mod-name ,caller)))
(let ((callers (assoc mod-name all-callers)))
(if callers
(if (not (member caller callers))
(set-cdr! callers (cons caller (cdr callers))))
(hashq-set! *callers-db* callee
(cons `(,mod-name ,caller) all-callers)))))))
(define (forget-callers callee mod-name)
(hashq-set! *callers-db* callee
(assoc-remove! (hashq-ref *callers-db* callee '()) mod-name)))
(define (add-callees callees mod-name)
(hash-set! *module-callees-db* mod-name
(append callees (hash-ref *module-callees-db* mod-name '()))))
(define (untaint-modules)
(define (untaint m)
(for-each (lambda (callee) (forget-callers callee m))
(hash-ref *module-callees-db* m '()))
(ensure-callers-db m))
(ensure-callers-db #f)
(for-each untaint *tainted-modules*)
(set! *tainted-modules* '()))
(define (ensure-callers-db mod-name)
(let ((mod (and mod-name (resolve-module mod-name)))
(visited #f))
(define (visit-variable var mod-name)
(if (variable-bound? var)
(let ((x (variable-ref var)))
(cond
((and visited (hashq-ref visited x)))
((procedure? x)
(if visited (hashq-set! visited x #t))
(let ((callees (filter variable-bound?
(procedure-callee-rev-vars x))))
(for-each (lambda (callee)
(add-caller callee x mod-name))
callees)
(add-callees callees mod-name)))))))
(define (visit-module mod)
(if visited (hashq-set! visited mod #t))
(if (not (memq on-module-modified (module-observers mod)))
(module-observe mod on-module-modified))
(let ((name (module-name mod)))
(module-for-each (lambda (sym var)
(visit-variable var name))
mod)))
(define (visit-submodules mod)
(hash-for-each
(lambda (name sub)
(if (not (and visited (hashq-ref visited sub)))
(begin
(visit-module sub)
(visit-submodules sub))))
(module-submodules mod)))
(cond ((and (not mod-name) (not *callers-db*))
(set! *callers-db* (make-hash-table 1000))
(set! visited (make-hash-table 1000))
(visit-submodules (resolve-module '() #f)))
(mod-name (visit-module mod)))))
(define (procedure-callers var)
"Returns an association list, keyed by module name, of known callers
of the given procedure. The latter can specified directly as a
variable, a symbol (which gets resolved in the current module) or a
pair of the form (module-name . variable-name), "
(let ((v (cond ((variable? var) var)
((symbol? var) (module-variable (current-module) var))
(else
(pmatch var
((,modname . ,sym)
(module-variable (resolve-module modname) sym))
(else
(error "expected a variable, symbol, or (modname . sym)" var)))))))
(untaint-modules)
(hashq-ref *callers-db* v '())))
;;;
;;; The source database_ procedures defined at a given source location.
;;;
;; FIXME_ refactor to share code with the xref database.
;; ((ip file line . col) ...)
(define (procedure-sources proc)
(cond
((program? proc) (program-sources proc))
(else '())))
;; file -> line -> (proc ...)
(define *closure-sources-db* #f)
;; file -> line -> (proc ...)
(define *sources-db* #f)
;; module-name -> proc -> sources
(define *module-sources-db* (make-hash-table))
;; (module-name ...)
(define *tainted-sources* '())
(define (on-source-modified m)
(let ((name (module-name m)))
(if (and (not (member name *xref-ignored-modules*))
(not (member name *tainted-sources*))
(pair? name))
(set! *tainted-sources* (cons name *tainted-sources*)))))
(define (add-source proc file line db)
(let ((file-table (or (hash-ref db file)
(let ((table (make-hash-table)))
(hash-set! db file table)
table))))
(hashv-set! file-table
line
(cons proc (hashv-ref file-table line '())))))
(define (forget-source proc file line db)
(let ((file-table (hash-ref db file)))
(if file-table
(let ((procs (delq proc (hashv-ref file-table line '()))))
(if (pair? procs)
(hashv-set! file-table line procs)
(hashv-remove! file-table line))))))
(define (add-sources proc mod-name db)
(let ((sources (procedure-sources proc)))
(if (pair? sources)
(begin
;; Add proc to *module-sources-db*, for book-keeping.
(hashq-set! (or (hash-ref *module-sources-db* mod-name)
(let ((table (make-hash-table)))
(hash-set! *module-sources-db* mod-name table)
table))
proc
sources)
;; Actually add the source entries.
(for-each (lambda (source)
(pmatch source
((,ip ,file ,line . ,col)
(add-source proc file line db))
(else (error "unexpected source format" source))))
sources)))
;; Add source entries for nested procedures.
(for-each (lambda (obj)
(if (procedure? obj)
(add-sources obj mod-name *closure-sources-db*)))
(or (and (program? proc)
(and=> (program-objects proc) vector->list))
'()))))
(define (forget-sources proc mod-name db)
(let ((mod-table (hash-ref *module-sources-db* mod-name)))
(if mod-table
(begin
;; Forget source entries.
(for-each (lambda (source)
(pmatch source
((,ip ,file ,line . ,col)
(forget-source proc file line db))
(else (error "unexpected source format" source))))
(hashq-ref mod-table proc '()))
;; Forget the proc.
(hashq-remove! mod-table proc)
;; Forget source entries for nested procedures.
(for-each (lambda (obj)
(if (procedure? obj)
(forget-sources obj mod-name *closure-sources-db*)))
(or (and (program? proc)
(and=> (program-objects proc) vector->list))
'()))))))
(define (untaint-sources)
(define (untaint m)
(for-each (lambda (proc) (forget-sources proc m *sources-db*))
(cond
((hash-ref *module-sources-db* m)
=> (lambda (table)
(hash-for-each (lambda (proc sources) proc) table)))
(else '())))
(ensure-sources-db m))
(ensure-sources-db #f)
(for-each untaint *tainted-sources*)
(set! *tainted-sources* '()))
(define (ensure-sources-db mod-name)
(define (visit-module mod)
(if (not (memq on-source-modified (module-observers mod)))
(module-observe mod on-source-modified))
(let ((name (module-name mod)))
(module-for-each
(lambda (sym var)
(if (variable-bound? var)
(let ((x (variable-ref var)))
(if (procedure? x)
(add-sources x name *sources-db*)))))
mod)))
(define visit-submodules
(let ((visited #f))
(lambda (mod)
(if (not visited)
(set! visited (make-hash-table)))
(hash-for-each
(lambda (name sub)
(if (not (hashq-ref visited sub))
(begin
(hashq-set! visited sub #t)
(visit-module sub)
(visit-submodules sub))))
(module-submodules mod)))))
(cond ((and (not mod-name) (not *sources-db*) (not *closure-sources-db*))
(set! *closure-sources-db* (make-hash-table 1000))
(set! *sources-db* (make-hash-table 1000))
(visit-submodules (resolve-module '() #f)))
(mod-name (visit-module (resolve-module mod-name)))))
(define (lines->ranges file-table)
(let ((ranges (make-hash-table)))
(hash-for-each
(lambda (line procs)
(for-each
(lambda (proc)
(cond
((hashq-ref ranges proc)
=> (lambda (pair)
(if (< line (car pair))
(set-car! pair line))
(if (> line (cdr pair))
(set-cdr! pair line))))
(else
(hashq-set! ranges proc (cons line line)))))
procs))
file-table)
(sort! (hash-map->list cons ranges)
(lambda (x y) (< (cadr x) (cadr y))))))
(define* (lookup-source-procedures canon-file line db)
(let ((file-table (hash-ref db canon-file)))
(let lp ((ranges (if file-table (lines->ranges file-table) '()))
(procs '()))
(cond
((null? ranges) (reverse procs))
((<= (cadar ranges) line (cddar ranges))
(lp (cdr ranges) (cons (caar ranges) procs)))
(else
(lp (cdr ranges) procs))))))
(define* (source-closures file line #\key (canonicalization 'relative))
(ensure-sources-db #f)
(let* ((port (with-fluids ((%file-port-name-canonicalization canonicalization))
(false-if-exception (open-input-file file))))
(file (if port (port-filename port) file)))
(lookup-source-procedures file line *closure-sources-db*)))
(define* (source-procedures file line #\key (canonicalization 'relative))
(ensure-sources-db #f)
(let* ((port (with-fluids ((%file-port-name-canonicalization canonicalization))
(false-if-exception (open-input-file file))))
(file (if port (port-filename port) file)))
(lookup-source-procedures file line *sources-db*)))
;;;; (texinfo) -- parsing of texinfo into SXML
;;;;
;;;; Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;;;; Copyright (C) 2004, 2009 Andy Wingo <wingo at pobox dot com>
;;;; Copyright (C) 2001,2002 Oleg Kiselyov <oleg at pobox dot com>
;;;;
;;;; This file is based on SSAX's SSAX.scm.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;; Commentary_
;;
;; @subheading Texinfo processing in scheme
;;
;; This module parses texinfo into SXML. TeX will always be the
;; processor of choice for print output, of course. However, although
;; @code{makeinfo} works well for info, its output in other formats is
;; not very customizable, and the program is not extensible as a whole.
;; This module aims to provide an extensible framework for texinfo
;; processing that integrates texinfo into the constellation of SXML
;; processing tools.
;;
;; @subheading Notes on the SXML vocabulary
;;
;; Consider the following texinfo fragment_
;;
;;@example
;; @@deffn Primitive set-car! pair value
;; This function...
;; @@end deffn
;;@end example
;;
;; Logically, the category (Primitive), name (set-car!), and arguments
;; (pair value) are ``attributes'' of the deffn, with the description as
;; the content. However, texinfo allows for @@-commands within the
;; arguments to an environment, like @code{@@deffn}, which means that
;; texinfo ``attributes'' are PCDATA. XML attributes, on the other hand,
;; are CDATA. For this reason, ``attributes'' of texinfo @@-commands are
;; called ``arguments'', and are grouped under the special element, `%'.
;;
;; Because `%' is not a valid NCName, stexinfo is a superset of SXML. In
;; the interests of interoperability, this module provides a conversion
;; function to replace the `%' with `texinfo-arguments'.
;;
;;; Code_
;; Comparison to xml output of texinfo (which is rather undocumented)_
;; Doesn't conform to texinfo dtd
;; No DTD at all, in fact _-/
;; Actually outputs valid xml, after transforming %
;; Slower (although with caching the SXML that problem can go away)
;; Doesn't parse menus (although menus are shite)
;; Args go in a dedicated element, FBOFW
;; Definitions are handled a lot better
;; Does parse comments
;; Outputs only significant line breaks (a biggie!)
;; Nodes are treated as anchors, rather than content organizers (a biggie)
;; (more book-like, less info-like)
;; TODO
;; Integration_ help, indexing, plain text
(define-module (texinfo)
#\use-module (sxml simple)
#\use-module (sxml transform)
#\use-module (sxml ssax input-parse)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-11)
#\use-module (srfi srfi-13)
#\export (call-with-file-and-dir
texi-command-specs
texi-command-depth
texi-fragment->stexi
texi->stexi
stexi->sxml))
;; Some utilities
(define (parser-error port message . rest)
(apply throw 'parser-error port message rest))
(define (call-with-file-and-dir filename proc)
"Call the one-argument procedure @var{proc} with an input port that
reads from @var{filename}. During the dynamic extent of @var{proc}'s
execution, the current directory will be @code{(dirname
@var{filename})}. This is useful for parsing documents that can include
files by relative path name."
(let ((current-dir (getcwd)))
(dynamic-wind
(lambda () (chdir (dirname filename)))
(lambda ()
(call-with-input-file (basename filename) proc))
(lambda () (chdir current-dir)))))
;;========================================================================
;; Reflection on the XML vocabulary
(define texi-command-specs
;~
"A list of (@var{name} @var{content-model} . @var{args})
@table @var
@item name
The name of an @@-command, as a symbol.
@item content-model
A symbol indicating the syntactic type of the @@-command_
@table @code
@item EMPTY-COMMAND
No content, and no @code{@@end} is coming
@item EOL-ARGS
Unparsed arguments until end of line
@item EOL-TEXT
Parsed arguments until end of line
@item INLINE-ARGS
Unparsed arguments ending with @code{#\\@}}
@item INLINE-TEXT
Parsed arguments ending with @code{#\\@}}
@item INLINE-TEXT-ARGS
Parsed arguments ending with @code{#\\@}}
@item ENVIRON
The tag is an environment tag, expect @code{@@end foo}.
@item TABLE-ENVIRON
Like ENVIRON, but with special parsing rules for its arguments.
@item FRAGMENT
For @code{*fragment*}, the command used for parsing fragments of
texinfo documents.
@end table
@code{INLINE-TEXT} commands will receive their arguments within their
bodies, whereas the @code{-ARGS} commands will receive them in their
attribute list.
@code{EOF-TEXT} receives its arguments in its body.
@code{ENVIRON} commands have both_ parsed arguments until the end of
line, received through their attribute list, and parsed text until the
@code{@@end}, received in their bodies.
@code{EOF-TEXT-ARGS} receives its arguments in its attribute list, as in
@code{ENVIRON}.
In addition, @code{ALIAS} can alias one command to another. The alias
will never be seen in parsed stexinfo.
There are four @@-commands that are treated specially. @code{@@include}
is a low-level token that will not be seen by higher-level parsers, so
it has no content-model. @code{@@para} is the paragraph command, which
is only implicit in the texinfo source. @code{@@item} has special
syntax, as noted above, and @code{@@entry} is how this parser treats
@code{@@item} commands within @code{@@table}, @code{@@ftable}, and
@code{@@vtable}.
Also, indexing commands (@code{@@cindex}, etc.) are treated specially.
Their arguments are parsed, but they are needed before entering the
element so that an anchor can be inserted into the text before the index
entry.
@item args
Named arguments to the command, in the same format as the formals for a
lambda. Only present for @code{INLINE-ARGS}, @code{EOL-ARGS},
@code{INLINE-TEXT-ARGS}, @code{ENVIRON}, @code{TABLE-ENVIRON} commands.
@end table"
'(;; Special commands
(include #f) ;; this is a low-level token
(para PARAGRAPH)
(item ITEM)
(entry ENTRY . heading)
(noindent EMPTY-COMMAND)
(*fragment* FRAGMENT)
;; Inline text commands
(*braces* INLINE-TEXT) ;; FIXME_ make me irrelevant
(bold INLINE-TEXT)
(sample INLINE-TEXT)
(samp INLINE-TEXT)
(code INLINE-TEXT)
(math INLINE-TEXT)
(kbd INLINE-TEXT)
(key INLINE-TEXT)
(var INLINE-TEXT)
(env INLINE-TEXT)
(file INLINE-TEXT)
(command INLINE-TEXT)
(option INLINE-TEXT)
(dfn INLINE-TEXT)
(cite INLINE-TEXT)
(acro INLINE-TEXT)
(email INLINE-TEXT)
(emph INLINE-TEXT)
(strong INLINE-TEXT)
(sample INLINE-TEXT)
(sc INLINE-TEXT)
(titlefont INLINE-TEXT)
(asis INLINE-TEXT)
(b INLINE-TEXT)
(i INLINE-TEXT)
(r INLINE-TEXT)
(sansserif INLINE-TEXT)
(slanted INLINE-TEXT)
(t INLINE-TEXT)
;; Inline args commands
(value INLINE-ARGS . (key))
(ref INLINE-ARGS . (node #\opt name section info-file manual))
(xref INLINE-ARGS . (node #\opt name section info-file manual))
(pxref INLINE-TEXT-ARGS
. (node #\opt name section info-file manual))
(url ALIAS . uref)
(uref INLINE-ARGS . (url #\opt title replacement))
(anchor INLINE-ARGS . (name))
(dots INLINE-ARGS . ())
(result INLINE-ARGS . ())
(bullet INLINE-ARGS . ())
(copyright INLINE-ARGS . ())
(tie INLINE-ARGS . ())
(image INLINE-ARGS . (file #\opt width height alt-text extension))
;; Inline parsed args commands
(acronym INLINE-TEXT-ARGS . (acronym #\opt meaning))
;; EOL args elements
(node EOL-ARGS . (name #\opt next previous up))
(c EOL-ARGS . all)
(comment EOL-ARGS . all)
(setchapternewpage EOL-ARGS . all)
(sp EOL-ARGS . all)
(page EOL-ARGS . ())
(vskip EOL-ARGS . all)
(syncodeindex EOL-ARGS . all)
(contents EOL-ARGS . ())
(shortcontents EOL-ARGS . ())
(summarycontents EOL-ARGS . ())
(insertcopying EOL-ARGS . ())
(dircategory EOL-ARGS . (category))
(top EOL-ARGS . (title))
(printindex EOL-ARGS . (type))
(paragraphindent EOL-ARGS . (indent))
;; EOL text commands
(*ENVIRON-ARGS* EOL-TEXT)
(itemx EOL-TEXT)
(set EOL-TEXT)
(center EOL-TEXT)
(title EOL-TEXT)
(subtitle EOL-TEXT)
(author EOL-TEXT)
(chapter EOL-TEXT)
(section EOL-TEXT)
(appendix EOL-TEXT)
(appendixsec EOL-TEXT)
(unnumbered EOL-TEXT)
(unnumberedsec EOL-TEXT)
(subsection EOL-TEXT)
(subsubsection EOL-TEXT)
(appendixsubsec EOL-TEXT)
(appendixsubsubsec EOL-TEXT)
(unnumberedsubsec EOL-TEXT)
(unnumberedsubsubsec EOL-TEXT)
(chapheading EOL-TEXT)
(majorheading EOL-TEXT)
(heading EOL-TEXT)
(subheading EOL-TEXT)
(subsubheading EOL-TEXT)
(deftpx EOL-TEXT-ARGS . (category name . attributes))
(defcvx EOL-TEXT-ARGS . (category class name))
(defivarx EOL-TEXT-ARGS . (class name))
(deftypeivarx EOL-TEXT-ARGS . (class data-type name))
(defopx EOL-TEXT-ARGS . (category class name . arguments))
(deftypeopx EOL-TEXT-ARGS . (category class data-type name . arguments))
(defmethodx EOL-TEXT-ARGS . (class name . arguments))
(deftypemethodx EOL-TEXT-ARGS . (class data-type name . arguments))
(defoptx EOL-TEXT-ARGS . (name))
(defvrx EOL-TEXT-ARGS . (category name))
(defvarx EOL-TEXT-ARGS . (name))
(deftypevrx EOL-TEXT-ARGS . (category data-type name))
(deftypevarx EOL-TEXT-ARGS . (data-type name))
(deffnx EOL-TEXT-ARGS . (category name . arguments))
(deftypefnx EOL-TEXT-ARGS . (category data-type name . arguments))
(defspecx EOL-TEXT-ARGS . (name . arguments))
(defmacx EOL-TEXT-ARGS . (name . arguments))
(defunx EOL-TEXT-ARGS . (name . arguments))
(deftypefunx EOL-TEXT-ARGS . (data-type name . arguments))
;; Indexing commands
(cindex INDEX . entry)
(findex INDEX . entry)
(vindex INDEX . entry)
(kindex INDEX . entry)
(pindex INDEX . entry)
(tindex INDEX . entry)
;; Environment commands (those that need @end)
(texinfo ENVIRON . title)
(ignore ENVIRON . ())
(ifinfo ENVIRON . ())
(iftex ENVIRON . ())
(ifhtml ENVIRON . ())
(ifxml ENVIRON . ())
(ifplaintext ENVIRON . ())
(ifnotinfo ENVIRON . ())
(ifnottex ENVIRON . ())
(ifnothtml ENVIRON . ())
(ifnotxml ENVIRON . ())
(ifnotplaintext ENVIRON . ())
(titlepage ENVIRON . ())
(menu ENVIRON . ())
(direntry ENVIRON . ())
(copying ENVIRON . ())
(example ENVIRON . ())
(smallexample ENVIRON . ())
(display ENVIRON . ())
(smalldisplay ENVIRON . ())
(verbatim ENVIRON . ())
(format ENVIRON . ())
(smallformat ENVIRON . ())
(lisp ENVIRON . ())
(smalllisp ENVIRON . ())
(cartouche ENVIRON . ())
(quotation ENVIRON . ())
(deftp ENVIRON . (category name . attributes))
(defcv ENVIRON . (category class name))
(defivar ENVIRON . (class name))
(deftypeivar ENVIRON . (class data-type name))
(defop ENVIRON . (category class name . arguments))
(deftypeop ENVIRON . (category class data-type name . arguments))
(defmethod ENVIRON . (class name . arguments))
(deftypemethod ENVIRON . (class data-type name . arguments))
(defopt ENVIRON . (name))
(defvr ENVIRON . (category name))
(defvar ENVIRON . (name))
(deftypevr ENVIRON . (category data-type name))
(deftypevar ENVIRON . (data-type name))
(deffn ENVIRON . (category name . arguments))
(deftypefn ENVIRON . (category data-type name . arguments))
(defspec ENVIRON . (name . arguments))
(defmac ENVIRON . (name . arguments))
(defun ENVIRON . (name . arguments))
(deftypefun ENVIRON . (data-type name . arguments))
(table TABLE-ENVIRON . (formatter))
(itemize TABLE-ENVIRON . (formatter))
(enumerate TABLE-ENVIRON . (start))
(ftable TABLE-ENVIRON . (formatter))
(vtable TABLE-ENVIRON . (formatter))))
(define command-depths
'((chapter . 1) (section . 2) (subsection . 3) (subsubsection . 4)
(top . 0) (unnumbered . 1) (unnumberedsec . 2)
(unnumberedsubsec . 3) (unnumberedsubsubsec . 4)
(appendix . 1) (appendixsec . 2) (appendixsection . 2)
(appendixsubsec . 3) (appendixsubsubsec . 4)))
(define (texi-command-depth command max-depth)
"Given the texinfo command @var{command}, return its nesting level, or
@code{#f} if it nests too deep for @var{max-depth}.
Examples_
@example
(texi-command-depth 'chapter 4) @result{} 1
(texi-command-depth 'top 4) @result{} 0
(texi-command-depth 'subsection 4) @result{} 3
(texi-command-depth 'appendixsubsec 4) @result{} 3
(texi-command-depth 'subsection 2) @result{} #f
@end example"
(let ((depth (and=> (assq command command-depths) cdr)))
(and depth (<= depth max-depth) depth)))
;; The % is for arguments
(define (space-significant? command)
(memq command
'(example smallexample verbatim lisp smalllisp menu %)))
;; Like a DTD for texinfo
(define (command-spec command)
(let ((spec (assq command texi-command-specs)))
(cond
((not spec)
(parser-error #f "Unknown command" command))
((eq? (cadr spec) 'ALIAS)
(command-spec (cddr spec)))
(else
spec))))
(define (inline-content? content)
(case content
((INLINE-TEXT INLINE-ARGS INLINE-TEXT-ARGS) #t)
(else #f)))
;;========================================================================
;; Lower-level parsers and scanners
;;
;; They deal with primitive lexical units (Names, whitespaces, tags) and
;; with pieces of more generic productions. Most of these parsers must
;; be called in appropriate context. For example, complete-start-command
;; must be called only when the @-command start has been detected and
;; its name token has been read.
;; Test if a string is made of only whitespace
;; An empty string is considered made of whitespace as well
(define (string-whitespace? str)
(or (string-null? str)
(string-every char-whitespace? str)))
;; Like read-text-line, but allows EOF.
(define read-eof-breaks '(*eof* #\return #\newline))
(define (read-eof-line port)
(if (eof-object? (peek-char port))
(peek-char port)
(let* ((line (next-token '() read-eof-breaks
"reading a line" port))
(c (read-char port))) ; must be either \n or \r or EOF
(if (and (eq? c #\return) (eq? (peek-char port) #\newline))
(read-char port)) ; skip \n that follows \r
line)))
(define (skip-whitespace port)
(skip-while '(#\space #\tab #\return #\newline) port))
(define (skip-horizontal-whitespace port)
(skip-while '(#\space #\tab) port))
;; command __= Letter+
;; procedure_ read-command PORT
;;
;; Read a command starting from the current position in the PORT and
;; return it as a symbol.
(define (read-command port)
(let ((first-char (peek-char port)))
(or (char-alphabetic? first-char)
(parser-error port "Nonalphabetic @-command char_ '" first-char "'")))
(string->symbol
(next-token-of
(lambda (c)
(cond
((eof-object? c) #f)
((char-alphabetic? c) c)
(else #f)))
port)))
;; A token is a primitive lexical unit. It is a record with two fields,
;; token-head and token-kind.
;;
;; Token types_
;; END The end of a texinfo command. If the command is ended by },
;; token-head will be #f. Otherwise if the command is ended by
;; @end COMMAND, token-head will be COMMAND. As a special case,
;; @bye is the end of a special @texinfo command.
;; START The start of a texinfo command. The token-head will be a
;; symbol of the @-command name.
;; INCLUDE An @include directive. The token-head will be empty -- the
;; caller is responsible for reading the include file name.
;; ITEM @item commands have an irregular syntax. They end at the
;; next @item, or at the end of the environment. For that
;; read-command-token treats them specially.
(define (make-token kind head) (cons kind head))
(define token? pair?)
(define token-kind car)
(define token-head cdr)
;; procedure_ read-command-token PORT
;;
;; This procedure starts parsing of a command token. The current
;; position in the stream must be #\@. This procedure scans enough of
;; the input stream to figure out what kind of a command token it is
;; seeing. The procedure returns a token structure describing the token.
(define (read-command-token port)
(assert-curr-char '(#\@) "start of the command" port)
(let ((peeked (peek-char port)))
(cond
((memq peeked '(#\! #\_ #\. #\? #\@ #\\ #\{ #\}))
;; @-commands that escape characters
(make-token 'STRING (string (read-char port))))
(else
(let ((name (read-command port)))
(case name
((end)
;; got an ending tag
(let ((command (string-trim-both
(read-eof-line port))))
(or (and (not (string-null? command))
(string-every char-alphabetic? command))
(parser-error port "malformed @end" command))
(make-token 'END (string->symbol command))))
((bye)
;; the end of the top
(make-token 'END 'texinfo))
((item)
(make-token 'ITEM 'item))
((include)
(make-token 'INCLUDE #f))
(else
(make-token 'START name))))))))
;; procedure+_ read-verbatim-body PORT STR-HANDLER SEED
;;
;; This procedure must be called after we have read a string
;; "@verbatim\n" that begins a verbatim section. The current position
;; must be the first position of the verbatim body. This function reads
;; _lines_ of the verbatim body and passes them to a STR-HANDLER, a
;; character data consumer.
;;
;; The str-handler is a STR-HANDLER, a procedure STRING1 STRING2 SEED.
;; The first STRING1 argument to STR-HANDLER never contains a newline.
;; The second STRING2 argument often will. On the first invocation of the
;; STR-HANDLER, the seed is the one passed to read-verbatim-body
;; as the third argument. The result of this first invocation will be
;; passed as the seed argument to the second invocation of the line
;; consumer, and so on. The result of the last invocation of the
;; STR-HANDLER is returned by the read-verbatim-body. Note a
;; similarity to the fundamental 'fold' iterator.
;;
;; Within a verbatim section all characters are taken at their face
;; value. It ends with "\n@end verbatim(\r)?\n".
;; Must be called right after the newline after @verbatim.
(define (read-verbatim-body port str-handler seed)
(let loop ((seed seed))
(let ((fragment (next-token '() '(#\newline)
"reading verbatim" port)))
;; We're reading the char after the 'fragment', which is
;; #\newline.
(read-char port)
(if (string=? fragment "@end verbatim")
seed
(loop (str-handler fragment "\n" seed))))))
;; procedure+_ read-arguments PORT
;;
;; This procedure reads and parses a production ArgumentList.
;; ArgumentList __= S* Argument (S* , S* Argument)* S*
;; Argument __= ([^@{},])*
;;
;; Arguments are the things in braces, i.e @ref{my node} has one
;; argument, "my node". Most commands taking braces actually don't have
;; arguments, they process text. For example, in
;; @emph{@strong{emphasized}}, the emph takes text, because the parse
;; continues into the braces.
;;
;; Any whitespace within Argument is replaced with a single space.
;; Whitespace around an Argument is trimmed.
;;
;; The procedure returns a list of arguments. Afterwards the current
;; character will be after the final #\}.
(define (read-arguments port stop-char)
(define (split str)
(read-char port) ;; eat the delimiter
(let ((ret (map (lambda (x) (if (string-null? x) #f x))
(map string-trim-both (string-split str #\,)))))
(if (and (pair? ret) (eq? (car ret) #f) (null? (cdr ret)))
'()
ret)))
(split (next-token '() (list stop-char)
"arguments of @-command" port)))
;; procedure+_ complete-start-command COMMAND PORT
;;
;; This procedure is to complete parsing of an @-command. The procedure
;; must be called after the command token has been read. COMMAND is a
;; TAG-NAME.
;;
;; This procedure returns several values_
;; COMMAND_ a symbol.
;; ARGUMENTS_ command's arguments, as an alist.
;; CONTENT-MODEL_ the content model of the command.
;;
;; On exit, the current position in PORT will depend on the CONTENT-MODEL.
;;
;; Content model Port position
;; ============= =============
;; INLINE-TEXT One character after the #\{.
;; INLINE-TEXT-ARGS One character after the #\{.
;; INLINE-ARGS The first character after the #\}.
;; EOL-TEXT The first non-whitespace character after the command.
;; ENVIRON, TABLE-ENVIRON, EOL-ARGS, EOL-TEXT
;; The first character on the next line.
;; PARAGRAPH, ITEM, EMPTY-COMMAND
;; The first character after the command.
(define (arguments->attlist port args arg-names)
(let loop ((in args) (names arg-names) (opt? #f) (out '()))
(cond
((symbol? names) ;; a rest arg
(reverse (if (null? in) out (acons names in out))))
((and (not (null? names)) (eq? (car names) #\opt))
(loop in (cdr names) #t out))
((null? in)
(if (or (null? names) opt?)
(reverse out)
(parser-error port "@-command expected more arguments_"
args arg-names names)))
((null? names)
(parser-error port "@-command didn't expect more arguments_" in))
((not (car in))
(or (and opt? (loop (cdr in) (cdr names) opt? out))
(parser-error "@-command missing required argument"
(car names))))
(else
(loop (cdr in) (cdr names) opt?
(acons (car names)
(if (list? (car in)) (car in) (list (car in)))
out))))))
(define (parse-table-args command port)
(let* ((line (string-trim-both (read-text-line port)))
(length (string-length line)))
(define (get-formatter)
(or (and (not (zero? length))
(eq? (string-ref line 0) #\@)
(let ((f (string->symbol (substring line 1))))
(or (inline-content? (cadr (command-spec f)))
(parser-error
port "@item formatter must be INLINE" f))
f))
(parser-error port "Invalid @item formatter" line)))
(case command
((enumerate)
(if (zero? length)
'()
`((start
,(if (or (and (eq? length 1)
(char-alphabetic? (string-ref line 0)))
(string-every char-numeric? line))
line
(parser-error
port "Invalid enumerate start" line))))))
((itemize)
`((bullet
,(or (and (eq? length 1) line)
(and (string-null? line) '(bullet))
(list (get-formatter))))))
(else ;; tables of various varieties
`((formatter (,(get-formatter))))))))
(define (complete-start-command command port)
(define (get-arguments type arg-names stop-char)
(arguments->attlist port (read-arguments port stop-char) arg-names))
(let* ((spec (command-spec command))
(command (car spec))
(type (cadr spec))
(arg-names (cddr spec)))
(case type
((INLINE-TEXT)
(assert-curr-char '(#\{) "Inline element lacks {" port)
(values command '() type))
((INLINE-ARGS)
(assert-curr-char '(#\{) "Inline element lacks {" port)
(values command (get-arguments type arg-names #\}) type))
((INLINE-TEXT-ARGS)
(assert-curr-char '(#\{) "Inline element lacks {" port)
(values command '() type))
((EOL-ARGS)
(values command (get-arguments type arg-names #\newline) type))
((ENVIRON ENTRY INDEX)
(skip-horizontal-whitespace port)
(values command (parse-environment-args command port) type))
((TABLE-ENVIRON)
(skip-horizontal-whitespace port)
(values command (parse-table-args command port) type))
((EOL-TEXT)
(skip-horizontal-whitespace port)
(values command '() type))
((EOL-TEXT-ARGS)
(skip-horizontal-whitespace port)
(values command (parse-eol-text-args command port) type))
((PARAGRAPH EMPTY-COMMAND ITEM FRAGMENT)
(values command '() type))
(else ;; INCLUDE shouldn't get here
(parser-error port "can't happen")))))
;;-----------------------------------------------------------------------------
;; Higher-level parsers and scanners
;;
;; They parse productions corresponding entire @-commands.
;; Only reads @settitle, leaves it to the command parser to finish
;; reading the title.
(define (take-until-settitle port)
(or (find-string-from-port? "\n@settitle " port)
(parser-error port "No \\n@settitle found"))
(skip-horizontal-whitespace port)
(and (eq? (peek-char port) #\newline)
(parser-error port "You have a @settitle, but no title")))
;; procedure+_ read-char-data PORT EXPECT-EOF? STR-HANDLER SEED
;;
;; This procedure is to read the CharData of a texinfo document.
;;
;; text __= (CharData | Command)*
;;
;; The procedure reads CharData and stops at @-commands (or
;; environments). It also stops at an open or close brace.
;;
;; port
;; a PORT to read
;; expect-eof?
;; a boolean indicating if EOF is normal, i.e., the character
;; data may be terminated by the EOF. EOF is normal
;; while processing the main document.
;; preserve-ws?
;; a boolean indicating if we are within a whitespace-preserving
;; environment. If #t, suppress paragraph detection.
;; str-handler
;; a STR-HANDLER, see read-verbatim-body
;; seed
;; an argument passed to the first invocation of STR-HANDLER.
;;
;; The procedure returns two results_ SEED and TOKEN. The SEED is the
;; result of the last invocation of STR-HANDLER, or the original seed if
;; STR-HANDLER was never called.
;;
;; TOKEN can be either an eof-object (this can happen only if expect-eof?
;; was #t), or a texinfo token denoting the start or end of a tag.
;; read-char-data port expect-eof? preserve-ws? str-handler seed
(define read-char-data
(let* ((end-chars-eof '(*eof* #\{ #\} #\@ #\newline)))
(define (handle str-handler str1 str2 seed)
(if (and (string-null? str1) (string-null? str2))
seed
(str-handler str1 str2 seed)))
(lambda (port expect-eof? preserve-ws? str-handler seed)
(let ((end-chars ((if expect-eof? identity cdr) end-chars-eof)))
(let loop ((seed seed))
(let* ((fragment (next-token '() end-chars "reading char data" port))
(term-char (peek-char port))) ; one of end-chars
(cond
((eof-object? term-char) ; only if expect-eof?
(values (handle str-handler fragment "" seed) term-char))
((memq term-char '(#\@ #\{ #\}))
(values (handle str-handler fragment "" seed)
(case term-char
((#\@) (read-command-token port))
((#\{) (make-token 'START '*braces*))
((#\}) (read-char port) (make-token 'END #f)))))
((eq? term-char #\newline)
;; Always significant, unless directly before an end token.
(let ((c (peek-next-char port)))
(cond
((eof-object? c)
(or expect-eof?
(parser-error port "EOF while reading char data"))
(values (handle str-handler fragment "" seed) c))
((eq? c #\@)
(let* ((token (read-command-token port))
(end? (eq? (token-kind token) 'END)))
(values
(handle str-handler fragment
(if end? "" (if preserve-ws? "\n" " "))
seed)
token)))
((and (not preserve-ws?) (eq? c #\newline))
;; paragraph-separator __= #\newline #\newline+
(skip-while '(#\newline) port)
(skip-horizontal-whitespace port)
(values (handle str-handler fragment "" seed)
(make-token 'PARA 'para)))
(else
(loop (handle str-handler fragment
(if preserve-ws? "\n" " ") seed)))))))))))))
; procedure+_ assert-token TOKEN KIND NAME
; Make sure that TOKEN is of anticipated KIND and has anticipated NAME
(define (assert-token token kind name)
(or (and (token? token)
(eq? kind (token-kind token))
(equal? name (token-head token)))
(parser-error #f "Expecting @end for " name ", got " token)))
;;========================================================================
;; Highest-level parsers_ Texinfo to SXML
;; These parsers are a set of syntactic forms to instantiate a SSAX
;; parser. The user tells what to do with the parsed character and
;; element data. These latter handlers determine if the parsing follows a
;; SAX or a DOM model.
;; syntax_ make-command-parser fdown fup str-handler
;; Create a parser to parse and process one element, including its
;; character content or children elements. The parser is typically
;; applied to the root element of a document.
;; fdown
;; procedure COMMAND ARGUMENTS EXPECTED-CONTENT SEED
;;
;; This procedure is to generate the seed to be passed to handlers
;; that process the content of the element. This is the function
;; identified as 'fdown' in the denotational semantics of the XML
;; parser given in the title comments to (sxml ssax).
;;
;; fup
;; procedure COMMAND ARGUMENTS PARENT-SEED SEED
;;
;; This procedure is called when parsing of COMMAND is finished.
;; The SEED is the result from the last content parser (or from
;; fdown if the element has the empty content). PARENT-SEED is the
;; same seed as was passed to fdown. The procedure is to generate a
;; seed that will be the result of the element parser. This is the
;; function identified as 'fup' in the denotational semantics of
;; the XML parser given in the title comments to (sxml ssax).
;;
;; str-handler
;; A STR-HANDLER, see read-verbatim-body
;;
;; The generated parser is a
;; procedure COMMAND PORT SEED
;;
;; The procedure must be called *after* the command token has been read.
(define (read-include-file-name port)
(let ((x (string-trim-both (read-eof-line port))))
(if (string-null? x)
(error "no file listed")
x))) ;; fixme_ should expand @value{} references
(define (sxml->node-name sxml)
"Turn some sxml string into a valid node name."
(let loop ((in (string->list (sxml->string sxml))) (out '()))
(if (null? in)
(apply string (reverse out))
(if (memq (car in) '(#\{ #\} #\@ #\,))
(loop (cdr in) out)
(loop (cdr in) (cons (car in) out))))))
(define (index command arguments fdown fup parent-seed)
(case command
((deftp defcv defivar deftypeivar defop deftypeop defmethod
deftypemethod defopt defvr defvar deftypevr deftypevar deffn
deftypefn defspec defmac defun deftypefun)
(let ((args `((name ,(string-append (symbol->string command) "-"
(cadr (assq 'name arguments)))))))
(fup 'anchor args parent-seed
(fdown 'anchor args 'INLINE-ARGS '()))))
((cindex findex vindex kindex pindex tindex)
(let ((args `((name ,(string-append (symbol->string command) "-"
(sxml->node-name
(assq 'entry arguments)))))))
(fup 'anchor args parent-seed
(fdown 'anchor args 'INLINE-ARGS '()))))
(else parent-seed)))
(define (make-command-parser fdown fup str-handler)
(lambda (command port seed)
(let visit ((command command) (port port) (sig-ws? #f) (parent-seed seed))
(let*-values (((command arguments expected-content)
(complete-start-command command port)))
(let* ((parent-seed (index command arguments fdown fup parent-seed))
(seed (fdown command arguments expected-content parent-seed))
(eof-closes? (or (memq command '(texinfo para *fragment*))
(eq? expected-content 'EOL-TEXT)))
(sig-ws? (or sig-ws? (space-significant? command)))
(up (lambda (s) (fup command arguments parent-seed s)))
(new-para (lambda (s) (fdown 'para '() 'PARAGRAPH s)))
(make-end-para (lambda (p) (lambda (s) (fup 'para '() p s)))))
(define (port-for-content)
(if (eq? expected-content 'EOL-TEXT)
(call-with-input-string (read-text-line port) identity)
port))
(cond
((memq expected-content '(EMPTY-COMMAND INLINE-ARGS EOL-ARGS INDEX
EOL-TEXT-ARGS))
;; empty or finished by complete-start-command
(up seed))
((eq? command 'verbatim)
(up (read-verbatim-body port str-handler seed)))
(else
(let loop ((port (port-for-content))
(expect-eof? eof-closes?)
(end-para identity)
(need-break? (and (not sig-ws?)
(memq expected-content
'(ENVIRON TABLE-ENVIRON
ENTRY ITEM FRAGMENT))))
(seed seed))
(cond
((and need-break? (or sig-ws? (skip-whitespace port))
(not (memq (peek-char port) '(#\@ #\})))
(not (eof-object? (peek-char port))))
;; Even if we have an @, it might be inline -- check
;; that later
(let ((seed (end-para seed)))
(loop port expect-eof? (make-end-para seed) #f
(new-para seed))))
(else
(let*-values (((seed token)
(read-char-data
port expect-eof? sig-ws? str-handler seed)))
(cond
((eof-object? token)
(case expect-eof?
((include #f) (end-para seed))
(else (up (end-para seed)))))
(else
(case (token-kind token)
((STRING)
;; this is only @-commands that escape
;; characters_ @}, @@, @{ -- new para if need-break
(let ((seed ((if need-break? end-para identity) seed)))
(loop port expect-eof?
(if need-break? (make-end-para seed) end-para) #f
(str-handler (token-head token) ""
((if need-break? new-para identity)
seed)))))
((END)
;; The end will only have a name if it's for an
;; environment
(cond
((memq command '(item entry))
(let ((spec (command-spec (token-head token))))
(or (eq? (cadr spec) 'TABLE-ENVIRON)
(parser-error
port "@item not ended by @end table/enumerate/itemize"
token))))
((eq? expected-content 'ENVIRON)
(assert-token token 'END command)))
(up (end-para seed)))
((ITEM)
(cond
((memq command '(enumerate itemize))
(up (visit 'item port sig-ws? (end-para seed))))
((eq? expected-content 'TABLE-ENVIRON)
(up (visit 'entry port sig-ws? (end-para seed))))
((memq command '(item entry))
(visit command port sig-ws? (up (end-para seed))))
(else
(parser-error
port "@item must be within a table environment"
command))))
((PARA)
;; examine valid paragraphs?
(loop port expect-eof? end-para (not sig-ws?) seed))
((INCLUDE)
;; Recurse for include files
(let ((seed (call-with-file-and-dir
(read-include-file-name port)
(lambda (port)
(loop port 'include end-para
need-break? seed)))))
(loop port expect-eof? end-para need-break? seed)))
((START) ; Start of an @-command
(let* ((head (token-head token))
(spec (command-spec head))
(head (car spec))
(type (cadr spec))
(inline? (inline-content? type))
(seed ((if (and inline? (not need-break?))
identity end-para) seed))
(end-para (if inline?
(if need-break? (make-end-para seed)
end-para)
identity))
(new-para (if (and inline? need-break?)
new-para identity)))
(loop port expect-eof? end-para (not inline?)
(visit head port sig-ws? (new-para seed)))))
(else
(parser-error port "Unknown token type" token))))))))))))))))
;; procedure_ reverse-collect-str-drop-ws fragments
;;
;; Given the list of fragments (some of which are text strings), reverse
;; the list and concatenate adjacent text strings. We also drop
;; "unsignificant" whitespace, that is, whitespace in front, behind and
;; between elements. The whitespace that is included in character data
;; is not affected.
(define (reverse-collect-str-drop-ws fragments)
(cond
((null? fragments) ; a shortcut
'())
((and (string? (car fragments)) ; another shortcut
(null? (cdr fragments)) ; remove single ws-only string
(string-whitespace? (car fragments)))
'())
(else
(let loop ((fragments fragments) (result '()) (strs '())
(all-whitespace? #t))
(cond
((null? fragments)
(if all-whitespace?
result ; remove leading ws
(cons (apply string-append strs) result)))
((string? (car fragments))
(loop (cdr fragments) result (cons (car fragments) strs)
(and all-whitespace?
(string-whitespace? (car fragments)))))
(else
(loop (cdr fragments)
(cons
(car fragments)
(cond
((null? strs) result)
(all-whitespace?
(if (null? result)
result ; remove trailing whitespace
(cons " " result))); replace interstitial ws with
; one space
(else
(cons (apply string-append strs) result))))
'() #t)))))))
(define (parse-inline-text-args port spec text)
(let lp ((in text) (cur '()) (out '()))
(cond
((null? in)
(if (and (pair? cur)
(string? (car cur))
(string-whitespace? (car cur)))
(lp in (cdr cur) out)
(let ((args (reverse (if (null? cur)
out
(cons (reverse cur) out)))))
(arguments->attlist port args (cddr spec)))))
((pair? (car in))
(lp (cdr in) (cons (car in) cur) out))
((string-index (car in) #\,)
(let* ((parts (string-split (car in) #\,))
(head (string-trim-right (car parts)))
(rev-tail (reverse (cdr parts)))
(last (string-trim (car rev-tail))))
(lp (cdr in)
(if (string-null? last) cur (cons last cur))
(append (cdr rev-tail)
(cons (reverse (if (string-null? head) cur (cons head cur)))
out)))))
(else
(lp (cdr in)
(cons (if (null? cur) (string-trim (car in)) (car in)) cur)
out)))))
(define (make-dom-parser)
(make-command-parser
(lambda (command args content seed) ; fdown
'())
(lambda (command args parent-seed seed) ; fup
(let* ((seed (reverse-collect-str-drop-ws seed))
(spec (command-spec command))
(command (car spec)))
(if (eq? (cadr spec) 'INLINE-TEXT-ARGS)
(cons (list command (cons '% (parse-inline-text-args #f spec seed)))
parent-seed)
(acons command
(if (null? args) seed (acons '% args seed))
parent-seed))))
(lambda (string1 string2 seed) ; str-handler
(if (string-null? string2)
(cons string1 seed)
(cons* string2 string1 seed)))))
(define parse-environment-args
(let ((parser (make-dom-parser)))
;; duplicate arguments->attlist to avoid unnecessary splitting
(lambda (command port)
(let* ((args (cdar (parser '*ENVIRON-ARGS* port '())))
(spec (command-spec command))
(command (car spec))
(arg-names (cddr spec)))
(cond
((not arg-names)
(if (null? args) '()
(parser-error port "@-command doesn't take args" command)))
((eq? arg-names #t)
(list (cons 'arguments args)))
(else
(let loop ((args args) (arg-names arg-names) (out '()))
(cond
((null? arg-names)
(if (null? args) (reverse! out)
(parser-error port "@-command didn't expect more args"
command args)))
((symbol? arg-names)
(reverse! (acons arg-names args out)))
((null? args)
(parser-error port "@-command expects more args"
command arg-names))
((and (string? (car args)) (string-index (car args) #\space))
=> (lambda (i)
(let ((rest (substring/shared (car args) (1+ i))))
(if (zero? i)
(loop (cons rest (cdr args)) arg-names out)
(loop (cons rest (cdr args)) (cdr arg-names)
(cons (list (car arg-names)
(substring (car args) 0 i))
out))))))
(else
(loop (cdr args) (cdr arg-names)
(if (and (pair? (car args)) (eq? (caar args) '*braces*))
(acons (car arg-names) (cdar args) out)
(cons (list (car arg-names) (car args)) out))))))))))))
(define (parse-eol-text-args command port)
;; perhaps parse-environment-args should be named more
;; generically.
(parse-environment-args command port))
;; procedure_ texi-fragment->stexi STRING
;;
;; A DOM parser for a texinfo fragment STRING.
;;
;; The procedure returns an SXML tree headed by the special tag,
;; *fragment*.
(define (texi-fragment->stexi string-or-port)
"Parse the texinfo commands in @var{string-or-port}, and return the
resultant stexi tree. The head of the tree will be the special command,
@code{*fragment*}."
(define (parse port)
(postprocess (car ((make-dom-parser) '*fragment* port '()))))
(if (input-port? string-or-port)
(parse string-or-port)
(call-with-input-string string-or-port parse)))
;; procedure_ texi->stexi PORT
;;
;; This is an instance of a SSAX parser above that returns an SXML
;; representation of the texinfo document ready to be read at PORT.
;;
;; The procedure returns an SXML tree. The port points to the
;; first character after the @bye, or to the end of the file.
(define (texi->stexi port)
"Read a full texinfo document from @var{port} and return the parsed
stexi tree. The parsing will start at the @code{@@settitle} and end at
@code{@@bye} or EOF."
(let ((parser (make-dom-parser)))
(take-until-settitle port)
(postprocess (car (parser 'texinfo port '())))))
(define (car-eq? x y) (and (pair? x) (eq? (car x) y)))
(define (make-contents tree)
(define (lp in out depth)
(cond
((null? in) (values in (cons 'enumerate (reverse! out))))
((and (pair? (cdr in)) (texi-command-depth (caadr in) 4))
=> (lambda (new-depth)
(let ((node-name (and (car-eq? (car in) 'node)
(cadr (assq 'name (cdadar in))))))
(cond
((< new-depth depth)
(values in (cons 'enumerate (reverse! out))))
((> new-depth depth)
(let ((out-cdr (if (null? out) '() (cdr out)))
(out-car (if (null? out) (list 'item) (car out))))
(let*-values (((new-in new-out) (lp in '() (1+ depth))))
(lp new-in
(cons (append out-car (list new-out)) out-cdr)
depth))))
(else ;; same depth
(lp (cddr in)
(cons
`(item (para
,@(if node-name
`((ref (% (node ,node-name))))
(cdadr in))))
out)
depth))))))
(else (lp (cdr in) out depth))))
(let*-values (((_ contents) (lp tree '() 1)))
`((chapheading "Table of Contents") ,contents)))
(define (trim-whitespace str trim-left? trim-right?)
(let* ((left-space? (and (not trim-left?)
(string-prefix? " " str)))
(right-space? (and (not trim-right?)
(string-suffix? " " str)))
(tail (append! (string-tokenize str)
(if right-space? '("") '()))))
(string-join (if left-space? (cons "" tail) tail))))
(define (postprocess tree)
(define (loop in out state first? sig-ws?)
(cond
((null? in)
(values (reverse! out) state))
((string? (car in))
(loop (cdr in)
(cons (if sig-ws? (car in)
(trim-whitespace (car in) first? (null? (cdr in))))
out)
state #f sig-ws?))
((pair? (car in))
(case (caar in)
((set)
(if (null? (cdar in)) (error "@set missing arguments" in))
(if (string? (cadar in))
(let ((i (string-index (cadar in) #\space)))
(if i
(loop (cdr in) out
(acons (substring (cadar in) 0 i)
(cons (substring (cadar in) (1+ i)) (cddar in))
state)
#f sig-ws?)
(loop (cdr in) out (acons (cadar in) (cddar in) state)
#f sig-ws?)))
(error "expected a constant to define for @set" in)))
((value)
(loop (fold-right cons (cdr in)
(or (and=>
(assoc (cadr (assq 'key (cdadar in))) state) cdr)
(error "unknown value" (cdadar in) state)))
out
state #f sig-ws?))
((copying)
(loop (cdr in) out (cons (car in) state) #f sig-ws?))
((insertcopying)
(loop (fold-right cons (cdr in)
(or (cdr (assoc 'copying state))
(error "copying isn't set yet")))
out
state #f sig-ws?))
((contents)
(loop (cdr in) (fold cons out (make-contents tree)) state #f sig-ws?))
(else
(let*-values (((kid-out state)
(loop (car in) '() state #t
(or sig-ws? (space-significant? (caar in))))))
(loop (cdr in) (cons kid-out out) state #f sig-ws?)))))
(else ; a symbol
(loop (cdr in) (cons (car in) out) state #t sig-ws?))))
(call-with-values
(lambda () (loop tree '() '() #t #f))
(lambda (out state) out)))
;; Replace % with texinfo-arguments.
(define (stexi->sxml tree)
"Transform the stexi tree @var{tree} into sxml. This involves
replacing the @code{%} element that keeps the texinfo arguments with an
element for each argument.
FIXME_ right now it just changes % to @code{texinfo-arguments} -- that
doesn't hang with the idea of making a dtd at some point"
(pre-post-order
tree
`((% . ,(lambda (x . t) (cons 'texinfo-arguments t)))
(*text* . ,(lambda (x t) t))
(*default* . ,(lambda (x . t) (cons x t))))))
;;; arch-tag_ 73890afa-597c-4264-ae70-46fe7756ffb5
;;; texinfo.scm ends here
;;;; (texinfo docbook) -- translating sdocbook into stexinfo
;;;;
;;;; Copyright (C) 2009, 2010, 2012 Free Software Foundation, Inc.
;;;; Copyright (C) 2007, 2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;; @c
;; This module exports procedures for transforming a limited subset of
;; the SXML representation of docbook into stexi. It is not complete by
;; any means. The intention is to gather a number of routines and
;; stylesheets so that external modules can parse specific subsets of
;; docbook, for example that set generated by certain tools.
;;
;;; Code_
(define-module (texinfo docbook)
#\use-module (sxml fold)
#\use-module ((srfi srfi-1) #\select (fold))
#\export (*sdocbook->stexi-rules*
*sdocbook-block-commands*
sdocbook-flatten
filter-empty-elements
replace-titles))
(define (identity . args)
args)
(define (identity-deattr tag . body)
`(,tag ,@(if (and (pair? body) (pair? (car body))
(eq? (caar body) '@))
(cdr body)
body)))
(define (detag-one tag body)
body)
(define tag-replacements
'((parameter var)
(replaceable var)
(type code)
(function code)
(literal samp)
(emphasis emph)
(simpara para)
(programlisting example)
(firstterm dfn)
(filename file)
(quote cite)
(application cite)
(symbol code)
(note cartouche)
(envar env)))
(define ignore-list '())
(define (stringify exp)
(with-output-to-string (lambda () (write exp))))
(define *sdocbook->stexi-rules*
;~
"A stylesheet for use with SSAX's @code{pre-post-order}, which defines
a number of generic rules for transforming docbook into texinfo."
`((@ *preorder* . ,identity)
(% *preorder* . ,identity)
(para . ,identity-deattr)
(orderedlist ((listitem
. ,(lambda (tag . body)
`(item ,@body))))
. ,(lambda (tag . body)
`(enumerate ,@body)))
(itemizedlist ((listitem
. ,(lambda (tag . body)
`(item ,@body))))
. ,(lambda (tag . body)
`(itemize ,@body)))
(acronym . ,(lambda (tag . body)
`(acronym (% (acronym . ,body)))))
(term . ,detag-one)
(informalexample . ,detag-one)
(section . ,identity)
(subsection . ,identity)
(subsubsection . ,identity)
(ulink . ,(lambda (tag attrs . body)
(cond
((assq 'url (cdr attrs))
=> (lambda (url)
`(uref (% ,url (title ,@body)))))
(else
(car body)))))
(*text* . ,detag-one)
(*default* . ,(lambda (tag . body)
(let ((subst (assq tag tag-replacements)))
(cond
(subst
(if (and (pair? body) (pair? (car body)) (eq? (caar body) '@))
(begin
(warn "Ignoring" tag "attributes" (car body))
(append (cdr subst) (cdr body)))
(append (cdr subst) body)))
((memq tag ignore-list) #f)
(else
(warn "Don't know how to convert" tag "to stexi")
`(c (% (all ,(stringify (cons tag body))))))))))))
;; (variablelist
;; ((varlistentry
;; . ,(lambda (tag term . body)
;; `(entry (% (heading ,@(cdr term))) ,@body)))
;; (listitem
;; . ,(lambda (tag simpara)
;; simpara)))
;; . ,(lambda (tag attrs . body)
;; `(table (% (formatter (var))) ,@body)))
(define *sdocbook-block-commands*
;~
"The set of sdocbook element tags that should not be nested inside
each other. @xref{texinfo docbook sdocbook-flatten,,sdocbook-flatten},
for more information."
'(para programlisting informalexample indexterm variablelist
orderedlist refsect1 refsect2 refsect3 refsect4 title example
note itemizedlist informaltable))
(define (inline-command? command)
(not (memq command *sdocbook-block-commands*)))
(define (sdocbook-flatten sdocbook)
"\"Flatten\" a fragment of sdocbook so that block elements do not nest
inside each other.
Docbook is a nested format, where e.g. a @code{refsect2} normally
appears inside a @code{refsect1}. Logical divisions in the document are
represented via the tree topology; a @code{refsect2} element
@emph{contains} all of the elements in its section.
On the contrary, texinfo is a flat format, in which sections are marked
off by standalone section headers like @code{@@chapter}, and block
elements do not nest inside each other.
This function takes a nested sdocbook fragment @var{sdocbook} and
flattens all of the sections, such that e.g.
@example
(refsect1 (refsect2 (para \"Hello\")))
@end example
becomes
@example
((refsect1) (refsect2) (para \"Hello\"))
@end example
Oftentimes (always?) sectioning elements have @code{<title>} as their
first element child; users interested in processing the @code{refsect*}
elements into proper sectioning elements like @code{chapter} might be
interested in @code{replace-titles} and @code{filter-empty-elements}.
@xref{texinfo docbook replace-titles,,replace-titles}, and @ref{texinfo
docbook filter-empty-elements,,filter-empty-elements}.
Returns a nodeset, as described in @ref{sxml xpath}. That is to say,
this function returns an untagged list of stexi elements."
(define (fhere str accum block cont)
(values (cons str accum)
block
cont))
(define (fdown node accum block cont)
(let ((command (car node))
(attrs (and (pair? (cdr node)) (pair? (cadr node))
(eq? (caadr node) '%)
(cadr node))))
(values (if attrs (cddr node) (cdr node))
'()
'()
(lambda (accum block)
(values
`(,command ,@(if attrs (list attrs) '())
,@(reverse accum))
block)))))
(define (fup node paccum pblock pcont kaccum kblock kcont)
(call-with-values (lambda () (kcont kaccum kblock))
(lambda (ret block)
(if (inline-command? (car ret))
(values (cons ret paccum) (append kblock pblock) pcont)
(values paccum (append kblock (cons ret pblock)) pcont)))))
(call-with-values
(lambda () (foldts*-values fdown fup fhere sdocbook '() '() #f))
(lambda (accum block cont)
(reverse block))))
(define (filter-empty-elements sdocbook)
"Filters out empty elements in an sdocbook nodeset. Mostly useful
after running @code{sdocbook-flatten}."
(reverse
(fold
(lambda (x rest)
(if (and (pair? x) (null? (cdr x)))
rest
(cons x rest)))
'()
sdocbook)))
(define (replace-titles sdocbook-fragment)
"Iterate over the sdocbook nodeset @var{sdocbook-fragment},
transforming contiguous @code{refsect} and @code{title} elements into
the appropriate texinfo sectioning command. Most useful after having run
@code{sdocbook-flatten}.
For example_
@example
(replace-titles '((refsect1) (title \"Foo\") (para \"Bar.\")))
@result{} '((chapter \"Foo\") (para \"Bar.\"))
@end example
"
(define sections '((refsect1 . chapter)
(refsect2 . section)
(refsect3 . subsection)
(refsect4 . subsubsection)))
(let lp ((in sdocbook-fragment) (out '()))
(cond
((null? in)
(reverse out))
((and (pair? (car in)) (assq (caar in) sections))
;; pull out the title
=> (lambda (pair)
(lp (cddr in) (cons `(,(cdr pair) ,@(cdadr in)) out))))
(else
(lp (cdr in) (cons (car in) out))))))
;;;; (texinfo html) -- translating stexinfo into shtml
;;;;
;;;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;; Copyright (C) 2003,2004,2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;;This module implements transformation from @code{stexi} to HTML. Note
;;that the output of @code{stexi->shtml} is actually SXML with the HTML
;;vocabulary. This means that the output can be further processed, and
;;that it must eventually be serialized by
;;@ref{sxml simple sxml->xml,sxml->xml}.
;;
;;References (i.e., the @code{@@ref} family of commands) are resolved by
;;a @dfn{ref-resolver}.
;;@xref{texinfo html add-ref-resolver!,add-ref-resolver!}, for more
;;information.
;;
;;; Code_
;; TODO_ nice ref resolving API, default CSS stylesheet (esp. to remove
;; margin-top on dd > p)
(define-module (texinfo html)
#\use-module (texinfo)
#\use-module (sxml transform)
#\use-module (ice-9 match)
#\use-module (srfi srfi-13)
#\export (stexi->shtml add-ref-resolver! urlify))
;; The caller is responsible for carring the returned list.
(define (arg-ref key %-args)
(and=> (assq key (cdr %-args)) (lambda (x) (stexi->shtml (cdr x)))))
(define (arg-req key %-args)
(or (arg-ref key %-args)
(error "Missing argument_" key %-args)))
(define (car* x) (and x (car x)))
(define (urlify str)
(string-downcase
(string-map
(lambda (c)
(case c
((#\space #\/ #\_) #\-)
(else c)))
str)))
(define ref-resolvers
(list
(lambda (node-name manual-name) ;; the default
(urlify (string-append (or manual-name "") "#" node-name)))))
(define (add-ref-resolver! proc)
"Add @var{proc} to the head of the list of ref-resolvers. @var{proc}
will be expected to take the name of a node and the name of a manual and
return the URL of the referent, or @code{#f} to pass control to the next
ref-resolver in the list.
The default ref-resolver will return the concatenation of the manual
name, @code{#}, and the node name."
(set! ref-resolvers (cons proc ref-resolvers)))
(define (resolve-ref node manual)
(or (or-map (lambda (x) (x node manual)) ref-resolvers)
(error "Could not resolve reference" node manual)))
(define (ref tag args)
(let* ((node (car (arg-req 'node args)))
(section (or (car* (arg-ref 'section args)) node))
(manual (car* (arg-ref 'manual args)))
(target (resolve-ref node manual)))
`(span ,(and=> (assq tag '((xref "See ") (pxref "see "))) cdr)
(a (@ (href ,target)) ,section))))
(define (uref tag args)
(let ((url (car (arg-req 'url args))))
`(a (@ (href ,url)) ,(or (car* (arg-ref 'title args)) url))))
;; @!*&%( Mozilla gets confused at an empty ("<a .. />") a tag. Put an
;; empty string here to placate the reptile.
(define (node tag args)
`(a (@ (name ,(urlify (car (arg-req 'name args))))) ""))
(define (def tag args . body)
(define (code x) (and x (cons 'code x)))
(define (var x) (and x (cons 'var x)))
(define (b x) (and x (cons 'b x)))
(define (list/spaces . elts)
(let lp ((in elts) (out '()))
(cond ((null? in) (reverse! out))
((null? (car in)) (lp (cdr in) out))
(else (lp (cdr in)
(cons (car in)
(if (null? out) out (cons " " out))))))))
(define (left-td-contents)
(list/spaces (code (arg-ref 'data-type args))
(b (list (code (arg-ref 'class args)))) ;; is this right?
(b (list (code (arg-ref 'name args))))
(if (memq tag '(deftypeop deftypefn deftypefun))
(code (arg-ref 'arguments args))
(var (list (code (arg-ref 'arguments args)))))))
(let* ((category (case tag
((defun) "Function")
((defspec) "Special Form")
((defvar) "Variable")
(else (car (arg-req 'category args))))))
`(div
(table
(@ (cellpadding "0") (cellspacing "0") (width "100%") (class "def"))
(tr (td ,@(left-td-contents))
(td (div (@ (class "right")) "[" ,category "]"))))
(div (@ (class "description")) ,@body))))
(define (enumerate tag . elts)
(define (tonumber start)
(let ((c (string-ref start 0)))
(cond ((number? c) (string->number start))
(else (1+ (- (char->integer c)
(char->integer (if (char-upper-case? c) #\A #\a))))))))
`(ol ,@(if (and (pair? elts) (pair? (car elts)) (eq? (caar elts) '%))
(cons `(@ (start ,@(tonumber (arg-req 'start (car elts)))))
;; (type ,(type (arg-ref 'start (car elts)))))
(cdr elts))
elts)))
(define (itemize tag . elts)
`(ul ,@(match elts
;; Strip `bullet' attribute.
((('% . attrs) . elts) elts)
(elts elts))))
(define (acronym tag . elts)
(match elts
;; FIXME_ Need attribute matcher that doesn't depend on attribute
;; order.
((('% ('acronym text) . _)) `(acronym ,text))))
(define (table tag args . body)
(let ((formatter (caar (arg-req 'formatter args))))
(cons 'dl
(map (lambda (x)
(cond ((and (pair? x) (eq? (car x) 'dt))
(list (car x) (cons formatter (cdr x))))
(else x)))
(apply append body)))))
(define (entry tag args . body)
(let lp ((out `((dt ,@(arg-req 'heading args))))
(body body))
(if (and (pair? body) (pair? (car body)) (eq? (caar body) 'itemx))
(lp (append out `(dt ,@(map stexi->shtml (cdar body))))
(cdr body))
(append out `((dd ,@(map stexi->shtml body)))))))
(define tag-replacements
'((titlepage div (@ (class "titlepage")))
(title h2 (@ (class "title")))
(subtitle h3 (@ (class "subtitle")))
(author h3 (@ (class "author")))
(example pre)
(lisp pre)
(smallexample pre (@ (class "smaller")))
(smalllisp pre (@ (class "smaller")))
(cartouche div (@ (class "cartouche")))
(verbatim pre (@ (class "verbatim")))
(chapter h2)
(section h3)
(subsection h4)
(subsubsection h5)
(appendix h2)
(appendixsec h3)
(appendixsubsec h4)
(appendixsubsubsec h5)
(unnumbered h2)
(unnumberedsec h3)
(unnumberedsubsec h4)
(unnumberedsubsubsec h5)
(majorheading h2)
(chapheading h2)
(heading h3)
(subheading h4)
(subsubheading h5)
(quotation blockquote)
(item li) ;; itemx ?
(para p)
(*fragment* div) ;; should be ok
(asis span)
(bold b)
(sample samp)
(samp samp)
(code code)
(kbd kbd)
(key code (@ (class "key")))
(var var)
(env code (@ (class "env")))
(file code (@ (class "file")))
(command code (@ (class "command")))
(option code (@ (class "option")))
(url code (@ (class "url")))
(dfn dfn)
(cite cite)
(acro acronym)
(email code (@ (class "email")))
(emph em)
(strong strong)
(sc span (@ (class "small-caps")))))
(define ignore-list
'(page setfilename setchapternewpage iftex ifinfo ifplaintext ifxml sp vskip
menu ignore syncodeindex comment c dircategory direntry top shortcontents
cindex printindex))
(define rules
`((% *preorder* . ,(lambda args args)) ;; Keep these around...
(texinfo . ,(lambda (tag args . body)
(pre-post-order
`(html
(@ (xmlns "http_//www.w3.org/1999/xhtml"))
(head (title ,(car (arg-req 'title args))))
(body ,@body))
`((% *preorder* . ,(lambda args #f)) ;; ... filter out.
(*text* . ,(lambda (tag x) x))
(*default* . ,(lambda (tag . body)
(cons tag body)))))))
(copyright . ,(lambda args '(*ENTITY* "copy")))
(result . ,(lambda args '(*ENTITY* "rArr")))
(xref . ,ref) (ref . ,ref) (pxref . ,ref)
(uref . ,uref)
(node . ,node) (anchor . ,node)
(table . ,table)
(enumerate . ,enumerate)
(itemize . ,itemize)
(acronym . ,acronym)
(entry *preorder* . ,entry)
(deftp . ,def) (defcv . ,def) (defivar . ,def) (deftypeivar . ,def)
(defop . ,def) (deftypeop . ,def) (defmethod . ,def)
(deftypemethod . ,def) (defopt . ,def) (defvr . ,def) (defvar . ,def)
(deftypevr . ,def) (deftypevar . ,def) (deffn . ,def)
(deftypefn . ,def) (defmac . ,def) (defspec . ,def) (defun . ,def)
(deftypefun . ,def)
(ifnottex . ,(lambda (tag . body) body))
(*text* . ,(lambda (tag x) x))
(*default* . ,(lambda (tag . body)
(let ((subst (assq tag tag-replacements)))
(cond
(subst (append (cdr subst) body))
((memq tag ignore-list) #f)
(else
(warn "Don't know how to convert" tag "to HTML")
body)))))))
(define (stexi->shtml tree)
"Transform the stexi @var{tree} into shtml, resolving references via
ref-resolvers. See the module commentary for more details."
(pre-post-order tree rules))
;;; arch-tag_ ab05f3fe-9981-4a78-b64c-48efcd9983a6
;;;; (texinfo indexing) -- indexing stexinfo
;;;;
;;;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
;;;; Copyright (C) 2003,2004,2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;;@c texinfo formatting
;;Given a piece of stexi, return an index of a specified variety.
;;
;;Note that currently, @code{stexi-extract-index} doesn't differentiate
;;between different kinds of index entries. That's a bug ;)
;;; Code_
(define-module (texinfo indexing)
#\use-module (sxml simple)
#\use-module (srfi srfi-13)
#\export (stexi-extract-index))
(define defines
'(deftp defcv defivar deftypeivar defop deftypeop defmethod
deftypemethod defopt defvr defvar deftypevr deftypevar deffn
deftypefn defspec defmac defun deftypefun))
(define indices
'(cindex findex vindex kindex pindex tindex))
(define (stexi-extract-index tree manual-name kind)
"Given an stexi tree @var{tree}, index all of the entries of type
@var{kind}. @var{kind} can be one of the predefined texinfo indices
(@code{concept}, @code{variable}, @code{function}, @code{key},
@code{program}, @code{type}) or one of the special symbols @code{auto}
or @code{all}. @code{auto} will scan the stext for a @code{(printindex)}
statement, and @code{all} will generate an index from all entries,
regardless of type.
The returned index is a list of pairs, the @sc{car} of which is the
entry (a string) and the @sc{cdr} of which is a node name (a string)."
(let loop ((in tree) (entries '()))
(cond
((null? in)
entries)
((pair? (car in))
(cond
((and (pair? (cdr in)) (pair? (cadr in))
(eq? (caar in) 'anchor) (memq (caadr in) defines))
(loop (cddr in) (acons (cadr (assq 'name (cdr (cadadr in))))
(cadr (assq 'name (cdadar in)))
entries)))
((and (pair? (cdr in)) (pair? (cadr in))
(eq? (caar in) 'anchor) (memq (caadr in) indices))
(loop (cddr in) (acons (sxml->string (cadr in))
(cadr (assq 'name (cdadar in)))
entries)))
(else
(loop (cdr in) (loop (car in) entries)))))
(else
(loop (cdr in) entries)))))
;;; arch-tag_ 216d29d3-1ed9-433f-9c19-0dc4d6b439b6
;;;; (texinfo plain-text) -- rendering stexinfo as plain text
;;;;
;;;; Copyright (C) 2009, 2010, 2011, 2013 Free Software Foundation, Inc.
;;;; Copyright (C) 2003,2004,2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;;Transformation from stexi to plain-text. Strives to re-create the
;;output from @code{info}; comes pretty damn close.
;;
;;; Code_
(define-module (texinfo plain-text)
#\use-module (texinfo)
#\use-module (texinfo string-utils)
#\use-module (sxml transform)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-13)
#\use-module (ice-9 match)
#\export (stexi->plain-text))
;; The return value is a string.
(define (arg-ref key %-args)
(and=> (and=> (assq key (cdr %-args)) cdr)
stexi->plain-text))
(define (arg-req key %-args)
(or (arg-ref key %-args)
(error "Missing argument_" key %-args)))
(define (make-ticker str)
(lambda () str))
(define (make-enumerator n)
(lambda ()
(let ((last n))
(set! n (1+ n))
(format #f "~A. " last))))
(define *indent* (make-fluid ""))
(define *itemizer* (make-fluid (make-ticker "* ")))
(define-macro (with-indent n . body)
`(with-fluids ((*indent* (string-append (fluid-ref *indent*)
(make-string ,n #\space))))
,@body))
(define (make-indenter n proc)
(lambda args (with-indent n (apply proc args))))
(define (string-indent str)
(string-append (fluid-ref *indent*) str "\n"))
(define-macro (with-itemizer itemizer . body)
`(with-fluids ((*itemizer* ,itemizer))
,@body))
(define (wrap* . strings)
(let ((indent (fluid-ref *indent*)))
(fill-string (string-concatenate strings)
#\line-width 72 #\initial-indent indent
#\subsequent-indent indent)))
(define (wrap . strings)
(string-append (apply wrap* strings) "\n\n"))
(define (wrap-heading . strings)
(string-append (apply wrap* strings) "\n"))
(define (ref tag args)
(let* ((node (arg-req 'node args))
(name (or (arg-ref 'name args) node))
(manual (arg-ref 'manual args)))
(string-concatenate
(cons*
(or (and=> (assq tag '((xref "See ") (pxref "see "))) cadr) "")
name
(if manual `(" in manual " ,manual) '())))))
(define (uref tag args)
(let ((url (arg-req 'url args))
(title (arg-ref 'title args)))
(if title
(string-append title " (" url ")")
(string-append "`" url "'"))))
(define (def tag args . body)
(define (first-line)
(string-join
(filter identity
(map (lambda (x) (arg-ref x args))
'(data-type class name arguments)))
" "))
(let* ((category (case tag
((defun) "Function")
((defspec) "Special Form")
((defvar) "Variable")
(else (arg-req 'category args)))))
(string-append
(wrap-heading (string-append " - " category "_ " (first-line)))
(with-indent 5 (stexi->plain-text body)))))
(define (enumerate tag . elts)
(define (tonumber start)
(let ((c (string-ref start 0)))
(cond ((number? c) (string->number start))
(else (1+ (- (char->integer c)
(char->integer (if (char-upper-case? c) #\A #\a))))))))
(let* ((args? (and (pair? elts) (pair? (car elts))
(eq? (caar elts) '%)))
(start (and args? (arg-ref 'start (car elts)))))
(with-itemizer (make-enumerator (if start (tonumber start) 1))
(with-indent 5
(stexi->plain-text (if start (cdr elts) elts))))))
(define (itemize tag args . elts)
(with-itemizer (make-ticker "* ")
(with-indent 5
(stexi->plain-text elts))))
(define (item tag . elts)
(let* ((ret (stexi->plain-text elts))
(tick ((fluid-ref *itemizer*)))
(tick-pos (- (string-length (fluid-ref *indent*))
(string-length tick))))
(if (and (not (string-null? ret)) (not (negative? tick-pos)))
(string-copy! ret tick-pos tick))
ret))
(define (table tag args . body)
(stexi->plain-text body))
(define (entry tag args . body)
(let ((heading (wrap-heading
(stexi->plain-text (arg-req 'heading args)))))
(string-append heading
(with-indent 5 (stexi->plain-text body)))))
(define (make-underliner char)
(lambda (tag . body)
(let ((str (stexi->plain-text body)))
(string-append
"\n"
(string-indent str)
(string-indent (make-string (string-length str) char))
"\n"))))
(define chapter (make-underliner #\*))
(define section (make-underliner #\=))
(define subsection (make-underliner #\-))
(define subsubsection (make-underliner #\.))
(define (example tag . body)
(let ((ret (stexi->plain-text body)))
(string-append
(string-concatenate
(with-indent 5 (map string-indent (string-split ret #\newline))))
"\n")))
(define (verbatim tag . body)
(let ((ret (stexi->plain-text body)))
(string-append
(string-concatenate
(map string-indent (string-split ret #\newline)))
"\n")))
(define (fragment tag . body)
(string-concatenate (map-in-order stexi->plain-text body)))
(define (para tag . body)
(wrap (stexi->plain-text body)))
(define (make-surrounder str)
(lambda (tag . body)
(string-append str (stexi->plain-text body) str)))
(define (code tag . body)
(string-append "`" (stexi->plain-text body) "'"))
(define (key tag . body)
(string-append "<" (stexi->plain-text body) ">"))
(define (var tag . body)
(string-upcase (stexi->plain-text body)))
(define (passthrough tag . body)
(stexi->plain-text body))
(define (texinfo tag args . body)
(let ((title (chapter 'foo (arg-req 'title args))))
(string-append title (stexi->plain-text body))))
(define ignore-list
'(page setfilename setchapternewpage iftex ifinfo ifplaintext ifxml sp vskip
menu ignore syncodeindex comment c % node anchor))
(define (ignored? tag)
(memq tag ignore-list))
(define tag-handlers
`((title ,chapter)
(chapter ,chapter)
(section ,section)
(subsection ,subsection)
(subsubsection ,subsubsection)
(appendix ,chapter)
(appendixsec ,section)
(appendixsubsec ,subsection)
(appendixsubsubsec ,subsubsection)
(unnumbered ,chapter)
(unnumberedsec ,section)
(unnumberedsubsec ,subsection)
(unnumberedsubsubsec ,subsubsection)
(majorheading ,chapter)
(chapheading ,chapter)
(heading ,section)
(subheading ,subsection)
(subsubheading ,subsubsection)
(strong ,(make-surrounder "*"))
(sample ,code)
(samp ,code)
(code ,code)
(math ,passthrough)
(kbd ,code)
(key ,key)
(var ,var)
(env ,code)
(file ,code)
(command ,code)
(option ,code)
(url ,code)
(dfn ,(make-surrounder "\""))
(cite ,(make-surrounder "\""))
(acro ,passthrough)
(email ,key)
(emph ,(make-surrounder "_"))
(sc ,var)
(copyright ,(lambda args "(C)"))
(result ,(lambda args "==>"))
(dots ,(lambda args "..."))
(xref ,ref)
(ref ,ref)
(pxref ,ref)
(uref ,uref)
(texinfo ,texinfo)
(quotation ,(make-indenter 5 para))
(itemize ,itemize)
(enumerate ,enumerate)
(item ,item)
(table ,table)
(entry ,entry)
(example ,example)
(lisp ,example)
(smallexample ,example)
(smalllisp ,example)
(verbatim ,verbatim)
(*fragment* ,fragment)
(deftp ,def)
(defcv ,def)
(defivar ,def)
(deftypeivar ,def)
(defop ,def)
(deftypeop ,def)
(defmethod ,def)
(deftypemethod ,def)
(defopt ,def)
(defvr ,def)
(defvar ,def)
(deftypevr ,def)
(deftypevar ,def)
(deffn ,def)
(deftypefn ,def)
(defmac ,def)
(defspec ,def)
(defun ,def)
(deftypefun ,def)))
(define (stexi->plain-text tree)
"Transform @var{tree} into plain text. Returns a string."
(match tree
(() "")
((? string?) tree)
(((? symbol? tag) body ...)
(let ((handler (and (not (ignored? tag))
(or (and=> (assq tag tag-handlers) cadr)
para))))
(if handler
(apply handler tree)
"")))
((tree ...)
(string-concatenate (map-in-order stexi->plain-text tree)))
(_ "")))
;;; arch-tag_ f966c3f6-3b46-4790-bbf9-3ad27e4917c2
;;;; (texinfo reflection) -- documenting Scheme as stexinfo
;;;;
;;;; Copyright (C) 2009, 2010, 2011 Free Software Foundation, Inc.
;;;; Copyright (C) 2003,2004,2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;;Routines to generare @code{stexi} documentation for objects and
;;modules.
;;
;;Note that in this context, an @dfn{object} is just a value associated
;;with a location. It has nothing to do with GOOPS.
;;
;;; Code_
(define-module (texinfo reflection)
#\use-module ((srfi srfi-1) #\select (append-map))
#\use-module (oop goops)
#\use-module (texinfo)
#\use-module (texinfo plain-text)
#\use-module (srfi srfi-13)
#\use-module (ice-9 session)
#\use-module (ice-9 documentation)
#\use-module (ice-9 optargs)
#\use-module ((sxml transform) #\select (pre-post-order))
#\export (module-stexi-documentation
script-stexi-documentation
object-stexi-documentation
package-stexi-standard-copying
package-stexi-standard-titlepage
package-stexi-generic-menu
package-stexi-standard-menu
package-stexi-extended-menu
package-stexi-standard-prologue
package-stexi-documentation
package-stexi-documentation-for-include))
;; List for sorting the definitions in a module
(define defs
'(deftp defcv defivar deftypeivar defop deftypeop defmethod
deftypemethod defopt defvr defvar deftypevr deftypevar deffn
deftypefn defmac defspec defun deftypefun))
(define (sort-defs ordering a b)
(define (def x)
;; a and b are lists of the form ((anchor ...) (def* ...)...)
(cadr x))
(define (name x)
(cadr (assq 'name (cdadr (def x)))))
(define (priority x)
(list-index defs (car (def x))))
(define (order x)
(or (list-index ordering (string->symbol (name x)))
;; if the def is not in the list, a big number
1234567890))
(define (compare-in-order proc eq? < . args)
(if (not (eq? (proc a) (proc b)))
(< (proc a) (proc b))
(or (null? args)
(apply compare-in-order args))))
(compare-in-order order = <
priority = <
name string=? string<=?))
(define (list*-join l infix restfix)
(let lp ((in l) (out '()))
(cond ((null? in) (reverse! out))
((symbol? in) (reverse! (cons* in restfix out)))
(else (lp (cdr in) (if (null? out)
(list (car in))
(cons* (car in) infix out)))))))
(define (process-args args)
(map (lambda (x) (if (string? x) x (object->string x)))
(list*-join (or args '())
" " " . ")))
(define (get-proc-args proc)
(cond
((procedure-arguments proc)
=> (lambda (args)
(let ((required-args (assq-ref args 'required))
(optional-args (assq-ref args 'optional))
(keyword-args (assq-ref args 'keyword))
(rest-arg (assq-ref args 'rest)))
(process-args
(append
;; start with the required args...
(map symbol->string required-args)
;; add any optional args if needed...
(map (lambda (a)
(if (list? a)
(format #f "[~a = ~s]" (car a) (cadr a))
(format #f "[~a]" a)))
optional-args)
;; now the keyword args..
(map (lambda (a)
(if (pair? a)
(format #f "[~a]" (car a))
(format #f "[#:~a]" a)))
keyword-args)
;; now the rest arg...
(if rest-arg
(list "." (symbol->string rest-arg))
'()))))))))
(define (macro-arguments name type transformer)
(process-args
(case type
((syntax-rules)
(let ((patterns (procedure-property transformer 'patterns)))
(if (pair? patterns)
(car patterns)
'())))
((identifier-syntax)
'())
((defmacro)
(or (procedure-property transformer 'defmacro-args)
'()))
(else
;; a procedural (syntax-case) macro. how to document these?
'()))))
(define (macro-additional-stexi name type transformer)
(case type
((syntax-rules)
(let ((patterns (procedure-property transformer 'patterns)))
(if (pair? patterns)
(map (lambda (x)
`(defspecx (% (name ,name)
(arguments ,@(process-args x)))))
(cdr patterns))
'())))
(else
'())))
(define many-space? (make-regexp "[[_space_]][[_space_]][[_space_]]"))
(define initial-space? (make-regexp "^[[_space_]]"))
(define (string->stexi str)
(or (and (or (not str) (string-null? str))
'(*fragment*))
(and (or (string-index str #\@)
(and (not (regexp-exec many-space? str))
(not (regexp-exec initial-space? str))))
(false-if-exception
(texi-fragment->stexi str)))
`(*fragment* (verbatim ,str))))
(define method-formals
(and (defined? 'method-formals) method-formals))
(define (method-stexi-arguments method)
(cond
(method-formals
(let lp ((formals (method-formals method))
(specializers (method-specializers method))
(out '()))
(define (arg-texinfo formal specializer)
`(" (" (var ,(symbol->string formal)) " "
(code ,(symbol->string (class-name specializer))) ")"))
(cond
((null? formals) (reverse out))
((pair? formals)
(lp (cdr formals) (cdr specializers)
(append (reverse (arg-texinfo (car formals) (car specializers)))
out)))
(else
(append (reverse out) (arg-texinfo formals specializers)
(list "..."))))))
((method-source method)
(let lp ((bindings (cadr (method-source method))) (out '()))
(define (arg-texinfo arg)
`(" (" (var ,(symbol->string (car arg))) " "
(code ,(symbol->string (cadr arg))) ")"))
(cond
((null? bindings)
(reverse out))
((not (pair? (car bindings)))
(append (reverse out) (arg-texinfo bindings) (list "...")))
(else
(lp (cdr bindings)
(append (reverse (arg-texinfo (car bindings))) out))))))
(else (warn method) '())))
(define* (object-stexi-documentation object #\optional (name "[unknown]")
#\key (force #f))
(if (symbol? name)
(set! name (symbol->string name)))
(let ((stexi ((lambda (x)
(cond ((string? x) (string->stexi x))
((and (pair? x) (eq? (car x) '*fragment*)) x)
(force `(*fragment*))
(else #f)))
(object-documentation
(if (is-a? object <method>)
(method-procedure object)
object)))))
(define (make-def type args)
`(,type (% ,@args) ,@(cdr stexi)))
(cond
((not stexi) #f)
;; stexi is now a list, headed by *fragment*.
((and (pair? (cdr stexi)) (pair? (cadr stexi))
(memq (caadr stexi) defs))
;; it's already a deffoo.
stexi)
((is-a? object <class>)
(make-def 'deftp `((name ,name)
(category "Class"))))
((is-a? object <macro>)
(let* ((proc (macro-transformer object))
(type (and proc (procedure-property proc 'macro-type))))
`(defspec (% (name ,name)
(arguments ,@(macro-arguments name type proc)))
,@(macro-additional-stexi name type proc)
,@(cdr stexi))))
((is-a? object <procedure>)
(make-def 'defun `((name ,name)
(arguments ,@(get-proc-args object)))))
((is-a? object <method>)
(make-def 'deffn `((category "Method")
(name ,name)
(arguments ,@(method-stexi-arguments object)))))
((is-a? object <generic>)
`(*fragment*
,(make-def 'deffn `((name ,name)
(category "Generic")))
,@(map
(lambda (method)
(object-stexi-documentation method name #\force force))
(generic-function-methods object))))
(else
(make-def 'defvar `((name ,name)))))))
(define (module-name->node-name sym-name)
(string-join (map symbol->string sym-name) " "))
;; this copied from (ice-9 session); need to find a better way
(define (module-filename name)
(let* ((name (map symbol->string name))
(reverse-name (reverse name))
(leaf (car reverse-name))
(dir-hint-module-name (reverse (cdr reverse-name)))
(dir-hint (apply string-append
(map (lambda (elt)
(string-append elt "/"))
dir-hint-module-name))))
(%search-load-path (in-vicinity dir-hint leaf))))
(define (read-module name)
(let ((filename (module-filename name)))
(if filename
(let ((port (open-input-file filename)))
(let lp ((out '()) (form (read port)))
(if (eof-object? form)
(reverse out)
(lp (cons form out) (read port)))))
'())))
(define (module-export-list sym-name)
(define (module-form-export-list form)
(and (pair? form)
(eq? (car form) 'define-module)
(equal? (cadr form) sym-name)
(and=> (memq #\export (cddr form)) cadr)))
(let lp ((forms (read-module sym-name)))
(cond ((null? forms) '())
((module-form-export-list (car forms)) => identity)
(else (lp (cdr forms))))))
(define* (module-stexi-documentation sym-name
#\optional %docs-resolver
#\key (docs-resolver
(or %docs-resolver
(lambda (name def) def))))
"Return documentation for the module named @var{sym-name}. The
documentation will be formatted as @code{stexi}
(@pxref{texinfo,texinfo})."
(if %docs-resolver
(issue-deprecation-warning
"module-stexi-documentation_ use #:docs-resolver instead of a positional argument."))
(let* ((commentary (and=> (module-commentary sym-name)
(lambda (x) (string-trim-both x #\newline))))
(stexi (string->stexi commentary))
(node-name (module-name->node-name sym-name))
(name-str (with-output-to-string
(lambda () (display sym-name))))
(module (resolve-interface sym-name))
(export-list (module-export-list sym-name)))
(define (anchor-name sym)
(string-append node-name " " (symbol->string sym)))
(define (make-defs)
(sort!
(module-map
(lambda (sym var)
`((anchor (% (name ,(anchor-name sym))))
,@((lambda (x)
(if (eq? (car x) '*fragment*)
(cdr x)
(list x)))
(if (variable-bound? var)
(docs-resolver
sym
(object-stexi-documentation (variable-ref var) sym
#\force #t))
(begin
(warn "variable unbound!" sym)
`(defvar (% (name ,(symbol->string sym)))
"[unbound!]"))))))
module)
(lambda (a b) (sort-defs export-list a b))))
`(texinfo (% (title ,name-str))
(node (% (name ,node-name)))
(section "Overview")
,@(cdr stexi)
(section "Usage")
,@(apply append! (make-defs)))))
(define (script-stexi-documentation scriptpath)
"Return documentation for given script. The documentation will be
taken from the script's commentary, and will be returned in the
@code{stexi} format (@pxref{texinfo,texinfo})."
(let ((commentary (file-commentary scriptpath)))
`(texinfo (% (title ,(basename scriptpath)))
(node (% (name ,(basename scriptpath))))
,@(if commentary
(cdr
(string->stexi
(string-trim-both commentary #\newline)))
'()))))
(cond
((defined? 'add-value-help-handler!)
(add-value-help-handler!
(lambda (name value)
(stexi->plain-text
(object-stexi-documentation value name #\force #t))))
(add-name-help-handler!
(lambda (name)
(and (list? name)
(and-map symbol? name)
(stexi->plain-text (module-stexi-documentation name)))))))
;; we could be dealing with an old (ice-9 session); fondle it to get
;; module-commentary
(define module-commentary (@@ (ice-9 session) module-commentary))
(define (package-stexi-standard-copying name version updated years
copyright-holder permissions)
"Create a standard texinfo @code{copying} section.
@var{years} is a list of years (as integers) in which the modules
being documented were released. All other arguments are strings."
`(copying
(para "This manual is for " ,name
" (version " ,version ", updated " ,updated ")")
(para "Copyright " ,(string-join (map number->string years) ",")
" " ,copyright-holder)
(quotation
(para ,permissions))))
(define (package-stexi-standard-titlepage name version updated authors)
"Create a standard GNU title page.
@var{authors} is a list of @code{(@var{name} . @var{email})}
pairs. All other arguments are strings.
Here is an example of the usage of this procedure_
@smallexample
(package-stexi-standard-titlepage
\"Foolib\"
\"3.2\"
\"26 September 2006\"
'((\"Alyssa P Hacker\" . \"alyssa@@example.com\"))
'(2004 2005 2006)
\"Free Software Foundation, Inc.\"
\"Standard GPL permissions blurb goes here\")
@end smallexample
"
`(;(setchapternewpage (% (all "odd"))) makes manuals too long
(titlepage
(title ,name)
(subtitle "version " ,version ", updated " ,updated)
,@(map (lambda (pair)
`(author ,(car pair)
" (" (email ,(cdr pair)) ")"))
authors)
(page)
(vskip (% (all "0pt plus 1filll")))
(insertcopying))))
(define (package-stexi-generic-menu name entries)
"Create a menu from a generic alist of entries, the car of which
should be the node name, and the cdr the description. As an exception,
an entry of @code{#f} will produce a separator."
(define (make-entry node description)
`("* " ,node "__"
,(make-string (max (- 21 (string-length node)) 2) #\space)
,@description "\n"))
`((ifnottex
(node (% (name "Top")))
(top (% (title ,name)))
(insertcopying)
(menu
,@(apply
append
(map
(lambda (entry)
(if entry
(make-entry (car entry) (cdr entry))
'("\n")))
entries))))
(iftex
(shortcontents))))
(define (package-stexi-standard-menu name modules module-descriptions
extra-entries)
"Create a standard top node and menu, suitable for processing
by makeinfo."
(package-stexi-generic-menu
name
(let ((module-entries (map cons
(map module-name->node-name modules)
module-descriptions))
(separate-sections (lambda (x) (if (null? x) x (cons #f x)))))
`(,@module-entries
,@(separate-sections extra-entries)))))
(define (package-stexi-extended-menu name module-pairs script-pairs
extra-entries)
"Create an \"extended\" menu, like the standard menu but with a
section for scripts."
(package-stexi-generic-menu
name
(let ((module-entries (map cons
(map module-name->node-name
(map car module-pairs))
(map cdr module-pairs)))
(script-entries (map cons
(map basename (map car script-pairs))
(map cdr script-pairs)))
(separate-sections (lambda (x) (if (null? x) x (cons #f x)))))
`(,@module-entries
,@(separate-sections script-entries)
,@(separate-sections extra-entries)))))
(define (package-stexi-standard-prologue name filename category
description copying titlepage
menu)
"Create a standard prologue, suitable for later serialization
to texinfo and .info creation with makeinfo.
Returns a list of stexinfo forms suitable for passing to
@code{package-stexi-documentation} as the prologue. @xref{texinfo
reflection package-stexi-documentation}, @ref{texinfo reflection
package-stexi-standard-titlepage,package-stexi-standard-titlepage},
@ref{texinfo reflection
package-stexi-standard-copying,package-stexi-standard-copying},
and @ref{texinfo reflection
package-stexi-standard-menu,package-stexi-standard-menu}."
`(,copying
(dircategory (% (category ,category)))
(direntry
"* " ,name "_ (" ,filename "). " ,description ".")
,@titlepage
,@menu))
(define (stexi->chapter stexi)
(pre-post-order
stexi
`((texinfo . ,(lambda (tag attrs node . body)
`(,node
(chapter ,@(assq-ref (cdr attrs) 'title))
,@body)))
(*text* . ,(lambda (tag text) text))
(*default* . ,(lambda args args)))))
(define* (package-stexi-documentation modules name filename
prologue epilogue
#\key
(module-stexi-documentation-args
'())
(scripts '()))
"Create stexi documentation for a @dfn{package}, where a
package is a set of modules that is released together.
@var{modules} is expected to be a list of module names, where a
module name is a list of symbols. The stexi that is returned will
be titled @var{name} and a texinfo filename of @var{filename}.
@var{prologue} and @var{epilogue} are lists of stexi forms that
will be spliced into the output document before and after the
generated modules documentation, respectively.
@xref{texinfo reflection package-stexi-standard-prologue}, to
create a conventional GNU texinfo prologue.
@var{module-stexi-documentation-args} is an optional argument that, if
given, will be added to the argument list when
@code{module-texi-documentation} is called. For example, it might be
useful to define a @code{#:docs-resolver} argument."
(define (verify-modules-list l)
(define (all pred l)
(and (pred (car l))
(or (null? (cdr l)) (all pred (cdr l)))))
(false-if-exception
(all (lambda (x) (all symbol? x)) modules)))
(if (not (verify-modules-list modules))
(error "expected modules to be a list of a list of symbols"
modules))
`(texinfo
(% (title ,name)
(filename ,filename))
,@prologue
,@(append-map (lambda (mod)
(stexi->chapter
(apply module-stexi-documentation
mod module-stexi-documentation-args)))
modules)
,@(append-map (lambda (script)
(stexi->chapter
(script-stexi-documentation script)))
scripts)
,@epilogue))
(define* (package-stexi-documentation-for-include modules module-descriptions
#\key
(module-stexi-documentation-args '()))
"Create stexi documentation for a @dfn{package}, where a
package is a set of modules that is released together.
@var{modules} is expected to be a list of module names, where a
module name is a list of symbols. Returns an stexinfo fragment.
Unlike @code{package-stexi-documentation}, this function simply produces
a menu and the module documentations instead of producing a full texinfo
document. This can be useful if you write part of your manual by hand,
and just use @code{@@include} to pull in the automatically generated
parts.
@var{module-stexi-documentation-args} is an optional argument that, if
given, will be added to the argument list when
@code{module-texi-documentation} is called. For example, it might be
useful to define a @code{#:docs-resolver} argument."
(define (make-entry node description)
`("* " ,node "__"
,(make-string (max (- 21 (string-length node)) 2) #\space)
,@description "\n"))
`(*fragment*
(menu
,@(append-map (lambda (modname desc)
(make-entry (module-name->node-name modname)
desc))
modules
module-descriptions))
,@(append-map (lambda (modname)
(stexi->chapter
(apply module-stexi-documentation
modname
module-stexi-documentation-args)))
modules)))
;;; arch-tag_ bbe2bc03-e16d-4a9e-87b9-55225dc9836c
;;;; (texinfo serialize) -- rendering stexinfo as texinfo
;;;;
;;;; Copyright (C) 2009, 2012, 2013 Free Software Foundation, Inc.
;;;; Copyright (C) 2003,2004,2009 Andy Wingo <wingo at pobox dot com>
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;;
;;Serialization of @code{stexi} to plain texinfo.
;;
;;; Code_
(define-module (texinfo serialize)
#\use-module (texinfo)
#\use-module (texinfo string-utils)
#\use-module (sxml transform)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-13)
#\export (stexi->texi))
(define (list-intersperse src-l elem)
(if (null? src-l) src-l
(let loop ((l (cdr src-l)) (dest (cons (car src-l) '())))
(if (null? l) (reverse dest)
(loop (cdr l) (cons (car l) (cons elem dest)))))))
;; converts improper lists to proper lists.
(define (filter* pred l)
(let lp ((in l) (out '()))
(cond ((null? in)
(reverse! out))
((pair? in)
(lp (cdr in) (if (pred (car in)) (cons (car in) out) out)))
(else
(lp '() (if (pred in) (cons in out) out))))))
;; (list* 'a '(b c) 'd '(e f g)) => '(a b c d e f g)
(define (list* . args)
(let* ((args (reverse args))
(tail (car args)))
(let lp ((in (cdr args)) (out tail))
(cond ((null? in) out)
((pair? (car in)) (lp (cdr in) (append (car in) out)))
((null? (car in)) (lp (cdr in) out))
(else (lp (cdr in) (cons (car in) out)))))))
;; Why? Well, because syntax-case defines `include', and carps about its
;; wrong usage below...
(eval-when (expand load eval)
(define (include exp lp command type formals args accum)
(list* "\n"
(list-intersperse
args
" ")
" " command "@" accum)))
(define (empty-command exp lp command type formals args accum)
(list* " " command "@" accum))
(define (inline-text exp lp command type formals args accum)
(if (not (string=? command "*braces*")) ;; fixme _(
(list* "}"
(append-map (lambda (x) (lp x '())) (reverse (cdr exp)))
"{" command "@" accum)
(list* "@}"
(append-map (lambda (x) (lp x '())) (reverse (cdr exp)))
"@{" accum)))
(define (inline-args exp lp command type formals args accum)
(list* "}"
(if (not args) ""
(list-intersperse
(map
(lambda (x)
(cond ((not x) "")
((pair? x)
(if (pair? (cdr x))
(warn "Strange inline-args!" args))
(car x))
(else (error "Invalid inline-args" args))))
(drop-while not
(map (lambda (x) (assq-ref args x))
(reverse formals))))
","))
"{" command "@" accum))
(define (inline-text-args exp lp command type formals args accum)
(list* "}"
(if (not args) ""
(apply
append
(list-intersperse
(map
(lambda (x) (append-map (lambda (x) (lp x '())) (reverse x)))
(drop-while not
(map (lambda (x) (assq-ref args x))
(reverse formals))))
'(","))))
"{" command "@" accum))
(define (serialize-text-args lp formals args)
(apply
append
(list-intersperse
(map (lambda (arg) (append-map (lambda (x) (lp x '())) arg))
(map
reverse
(drop-while
not (map (lambda (x) (assq-ref args x))
(reverse formals)))))
'(" "))))
(define (eol-text-args exp lp command type formals args accum)
(list* "\n"
(serialize-text-args lp formals args)
" " command "@" accum))
(define (eol-text exp lp command type formals args accum)
(list* "\n"
(append-map (lambda (x) (lp x '()))
(reverse (if args (cddr exp) (cdr exp))))
" " command "@" accum))
(define (eol-args exp lp command type formals args accum)
(list* "\n"
(list-intersperse
(apply append
(drop-while not
(map (lambda (x) (assq-ref args x))
(reverse formals))))
", ")
" " command "@" accum))
(define (environ exp lp command type formals args accum)
(case (car exp)
((texinfo)
(list* "@bye\n"
(append-map (lambda (x) (lp x '())) (reverse (cddr exp)))
"\n@c %**end of header\n\n"
(reverse (assq-ref args 'title)) "@settitle "
(or (and=> (assq-ref args 'filename)
(lambda (filename)
(cons "\n" (reverse (cons "@setfilename " filename)))))
"")
"\\input texinfo @c -*-texinfo-*-\n@c %**start of header\n"
accum))
(else
(list* "\n\n" command "@end "
(let ((body (append-map (lambda (x) (lp x '()))
(reverse (if args (cddr exp) (cdr exp))))))
(if (or (null? body)
(eqv? (string-ref (car body)
(1- (string-length (car body))))
#\newline))
body
(cons "\n" body)))
"\n"
(serialize-text-args lp formals args)
" " command "@" accum))))
(define (table-environ exp lp command type formals args accum)
(list* "\n\n" command "@end "
(append-map (lambda (x) (lp x '()))
(reverse (if args (cddr exp) (cdr exp))))
"\n"
(let* ((arg (if args (cadar args) ""))) ;; zero or one args
(if (pair? arg)
(list (symbol->string (car arg)) "@")
arg))
" " command "@" accum))
(define (wrap strings)
(fill-string (string-concatenate strings)
#\line-width 72
#\break-long-words? #f))
(define (paragraph exp lp command type formals args accum)
(list* "\n\n"
(wrap
(reverse
(append-map (lambda (x) (lp x '())) (reverse (cdr exp)))))
accum))
(define (item exp lp command type formals args accum)
(list* (append-map (lambda (x) (lp x '())) (reverse (cdr exp)))
"@item\n"
accum))
(define (entry exp lp command type formals args accum)
(list* (append-map (lambda (x) (lp x '())) (reverse (cddr exp)))
"\n"
(append-map (lambda (x) (lp x '())) (reverse (cdar args)))
"@item "
accum))
(define (fragment exp lp command type formals args accum)
(list* "\n@c %end of fragment\n"
(append-map (lambda (x) (lp x '())) (reverse (cdr exp)))
"\n@c %start of fragment\n\n"
accum))
(define serializers
`((EMPTY-COMMAND . ,empty-command)
(INLINE-TEXT . ,inline-text)
(INLINE-ARGS . ,inline-args)
(INLINE-TEXT-ARGS . ,inline-text-args)
(EOL-TEXT . ,eol-text)
(EOL-TEXT-ARGS . ,eol-text-args)
(INDEX . ,eol-text-args)
(EOL-ARGS . ,eol-args)
(ENVIRON . ,environ)
(TABLE-ENVIRON . ,table-environ)
(ENTRY . ,entry)
(ITEM . ,item)
(PARAGRAPH . ,paragraph)
(FRAGMENT . ,fragment)
(#f . ,include))) ; support writing include statements
(define (serialize exp lp command type formals args accum)
((or (assq-ref serializers type)
(error "Unknown command type" exp type))
exp lp command type formals args accum))
(define escaped-chars '(#\} #\{ #\@))
(define (escape str)
"Escapes any illegal texinfo characters (currently @{, @}, and @@)."
(let loop ((in (string->list str)) (out '()))
(if (null? in)
(apply string (reverse out))
(if (memq (car in) escaped-chars)
(loop (cdr in) (cons* (car in) #\@ out))
(loop (cdr in) (cons (car in) out))))))
(define (stexi->texi tree)
"Serialize the stexi @var{tree} into plain texinfo."
(string-concatenate-reverse
(let lp ((in tree) (out '()))
(cond
((or (not in) (null? in)) out)
((string? in) (cons (escape in) out))
((pair? in)
(let ((command-spec (assq (car in) texi-command-specs)))
(if (not command-spec)
(begin
(warn "Unknown stexi command, not rendering" in)
out)
(serialize in
lp
(symbol->string (car in))
(cadr command-spec)
(filter* symbol? (cddr command-spec))
(cond
((and (pair? (cdr in)) (pair? (cadr in))
(eq? (caadr in) '%))
(cdadr in))
((not (cadr command-spec))
;; include
(cdr in))
(else
#f))
out))))
(else
(error "Invalid stexi" in))))))
;;; arch-tag_ d3fa16ea-0bf7-4ec5-ab9f-3f08490f77f5
;;;; (texinfo string-utils) -- text filling and wrapping
;;;;
;;;; Copyright (C) 2009, 2013 Free Software Foundation, Inc.
;;;; Copyright (C) 2003 Richard Todd
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;; Module @samp{(texinfo string-utils)} provides various string-related
;; functions useful to Guile's texinfo support.
;;; Code_
(define-module (texinfo string-utils)
#\use-module (srfi srfi-13)
#\use-module (srfi srfi-14)
#\export (escape-special-chars
transform-string
expand-tabs
center-string
left-justify-string
right-justify-string
collapse-repeated-chars
make-text-wrapper
fill-string
string->wrapped-lines))
(define* (transform-string str match? replace #\optional (start #f) (end #f))
"Uses @var{match?} against each character in @var{str}, and performs a
replacement on each character for which matches are found.
@var{match?} may either be a function, a character, a string, or
@code{#t}. If @var{match?} is a function, then it takes a single
character as input, and should return @samp{#t} for matches.
@var{match?} is a character, it is compared to each string character
using @code{char=?}. If @var{match?} is a string, then any character
in that string will be considered a match. @code{#t} will cause
every character to be a match.
If @var{replace} is a function, it is called with the matched
character as an argument, and the returned value is sent to the output
string via @samp{display}. If @var{replace} is anything else, it is
sent through the output string via @samp{display}.
Note that te replacement for the matched characters does not need to
be a single character. That is what differentiates this function from
@samp{string-map}, and what makes it useful for applications such as
converting @samp{#\\&} to @samp{\"&\"} in web page text. Some other
functions in this module are just wrappers around common uses of
@samp{transform-string}. Transformations not possible with this
function should probably be done with regular expressions.
If @var{start} and @var{end} are given, they control which portion
of the string undergoes transformation. The entire input string
is still output, though. So, if @var{start} is @samp{5}, then the
first five characters of @var{str} will still appear in the returned
string.
@lisp
; these two are equivalent...
(transform-string str #\\space #\\-) ; change all spaces to -'s
(transform-string str (lambda (c) (char=? #\\space c)) #\\-)
@end lisp"
;; I had implemented this with string-fold, but it was
;; slower...
(let* ((os (open-output-string))
(matcher (cond ((char? match?)
(lambda (c) (char=? match? c)))
((procedure? match?)
match?)
((string? match?)
(lambda (c) (string-index match? c)))
((boolean? match?)
(lambda (c) match?))
(else (throw 'bad-type "expected #t, char, string, or procedure"))))
(replacer (if (procedure? replace)
(lambda (c) (display (replace c) os))
(lambda (c) (display replace os)))))
;; put the first part in, un-transformed if they asked for it...
(if (and start (<= start (string-length str)))
(display (substring str 0 start) os))
;; process the portion they want processed....
(string-for-each
(lambda (c)
(if (matcher c)
;; we have a match! replace the char as directed...
(replacer c)
;; not a match, just insert the character itself...
(write-char c os)))
str
(or start 0)
(or end (string-length str)))
;; if there was any at the end, tack it on...
(if (and end (< end (string-length str)))
(display (substring str end) os))
(get-output-string os)))
(define* (expand-tabs str #\optional (tab-size 8))
"Returns a copy of @var{str} with all tabs expanded to spaces. @var{tab-size} defaults to 8.
Assuming tab size of 8, this is equivalent to_ @lisp
(transform-string str #\\tab \" \")
@end lisp"
(transform-string str
#\tab
(make-string tab-size #\space)))
(define (escape-special-chars str special-chars escape-char)
"Returns a copy of @var{str} with all given special characters preceded
by the given @var{escape-char}.
@var{special-chars} can either be a single character, or a string consisting
of all the special characters.
@lisp
;; make a string regexp-safe...
(escape-special-chars \"***(Example String)***\"
\"[]()/*.\"
#\\\\)
=> \"\\\\*\\\\*\\\\*\\\\(Example String\\\\)\\\\*\\\\*\\\\*\"
;; also can escape a singe char...
(escape-special-chars \"richardt@@vzavenue.net\"
#\\@@
#\\@@)
=> \"richardt@@@@vzavenue.net\"
@end lisp"
(transform-string str
(if (char? special-chars)
;; if they gave us a char, use char=?
(lambda (c) (char=? c special-chars))
;; if they gave us a string, see if our character is in it
(lambda (c) (string-index special-chars c)))
;; replace matches with the character preceded by the escape character
(lambda (c) (string escape-char c))))
(define* (center-string str #\optional (width 80) (chr #\space) (rchr #f))
"Returns a copy of @var{str} centered in a field of @var{width}
characters. Any needed padding is done by character @var{chr}, which
defaults to @samp{#\\space}. If @var{rchr} is provided, then the
padding to the right will use it instead. See the examples below.
left and @var{rchr} on the right. The default @var{width} is 80. The
default @var{chr} and @var{rchr} is @samp{#\\space}. The string is
never truncated.
@lisp
(center-string \"Richard Todd\" 24)
=> \" Richard Todd \"
(center-string \" Richard Todd \" 24 #\\=)
=> \"===== Richard Todd =====\"
(center-string \" Richard Todd \" 24 #\\< #\\>)
=> \"<<<<< Richard Todd >>>>>\"
@end lisp"
(let* ((len (string-length str))
(lpad (make-string (max (quotient (- width len) 2) 0) chr))
;; right-char == char unless it has been provided by the user
(right-chr (or rchr chr))
(rpad (if (char=? right-chr chr)
lpad
(make-string (max (quotient (- width len) 2) 0) right-chr))))
(if (>= len width)
str
(string-append lpad str rpad (if (odd? (- width len)) (string right-chr) "")))))
(define* (left-justify-string str #\optional (width 80) (chr #\space))
"@code{left-justify-string str [width chr]}.
Returns a copy of @var{str} padded with @var{chr} such that it is left
justified in a field of @var{width} characters. The default
@var{width} is 80. Unlike @samp{string-pad} from srfi-13, the string
is never truncated."
(let* ((len (string-length str))
(pad (make-string (max (- width len) 0) chr)))
(if (>= len width)
str
(string-append str pad))))
(define* (right-justify-string str #\optional (width 80) (chr #\space))
"Returns a copy of @var{str} padded with @var{chr} such that it is
right justified in a field of @var{width} characters. The default
@var{width} is 80. The default @var{chr} is @samp{#\\space}. Unlike
@samp{string-pad} from srfi-13, the string is never truncated."
(let* ((len (string-length str))
(pad (make-string (max (- width len) 0) chr)))
(if (>= len width)
str
(string-append pad str))))
(define* (collapse-repeated-chars str #\optional (chr #\space) (num 1))
"Returns a copy of @var{str} with all repeated instances of
@var{chr} collapsed down to at most @var{num} instances.
The default value for @var{chr} is @samp{#\\space}, and
the default value for @var{num} is 1.
@lisp
(collapse-repeated-chars \"H e l l o\")
=> \"H e l l o\"
(collapse-repeated-chars \"H--e--l--l--o\" #\\-)
=> \"H-e-l-l-o\"
(collapse-repeated-chars \"H-e--l---l----o\" #\\- 2)
=> \"H-e--l--l--o\"
@end lisp"
;; define repeat-locator as a stateful match? function which remembers
;; the last character it had seen.
(let ((repeat-locator
;; initialize prev-chr to something other than what we're seeking...
(let ((prev-chr (if (char=? chr #\space) #\A #\space))
(match-count 0))
(lambda (c)
(if (and (char=? c prev-chr)
(char=? prev-chr chr))
;; found enough duplicates if the match-count is high enough
(begin
(set! match-count (+ 1 match-count))
(>= match-count num))
;; did not find a duplicate
(begin (set! match-count 0)
(set! prev-chr c)
#f))))))
;; transform the string with our stateful matcher...
;; deleting matches...
(transform-string str repeat-locator "")))
;; split a text string into segments that have the form...
;; <ws non-ws> <ws non-ws> etc..
(define (split-by-single-words str)
(let ((non-wschars (char-set-complement char-set_whitespace)))
(let loop ((ans '())
(index 0))
(let ((next-non-ws (string-index str non-wschars index)))
(if next-non-ws
;; found non-ws...look for ws following...
(let ((next-ws (string-index str char-set_whitespace next-non-ws)))
(if next-ws
;; found the ws following...
(loop (cons (substring str index next-ws) ans)
next-ws)
;; did not find ws...must be the end...
(reverse (cons (substring str index) ans))))
;; did not find non-ws... only ws at end of the string...
(reverse ans))))))
(define (end-of-sentence? str)
"Return #t when STR likely denotes the end of sentence."
(let ((len (string-length str)))
(and (> len 1)
(eqv? #\. (string-ref str (- len 1)))
(not (eqv? #\. (string-ref str (- len 2)))))))
(define* (make-text-wrapper #\key
(line-width 80)
(expand-tabs? #t)
(tab-width 8)
(collapse-whitespace? #t)
(subsequent-indent "")
(initial-indent "")
(break-long-words? #t))
"Returns a procedure that will split a string into lines according to the
given parameters.
@table @code
@item #:line-width
This is the target length used when deciding where to wrap lines.
Default is 80.
@item #:expand-tabs?
Boolean describing whether tabs in the input should be expanded. Default
is #t.
@item #:tab-width
If tabs are expanded, this will be the number of spaces to which they
expand. Default is 8.
@item #:collapse-whitespace?
Boolean describing whether the whitespace inside the existing text
should be removed or not. Default is #t.
If text is already well-formatted, and is just being wrapped to fit in a
different width, then set this to @samp{#f}. This way, many common text
conventions (such as two spaces between sentences) can be preserved if
in the original text. If the input text spacing cannot be trusted, then
leave this setting at the default, and all repeated whitespace will be
collapsed down to a single space.
@item #:initial-indent
Defines a string that will be put in front of the first line of wrapped
text. Default is the empty string, ``''.
@item #:subsequent-indent
Defines a string that will be put in front of all lines of wrapped
text, except the first one. Default is the empty string, ``''.
@item #:break-long-words?
If a single word is too big to fit on a line, this setting tells the
wrapper what to do. Defaults to #t, which will break up long words.
When set to #f, the line will be allowed, even though it is longer
than the defined @code{#:line-width}.
@end table
The return value is a procedure of one argument, the input string, which
returns a list of strings, where each element of the list is one line."
(lambda (str)
;; replace newlines with spaces
(set! str (transform-string str (lambda (c) (char=? c #\nl)) #\space))
;; expand tabs if they wanted us to...
(if expand-tabs?
(set! str (expand-tabs str tab-width)))
;; collapse whitespace if they wanted us to...
(if collapse-whitespace?
(set! str (collapse-repeated-chars str)))
;; drop any whitespace from the front...
(set! str (string-trim str))
;; now start breaking the text into lines...
(let loop ((ans '())
(words (split-by-single-words str))
(line initial-indent)
(count 0))
(if (null? words)
;; out of words? ...done!
(reverse (if (> count 0)
(cons line ans)
ans))
;; not out of words...keep going...
(let ((length-left (- line-width
(string-length line)))
(next-word (if (= count 0)
(string-trim (car words))
(car words))))
(cond
;; does the next entry fit?
((<= (string-length next-word)
length-left)
(loop ans
(cdr words)
(if (and collapse-whitespace?
(end-of-sentence? line))
;; Add an extra space after the period.
(string-append line " " next-word)
(string-append line next-word))
(+ count 1)))
;; ok, it didn't fit...is there already at least one word on the line?
((> count 0)
;; try to use it for the next line, then...
(loop (cons line ans)
words
subsequent-indent
0))
;; ok, it didn't fit...and it's the first word.
;; were we told to break up long words?
(break-long-words?
;; break the like at the limit, since the user wants us to...
(loop (cons (string-append line (substring next-word 0 length-left))
ans)
(cons (substring next-word length-left)
(cdr words))
subsequent-indent
0))
;; well, then is it the first word and we *shouldn't* break long words, then...
(else
(loop (cons (string-append line next-word)
ans)
(cdr words)
subsequent-indent
0))))))))
(define (string->wrapped-lines str . kwargs)
"@code{string->wrapped-lines str keywds ...}. Wraps the text given in
string @var{str} according to the parameters provided in @var{keywds},
or the default setting if they are not given. Returns a list of strings
representing the formatted lines. Valid keyword arguments are discussed
in @code{make-text-wrapper}."
((apply make-text-wrapper kwargs) str))
(define (fill-string str . kwargs)
"Wraps the text given in string @var{str} according to the parameters
provided in @var{kwargs}, or the default setting if they are not
given. Returns a single string with the wrapped text. Valid keyword
arguments are discussed in @code{make-text-wrapper}."
(string-join (apply string->wrapped-lines str kwargs)
"\n"
'infix))
;;; Web client
;; Copyright (C) 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary_
;;;
;;; (web client) is a simple HTTP URL fetcher for Guile.
;;;
;;; In its current incarnation, (web client) is synchronous. If you
;;; want to fetch a number of URLs at once, probably the best thing to
;;; do is to write an event-driven URL fetcher, similar in structure to
;;; the web server.
;;;
;;; Another option, good but not as performant, would be to use threads,
;;; possibly via a thread pool.
;;;
;;; Code_
(define-module (web client)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\use-module (ice-9 iconv)
#\use-module (ice-9 rdelim)
#\use-module (web request)
#\use-module (web response)
#\use-module (web uri)
#\use-module (web http)
#\use-module (srfi srfi-1)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\export (current-http-proxy
open-socket-for-uri
http-get
http-get*
http-head
http-post
http-put
http-delete
http-trace
http-options))
(define current-http-proxy
(make-parameter (let ((proxy (getenv "http_proxy")))
(and (not (equal? proxy ""))
proxy))))
(define (ensure-uri uri-or-string)
(cond
((string? uri-or-string) (string->uri uri-or-string))
((uri? uri-or-string) uri-or-string)
(else (error "Invalid URI" uri-or-string))))
(define (open-socket-for-uri uri-or-string)
"Return an open input/output port for a connection to URI."
(define http-proxy (current-http-proxy))
(define uri (ensure-uri (or http-proxy uri-or-string)))
(define addresses
(let ((port (uri-port uri)))
(delete-duplicates
(getaddrinfo (uri-host uri)
(cond (port => number->string)
(else (symbol->string (uri-scheme uri))))
(if port
AI_NUMERICSERV
0))
(lambda (ai1 ai2)
(equal? (addrinfo_addr ai1) (addrinfo_addr ai2))))))
(let loop ((addresses addresses))
(let* ((ai (car addresses))
(s (with-fluids ((%default-port-encoding #f))
;; Restrict ourselves to TCP.
(socket (addrinfo_fam ai) SOCK_STREAM IPPROTO_IP))))
(catch 'system-error
(lambda ()
(connect s (addrinfo_addr ai))
;; Buffer input and output on this port.
(setvbuf s _IOFBF)
;; If we're using a proxy, make a note of that.
(when http-proxy (set-http-proxy-port?! s #t))
s)
(lambda args
;; Connection failed, so try one of the other addresses.
(close s)
(if (null? (cdr addresses))
(apply throw args)
(loop (cdr addresses))))))))
(define (extend-request r k v . additional)
(let ((r (set-field r (request-headers)
(assoc-set! (copy-tree (request-headers r))
k v))))
(if (null? additional)
r
(apply extend-request r additional))))
;; -> request body
(define (sanitize-request request body)
"\"Sanitize\" the given request and body, ensuring that they are
complete and coherent. This method is most useful for methods that send
data to the server, like POST, but can be used for any method. Return
two values_ a request and a bytevector, possibly the same ones that were
passed as arguments.
If BODY is a string, encodes the string to a bytevector, in an encoding
appropriate for REQUEST. Adds a ‘content-length’ and ‘content-type’
header, as necessary.
If BODY is a procedure, it is called with a port as an argument, and the
output collected as a bytevector. In the future we might try to instead
use a compressing, chunk-encoded port, and call this procedure later.
Authors are advised not to rely on the procedure being called at any
particular time.
Note that we rely on the request itself already having been validated,
as is the case by default with a request returned by `build-request'."
(cond
((not body)
(let ((length (request-content-length request)))
(if length
;; FIXME make this stricter_ content-length header should be
;; prohibited if there's no body, even if the content-length
;; is 0.
(unless (zero? length)
(error "content-length, but no body"))
(when (assq 'transfer-encoding (request-headers request))
(error "transfer-encoding not allowed with no body")))
(values request #vu8())))
((string? body)
(let* ((type (request-content-type request '(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-request
(if declared-charset
request
(extend-request request 'content-type
`(,@type (charset . ,charset))))
(string->bytevector body charset))))
((procedure? body)
(let* ((type (request-content-type request
'(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-request
(if declared-charset
request
(extend-request request 'content-type
`(,@type (charset . ,charset))))
(call-with-encoded-output-string charset body))))
((not (bytevector? body))
(error "unexpected body type"))
(else
(values (let ((rlen (request-content-length request))
(blen (bytevector-length body)))
(cond
(rlen (if (= rlen blen)
request
(error "bad content-length" rlen blen)))
(else (extend-request request 'content-length blen))))
body))))
(define (decode-response-body response body)
;; `body' is either #f or a bytevector.
(cond
((not body) body)
((bytevector? body)
(let ((rlen (response-content-length response))
(blen (bytevector-length body)))
(cond
((and rlen (not (= rlen blen)))
(error "bad content-length" rlen blen))
((response-content-type response)
=> (lambda (type)
(cond
((text-content-type? (car type))
;; RFC 2616 3.7.1_ "When no explicit charset parameter is
;; provided by the sender, media subtypes of the "text"
;; type are defined to have a default charset value of
;; "ISO-8859-1" when received via HTTP."
(bytevector->string body (or (assq-ref (cdr type) 'charset)
"iso-8859-1")))
(else body))))
(else body))))
(else
(error "unexpected body type" body))))
;; We could expose this to user code if there is demand.
(define* (request uri #\key
(body #f)
(port (open-socket-for-uri uri))
(method 'GET)
(version '(1 . 1))
(keep-alive? #f)
(headers '())
(decode-body? #t)
(streaming? #f)
(request
(build-request
(ensure-uri uri)
#\method method
#\version version
#\headers (if keep-alive?
headers
(cons '(connection close) headers))
#\port port)))
(call-with-values (lambda () (sanitize-request request body))
(lambda (request body)
(let ((request (write-request request port)))
(when body
(write-request-body request body))
(force-output (request-port request))
(let ((response (read-response port)))
(cond
((eq? (request-method request) 'HEAD)
(unless keep-alive?
(close-port port))
(values response #f))
(streaming?
(values response
(response-body-port response
#\keep-alive? keep-alive?
#\decode? decode-body?)))
(else
(let ((body (read-response-body response)))
(unless keep-alive?
(close-port port))
(values response
(if decode-body?
(decode-response-body response body)
body))))))))))
(define* (http-get uri #\key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1)) (keep-alive? #f)
;; #\headers is the new name of #\extra-headers.
(extra-headers #f) (headers (or extra-headers '()))
(decode-body? #t) (streaming? #f))
"Connect to the server corresponding to URI and ask for the
resource, using the ‘GET’ method. If you already have a port open,
pass it as PORT. The port will be closed at the end of the
request unless KEEP-ALIVE? is true. Any extra headers in the
alist HEADERS will be added to the request.
If BODY is not ‘#f’, a message body will also be sent with the HTTP
request. If BODY is a string, it is encoded according to the
content-type in HEADERS, defaulting to UTF-8. Otherwise BODY should be
a bytevector, or ‘#f’ for no body. Although it's allowed to send a
message body along with any request, usually only POST and PUT requests
have bodies. See ‘http-put’ and ‘http-post’ documentation, for more.
If DECODE-BODY? is true, as is the default, the body of the
response will be decoded to string, if it is a textual content-type.
Otherwise it will be returned as a bytevector.
However, if STREAMING? is true, instead of eagerly reading the response
body from the server, this function only reads off the headers. The
response body will be returned as a port on which the data may be read.
Unless KEEP-ALIVE? is true, the port will be closed after the full
response body has been read.
Returns two values_ the response read from the server, and the response
body as a string, bytevector, #f value, or as a port (if STREAMING? is
true)."
(when extra-headers
(issue-deprecation-warning
"The #\extra-headers argument to http-get has been renamed to #:headers. "
"Please update your code."))
(request uri #\method 'GET #\body body
#\port port #\version version #\keep-alive? keep-alive?
#\headers headers #\decode-body? decode-body?
#\streaming? streaming?))
(define* (http-get* uri #\key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1)) (keep-alive? #f)
;; #\headers is the new name of #\extra-headers.
(extra-headers #f) (headers (or extra-headers '()))
(decode-body? #t))
"Deprecated in favor of (http-get #:streaming? #t)."
(issue-deprecation-warning
"`http-get*' has been deprecated. "
"Instead, use `http-get' with the #:streaming? #t keyword argument.")
(http-get uri #\body body
#\port port #\version version #\keep-alive? keep-alive?
#\headers headers #\decode-body? #t #\streaming? #t))
(define-syntax-rule (define-http-verb http-verb method doc)
(define* (http-verb uri #\key
(body #f)
(port (open-socket-for-uri uri))
(version '(1 . 1))
(keep-alive? #f)
(headers '())
(decode-body? #t)
(streaming? #f))
doc
(request uri
#\body body #\method method
#\port port #\version version #\keep-alive? keep-alive?
#\headers headers #\decode-body? decode-body?
#\streaming? streaming?)))
(define-http-verb http-head
'HEAD
"Fetch message headers for the given URI using the HTTP \"HEAD\"
method.
This function is similar to ‘http-get’, except it uses the \"HEAD\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and ‘#f’. Responses to HEAD
requests do not have a body. The second value is only returned so that
other procedures can treat all of the http-foo verbs identically.")
(define-http-verb http-post
'POST
"Post data to the given URI using the HTTP \"POST\" method.
This function is similar to ‘http-get’, except it uses the \"POST\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and the response body.")
(define-http-verb http-put
'PUT
"Put data at the given URI using the HTTP \"PUT\" method.
This function is similar to ‘http-get’, except it uses the \"PUT\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and the response body.")
(define-http-verb http-delete
'DELETE
"Delete data at the given URI using the HTTP \"DELETE\" method.
This function is similar to ‘http-get’, except it uses the \"DELETE\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and the response body.")
(define-http-verb http-trace
'TRACE
"Send an HTTP \"TRACE\" request.
This function is similar to ‘http-get’, except it uses the \"TRACE\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and the response body.")
(define-http-verb http-options
'OPTIONS
"Query characteristics of an HTTP resource using the HTTP \"OPTIONS\"
method.
This function is similar to ‘http-get’, except it uses the \"OPTIONS\"
method. See ‘http-get’ for full documentation on the various keyword
arguments that are accepted by this function.
Returns two values_ the resulting response, and the response body.")
;;; HTTP messages
;; Copyright (C) 2010-2016 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary_
;;;
;;; This module has a number of routines to parse textual
;;; representations of HTTP data into native Scheme data structures.
;;;
;;; It tries to follow RFCs fairly strictly---the road to perdition
;;; being paved with compatibility hacks---though some allowances are
;;; made for not-too-divergent texts (like a quality of .2 which should
;;; be 0.2, etc).
;;;
;;; Code_
(define-module (web http)
#\use-module ((srfi srfi-1) #\select (append-map! map!))
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-19)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 match)
#\use-module (ice-9 q)
#\use-module (ice-9 binary-ports)
#\use-module (rnrs bytevectors)
#\use-module (web uri)
#\export (string->header
header->string
declare-header!
declare-opaque-header!
known-header?
header-parser
header-validator
header-writer
read-header
parse-header
valid-header?
write-header
read-headers
write-headers
parse-http-method
parse-http-version
parse-request-uri
read-request-line
write-request-line
read-response-line
write-response-line
make-chunked-input-port
make-chunked-output-port
http-proxy-port?
set-http-proxy-port?!))
(define (string->header name)
"Parse NAME to a symbolic header name."
(string->symbol (string-downcase name)))
(define-record-type <header-decl>
(make-header-decl name parser validator writer multiple?)
header-decl?
(name header-decl-name)
(parser header-decl-parser)
(validator header-decl-validator)
(writer header-decl-writer)
(multiple? header-decl-multiple?))
;; sym -> header
(define *declared-headers* (make-hash-table))
(define (lookup-header-decl sym)
(hashq-ref *declared-headers* sym))
(define* (declare-header! name
parser
validator
writer
#\key multiple?)
"Declare a parser, validator, and writer for a given header."
(if (and (string? name) parser validator writer)
(let ((decl (make-header-decl name parser validator writer multiple?)))
(hashq-set! *declared-headers* (string->header name) decl)
decl)
(error "bad header decl" name parser validator writer multiple?)))
(define (header->string sym)
"Return the string form for the header named SYM."
(let ((decl (lookup-header-decl sym)))
(if decl
(header-decl-name decl)
(string-titlecase (symbol->string sym)))))
(define (known-header? sym)
"Return ‘#t’ iff SYM is a known header, with associated
parsers and serialization procedures."
(and (lookup-header-decl sym) #t))
(define (header-parser sym)
"Return the value parser for headers named SYM. The result is a
procedure that takes one argument, a string, and returns the parsed
value. If the header isn't known to Guile, a default parser is returned
that passes through the string unchanged."
(let ((decl (lookup-header-decl sym)))
(if decl
(header-decl-parser decl)
(lambda (x) x))))
(define (header-validator sym)
"Return a predicate which returns ‘#t’ if the given value is valid
for headers named SYM. The default validator for unknown headers
is ‘string?’."
(let ((decl (lookup-header-decl sym)))
(if decl
(header-decl-validator decl)
string?)))
(define (header-writer sym)
"Return a procedure that writes values for headers named SYM to a
port. The resulting procedure takes two arguments_ a value and a port.
The default writer is ‘display’."
(let ((decl (lookup-header-decl sym)))
(if decl
(header-decl-writer decl)
display)))
(define (read-header-line port)
"Read an HTTP header line and return it without its final CRLF or LF.
Raise a 'bad-header' exception if the line does not end in CRLF or LF,
or if EOF is reached."
(match (%read-line port)
(((? string? line) . #\newline)
;; '%read-line' does not consider #\return a delimiter; so if it's
;; there, remove it. We are more tolerant than the RFC in that we
;; tolerate LF-only endings.
(if (string-suffix? "\r" line)
(string-drop-right line 1)
line))
((line . _) ;EOF or missing delimiter
(bad-header 'read-header-line line))))
(define (read-continuation-line port val)
(if (or (eqv? (peek-char port) #\space)
(eqv? (peek-char port) #\tab))
(read-continuation-line port
(string-append val
(read-header-line port)))
val))
(define *eof* (call-with-input-string "" read))
(define (read-header port)
"Read one HTTP header from PORT. Return two values_ the header
name and the parsed Scheme value. May raise an exception if the header
was known but the value was invalid.
Returns the end-of-file object for both values if the end of the message
body was reached (i.e., a blank line)."
(let ((line (read-header-line port)))
(if (or (string-null? line)
(string=? line "\r"))
(values *eof* *eof*)
(let* ((delim (or (string-index line #\_)
(bad-header '%read line)))
(sym (string->header (substring line 0 delim))))
(values
sym
(parse-header
sym
(read-continuation-line
port
(string-trim-both line char-set_whitespace (1+ delim)))))))))
(define (parse-header sym val)
"Parse VAL, a string, with the parser registered for the header
named SYM. Returns the parsed value."
((header-parser sym) val))
(define (valid-header? sym val)
"Returns a true value iff VAL is a valid Scheme value for the
header with name SYM."
(if (symbol? sym)
((header-validator sym) val)
(error "header name not a symbol" sym)))
(define (write-header sym val port)
"Write the given header name and value to PORT, using the writer
from ‘header-writer’."
(display (header->string sym) port)
(display "_ " port)
((header-writer sym) val port)
(display "\r\n" port))
(define (read-headers port)
"Read the headers of an HTTP message from PORT, returning them
as an ordered alist."
(let lp ((headers '()))
(call-with-values (lambda () (read-header port))
(lambda (k v)
(if (eof-object? k)
(reverse! headers)
(lp (acons k v headers)))))))
(define (write-headers headers port)
"Write the given header alist to PORT. Doesn't write the final
‘\\r\\n’, as the user might want to add another header."
(let lp ((headers headers))
(if (pair? headers)
(begin
(write-header (caar headers) (cdar headers) port)
(lp (cdr headers))))))
;;;
;;; Utilities
;;;
(define (bad-header sym val)
(throw 'bad-header sym val))
(define (bad-header-component sym val)
(throw 'bad-header-component sym val))
(define (bad-header-printer port key args default-printer)
(apply (case-lambda
((sym val)
(format port "Bad ~a header_ ~a\n" (header->string sym) val))
(_ (default-printer)))
args))
(define (bad-header-component-printer port key args default-printer)
(apply (case-lambda
((sym val)
(format port "Bad ~a header component_ ~a\n" sym val))
(_ (default-printer)))
args))
(set-exception-printer! 'bad-header bad-header-printer)
(set-exception-printer! 'bad-header-component bad-header-component-printer)
(define (parse-opaque-string str)
str)
(define (validate-opaque-string val)
(string? val))
(define (write-opaque-string val port)
(display val port))
(define separators-without-slash
(string->char-set "[^][()<>@,;_\\\"?= \t]"))
(define (validate-media-type str)
(let ((idx (string-index str #\/)))
(and idx (= idx (string-rindex str #\/))
(not (string-index str separators-without-slash)))))
(define (parse-media-type str)
(if (validate-media-type str)
(string->symbol str)
(bad-header-component 'media-type str)))
(define* (skip-whitespace str #\optional (start 0) (end (string-length str)))
(let lp ((i start))
(if (and (< i end) (char-whitespace? (string-ref str i)))
(lp (1+ i))
i)))
(define* (trim-whitespace str #\optional (start 0) (end (string-length str)))
(let lp ((i end))
(if (and (< start i) (char-whitespace? (string-ref str (1- i))))
(lp (1- i))
i)))
(define* (split-and-trim str #\optional (delim #\,)
(start 0) (end (string-length str)))
(let lp ((i start))
(if (< i end)
(let* ((idx (string-index str delim i end))
(tok (string-trim-both str char-set_whitespace i (or idx end))))
(cons tok (split-and-trim str delim (if idx (1+ idx) end) end)))
'())))
(define (list-of-strings? val)
(list-of? val string?))
(define (write-list-of-strings val port)
(write-list val port display ", "))
(define (split-header-names str)
(map string->header (split-and-trim str)))
(define (list-of-header-names? val)
(list-of? val symbol?))
(define (write-header-list val port)
(write-list val port
(lambda (x port)
(display (header->string x) port))
", "))
(define (collect-escaped-string from start len escapes)
(let ((to (make-string len)))
(let lp ((start start) (i 0) (escapes escapes))
(if (null? escapes)
(begin
(substring-move! from start (+ start (- len i)) to i)
to)
(let* ((e (car escapes))
(next-start (+ start (- e i) 2)))
(substring-move! from start (- next-start 2) to i)
(string-set! to e (string-ref from (- next-start 1)))
(lp next-start (1+ e) (cdr escapes)))))))
;; in incremental mode, returns two values_ the string, and the index at
;; which the string ended
(define* (parse-qstring str #\optional
(start 0) (end (trim-whitespace str start))
#\key incremental?)
(if (and (< start end) (eqv? (string-ref str start) #\"))
(let lp ((i (1+ start)) (qi 0) (escapes '()))
(if (< i end)
(case (string-ref str i)
((#\\)
(lp (+ i 2) (1+ qi) (cons qi escapes)))
((#\")
(let ((out (collect-escaped-string str (1+ start) qi escapes)))
(if incremental?
(values out (1+ i))
(if (= (1+ i) end)
out
(bad-header-component 'qstring str)))))
(else
(lp (1+ i) (1+ qi) escapes)))
(bad-header-component 'qstring str)))
(bad-header-component 'qstring str)))
(define (write-list l port write-item delim)
(if (pair? l)
(let lp ((l l))
(write-item (car l) port)
(if (pair? (cdr l))
(begin
(display delim port)
(lp (cdr l)))))))
(define (write-qstring str port)
(display #\" port)
(if (string-index str #\")
;; optimize me
(write-list (string-split str #\") port display "\\\"")
(display str port))
(display #\" port))
(define* (parse-quality str #\optional (start 0) (end (string-length str)))
(define (char->decimal c)
(let ((i (- (char->integer c) (char->integer #\0))))
(if (and (<= 0 i) (< i 10))
i
(bad-header-component 'quality str))))
(cond
((not (< start end))
(bad-header-component 'quality str))
((eqv? (string-ref str start) #\1)
(if (or (string= str "1" start end)
(string= str "1." start end)
(string= str "1.0" start end)
(string= str "1.00" start end)
(string= str "1.000" start end))
1000
(bad-header-component 'quality str)))
((eqv? (string-ref str start) #\0)
(if (or (string= str "0" start end)
(string= str "0." start end))
0
(if (< 2 (- end start) 6)
(let lp ((place 1) (i (+ start 4)) (q 0))
(if (= i (1+ start))
(if (eqv? (string-ref str (1+ start)) #\.)
q
(bad-header-component 'quality str))
(lp (* 10 place) (1- i)
(if (< i end)
(+ q (* place (char->decimal (string-ref str i))))
q))))
(bad-header-component 'quality str))))
;; Allow the nonstandard .2 instead of 0.2.
((and (eqv? (string-ref str start) #\.)
(< 1 (- end start) 5))
(let lp ((place 1) (i (+ start 3)) (q 0))
(if (= i start)
q
(lp (* 10 place) (1- i)
(if (< i end)
(+ q (* place (char->decimal (string-ref str i))))
q)))))
(else
(bad-header-component 'quality str))))
(define (valid-quality? q)
(and (non-negative-integer? q) (<= q 1000)))
(define (write-quality q port)
(define (digit->char d)
(integer->char (+ (char->integer #\0) d)))
(display (digit->char (modulo (quotient q 1000) 10)) port)
(display #\. port)
(display (digit->char (modulo (quotient q 100) 10)) port)
(display (digit->char (modulo (quotient q 10) 10)) port)
(display (digit->char (modulo q 10)) port))
(define (list-of? val pred)
(or (null? val)
(and (pair? val)
(pred (car val))
(list-of? (cdr val) pred))))
(define* (parse-quality-list str)
(map (lambda (part)
(cond
((string-rindex part #\;)
=> (lambda (idx)
(let ((qpart (string-trim-both part char-set_whitespace (1+ idx))))
(if (string-prefix? "q=" qpart)
(cons (parse-quality qpart 2)
(string-trim-both part char-set_whitespace 0 idx))
(bad-header-component 'quality qpart)))))
(else
(cons 1000 (string-trim-both part char-set_whitespace)))))
(string-split str #\,)))
(define (validate-quality-list l)
(list-of? l
(lambda (elt)
(and (pair? elt)
(valid-quality? (car elt))
(string? (cdr elt))))))
(define (write-quality-list l port)
(write-list l port
(lambda (x port)
(let ((q (car x))
(str (cdr x)))
(display str port)
(if (< q 1000)
(begin
(display ";q=" port)
(write-quality q port)))))
","))
(define* (parse-non-negative-integer val #\optional (start 0)
(end (string-length val)))
(define (char->decimal c)
(let ((i (- (char->integer c) (char->integer #\0))))
(if (and (<= 0 i) (< i 10))
i
(bad-header-component 'non-negative-integer val))))
(if (not (< start end))
(bad-header-component 'non-negative-integer val)
(let lp ((i start) (out 0))
(if (< i end)
(lp (1+ i)
(+ (* out 10) (char->decimal (string-ref val i))))
out))))
(define (non-negative-integer? code)
(and (number? code) (>= code 0) (exact? code) (integer? code)))
(define (default-val-parser k val)
val)
(define (default-val-validator k val)
(or (not val) (string? val)))
(define (default-val-writer k val port)
(if (or (string-index val #\;)
(string-index val #\,)
(string-index val #\"))
(write-qstring val port)
(display val port)))
(define* (parse-key-value-list str #\optional
(val-parser default-val-parser)
(start 0) (end (string-length str)))
(let lp ((i start) (out '()))
(if (not (< i end))
(reverse! out)
(let* ((i (skip-whitespace str i end))
(eq (string-index str #\= i end))
(comma (string-index str #\, i end))
(delim (min (or eq end) (or comma end)))
(k (string->symbol
(substring str i (trim-whitespace str i delim)))))
(call-with-values
(lambda ()
(if (and eq (or (not comma) (< eq comma)))
(let ((i (skip-whitespace str (1+ eq) end)))
(if (and (< i end) (eqv? (string-ref str i) #\"))
(parse-qstring str i end #\incremental? #t)
(values (substring str i
(trim-whitespace str i
(or comma end)))
(or comma end))))
(values #f delim)))
(lambda (v-str next-i)
(let ((v (val-parser k v-str))
(i (skip-whitespace str next-i end)))
(if (or (= i end) (eqv? (string-ref str i) #\,))
(lp (1+ i) (cons (if v (cons k v) k) out))
(bad-header-component 'key-value-list
(substring str start end))))))))))
(define* (key-value-list? list #\optional
(valid? default-val-validator))
(list-of? list
(lambda (elt)
(cond
((pair? elt)
(let ((k (car elt))
(v (cdr elt)))
(and (symbol? k)
(valid? k v))))
((symbol? elt)
(valid? elt #f))
(else #f)))))
(define* (write-key-value-list list port #\optional
(val-writer default-val-writer) (delim ", "))
(write-list
list port
(lambda (x port)
(let ((k (if (pair? x) (car x) x))
(v (if (pair? x) (cdr x) #f)))
(display k port)
(if v
(begin
(display #\= port)
(val-writer k v port)))))
delim))
;; param-component = token [ "=" (token | quoted-string) ] \
;; *(";" token [ "=" (token | quoted-string) ])
;;
(define param-delimiters (char-set #\, #\; #\=))
(define param-value-delimiters (char-set-adjoin char-set_whitespace #\, #\;))
(define* (parse-param-component str #\optional
(val-parser default-val-parser)
(start 0) (end (string-length str)))
(let lp ((i start) (out '()))
(if (not (< i end))
(values (reverse! out) end)
(let ((delim (string-index str param-delimiters i)))
(let ((k (string->symbol
(substring str i (trim-whitespace str i (or delim end)))))
(delimc (and delim (string-ref str delim))))
(case delimc
((#\=)
(call-with-values
(lambda ()
(let ((i (skip-whitespace str (1+ delim) end)))
(if (and (< i end) (eqv? (string-ref str i) #\"))
(parse-qstring str i end #\incremental? #t)
(let ((delim
(or (string-index str param-value-delimiters
i end)
end)))
(values (substring str i delim)
delim)))))
(lambda (v-str next-i)
(let* ((v (val-parser k v-str))
(x (if v (cons k v) k))
(i (skip-whitespace str next-i end)))
(case (and (< i end) (string-ref str i))
((#f)
(values (reverse! (cons x out)) end))
((#\;)
(lp (skip-whitespace str (1+ i) end)
(cons x out)))
(else ; including #\,
(values (reverse! (cons x out)) i)))))))
((#\;)
(let ((v (val-parser k #f)))
(lp (skip-whitespace str (1+ delim) end)
(cons (if v (cons k v) k) out))))
(else ;; either the end of the string or a #\,
(let ((v (val-parser k #f)))
(values (reverse! (cons (if v (cons k v) k) out))
(or delim end))))))))))
(define* (parse-param-list str #\optional
(val-parser default-val-parser)
(start 0) (end (string-length str)))
(let lp ((i start) (out '()))
(call-with-values
(lambda () (parse-param-component str val-parser i end))
(lambda (item i)
(if (< i end)
(if (eqv? (string-ref str i) #\,)
(lp (skip-whitespace str (1+ i) end)
(cons item out))
(bad-header-component 'param-list str))
(reverse! (cons item out)))))))
(define* (validate-param-list list #\optional
(valid? default-val-validator))
(list-of? list
(lambda (elt)
(key-value-list? elt valid?))))
(define* (write-param-list list port #\optional
(val-writer default-val-writer))
(write-list
list port
(lambda (item port)
(write-key-value-list item port val-writer ";"))
","))
(define-syntax string-match?
(lambda (x)
(syntax-case x ()
((_ str pat) (string? (syntax->datum #'pat))
(let ((p (syntax->datum #'pat)))
#`(let ((s str))
(and
(= (string-length s) #,(string-length p))
#,@(let lp ((i 0) (tests '()))
(if (< i (string-length p))
(let ((c (string-ref p i)))
(lp (1+ i)
(case c
((#\.) ; Whatever.
tests)
((#\d) ; Digit.
(cons #`(char-numeric? (string-ref s #,i))
tests))
((#\a) ; Alphabetic.
(cons #`(char-alphabetic? (string-ref s #,i))
tests))
(else ; Literal.
(cons #`(eqv? (string-ref s #,i) #,c)
tests)))))
tests)))))))))
;; "Jan" | "Feb" | "Mar" | "Apr" | "May" | "Jun"
;; "Jul" | "Aug" | "Sep" | "Oct" | "Nov" | "Dec"
(define (parse-month str start end)
(define (bad)
(bad-header-component 'month (substring str start end)))
(if (not (= (- end start) 3))
(bad)
(let ((a (string-ref str (+ start 0)))
(b (string-ref str (+ start 1)))
(c (string-ref str (+ start 2))))
(case a
((#\J)
(case b
((#\a) (case c ((#\n) 1) (else (bad))))
((#\u) (case c ((#\n) 6) ((#\l) 7) (else (bad))))
(else (bad))))
((#\F)
(case b
((#\e) (case c ((#\b) 2) (else (bad))))
(else (bad))))
((#\M)
(case b
((#\a) (case c ((#\r) 3) ((#\y) 5) (else (bad))))
(else (bad))))
((#\A)
(case b
((#\p) (case c ((#\r) 4) (else (bad))))
((#\u) (case c ((#\g) 8) (else (bad))))
(else (bad))))
((#\S)
(case b
((#\e) (case c ((#\p) 9) (else (bad))))
(else (bad))))
((#\O)
(case b
((#\c) (case c ((#\t) 10) (else (bad))))
(else (bad))))
((#\N)
(case b
((#\o) (case c ((#\v) 11) (else (bad))))
(else (bad))))
((#\D)
(case b
((#\e) (case c ((#\c) 12) (else (bad))))
(else (bad))))
(else (bad))))))
;; "GMT" | "+" 4DIGIT | "-" 4DIGIT
;;
;; RFC 2616 requires date values to use "GMT", but recommends accepting
;; the others as they are commonly generated by e.g. RFC 822 sources.
(define (parse-zone-offset str start)
(let ((s (substring str start)))
(define (bad)
(bad-header-component 'zone-offset s))
(cond
((string=? s "GMT")
0)
((string=? s "UTC")
0)
((string-match? s ".dddd")
(let ((sign (case (string-ref s 0)
((#\+) +1)
((#\-) -1)
(else (bad))))
(hours (parse-non-negative-integer s 1 3))
(minutes (parse-non-negative-integer s 3 5)))
(* sign 60 (+ (* 60 hours) minutes)))) ; seconds east of Greenwich
(else (bad)))))
;; RFC 822, updated by RFC 1123
;;
;; Sun, 06 Nov 1994 08_49_37 GMT
;; 01234567890123456789012345678
;; 0 1 2
(define (parse-rfc-822-date str space zone-offset)
;; We could verify the day of the week but we don't.
(cond ((string-match? (substring str 0 space) "aaa, dd aaa dddd dd_dd_dd")
(let ((date (parse-non-negative-integer str 5 7))
(month (parse-month str 8 11))
(year (parse-non-negative-integer str 12 16))
(hour (parse-non-negative-integer str 17 19))
(minute (parse-non-negative-integer str 20 22))
(second (parse-non-negative-integer str 23 25)))
(make-date 0 second minute hour date month year zone-offset)))
((string-match? (substring str 0 space) "aaa, d aaa dddd dd_dd_dd")
(let ((date (parse-non-negative-integer str 5 6))
(month (parse-month str 7 10))
(year (parse-non-negative-integer str 11 15))
(hour (parse-non-negative-integer str 16 18))
(minute (parse-non-negative-integer str 19 21))
(second (parse-non-negative-integer str 22 24)))
(make-date 0 second minute hour date month year zone-offset)))
;; The next two clauses match dates that have a space instead of
;; a leading zero for hours, like " 8_49_37".
((string-match? (substring str 0 space) "aaa, dd aaa dddd d_dd_dd")
(let ((date (parse-non-negative-integer str 5 7))
(month (parse-month str 8 11))
(year (parse-non-negative-integer str 12 16))
(hour (parse-non-negative-integer str 18 19))
(minute (parse-non-negative-integer str 20 22))
(second (parse-non-negative-integer str 23 25)))
(make-date 0 second minute hour date month year zone-offset)))
((string-match? (substring str 0 space) "aaa, d aaa dddd d_dd_dd")
(let ((date (parse-non-negative-integer str 5 6))
(month (parse-month str 7 10))
(year (parse-non-negative-integer str 11 15))
(hour (parse-non-negative-integer str 17 18))
(minute (parse-non-negative-integer str 19 21))
(second (parse-non-negative-integer str 22 24)))
(make-date 0 second minute hour date month year zone-offset)))
(else
(bad-header 'date str) ; prevent tail call
#f)))
;; RFC 850, updated by RFC 1036
;; Sunday, 06-Nov-94 08_49_37 GMT
;; 0123456789012345678901
;; 0 1 2
(define (parse-rfc-850-date str comma space zone-offset)
;; We could verify the day of the week but we don't.
(let ((tail (substring str (1+ comma) space)))
(if (not (string-match? tail " dd-aaa-dd dd_dd_dd"))
(bad-header 'date str))
(let ((date (parse-non-negative-integer tail 1 3))
(month (parse-month tail 4 7))
(year (parse-non-negative-integer tail 8 10))
(hour (parse-non-negative-integer tail 11 13))
(minute (parse-non-negative-integer tail 14 16))
(second (parse-non-negative-integer tail 17 19)))
(make-date 0 second minute hour date month
(let* ((now (date-year (current-date)))
(then (+ now year (- (modulo now 100)))))
(cond ((< (+ then 50) now) (+ then 100))
((< (+ now 50) then) (- then 100))
(else then)))
zone-offset))))
;; ANSI C's asctime() format
;; Sun Nov 6 08_49_37 1994
;; 012345678901234567890123
;; 0 1 2
(define (parse-asctime-date str)
(if (not (string-match? str "aaa aaa .d dd_dd_dd dddd"))
(bad-header 'date str))
(let ((date (parse-non-negative-integer
str
(if (eqv? (string-ref str 8) #\space) 9 8)
10))
(month (parse-month str 4 7))
(year (parse-non-negative-integer str 20 24))
(hour (parse-non-negative-integer str 11 13))
(minute (parse-non-negative-integer str 14 16))
(second (parse-non-negative-integer str 17 19)))
(make-date 0 second minute hour date month year 0)))
;; Convert all date values to GMT time zone, as per RFC 2616 appendix C.
(define (normalize-date date)
(if (zero? (date-zone-offset date))
date
(time-utc->date (date->time-utc date) 0)))
(define (parse-date str)
(let* ((space (string-rindex str #\space))
(zone-offset (and space (false-if-exception
(parse-zone-offset str (1+ space))))))
(normalize-date
(if zone-offset
(let ((comma (string-index str #\,)))
(cond ((not comma) (bad-header 'date str))
((= comma 3) (parse-rfc-822-date str space zone-offset))
(else (parse-rfc-850-date str comma space zone-offset))))
(parse-asctime-date str)))))
(define (write-date date port)
(define (display-digits n digits port)
(define zero (char->integer #\0))
(let lp ((tens (expt 10 (1- digits))))
(if (> tens 0)
(begin
(display (integer->char (+ zero (modulo (truncate/ n tens) 10)))
port)
(lp (floor/ tens 10))))))
(let ((date (if (zero? (date-zone-offset date))
date
(time-tai->date (date->time-tai date) 0))))
(display (case (date-week-day date)
((0) "Sun, ") ((1) "Mon, ") ((2) "Tue, ")
((3) "Wed, ") ((4) "Thu, ") ((5) "Fri, ")
((6) "Sat, ") (else (error "bad date" date)))
port)
(display-digits (date-day date) 2 port)
(display (case (date-month date)
((1) " Jan ") ((2) " Feb ") ((3) " Mar ")
((4) " Apr ") ((5) " May ") ((6) " Jun ")
((7) " Jul ") ((8) " Aug ") ((9) " Sep ")
((10) " Oct ") ((11) " Nov ") ((12) " Dec ")
(else (error "bad date" date)))
port)
(display-digits (date-year date) 4 port)
(display #\space port)
(display-digits (date-hour date) 2 port)
(display #\_ port)
(display-digits (date-minute date) 2 port)
(display #\_ port)
(display-digits (date-second date) 2 port)
(display " GMT" port)))
;; Following https_//tools.ietf.org/html/rfc7232#section-2.3, an entity
;; tag should really be a qstring. However there are a number of
;; servers that emit etags as unquoted strings. Assume that if the
;; value doesn't start with a quote, it's an unquoted strong etag.
(define (parse-entity-tag val)
(cond
((string-prefix? "W/" val) (cons (parse-qstring val 2) #f))
((string-prefix? "\"" val) (cons (parse-qstring val) #t))
(else (cons val #t))))
(define (entity-tag? val)
(and (pair? val)
(string? (car val))))
(define (write-entity-tag val port)
(if (not (cdr val))
(display "W/" port))
(write-qstring (car val) port))
(define* (parse-entity-tag-list val #\optional
(start 0) (end (string-length val)))
(let ((strong? (not (string-prefix? "W/" val 0 2 start end))))
(call-with-values (lambda ()
(parse-qstring val (if strong? start (+ start 2))
end #\incremental? #t))
(lambda (tag next)
(acons tag strong?
(let ((next (skip-whitespace val next end)))
(if (< next end)
(if (eqv? (string-ref val next) #\,)
(parse-entity-tag-list
val
(skip-whitespace val (1+ next) end)
end)
(bad-header-component 'entity-tag-list val))
'())))))))
(define (entity-tag-list? val)
(list-of? val entity-tag?))
(define (write-entity-tag-list val port)
(write-list val port write-entity-tag ", "))
;; credentials = auth-scheme #auth-param
;; auth-scheme = token
;; auth-param = token "=" ( token | quoted-string )
;;
;; That's what the spec says. In reality the Basic scheme doesn't have
;; k-v pairs, just one auth token, so we give that token as a string.
;;
(define* (parse-credentials str #\optional (val-parser default-val-parser)
(start 0) (end (string-length str)))
(let* ((start (skip-whitespace str start end))
(delim (or (string-index str char-set_whitespace start end) end)))
(if (= start end)
(bad-header-component 'authorization str))
(let ((scheme (string->symbol
(string-downcase (substring str start (or delim end))))))
(case scheme
((basic)
(let* ((start (skip-whitespace str delim end)))
(if (< start end)
(cons scheme (substring str start end))
(bad-header-component 'credentials str))))
(else
(cons scheme (parse-key-value-list str default-val-parser delim end)))))))
(define (validate-credentials val)
(and (pair? val) (symbol? (car val))
(case (car val)
((basic) (string? (cdr val)))
(else (key-value-list? (cdr val))))))
(define (write-credentials val port)
(display (car val) port)
(display #\space port)
(case (car val)
((basic) (display (cdr val) port))
(else (write-key-value-list (cdr val) port))))
;; challenges = 1#challenge
;; challenge = auth-scheme 1*SP 1#auth-param
;;
;; A pain to parse, as both challenges and auth params are delimited by
;; commas, and qstrings can contain anything. We rely on auth params
;; necessarily having "=" in them.
;;
(define* (parse-challenge str #\optional
(start 0) (end (string-length str)))
(let* ((start (skip-whitespace str start end))
(sp (string-index str #\space start end))
(scheme (if sp
(string->symbol (string-downcase (substring str start sp)))
(bad-header-component 'challenge str))))
(let lp ((i sp) (out (list scheme)))
(if (not (< i end))
(values (reverse! out) end)
(let* ((i (skip-whitespace str i end))
(eq (string-index str #\= i end))
(comma (string-index str #\, i end))
(delim (min (or eq end) (or comma end)))
(token-end (trim-whitespace str i delim)))
(if (string-index str #\space i token-end)
(values (reverse! out) i)
(let ((k (string->symbol (substring str i token-end))))
(call-with-values
(lambda ()
(if (and eq (or (not comma) (< eq comma)))
(let ((i (skip-whitespace str (1+ eq) end)))
(if (and (< i end) (eqv? (string-ref str i) #\"))
(parse-qstring str i end #\incremental? #t)
(values (substring
str i
(trim-whitespace str i
(or comma end)))
(or comma end))))
(values #f delim)))
(lambda (v next-i)
(let ((i (skip-whitespace str next-i end)))
(if (or (= i end) (eqv? (string-ref str i) #\,))
(lp (1+ i) (cons (if v (cons k v) k) out))
(bad-header-component
'challenge
(substring str start end)))))))))))))
(define* (parse-challenges str #\optional (val-parser default-val-parser)
(start 0) (end (string-length str)))
(let lp ((i start) (ret '()))
(let ((i (skip-whitespace str i end)))
(if (< i end)
(call-with-values (lambda () (parse-challenge str i end))
(lambda (challenge i)
(lp i (cons challenge ret))))
(reverse ret)))))
(define (validate-challenges val)
(list-of? val (lambda (x)
(and (pair? x) (symbol? (car x))
(key-value-list? (cdr x))))))
(define (write-challenge val port)
(display (car val) port)
(display #\space port)
(write-key-value-list (cdr val) port))
(define (write-challenges val port)
(write-list val port write-challenge ", "))
;;;
;;; Request-Line and Response-Line
;;;
;; Hmm.
(define (bad-request message . args)
(throw 'bad-request message args))
(define (bad-response message . args)
(throw 'bad-response message args))
(define *known-versions* '())
(define* (parse-http-version str #\optional (start 0) (end (string-length str)))
"Parse an HTTP version from STR, returning it as a major–minor
pair. For example, ‘HTTP/1.1’ parses as the pair of integers,
‘(1 . 1)’."
(or (let lp ((known *known-versions*))
(and (pair? known)
(if (string= str (caar known) start end)
(cdar known)
(lp (cdr known)))))
(let ((dot-idx (string-index str #\. start end)))
(if (and (string-prefix? "HTTP/" str 0 5 start end)
dot-idx
(= dot-idx (string-rindex str #\. start end)))
(cons (parse-non-negative-integer str (+ start 5) dot-idx)
(parse-non-negative-integer str (1+ dot-idx) end))
(bad-header-component 'http-version (substring str start end))))))
(define (write-http-version val port)
"Write the given major-minor version pair to PORT."
(display "HTTP/" port)
(display (car val) port)
(display #\. port)
(display (cdr val) port))
(for-each
(lambda (v)
(set! *known-versions*
(acons v (parse-http-version v 0 (string-length v))
*known-versions*)))
'("HTTP/1.0" "HTTP/1.1"))
;; Request-URI = "*" | absoluteURI | abs_path | authority
;;
;; The `authority' form is only permissible for the CONNECT method, so
;; because we don't expect people to implement CONNECT, we save
;; ourselves the trouble of that case, and disallow the CONNECT method.
;;
(define* (parse-http-method str #\optional (start 0) (end (string-length str)))
"Parse an HTTP method from STR. The result is an upper-case
symbol, like ‘GET’."
(cond
((string= str "GET" start end) 'GET)
((string= str "HEAD" start end) 'HEAD)
((string= str "POST" start end) 'POST)
((string= str "PUT" start end) 'PUT)
((string= str "DELETE" start end) 'DELETE)
((string= str "OPTIONS" start end) 'OPTIONS)
((string= str "TRACE" start end) 'TRACE)
(else (bad-request "Invalid method_ ~a" (substring str start end)))))
(define* (parse-request-uri str #\optional (start 0) (end (string-length str)))
"Parse a URI from an HTTP request line. Note that URIs in requests do
not have to have a scheme or host name. The result is a URI object."
(cond
((= start end)
(bad-request "Missing Request-URI"))
((string= str "*" start end)
#f)
((eqv? (string-ref str start) #\/)
(let* ((q (string-index str #\? start end))
(f (string-index str #\# start end))
(q (and q (or (not f) (< q f)) q)))
(build-uri 'http
#\path (substring str start (or q f end))
#\query (and q (substring str (1+ q) (or f end)))
#\fragment (and f (substring str (1+ f) end)))))
(else
(or (string->uri (substring str start end))
(bad-request "Invalid URI_ ~a" (substring str start end))))))
(define (read-request-line port)
"Read the first line of an HTTP request from PORT, returning
three values_ the method, the URI, and the version."
(let* ((line (read-header-line port))
(d0 (string-index line char-set_whitespace)) ; "delimiter zero"
(d1 (string-rindex line char-set_whitespace)))
(if (and d0 d1 (< d0 d1))
(values (parse-http-method line 0 d0)
(parse-request-uri line (skip-whitespace line (1+ d0) d1) d1)
(parse-http-version line (1+ d1) (string-length line)))
(bad-request "Bad Request-Line_ ~s" line))))
(define (write-uri uri port)
(if (uri-host uri)
(begin
(display (uri-scheme uri) port)
(display "_//" port)
(if (uri-userinfo uri)
(begin
(display (uri-userinfo uri) port)
(display #\@ port)))
(display (uri-host uri) port)
(let ((p (uri-port uri)))
(if (and p (not (eqv? p 80)))
(begin
(display #\_ port)
(display p port))))))
(let* ((path (uri-path uri))
(len (string-length path)))
(cond
((and (> len 0) (not (eqv? (string-ref path 0) #\/)))
(bad-request "Non-absolute URI path_ ~s" path))
((and (zero? len) (not (uri-host uri)))
(bad-request "Empty path and no host for URI_ ~s" uri))
(else
(display path port))))
(if (uri-query uri)
(begin
(display #\? port)
(display (uri-query uri) port))))
(define (write-request-line method uri version port)
"Write the first line of an HTTP request to PORT."
(display method port)
(display #\space port)
(when (http-proxy-port? port)
(let ((scheme (uri-scheme uri))
(host (uri-host uri))
(host-port (uri-port uri)))
(when (and scheme host)
(display scheme port)
(display "_//" port)
(if (string-index host #\_)
(begin (display #\[ port)
(display host port)
(display #\] port))
(display host port))
(unless ((@@ (web uri) default-port?) scheme host-port)
(display #\_ port)
(display host-port port)))))
(let ((path (uri-path uri))
(query (uri-query uri)))
(if (string-null? path)
(display "/" port)
(display path port))
(if query
(begin
(display "?" port)
(display query port))))
(display #\space port)
(write-http-version version port)
(display "\r\n" port))
(define (read-response-line port)
"Read the first line of an HTTP response from PORT, returning three
values_ the HTTP version, the response code, and the (possibly empty)
\"reason phrase\"."
(let* ((line (read-header-line port))
(d0 (string-index line char-set_whitespace)) ; "delimiter zero"
(d1 (and d0 (string-index line char-set_whitespace
(skip-whitespace line d0)))))
(if (and d0 d1)
(values (parse-http-version line 0 d0)
(parse-non-negative-integer line (skip-whitespace line d0 d1)
d1)
(string-trim-both line char-set_whitespace d1))
(bad-response "Bad Response-Line_ ~s" line))))
(define (write-response-line version code reason-phrase port)
"Write the first line of an HTTP response to PORT."
(write-http-version version port)
(display #\space port)
(display code port)
(display #\space port)
(display reason-phrase port)
(display "\r\n" port))
;;;
;;; Helpers for declaring headers
;;;
;; emacs_ (put 'declare-header! 'scheme-indent-function 1)
;; emacs_ (put 'declare-opaque!-header 'scheme-indent-function 1)
(define (declare-opaque-header! name)
"Declares a given header as \"opaque\", meaning that its value is not
treated specially, and is just returned as a plain string."
(declare-header! name
parse-opaque-string validate-opaque-string write-opaque-string))
;; emacs_ (put 'declare-date-header! 'scheme-indent-function 1)
(define (declare-date-header! name)
(declare-header! name
parse-date date? write-date))
;; emacs_ (put 'declare-string-list-header! 'scheme-indent-function 1)
(define (declare-string-list-header! name)
(declare-header! name
split-and-trim list-of-strings? write-list-of-strings))
;; emacs_ (put 'declare-symbol-list-header! 'scheme-indent-function 1)
(define (declare-symbol-list-header! name)
(declare-header! name
(lambda (str)
(map string->symbol (split-and-trim str)))
(lambda (v)
(list-of? v symbol?))
(lambda (v port)
(write-list v port display ", "))))
;; emacs_ (put 'declare-header-list-header! 'scheme-indent-function 1)
(define (declare-header-list-header! name)
(declare-header! name
split-header-names list-of-header-names? write-header-list))
;; emacs_ (put 'declare-integer-header! 'scheme-indent-function 1)
(define (declare-integer-header! name)
(declare-header! name
parse-non-negative-integer non-negative-integer? display))
;; emacs_ (put 'declare-uri-header! 'scheme-indent-function 1)
(define (declare-uri-header! name)
(declare-header! name
(lambda (str) (or (string->uri str) (bad-header-component 'uri str)))
(@@ (web uri) absolute-uri?)
write-uri))
;; emacs_ (put 'declare-relative-uri-header! 'scheme-indent-function 1)
(define (declare-relative-uri-header! name)
(declare-header! name
(lambda (str)
(or ((@@ (web uri) string->uri*) str)
(bad-header-component 'uri str)))
uri?
write-uri))
;; emacs_ (put 'declare-quality-list-header! 'scheme-indent-function 1)
(define (declare-quality-list-header! name)
(declare-header! name
parse-quality-list validate-quality-list write-quality-list))
;; emacs_ (put 'declare-param-list-header! 'scheme-indent-function 1)
(define* (declare-param-list-header! name #\optional
(val-parser default-val-parser)
(val-validator default-val-validator)
(val-writer default-val-writer))
(declare-header! name
(lambda (str) (parse-param-list str val-parser))
(lambda (val) (validate-param-list val val-validator))
(lambda (val port) (write-param-list val port val-writer))))
;; emacs_ (put 'declare-key-value-list-header! 'scheme-indent-function 1)
(define* (declare-key-value-list-header! name #\optional
(val-parser default-val-parser)
(val-validator default-val-validator)
(val-writer default-val-writer))
(declare-header! name
(lambda (str) (parse-key-value-list str val-parser))
(lambda (val) (key-value-list? val val-validator))
(lambda (val port) (write-key-value-list val port val-writer))))
;; emacs_ (put 'declare-entity-tag-list-header! 'scheme-indent-function 1)
(define (declare-entity-tag-list-header! name)
(declare-header! name
(lambda (str) (if (string=? str "*") '* (parse-entity-tag-list str)))
(lambda (val) (or (eq? val '*) (entity-tag-list? val)))
(lambda (val port)
(if (eq? val '*)
(display "*" port)
(write-entity-tag-list val port)))))
;; emacs_ (put 'declare-credentials-header! 'scheme-indent-function 1)
(define (declare-credentials-header! name)
(declare-header! name
parse-credentials validate-credentials write-credentials))
;; emacs_ (put 'declare-challenge-list-header! 'scheme-indent-function 1)
(define (declare-challenge-list-header! name)
(declare-header! name
parse-challenges validate-challenges write-challenges))
;;;
;;; General headers
;;;
;; Cache-Control = 1#(cache-directive)
;; cache-directive = cache-request-directive | cache-response-directive
;; cache-request-directive =
;; "no-cache" ; Section 14.9.1
;; | "no-store" ; Section 14.9.2
;; | "max-age" "=" delta-seconds ; Section 14.9.3, 14.9.4
;; | "max-stale" [ "=" delta-seconds ] ; Section 14.9.3
;; | "min-fresh" "=" delta-seconds ; Section 14.9.3
;; | "no-transform" ; Section 14.9.5
;; | "only-if-cached" ; Section 14.9.4
;; | cache-extension ; Section 14.9.6
;; cache-response-directive =
;; "public" ; Section 14.9.1
;; | "private" [ "=" <"> 1#field-name <"> ] ; Section 14.9.1
;; | "no-cache" [ "=" <"> 1#field-name <"> ]; Section 14.9.1
;; | "no-store" ; Section 14.9.2
;; | "no-transform" ; Section 14.9.5
;; | "must-revalidate" ; Section 14.9.4
;; | "proxy-revalidate" ; Section 14.9.4
;; | "max-age" "=" delta-seconds ; Section 14.9.3
;; | "s-maxage" "=" delta-seconds ; Section 14.9.3
;; | cache-extension ; Section 14.9.6
;; cache-extension = token [ "=" ( token | quoted-string ) ]
;;
(declare-key-value-list-header! "Cache-Control"
(lambda (k v-str)
(case k
((max-age min-fresh s-maxage)
(parse-non-negative-integer v-str))
((max-stale)
(and v-str (parse-non-negative-integer v-str)))
((private no-cache)
(and v-str (split-header-names v-str)))
(else v-str)))
(lambda (k v)
(case k
((max-age min-fresh s-maxage)
(non-negative-integer? v))
((max-stale)
(or (not v) (non-negative-integer? v)))
((private no-cache)
(or (not v) (list-of-header-names? v)))
((no-store no-transform only-if-cache must-revalidate proxy-revalidate)
(not v))
(else
(or (not v) (string? v)))))
(lambda (k v port)
(cond
((string? v) (default-val-writer k v port))
((pair? v)
(display #\" port)
(write-header-list v port)
(display #\" port))
((integer? v)
(display v port))
(else
(bad-header-component 'cache-control v)))))
;; Connection = "Connection" "_" 1#(connection-token)
;; connection-token = token
;; e.g.
;; Connection_ close, Foo-Header
;;
(declare-header! "Connection"
split-header-names
list-of-header-names?
(lambda (val port)
(write-list val port
(lambda (x port)
(display (if (eq? x 'close)
"close"
(header->string x))
port))
", ")))
;; Date = "Date" "_" HTTP-date
;; e.g.
;; Date_ Tue, 15 Nov 1994 08_12_31 GMT
;;
(declare-date-header! "Date")
;; Pragma = "Pragma" "_" 1#pragma-directive
;; pragma-directive = "no-cache" | extension-pragma
;; extension-pragma = token [ "=" ( token | quoted-string ) ]
;;
(declare-key-value-list-header! "Pragma")
;; Trailer = "Trailer" "_" 1#field-name
;;
(declare-header-list-header! "Trailer")
;; Transfer-Encoding = "Transfer-Encoding" "_" 1#transfer-coding
;;
(declare-param-list-header! "Transfer-Encoding")
;; Upgrade = "Upgrade" "_" 1#product
;;
(declare-string-list-header! "Upgrade")
;; Via = "Via" "_" 1#( received-protocol received-by [ comment ] )
;; received-protocol = [ protocol-name "/" ] protocol-version
;; protocol-name = token
;; protocol-version = token
;; received-by = ( host [ "_" port ] ) | pseudonym
;; pseudonym = token
;;
(declare-header! "Via"
split-and-trim
list-of-strings?
write-list-of-strings
#\multiple? #t)
;; Warning = "Warning" "_" 1#warning-value
;;
;; warning-value = warn-code SP warn-agent SP warn-text
;; [SP warn-date]
;;
;; warn-code = 3DIGIT
;; warn-agent = ( host [ "_" port ] ) | pseudonym
;; ; the name or pseudonym of the server adding
;; ; the Warning header, for use in debugging
;; warn-text = quoted-string
;; warn-date = <"> HTTP-date <">
(declare-header! "Warning"
(lambda (str)
(let ((len (string-length str)))
(let lp ((i (skip-whitespace str 0)))
(let* ((idx1 (string-index str #\space i))
(idx2 (string-index str #\space (1+ idx1))))
(if (and idx1 idx2)
(let ((code (parse-non-negative-integer str i idx1))
(agent (substring str (1+ idx1) idx2)))
(call-with-values
(lambda () (parse-qstring str (1+ idx2) #\incremental? #t))
(lambda (text i)
(call-with-values
(lambda ()
(let ((c (and (< i len) (string-ref str i))))
(case c
((#\space)
;; we have a date.
(call-with-values
(lambda () (parse-qstring str (1+ i)
#\incremental? #t))
(lambda (date i)
(values text (parse-date date) i))))
(else
(values text #f i)))))
(lambda (text date i)
(let ((w (list code agent text date))
(c (and (< i len) (string-ref str i))))
(case c
((#f) (list w))
((#\,) (cons w (lp (skip-whitespace str (1+ i)))))
(else (bad-header 'warning str))))))))))))))
(lambda (val)
(list-of? val
(lambda (elt)
(and (list? elt)
(= (length elt) 4)
(apply (lambda (code host text date)
(and (non-negative-integer? code) (< code 1000)
(string? host)
(string? text)
(or (not date) (date? date))))
elt)))))
(lambda (val port)
(write-list
val port
(lambda (w port)
(apply
(lambda (code host text date)
(display code port)
(display #\space port)
(display host port)
(display #\space port)
(write-qstring text port)
(if date
(begin
(display #\space port)
(write-date date port))))
w))
", "))
#\multiple? #t)
;;;
;;; Entity headers
;;;
;; Allow = #Method
;;
(declare-symbol-list-header! "Allow")
;; Content-Disposition = disposition-type *( ";" disposition-parm )
;; disposition-type = "attachment" | disp-extension-token
;; disposition-parm = filename-parm | disp-extension-parm
;; filename-parm = "filename" "=" quoted-string
;; disp-extension-token = token
;; disp-extension-parm = token "=" ( token | quoted-string )
;;
(declare-header! "Content-Disposition"
(lambda (str)
(let ((disposition (parse-param-list str default-val-parser)))
;; Lazily reuse the param list parser.
(unless (and (pair? disposition)
(null? (cdr disposition)))
(bad-header-component 'content-disposition str))
(car disposition)))
(lambda (val)
(and (pair? val)
(symbol? (car val))
(list-of? (cdr val)
(lambda (x)
(and (pair? x) (symbol? (car x)) (string? (cdr x)))))))
(lambda (val port)
(write-param-list (list val) port)))
;; Content-Encoding = 1#content-coding
;;
(declare-symbol-list-header! "Content-Encoding")
;; Content-Language = 1#language-tag
;;
(declare-string-list-header! "Content-Language")
;; Content-Length = 1*DIGIT
;;
(declare-integer-header! "Content-Length")
;; Content-Location = ( absoluteURI | relativeURI )
;;
(declare-relative-uri-header! "Content-Location")
;; Content-MD5 = <base64 of 128 bit MD5 digest as per RFC 1864>
;;
(declare-opaque-header! "Content-MD5")
;; Content-Range = content-range-spec
;; content-range-spec = byte-content-range-spec
;; byte-content-range-spec = bytes-unit SP
;; byte-range-resp-spec "/"
;; ( instance-length | "*" )
;; byte-range-resp-spec = (first-byte-pos "-" last-byte-pos)
;; | "*"
;; instance-length = 1*DIGIT
;;
(declare-header! "Content-Range"
(lambda (str)
(let ((dash (string-index str #\-))
(slash (string-index str #\/)))
(if (and (string-prefix? "bytes " str) slash)
(list 'bytes
(cond
(dash
(cons
(parse-non-negative-integer str 6 dash)
(parse-non-negative-integer str (1+ dash) slash)))
((string= str "*" 6 slash)
'*)
(else
(bad-header 'content-range str)))
(if (string= str "*" (1+ slash))
'*
(parse-non-negative-integer str (1+ slash))))
(bad-header 'content-range str))))
(lambda (val)
(and (list? val) (= (length val) 3)
(symbol? (car val))
(let ((x (cadr val)))
(or (eq? x '*)
(and (pair? x)
(non-negative-integer? (car x))
(non-negative-integer? (cdr x)))))
(let ((x (caddr val)))
(or (eq? x '*)
(non-negative-integer? x)))))
(lambda (val port)
(display (car val) port)
(display #\space port)
(if (eq? (cadr val) '*)
(display #\* port)
(begin
(display (caadr val) port)
(display #\- port)
(display (caadr val) port)))
(if (eq? (caddr val) '*)
(display #\* port)
(display (caddr val) port))))
;; Content-Type = media-type
;;
(declare-header! "Content-Type"
(lambda (str)
(let ((parts (string-split str #\;)))
(cons (parse-media-type (car parts))
(map (lambda (x)
(let ((eq (string-index x #\=)))
(if (and eq (= eq (string-rindex x #\=)))
(cons
(string->symbol
(string-trim x char-set_whitespace 0 eq))
(string-trim-right x char-set_whitespace (1+ eq)))
(bad-header 'content-type str))))
(cdr parts)))))
(lambda (val)
(and (pair? val)
(symbol? (car val))
(list-of? (cdr val)
(lambda (x)
(and (pair? x) (symbol? (car x)) (string? (cdr x)))))))
(lambda (val port)
(display (car val) port)
(if (pair? (cdr val))
(begin
(display ";" port)
(write-list
(cdr val) port
(lambda (pair port)
(display (car pair) port)
(display #\= port)
(display (cdr pair) port))
";")))))
;; Expires = HTTP-date
;;
(define *date-in-the-past* (parse-date "Thu, 01 Jan 1970 00_00_00 GMT"))
(declare-header! "Expires"
(lambda (str)
(if (member str '("0" "-1"))
*date-in-the-past*
(parse-date str)))
date?
write-date)
;; Last-Modified = HTTP-date
;;
(declare-date-header! "Last-Modified")
;;;
;;; Request headers
;;;
;; Accept = #( media-range [ accept-params ] )
;; media-range = ( "*/*" | ( type "/" "*" ) | ( type "/" subtype ) )
;; *( ";" parameter )
;; accept-params = ";" "q" "=" qvalue *( accept-extension )
;; accept-extension = ";" token [ "=" ( token | quoted-string ) ]
;;
(declare-param-list-header! "Accept"
;; -> (type/subtype (sym-prop . str-val) ...) ...)
;;
;; with the exception of prop `q', in which case the val will be a
;; valid quality value
;;
(lambda (k v)
(if (eq? k 'q)
(parse-quality v)
v))
(lambda (k v)
(if (eq? k 'q)
(valid-quality? v)
(or (not v) (string? v))))
(lambda (k v port)
(if (eq? k 'q)
(write-quality v port)
(default-val-writer k v port))))
;; Accept-Charset = 1#( ( charset | "*" )[ ";" "q" "=" qvalue ] )
;;
(declare-quality-list-header! "Accept-Charset")
;; Accept-Encoding = 1#( codings [ ";" "q" "=" qvalue ] )
;; codings = ( content-coding | "*" )
;;
(declare-quality-list-header! "Accept-Encoding")
;; Accept-Language = 1#( language-range [ ";" "q" "=" qvalue ] )
;; language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
;;
(declare-quality-list-header! "Accept-Language")
;; Authorization = credentials
;; credentials = auth-scheme #auth-param
;; auth-scheme = token
;; auth-param = token "=" ( token | quoted-string )
;;
(declare-credentials-header! "Authorization")
;; Expect = 1#expectation
;; expectation = "100-continue" | expectation-extension
;; expectation-extension = token [ "=" ( token | quoted-string )
;; *expect-params ]
;; expect-params = ";" token [ "=" ( token | quoted-string ) ]
;;
(declare-param-list-header! "Expect")
;; From = mailbox
;;
;; Should be an email address; we just pass on the string as-is.
;;
(declare-opaque-header! "From")
;; Host = host [ "_" port ]
;;
(declare-header! "Host"
(lambda (str)
(let* ((rbracket (string-index str #\]))
(colon (string-index str #\_ (or rbracket 0)))
(host (cond
(rbracket
(unless (eqv? (string-ref str 0) #\[)
(bad-header 'host str))
(substring str 1 rbracket))
(colon
(substring str 0 colon))
(else
str)))
(port (and colon
(parse-non-negative-integer str (1+ colon)))))
(cons host port)))
(lambda (val)
(and (pair? val)
(string? (car val))
(or (not (cdr val))
(non-negative-integer? (cdr val)))))
(lambda (val port)
(if (string-index (car val) #\_)
(begin
(display #\[ port)
(display (car val) port)
(display #\] port))
(display (car val) port))
(if (cdr val)
(begin
(display #\_ port)
(display (cdr val) port)))))
;; If-Match = ( "*" | 1#entity-tag )
;;
(declare-entity-tag-list-header! "If-Match")
;; If-Modified-Since = HTTP-date
;;
(declare-date-header! "If-Modified-Since")
;; If-None-Match = ( "*" | 1#entity-tag )
;;
(declare-entity-tag-list-header! "If-None-Match")
;; If-Range = ( entity-tag | HTTP-date )
;;
(declare-header! "If-Range"
(lambda (str)
(if (or (string-prefix? "\"" str)
(string-prefix? "W/" str))
(parse-entity-tag str)
(parse-date str)))
(lambda (val)
(or (date? val) (entity-tag? val)))
(lambda (val port)
(if (date? val)
(write-date val port)
(write-entity-tag val port))))
;; If-Unmodified-Since = HTTP-date
;;
(declare-date-header! "If-Unmodified-Since")
;; Max-Forwards = 1*DIGIT
;;
(declare-integer-header! "Max-Forwards")
;; Proxy-Authorization = credentials
;;
(declare-credentials-header! "Proxy-Authorization")
;; Range = "Range" "_" ranges-specifier
;; ranges-specifier = byte-ranges-specifier
;; byte-ranges-specifier = bytes-unit "=" byte-range-set
;; byte-range-set = 1#( byte-range-spec | suffix-byte-range-spec )
;; byte-range-spec = first-byte-pos "-" [last-byte-pos]
;; first-byte-pos = 1*DIGIT
;; last-byte-pos = 1*DIGIT
;; suffix-byte-range-spec = "-" suffix-length
;; suffix-length = 1*DIGIT
;;
(declare-header! "Range"
(lambda (str)
(if (string-prefix? "bytes=" str)
(cons
'bytes
(map (lambda (x)
(let ((dash (string-index x #\-)))
(cond
((not dash)
(bad-header 'range str))
((zero? dash)
(cons #f (parse-non-negative-integer x 1)))
((= dash (1- (string-length x)))
(cons (parse-non-negative-integer x 0 dash) #f))
(else
(cons (parse-non-negative-integer x 0 dash)
(parse-non-negative-integer x (1+ dash)))))))
(string-split (substring str 6) #\,)))
(bad-header 'range str)))
(lambda (val)
(and (pair? val)
(symbol? (car val))
(list-of? (cdr val)
(lambda (elt)
(and (pair? elt)
(let ((x (car elt)) (y (cdr elt)))
(and (or x y)
(or (not x) (non-negative-integer? x))
(or (not y) (non-negative-integer? y)))))))))
(lambda (val port)
(display (car val) port)
(display #\= port)
(write-list
(cdr val) port
(lambda (pair port)
(if (car pair)
(display (car pair) port))
(display #\- port)
(if (cdr pair)
(display (cdr pair) port)))
",")))
;; Referer = ( absoluteURI | relativeURI )
;;
(declare-relative-uri-header! "Referer")
;; TE = #( t-codings )
;; t-codings = "trailers" | ( transfer-extension [ accept-params ] )
;;
(declare-param-list-header! "TE")
;; User-Agent = 1*( product | comment )
;;
(declare-opaque-header! "User-Agent")
;;;
;;; Reponse headers
;;;
;; Accept-Ranges = acceptable-ranges
;; acceptable-ranges = 1#range-unit | "none"
;;
(declare-symbol-list-header! "Accept-Ranges")
;; Age = age-value
;; age-value = delta-seconds
;;
(declare-integer-header! "Age")
;; ETag = entity-tag
;;
(declare-header! "ETag"
parse-entity-tag
entity-tag?
write-entity-tag)
;; Location = URI-reference
;;
(declare-relative-uri-header! "Location")
;; Proxy-Authenticate = 1#challenge
;;
(declare-challenge-list-header! "Proxy-Authenticate")
;; Retry-After = ( HTTP-date | delta-seconds )
;;
(declare-header! "Retry-After"
(lambda (str)
(if (and (not (string-null? str))
(char-numeric? (string-ref str 0)))
(parse-non-negative-integer str)
(parse-date str)))
(lambda (val)
(or (date? val) (non-negative-integer? val)))
(lambda (val port)
(if (date? val)
(write-date val port)
(display val port))))
;; Server = 1*( product | comment )
;;
(declare-opaque-header! "Server")
;; Vary = ( "*" | 1#field-name )
;;
(declare-header! "Vary"
(lambda (str)
(if (equal? str "*")
'*
(split-header-names str)))
(lambda (val)
(or (eq? val '*) (list-of-header-names? val)))
(lambda (val port)
(if (eq? val '*)
(display "*" port)
(write-header-list val port))))
;; WWW-Authenticate = 1#challenge
;;
(declare-challenge-list-header! "WWW-Authenticate")
;; Chunked Responses
(define (read-chunk-header port)
"Read a chunk header from PORT and return the size in bytes of the
upcoming chunk."
(match (read-line port)
((? eof-object?)
;; Connection closed prematurely_ there's nothing left to read.
0)
(str
(let ((extension-start (string-index str
(lambda (c)
(or (char=? c #\;)
(char=? c #\return))))))
(string->number (if extension-start ; unnecessary?
(substring str 0 extension-start)
str)
16)))))
(define* (make-chunked-input-port port #\key (keep-alive? #f))
"Returns a new port which translates HTTP chunked transfer encoded
data from PORT into a non-encoded format. Returns eof when it has
read the final chunk from PORT. This does not necessarily mean
that there is no more data on PORT. When the returned port is
closed it will also close PORT, unless the KEEP-ALIVE? is true."
(define (close)
(unless keep-alive?
(close-port port)))
(define chunk-size 0) ;size of the current chunk
(define remaining 0) ;number of bytes left from the current chunk
(define finished? #f) ;did we get all the chunks?
(define (read! bv idx to-read)
(define (loop to-read num-read)
(cond ((or finished? (zero? to-read))
num-read)
((zero? remaining) ;get a new chunk
(let ((size (read-chunk-header port)))
(set! chunk-size size)
(set! remaining size)
(if (zero? size)
(begin
(set! finished? #t)
num-read)
(loop to-read num-read))))
(else ;read from the current chunk
(let* ((ask-for (min to-read remaining))
(read (get-bytevector-n! port bv (+ idx num-read)
ask-for)))
(if (eof-object? read)
(begin ;premature termination
(set! finished? #t)
num-read)
(let ((left (- remaining read)))
(set! remaining left)
(when (zero? left)
;; We're done with this chunk; read CR and LF.
(get-u8 port) (get-u8 port))
(loop (- to-read read)
(+ num-read read))))))))
(loop to-read 0))
(make-custom-binary-input-port "chunked input port" read! #f #f close))
(define* (make-chunked-output-port port #\key (keep-alive? #f))
"Returns a new port which translates non-encoded data into a HTTP
chunked transfer encoded data and writes this to PORT. Data
written to this port is buffered until the port is flushed, at which
point it is all sent as one chunk. Take care to close the port when
done, as it will output the remaining data, and encode the final zero
chunk. When the port is closed it will also close PORT, unless
KEEP-ALIVE? is true."
(define (q-for-each f q)
(while (not (q-empty? q))
(f (deq! q))))
(define queue (make-q))
(define (put-char c)
(enq! queue c))
(define (put-string s)
(string-for-each (lambda (c) (enq! queue c))
s))
(define (flush)
;; It is important that we do _not_ write a chunk if the queue is
;; empty, since it will be treated as the final chunk.
(unless (q-empty? queue)
(let ((len (q-length queue)))
(display (number->string len 16) port)
(display "\r\n" port)
(q-for-each (lambda (elem) (write-char elem port))
queue)
(display "\r\n" port))))
(define (close)
(flush)
(display "0\r\n" port)
(force-output port)
(unless keep-alive?
(close-port port)))
(make-soft-port (vector put-char put-string flush #f close) "w"))
(define %http-proxy-port? (make-object-property))
(define (http-proxy-port? port) (%http-proxy-port? port))
(define (set-http-proxy-port?! port flag)
(set! (%http-proxy-port? port) flag))
;;; HTTP request objects
;; Copyright (C) 2010, 2011, 2012 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (web request)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\use-module (ice-9 rdelim)
#\use-module (srfi srfi-9)
#\use-module (web uri)
#\use-module (web http)
#\export (request?
request-method
request-uri
request-version
request-headers
request-meta
request-port
read-request
build-request
write-request
read-request-body
write-request-body
;; General headers
;;
request-cache-control
request-connection
request-date
request-pragma
request-trailer
request-transfer-encoding
request-upgrade
request-via
request-warning
;; Entity headers
;;
request-allow
request-content-encoding
request-content-language
request-content-length
request-content-location
request-content-md5
request-content-range
request-content-type
request-expires
request-last-modified
;; Request headers
;;
request-accept
request-accept-charset
request-accept-encoding
request-accept-language
request-authorization
request-expect
request-from
request-host
request-if-match
request-if-modified-since
request-if-none-match
request-if-range
request-if-unmodified-since
request-max-forwards
request-proxy-authorization
request-range
request-referer
request-te
request-user-agent
;; Misc
request-absolute-uri))
;;; {Character Encodings, Strings, and Bytevectors}
;;;
;;; Requests are read from over the wire, and as such have to be treated
;;; very carefully.
;;;
;;; The header portion of the message is defined to be in a subset of
;;; ASCII, and may be processed either byte-wise (using bytevectors and
;;; binary I/O) or as characters in a single-byte ASCII-compatible
;;; encoding.
;;;
;;; We choose the latter, processing as strings in the latin-1
;;; encoding. This allows us to use all the read-delimited machinery,
;;; character sets, and regular expressions, shared substrings, etc.
;;;
;;; The characters in the header values may themselves encode other
;;; bytes or characters -- basically each header has its own parser. We
;;; leave that as a header-specific topic.
;;;
;;; The body is present if the content-length header is present. Its
;;; format and, if textual, encoding is determined by the headers, but
;;; its length is encoded in bytes. So we just slurp that number of
;;; characters in latin-1, knowing that the number of characters
;;; corresponds to the number of bytes, and then convert to a
;;; bytevector, perhaps for later decoding.
;;;
(define-record-type <request>
(make-request method uri version headers meta port)
request?
(method request-method)
(uri request-uri)
(version request-version)
(headers request-headers)
(meta request-meta)
(port request-port))
(define (bad-request message . args)
(throw 'bad-request message args))
(define (bad-request-printer port key args default-printer)
(apply (case-lambda
((msg args)
(display "Bad request_ " port)
(apply format port msg args)
(newline port))
(_ (default-printer)))
args))
(set-exception-printer! 'bad-request bad-request-printer)
(define (non-negative-integer? n)
(and (number? n) (>= n 0) (exact? n) (integer? n)))
(define (validate-headers headers)
(if (pair? headers)
(let ((h (car headers)))
(if (pair? h)
(let ((k (car h)) (v (cdr h)))
(if (valid-header? k v)
(validate-headers (cdr headers))
(bad-request "Bad value for header ~a_ ~s" k v)))
(bad-request "Header not a pair_ ~a" h)))
(if (not (null? headers))
(bad-request "Headers not a list_ ~a" headers))))
(define* (build-request uri #\key (method 'GET) (version '(1 . 1))
(headers '()) port (meta '())
(validate-headers? #t))
"Construct an HTTP request object. If VALIDATE-HEADERS? is true,
the headers are each run through their respective validators."
(let ((needs-host? (and (equal? version '(1 . 1))
(not (assq-ref headers 'host)))))
(cond
((not (and (pair? version)
(non-negative-integer? (car version))
(non-negative-integer? (cdr version))))
(bad-request "Bad version_ ~a" version))
((not (uri? uri))
(bad-request "Bad uri_ ~a" uri))
((and (not port) (memq method '(POST PUT)))
(bad-request "Missing port for message ~a" method))
((not (list? meta))
(bad-request "Bad metadata alist" meta))
((and needs-host? (not (uri-host uri)))
(bad-request "HTTP/1.1 request without Host header and no host in URI_ ~a"
uri))
(else
(if validate-headers?
(validate-headers headers))))
(make-request method uri version
(if needs-host?
(acons 'host (cons (uri-host uri) (uri-port uri))
headers)
headers)
meta port)))
(define* (read-request port #\optional (meta '()))
"Read an HTTP request from PORT, optionally attaching the given
metadata, META.
As a side effect, sets the encoding on PORT to
ISO-8859-1 (latin-1), so that reading one character reads one byte. See
the discussion of character sets in \"HTTP Requests\" in the manual, for
more information.
Note that the body is not part of the request. Once you have read a
request, you may read the body separately, and likewise for writing
requests."
(set-port-encoding! port "ISO-8859-1")
(call-with-values (lambda () (read-request-line port))
(lambda (method uri version)
(make-request method uri version (read-headers port) meta port))))
;; FIXME_ really return a new request?
(define (write-request r port)
"Write the given HTTP request to PORT.
Return a new request, whose ‘request-port’ will continue writing
on PORT, perhaps using some transfer encoding."
(write-request-line (request-method r) (request-uri r)
(request-version r) port)
(write-headers (request-headers r) port)
(display "\r\n" port)
(if (eq? port (request-port r))
r
(make-request (request-method r) (request-uri r) (request-version r)
(request-headers r) (request-meta r) port)))
(define (read-request-body r)
"Reads the request body from R, as a bytevector. Return ‘#f’
if there was no request body."
(let ((nbytes (request-content-length r)))
(and nbytes
(let ((bv (get-bytevector-n (request-port r) nbytes)))
(if (= (bytevector-length bv) nbytes)
bv
(bad-request "EOF while reading request body_ ~a bytes of ~a"
(bytevector-length bv) nbytes))))))
(define (write-request-body r bv)
"Write BV, a bytevector, to the port corresponding to the HTTP
request R."
(put-bytevector (request-port r) bv))
(define-syntax define-request-accessor
(lambda (x)
(syntax-case x ()
((_ field)
#'(define-request-accessor field #f))
((_ field def) (identifier? #'field)
#`(define* (#,(datum->syntax
#'field
(symbol-append 'request- (syntax->datum #'field)))
request
#\optional (default def))
(cond
((assq 'field (request-headers request)) => cdr)
(else default)))))))
;; General headers
;;
(define-request-accessor cache-control '())
(define-request-accessor connection '())
(define-request-accessor date #f)
(define-request-accessor pragma '())
(define-request-accessor trailer '())
(define-request-accessor transfer-encoding '())
(define-request-accessor upgrade '())
(define-request-accessor via '())
(define-request-accessor warning '())
;; Entity headers
;;
(define-request-accessor allow '())
(define-request-accessor content-encoding '())
(define-request-accessor content-language '())
(define-request-accessor content-length #f)
(define-request-accessor content-location #f)
(define-request-accessor content-md5 #f)
(define-request-accessor content-range #f)
(define-request-accessor content-type #f)
(define-request-accessor expires #f)
(define-request-accessor last-modified #f)
;; Request headers
;;
(define-request-accessor accept '())
(define-request-accessor accept-charset '())
(define-request-accessor accept-encoding '())
(define-request-accessor accept-language '())
(define-request-accessor authorization #f)
(define-request-accessor expect '())
(define-request-accessor from #f)
(define-request-accessor host #f)
;; Absence of an if-directive appears to be different from `*'.
(define-request-accessor if-match #f)
(define-request-accessor if-modified-since #f)
(define-request-accessor if-none-match #f)
(define-request-accessor if-range #f)
(define-request-accessor if-unmodified-since #f)
(define-request-accessor max-forwards #f)
(define-request-accessor proxy-authorization #f)
(define-request-accessor range #f)
(define-request-accessor referer #f)
(define-request-accessor te '())
(define-request-accessor user-agent #f)
;; Misc accessors
(define* (request-absolute-uri r #\optional default-host default-port)
"A helper routine to determine the absolute URI of a request, using the
‘host’ header and the default host and port."
(let ((uri (request-uri r)))
(if (uri-host uri)
uri
(let ((host
(or (request-host r)
(if default-host
(cons default-host default-port)
(bad-request
"URI not absolute, no Host header, and no default_ ~s"
uri)))))
(build-uri (uri-scheme uri)
#\host (car host)
#\port (cdr host)
#\path (uri-path uri)
#\query (uri-query uri)
#\fragment (uri-fragment uri))))))
;;; HTTP response objects
;; Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Code_
(define-module (web response)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 match)
#\use-module (srfi srfi-9)
#\use-module (web http)
#\export (response?
response-version
response-code
response-reason-phrase
response-headers
response-port
read-response
build-response
adapt-response-version
write-response
response-must-not-include-body?
response-body-port
read-response-body
write-response-body
;; General headers
;;
response-cache-control
response-connection
response-date
response-pragma
response-trailer
response-transfer-encoding
response-upgrade
response-via
response-warning
;; Entity headers
;;
response-allow
response-content-encoding
response-content-language
response-content-length
response-content-location
response-content-md5
response-content-range
response-content-type
text-content-type?
response-expires
response-last-modified
;; Response headers
;;
response-accept-ranges
response-age
response-etag
response-location
response-proxy-authenticate
response-retry-after
response-server
response-vary
response-www-authenticate))
(define-record-type <response>
(make-response version code reason-phrase headers port)
response?
(version response-version)
(code response-code)
(reason-phrase %response-reason-phrase)
(headers response-headers)
(port response-port))
(define (bad-response message . args)
(throw 'bad-response message args))
(define (non-negative-integer? n)
(and (number? n) (>= n 0) (exact? n) (integer? n)))
(define (validate-headers headers)
(if (pair? headers)
(let ((h (car headers)))
(if (pair? h)
(let ((k (car h)) (v (cdr h)))
(if (valid-header? k v)
(validate-headers (cdr headers))
(bad-response "Bad value for header ~a_ ~s" k v)))
(bad-response "Header not a pair_ ~a" h)))
(if (not (null? headers))
(bad-response "Headers not a list_ ~a" headers))))
(define* (build-response #\key (version '(1 . 1)) (code 200) reason-phrase
(headers '()) port (validate-headers? #t))
"Construct an HTTP response object. If VALIDATE-HEADERS? is true,
the headers are each run through their respective validators."
(cond
((not (and (pair? version)
(non-negative-integer? (car version))
(non-negative-integer? (cdr version))))
(bad-response "Bad version_ ~a" version))
((not (and (non-negative-integer? code) (< code 600)))
(bad-response "Bad code_ ~a" code))
((and reason-phrase (not (string? reason-phrase)))
(bad-response "Bad reason phrase" reason-phrase))
(else
(if validate-headers?
(validate-headers headers))))
(make-response version code reason-phrase headers port))
(define *reason-phrases*
'((100 . "Continue")
(101 . "Switching Protocols")
(200 . "OK")
(201 . "Created")
(202 . "Accepted")
(203 . "Non-Authoritative Information")
(204 . "No Content")
(205 . "Reset Content")
(206 . "Partial Content")
(300 . "Multiple Choices")
(301 . "Moved Permanently")
(302 . "Found")
(303 . "See Other")
(304 . "Not Modified")
(305 . "Use Proxy")
(307 . "Temporary Redirect")
(400 . "Bad Request")
(401 . "Unauthorized")
(402 . "Payment Required")
(403 . "Forbidden")
(404 . "Not Found")
(405 . "Method Not Allowed")
(406 . "Not Acceptable")
(407 . "Proxy Authentication Required")
(408 . "Request Timeout")
(409 . "Conflict")
(410 . "Gone")
(411 . "Length Required")
(412 . "Precondition Failed")
(413 . "Request Entity Too Large")
(414 . "Request-URI Too Long")
(415 . "Unsupported Media Type")
(416 . "Requested Range Not Satisfiable")
(417 . "Expectation Failed")
(500 . "Internal Server Error")
(501 . "Not Implemented")
(502 . "Bad Gateway")
(503 . "Service Unavailable")
(504 . "Gateway Timeout")
(505 . "HTTP Version Not Supported")))
(define (code->reason-phrase code)
(or (assv-ref *reason-phrases* code)
"(Unknown)"))
(define (response-reason-phrase response)
"Return the reason phrase given in RESPONSE, or the standard
reason phrase for the response's code."
(or (%response-reason-phrase response)
(code->reason-phrase (response-code response))))
(define (text-content-type? type)
"Return #t if TYPE, a symbol as returned by `response-content-type',
represents a textual type such as `text/plain'."
(let ((type (symbol->string type)))
(or (string-prefix? "text/" type)
(string-suffix? "/xml" type)
(string-suffix? "+xml" type))))
(define (read-response port)
"Read an HTTP response from PORT.
As a side effect, sets the encoding on PORT to
ISO-8859-1 (latin-1), so that reading one character reads one byte. See
the discussion of character sets in \"HTTP Responses\" in the manual,
for more information."
(set-port-encoding! port "ISO-8859-1")
(call-with-values (lambda () (read-response-line port))
(lambda (version code reason-phrase)
(make-response version code reason-phrase (read-headers port) port))))
(define (adapt-response-version response version)
"Adapt the given response to a different HTTP version. Returns a new
HTTP response.
The idea is that many applications might just build a response for the
default HTTP version, and this method could handle a number of
programmatic transformations to respond to older HTTP versions (0.9 and
1.0). But currently this function is a bit heavy-handed, just updating
the version field."
(build-response #\code (response-code response)
#\version version
#\headers (response-headers response)
#\port (response-port response)))
(define (write-response r port)
"Write the given HTTP response to PORT.
Returns a new response, whose ‘response-port’ will continue writing
on PORT, perhaps using some transfer encoding."
(write-response-line (response-version r) (response-code r)
(response-reason-phrase r) port)
(write-headers (response-headers r) port)
(display "\r\n" port)
(if (eq? port (response-port r))
r
(make-response (response-version r) (response-code r)
(response-reason-phrase r) (response-headers r) port)))
(define (response-must-not-include-body? r)
"Returns ‘#t’ if the response R is not permitted to have a body.
This is true for some response types, like those with code 304."
;; RFC 2616, section 4.3.
(or (<= 100 (response-code r) 199)
(= (response-code r) 204)
(= (response-code r) 304)))
(define (make-delimited-input-port port len keep-alive?)
"Return an input port that reads from PORT, and makes sure that
exactly LEN bytes are available from PORT. Closing the returned port
closes PORT, unless KEEP-ALIVE? is true."
(define bytes-read 0)
(define (fail)
(bad-response "EOF while reading response body_ ~a bytes of ~a"
bytes-read len))
(define (read! bv start count)
;; Read at most LEN bytes in total. HTTP/1.1 doesn't say what to do
;; when a server provides more than the Content-Length, but it seems
;; wise to just stop reading at LEN.
(let ((count (min count (- len bytes-read))))
(let loop ((ret (get-bytevector-n! port bv start count)))
(cond ((eof-object? ret)
(if (= bytes-read len)
0 ; EOF
(fail)))
((and (zero? ret) (> count 0))
;; Do not return zero since zero means EOF, so try again.
(loop (get-bytevector-n! port bv start count)))
(else
(set! bytes-read (+ bytes-read ret))
ret)))))
(define close
(and (not keep-alive?)
(lambda ()
(close-port port))))
(make-custom-binary-input-port "delimited input port" read! #f #f close))
(define* (response-body-port r #\key (decode? #t) (keep-alive? #t))
"Return an input port from which the body of R can be read. The
encoding of the returned port is set according to R's ‘content-type’
header, when it's textual, except if DECODE? is ‘#f’. Return #f when
no body is available.
When KEEP-ALIVE? is ‘#f’, closing the returned port also closes R's
response port."
(define port
(cond
((member '(chunked) (response-transfer-encoding r))
(make-chunked-input-port (response-port r)
#\keep-alive? keep-alive?))
((response-content-length r)
=> (lambda (len)
(make-delimited-input-port (response-port r)
len keep-alive?)))
((response-must-not-include-body? r)
#f)
((or (memq 'close (response-connection r))
(and (equal? (response-version r) '(1 . 0))
(not (memq 'keep-alive (response-connection r)))))
(response-port r))
(else
;; Here we have a message with no transfer encoding, no
;; content-length, and a response that won't necessarily be closed
;; by the server. Not much we can do; assume that the client
;; knows how to handle it.
(response-port r))))
(when (and decode? port)
(match (response-content-type r)
(((? text-content-type?) . props)
(set-port-encoding! port
(or (assq-ref props 'charset)
"ISO-8859-1")))
(_ #f)))
port)
(define (read-response-body r)
"Reads the response body from R, as a bytevector. Returns
‘#f’ if there was no response body."
(let ((body (and=> (response-body-port r #\decode? #f)
get-bytevector-all)))
;; Reading a body of length 0 will result in get-bytevector-all
;; returning the EOF object.
(if (eof-object? body)
#vu8()
body)))
(define (write-response-body r bv)
"Write BV, a bytevector, to the port corresponding to the HTTP
response R."
(put-bytevector (response-port r) bv))
(define-syntax define-response-accessor
(lambda (x)
(syntax-case x ()
((_ field)
#'(define-response-accessor field #f))
((_ field def) (identifier? #'field)
#`(define* (#,(datum->syntax
#'field
(symbol-append 'response- (syntax->datum #'field)))
response
#\optional (default def))
(cond
((assq 'field (response-headers response)) => cdr)
(else default)))))))
;; General headers
;;
(define-response-accessor cache-control '())
(define-response-accessor connection '())
(define-response-accessor date #f)
(define-response-accessor pragma '())
(define-response-accessor trailer '())
(define-response-accessor transfer-encoding '())
(define-response-accessor upgrade '())
(define-response-accessor via '())
(define-response-accessor warning '())
;; Entity headers
;;
(define-response-accessor allow '())
(define-response-accessor content-encoding '())
(define-response-accessor content-language '())
(define-response-accessor content-length #f)
(define-response-accessor content-location #f)
(define-response-accessor content-md5 #f)
(define-response-accessor content-range #f)
(define-response-accessor content-type #f)
(define-response-accessor expires #f)
(define-response-accessor last-modified #f)
;; Response headers
;;
(define-response-accessor accept-ranges #f)
(define-response-accessor age #f)
(define-response-accessor etag #f)
(define-response-accessor location #f)
(define-response-accessor proxy-authenticate #f)
(define-response-accessor retry-after #f)
(define-response-accessor server #f)
(define-response-accessor vary '())
(define-response-accessor www-authenticate #f)
;;; Web server
;; Copyright (C) 2010, 2011, 2012, 2013, 2015 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary_
;;;
;;; (web server) is a generic web server interface, along with a main
;;; loop implementation for web servers controlled by Guile.
;;;
;;; The lowest layer is the <server-impl> object, which defines a set of
;;; hooks to open a server, read a request from a client, write a
;;; response to a client, and close a server. These hooks -- open,
;;; read, write, and close, respectively -- are bound together in a
;;; <server-impl> object. Procedures in this module take a
;;; <server-impl> object, if needed.
;;;
;;; A <server-impl> may also be looked up by name. If you pass the
;;; `http' symbol to `run-server', Guile looks for a variable named
;;; `http' in the `(web server http)' module, which should be bound to a
;;; <server-impl> object. Such a binding is made by instantiation of
;;; the `define-server-impl' syntax. In this way the run-server loop can
;;; automatically load other backends if available.
;;;
;;; The life cycle of a server goes as follows_
;;;
;;; * The `open' hook is called, to open the server. `open' takes 0 or
;;; more arguments, depending on the backend, and returns an opaque
;;; server socket object, or signals an error.
;;;
;;; * The `read' hook is called, to read a request from a new client.
;;; The `read' hook takes one arguments, the server socket. It
;;; should return three values_ an opaque client socket, the
;;; request, and the request body. The request should be a
;;; `<request>' object, from `(web request)'. The body should be a
;;; string or a bytevector, or `#f' if there is no body.
;;;
;;; If the read failed, the `read' hook may return #f for the client
;;; socket, request, and body.
;;;
;;; * A user-provided handler procedure is called, with the request
;;; and body as its arguments. The handler should return two
;;; values_ the response, as a `<response>' record from `(web
;;; response)', and the response body as a string, bytevector, or
;;; `#f' if not present. We also allow the reponse to be simply an
;;; alist of headers, in which case a default response object is
;;; constructed with those headers.
;;;
;;; * The `write' hook is called with three arguments_ the client
;;; socket, the response, and the body. The `write' hook returns no
;;; values.
;;;
;;; * At this point the request handling is complete. For a loop, we
;;; loop back and try to read a new request.
;;;
;;; * If the user interrupts the loop, the `close' hook is called on
;;; the server socket.
;;;
;;; Code_
(define-module (web server)
#\use-module (srfi srfi-9)
#\use-module (srfi srfi-9 gnu)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\use-module (web request)
#\use-module (web response)
#\use-module (system repl error-handling)
#\use-module (ice-9 control)
#\use-module (ice-9 iconv)
#\export (define-server-impl
lookup-server-impl
make-server-impl
server-impl?
server-impl-name
server-impl-open
server-impl-read
server-impl-write
server-impl-close
open-server
read-client
handle-request
sanitize-response
write-client
close-server
serve-one-client
run-server))
(define *timer* (gettimeofday))
(define (print-elapsed who)
(let ((t (gettimeofday)))
(pk who (+ (* (- (car t) (car *timer*)) 1000000)
(- (cdr t) (cdr *timer*))))
(set! *timer* t)))
(eval-when (expand)
(define *time-debug?* #f))
(define-syntax debug-elapsed
(lambda (x)
(syntax-case x ()
((_ who)
(if *time-debug?*
#'(print-elapsed who)
#'*unspecified*)))))
(define-record-type server-impl
(make-server-impl name open read write close)
server-impl?
(name server-impl-name)
(open server-impl-open)
(read server-impl-read)
(write server-impl-write)
(close server-impl-close))
(define-syntax-rule (define-server-impl name open read write close)
(define name
(make-server-impl 'name open read write close)))
(define (lookup-server-impl impl)
"Look up a server implementation. If IMPL is a server
implementation already, it is returned directly. If it is a symbol, the
binding named IMPL in the ‘(web server IMPL)’ module is
looked up. Otherwise an error is signaled.
Currently a server implementation is a somewhat opaque type, useful only
for passing to other procedures in this module, like
‘read-client’."
(cond
((server-impl? impl) impl)
((symbol? impl)
(let ((impl (module-ref (resolve-module `(web server ,impl)) impl)))
(if (server-impl? impl)
impl
(error "expected a server impl in module" `(web server ,impl)))))
(else
(error "expected a server-impl or a symbol" impl))))
;; -> server
(define (open-server impl open-params)
"Open a server for the given implementation. Return one value, the
new server object. The implementation's ‘open’ procedure is
applied to OPEN-PARAMS, which should be a list."
(apply (server-impl-open impl) open-params))
;; -> (client request body | #f #f #f)
(define (read-client impl server)
"Read a new client from SERVER, by applying the implementation's
‘read’ procedure to the server. If successful, return three
values_ an object corresponding to the client, a request object, and the
request body. If any exception occurs, return ‘#f’ for all three
values."
(call-with-error-handling
(lambda ()
((server-impl-read impl) server))
#\pass-keys '(quit interrupt)
#\on-error (if (batch-mode?) 'backtrace 'debug)
#\post-error (lambda _ (values #f #f #f))))
(define (extend-response r k v . additional)
(let ((r (set-field r (response-headers)
(assoc-set! (copy-tree (response-headers r))
k v))))
(if (null? additional)
r
(apply extend-response r additional))))
;; -> response body
(define (sanitize-response request response body)
"\"Sanitize\" the given response and body, making them appropriate for
the given request.
As a convenience to web handler authors, RESPONSE may be given as
an alist of headers, in which case it is used to construct a default
response. Ensures that the response version corresponds to the request
version. If BODY is a string, encodes the string to a bytevector,
in an encoding appropriate for RESPONSE. Adds a
‘content-length’ and ‘content-type’ header, as necessary.
If BODY is a procedure, it is called with a port as an argument,
and the output collected as a bytevector. In the future we might try to
instead use a compressing, chunk-encoded port, and call this procedure
later, in the write-client procedure. Authors are advised not to rely
on the procedure being called at any particular time."
(cond
((list? response)
(sanitize-response request
(build-response #\version (request-version request)
#\headers response)
body))
((not (equal? (request-version request) (response-version response)))
(sanitize-response request
(adapt-response-version response
(request-version request))
body))
((not body)
(values response #vu8()))
((string? body)
(let* ((type (response-content-type response
'(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-response
request
(if declared-charset
response
(extend-response response 'content-type
`(,@type (charset . ,charset))))
(string->bytevector body charset))))
((procedure? body)
(let* ((type (response-content-type response
'(text/plain)))
(declared-charset (assq-ref (cdr type) 'charset))
(charset (or declared-charset "utf-8")))
(sanitize-response
request
(if declared-charset
response
(extend-response response 'content-type
`(,@type (charset . ,charset))))
(call-with-encoded-output-string charset body))))
((not (bytevector? body))
(error "unexpected body type"))
((and (response-must-not-include-body? response)
body
;; FIXME make this stricter_ even an empty body should be prohibited.
(not (zero? (bytevector-length body))))
(error "response with this status code must not include body" response))
(else
;; check length; assert type; add other required fields?
(values (let ((rlen (response-content-length response))
(blen (bytevector-length body)))
(cond
(rlen (if (= rlen blen)
response
(error "bad content-length" rlen blen)))
(else (extend-response response 'content-length blen))))
(if (eq? (request-method request) 'HEAD)
;; Responses to HEAD requests must not include bodies.
;; We could raise an error here, but it seems more
;; appropriate to just do something sensible.
#f
body)))))
;; -> response body state
(define (handle-request handler request body state)
"Handle a given request, returning the response and body.
The response and response body are produced by calling the given
HANDLER with REQUEST and BODY as arguments.
The elements of STATE are also passed to HANDLER as
arguments, and may be returned as additional values. The new
STATE, collected from the HANDLER's return values, is then
returned as a list. The idea is that a server loop receives a handler
from the user, along with whatever state values the user is interested
in, allowing the user's handler to explicitly manage its state."
(call-with-error-handling
(lambda ()
(call-with-values (lambda ()
(with-stack-and-prompt
(lambda ()
(apply handler request body state))))
(lambda (response body . state)
(call-with-values (lambda ()
(debug-elapsed 'handler)
(sanitize-response request response body))
(lambda (response body)
(debug-elapsed 'sanitize)
(values response body state))))))
#\pass-keys '(quit interrupt)
#\on-error (if (batch-mode?) 'backtrace 'debug)
#\post-error (lambda _
(values (build-response #\code 500) #f state))))
;; -> unspecified values
(define (write-client impl server client response body)
"Write an HTTP response and body to CLIENT. If the server and
client support persistent connections, it is the implementation's
responsibility to keep track of the client thereafter, presumably by
attaching it to the SERVER argument somehow."
(call-with-error-handling
(lambda ()
((server-impl-write impl) server client response body))
#\pass-keys '(quit interrupt)
#\on-error (if (batch-mode?) 'backtrace 'debug)
#\post-error (lambda _ (values))))
;; -> unspecified values
(define (close-server impl server)
"Release resources allocated by a previous invocation of
‘open-server’."
((server-impl-close impl) server))
(define call-with-sigint
(if (not (provided? 'posix))
(lambda (thunk handler-thunk) (thunk))
(lambda (thunk handler-thunk)
(let ((handler #f))
(catch 'interrupt
(lambda ()
(dynamic-wind
(lambda ()
(set! handler
(sigaction SIGINT (lambda (sig) (throw 'interrupt)))))
thunk
(lambda ()
(if handler
;; restore Scheme handler, SIG_IGN or SIG_DFL.
(sigaction SIGINT (car handler) (cdr handler))
;; restore original C handler.
(sigaction SIGINT #f)))))
(lambda (k . _) (handler-thunk)))))))
(define (with-stack-and-prompt thunk)
(call-with-prompt (default-prompt-tag)
(lambda () (start-stack #t (thunk)))
(lambda (k proc)
(with-stack-and-prompt (lambda () (proc k))))))
;; -> new-state
(define (serve-one-client handler impl server state)
"Read one request from SERVER, call HANDLER on the request
and body, and write the response to the client. Return the new state
produced by the handler procedure."
(debug-elapsed 'serve-again)
(call-with-values
(lambda ()
(read-client impl server))
(lambda (client request body)
(debug-elapsed 'read-client)
(if client
(call-with-values
(lambda ()
(handle-request handler request body state))
(lambda (response body state)
(debug-elapsed 'handle-request)
(write-client impl server client response body)
(debug-elapsed 'write-client)
state))
state))))
(define* (run-server handler #\optional (impl 'http) (open-params '())
. state)
"Run Guile's built-in web server.
HANDLER should be a procedure that takes two or more arguments,
the HTTP request and request body, and returns two or more values, the
response and response body.
For example, here is a simple \"Hello, World!\" server_
@example
(define (handler request body)
(values '((content-type . (text/plain)))
\"Hello, World!\"))
(run-server handler)
@end example
The response and body will be run through ‘sanitize-response’
before sending back to the client.
Additional arguments to HANDLER are taken from
STATE. Additional return values are accumulated into a new
STATE, which will be used for subsequent requests. In this way a
handler can explicitly manage its state.
The default server implementation is ‘http’, which accepts
OPEN-PARAMS like ‘(#:port 8081)’, among others. See \"Web
Server\" in the manual, for more information."
(let* ((impl (lookup-server-impl impl))
(server (open-server impl open-params)))
(call-with-sigint
(lambda ()
(let lp ((state state))
(lp (serve-one-client handler impl server state))))
(lambda ()
(close-server impl server)
(values)))))
;;; Web I/O_ HTTP
;; Copyright (C) 2010, 2011, 2012, 2015 Free Software Foundation, Inc.
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301 USA
;;; Commentary_
;;;
;;; This is the HTTP implementation of the (web server) interface.
;;;
;;; `read-request' sets the character encoding on the new port to
;;; latin-1. See the note in request.scm regarding character sets,
;;; strings, and bytevectors for more information.
;;;
;;; Code_
(define-module (web server http)
#\use-module ((srfi srfi-1) #\select (fold))
#\use-module (srfi srfi-9)
#\use-module (rnrs bytevectors)
#\use-module (web request)
#\use-module (web response)
#\use-module (web server)
#\use-module (ice-9 poll)
#\export (http))
(define (make-default-socket family addr port)
(let ((sock (socket PF_INET SOCK_STREAM 0)))
(setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
(bind sock family addr port)
sock))
(define-record-type <http-server>
(make-http-server socket poll-idx poll-set)
http-server?
(socket http-socket)
(poll-idx http-poll-idx set-http-poll-idx!)
(poll-set http-poll-set))
(define *error-events* (logior POLLHUP POLLERR))
(define *read-events* POLLIN)
(define *events* (logior *error-events* *read-events*))
;; -> server
(define* (http-open #\key
(host #f)
(family AF_INET)
(addr (if host
(inet-pton family host)
INADDR_LOOPBACK))
(port 8080)
(socket (make-default-socket family addr port)))
(listen socket 128)
(sigaction SIGPIPE SIG_IGN)
(let ((poll-set (make-empty-poll-set)))
(poll-set-add! poll-set socket *events*)
(make-http-server socket 0 poll-set)))
(define (bad-request port)
(write-response (build-response #\version '(1 . 0) #\code 400
#\headers '((content-length . 0)))
port))
;; -> (client request body | #f #f #f)
(define (http-read server)
(let* ((poll-set (http-poll-set server)))
(let lp ((idx (http-poll-idx server)))
(let ((revents (poll-set-revents poll-set idx)))
(cond
((zero? idx)
;; The server socket, and the end of our downward loop.
(cond
((zero? revents)
;; No client ready, and no error; poll and loop.
(poll poll-set)
(lp (1- (poll-set-nfds poll-set))))
((not (zero? (logand revents *error-events*)))
;; An error.
(set-http-poll-idx! server idx)
(throw 'interrupt))
(else
;; A new client. Add to set, poll, and loop.
;;
;; FIXME_ preserve meta-info.
(let ((client (accept (poll-set-port poll-set idx))))
;; Buffer input and output on this port.
(setvbuf (car client) _IOFBF)
;; From "HOP, A Fast Server for the Diffuse Web", Serrano.
(setsockopt (car client) SOL_SOCKET SO_SNDBUF (* 12 1024))
(poll-set-add! poll-set (car client) *events*)
(poll poll-set)
(lp (1- (poll-set-nfds poll-set)))))))
((zero? revents)
;; Nothing on this port.
(lp (1- idx)))
;; Otherwise, a client socket with some activity on
;; it. Remove it from the poll set.
(else
(let ((port (poll-set-remove! poll-set idx)))
;; Record the next index in all cases, in case the EOF check
;; throws an error.
(set-http-poll-idx! server (1- idx))
(cond
((eof-object? (peek-char port))
;; EOF.
(close-port port)
(lp (1- idx)))
(else
;; Otherwise, try to read a request from this port.
(with-throw-handler
#t
(lambda ()
(let ((req (read-request port)))
(values port
req
(read-request-body req))))
(lambda (k . args)
(define-syntax-rule (cleanup-catch statement)
(catch #t
(lambda () statement)
(lambda (k . args)
(format (current-error-port) "In ~a_\n" 'statement)
(print-exception (current-error-port) #f k args))))
(cleanup-catch (bad-request port))
(cleanup-catch (close-port port)))))))))))))
(define (keep-alive? response)
(let ((v (response-version response)))
(and (or (< (response-code response) 400)
(= (response-code response) 404))
(case (car v)
((1)
(case (cdr v)
((1) (not (memq 'close (response-connection response))))
((0) (memq 'keep-alive (response-connection response)))))
(else #f)))))
;; -> 0 values
(define (http-write server client response body)
(let* ((response (write-response response client))
(port (response-port response)))
(cond
((not body)) ; pass
((bytevector? body)
(write-response-body response body))
(else
(error "Expected a bytevector for body" body)))
(cond
((keep-alive? response)
(force-output port)
(poll-set-add! (http-poll-set server) port *events*))
(else
(close-port port)))
(values)))
;; -> unspecified values
(define (http-close server)
(let ((poll-set (http-poll-set server)))
(let lp ((n (poll-set-nfds poll-set)))
(if (positive? n)
(begin
(close-port (poll-set-remove! poll-set (1- n)))
(lp (1- n)))))))
(define-server-impl http
http-open
http-read
http-write
http-close)
;;;; (web uri) --- URI manipulation tools
;;;;
;;;; Copyright (C) 1997,2001,2002,2010,2011,2012,2013 Free Software Foundation, Inc.
;;;;
;;;; This library is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3 of the License, or (at your option) any later version.
;;;;
;;;; This library 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
;;;; Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this library; if not, write to the Free Software
;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;;;;
;;; Commentary_
;; A data type for Universal Resource Identifiers, as defined in RFC
;; 3986.
;;; Code_
(define-module (web uri)
#\use-module (srfi srfi-9)
#\use-module (ice-9 regex)
#\use-module (ice-9 rdelim)
#\use-module (ice-9 control)
#\use-module (rnrs bytevectors)
#\use-module (ice-9 binary-ports)
#\export (uri?
uri-scheme uri-userinfo uri-host uri-port
uri-path uri-query uri-fragment
build-uri
declare-default-port!
string->uri uri->string
uri-decode uri-encode
split-and-decode-uri-path
encode-and-join-uri-path))
(define-record-type <uri>
(make-uri scheme userinfo host port path query fragment)
uri?
(scheme uri-scheme)
(userinfo uri-userinfo)
(host uri-host)
(port uri-port)
(path uri-path)
(query uri-query)
(fragment uri-fragment))
(define (absolute-uri? obj)
(and (uri? obj) (uri-scheme obj) #t))
(define (uri-error message . args)
(throw 'uri-error message args))
(define (positive-exact-integer? port)
(and (number? port) (exact? port) (integer? port) (positive? port)))
(define (validate-uri scheme userinfo host port path query fragment)
(cond
((not (symbol? scheme))
(uri-error "Expected a symbol for the URI scheme_ ~s" scheme))
((and (or userinfo port) (not host))
(uri-error "Expected a host, given userinfo or port"))
((and port (not (positive-exact-integer? port)))
(uri-error "Expected port to be an integer_ ~s" port))
((and host (or (not (string? host)) (not (valid-host? host))))
(uri-error "Expected valid host_ ~s" host))
((and userinfo (not (string? userinfo)))
(uri-error "Expected string for userinfo_ ~s" userinfo))
((not (string? path))
(uri-error "Expected string for path_ ~s" path))
((and host (not (string-null? path))
(not (eqv? (string-ref path 0) #\/)))
(uri-error "Expected path of absolute URI to start with a /_ ~a" path))))
(define* (build-uri scheme #\key userinfo host port (path "") query fragment
(validate? #t))
"Construct a URI object. SCHEME should be a symbol, PORT
either a positive, exact integer or ‘#f’, and the rest of the
fields are either strings or ‘#f’. If VALIDATE? is true,
also run some consistency checks to make sure that the constructed URI
is valid."
(if validate?
(validate-uri scheme userinfo host port path query fragment))
(make-uri scheme userinfo host port path query fragment))
;; See RFC 3986 #3.2.2 for comments on percent-encodings, IDNA (RFC
;; 3490), and non-ASCII host names.
;;
(define ipv4-regexp
(make-regexp "^([0-9.]+)$"))
(define ipv6-regexp
(make-regexp "^([0-9a-fA-F_.]+)$"))
(define domain-label-regexp
(make-regexp "^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
(define top-label-regexp
(make-regexp "^[a-zA-Z]([a-zA-Z0-9-]*[a-zA-Z0-9])?$"))
(define (valid-host? host)
(cond
((regexp-exec ipv4-regexp host)
(false-if-exception (inet-pton AF_INET host)))
((regexp-exec ipv6-regexp host)
(false-if-exception (inet-pton AF_INET6 host)))
(else
(let lp ((start 0))
(let ((end (string-index host #\. start)))
(if end
(and (regexp-exec domain-label-regexp
(substring host start end))
(lp (1+ end)))
(regexp-exec top-label-regexp host start)))))))
(define userinfo-pat
"[a-zA-Z0-9_.!~*'();_&=+$,-]+")
(define host-pat
"[a-zA-Z0-9.-]+")
(define ipv6-host-pat
"[0-9a-fA-F_.]+")
(define port-pat
"[0-9]*")
(define authority-regexp
(make-regexp
(format #f "^//((~a)@)?((~a)|(\\[(~a)\\]))(_(~a))?$"
userinfo-pat host-pat ipv6-host-pat port-pat)))
(define (parse-authority authority fail)
(if (equal? authority "//")
;; Allow empty authorities_ file_///etc/hosts is a synonym of
;; file_/etc/hosts.
(values #f #f #f)
(let ((m (regexp-exec authority-regexp authority)))
(if (and m (valid-host? (or (match_substring m 4)
(match_substring m 6))))
(values (match_substring m 2)
(or (match_substring m 4)
(match_substring m 6))
(let ((port (match_substring m 8)))
(and port (not (string-null? port))
(string->number port))))
(fail)))))
;;; RFC 3986, #3.
;;;
;;; URI = scheme "_" hier-part [ "?" query ] [ "#" fragment ]
;;;
;;; hier-part = "//" authority path-abempty
;;; / path-absolute
;;; / path-rootless
;;; / path-empty
(define scheme-pat
"[a-zA-Z][a-zA-Z0-9+.-]*")
(define authority-pat
"[^/?#]*")
(define path-pat
"[^?#]*")
(define query-pat
"[^#]*")
(define fragment-pat
".*")
(define uri-pat
(format #f "^((~a)_)?(//~a)?(~a)(\\?(~a))?(#(~a))?$"
scheme-pat authority-pat path-pat query-pat fragment-pat))
(define uri-regexp
(make-regexp uri-pat))
(define (string->uri* string)
"Parse STRING into a URI object. Return ‘#f’ if the string
could not be parsed."
(% (let ((m (regexp-exec uri-regexp string)))
(if (not m) (abort))
(let ((scheme (let ((str (match_substring m 2)))
(and str (string->symbol (string-downcase str)))))
(authority (match_substring m 3))
(path (match_substring m 4))
(query (match_substring m 6))
(fragment (match_substring m 7)))
(call-with-values
(lambda ()
(if authority
(parse-authority authority abort)
(values #f #f #f)))
(lambda (userinfo host port)
(make-uri scheme userinfo host port path query fragment)))))
(lambda (k)
#f)))
(define (string->uri string)
"Parse STRING into a URI object. Return ‘#f’ if the string
could not be parsed."
(let ((uri (string->uri* string)))
(and uri (uri-scheme uri) uri)))
(define *default-ports* (make-hash-table))
(define (declare-default-port! scheme port)
"Declare a default port for the given URI scheme."
(hashq-set! *default-ports* scheme port))
(define (default-port? scheme port)
(or (not port)
(eqv? port (hashq-ref *default-ports* scheme))))
(declare-default-port! 'http 80)
(declare-default-port! 'https 443)
(define (uri->string uri)
"Serialize URI to a string. If the URI has a port that is the
default port for its scheme, the port is not included in the
serialization."
(let* ((scheme (uri-scheme uri))
(userinfo (uri-userinfo uri))
(host (uri-host uri))
(port (uri-port uri))
(path (uri-path uri))
(query (uri-query uri))
(fragment (uri-fragment uri)))
(string-append
(if scheme
(string-append (symbol->string scheme) "_")
"")
(if host
(string-append "//"
(if userinfo (string-append userinfo "@")
"")
(if (string-index host #\_)
(string-append "[" host "]")
host)
(if (default-port? (uri-scheme uri) port)
""
(string-append "_" (number->string port))))
"")
path
(if query
(string-append "?" query)
"")
(if fragment
(string-append "#" fragment)
""))))
;; like call-with-output-string, but actually closes the port (doh)
(define (call-with-output-string* proc)
(let ((port (open-output-string)))
(proc port)
(let ((str (get-output-string port)))
(close-port port)
str)))
(define (call-with-output-bytevector* proc)
(call-with-values
(lambda ()
(open-bytevector-output-port))
(lambda (port get-bytevector)
(proc port)
(let ((bv (get-bytevector)))
(close-port port)
bv))))
(define (call-with-encoded-output-string encoding proc)
(if (string-ci=? encoding "utf-8")
(string->utf8 (call-with-output-string* proc))
(call-with-output-bytevector*
(lambda (port)
(set-port-encoding! port encoding)
(proc port)))))
(define (encode-string str encoding)
(if (string-ci=? encoding "utf-8")
(string->utf8 str)
(call-with-encoded-output-string encoding
(lambda (port)
(display str port)))))
(define (decode-string bv encoding)
(if (string-ci=? encoding "utf-8")
(utf8->string bv)
(let ((p (open-bytevector-input-port bv)))
(set-port-encoding! p encoding)
(let ((res (read-string p)))
(close-port p)
res))))
;; A note on characters and bytes_ URIs are defined to be sequences of
;; characters in a subset of ASCII. Those characters may encode a
;; sequence of bytes (octets), which in turn may encode sequences of
;; characters in other character sets.
;;
;; Return a new string made from uri-decoding STR. Specifically,
;; turn ‘+’ into space, and hex-encoded ‘%XX’ strings into
;; their eight-bit characters.
;;
(define hex-chars
(string->char-set "0123456789abcdefABCDEF"))
(define* (uri-decode str #\key (encoding "utf-8") (decode-plus-to-space? #t))
"Percent-decode the given STR, according to ENCODING,
which should be the name of a character encoding.
Note that this function should not generally be applied to a full URI
string. For paths, use ‘split-and-decode-uri-path’ instead. For query
strings, split the query on ‘&’ and ‘=’ boundaries, and decode
the components separately.
Note also that percent-encoded strings encode _bytes_, not characters.
There is no guarantee that a given byte sequence is a valid string
encoding. Therefore this routine may signal an error if the decoded
bytes are not valid for the given encoding. Pass ‘#f’ for ENCODING if
you want decoded bytes as a bytevector directly. ‘set-port-encoding!’,
for more information on character encodings.
If DECODE-PLUS-TO-SPACE? is true, which is the default, also replace
instances of the plus character (+) with a space character. This is
needed when parsing application/x-www-form-urlencoded data.
Returns a string of the decoded characters, or a bytevector if
ENCODING was ‘#f’."
(let* ((len (string-length str))
(bv
(call-with-output-bytevector*
(lambda (port)
(let lp ((i 0))
(if (< i len)
(let ((ch (string-ref str i)))
(cond
((and (eqv? ch #\+) decode-plus-to-space?)
(put-u8 port (char->integer #\space))
(lp (1+ i)))
((and (< (+ i 2) len) (eqv? ch #\%)
(let ((a (string-ref str (+ i 1)))
(b (string-ref str (+ i 2))))
(and (char-set-contains? hex-chars a)
(char-set-contains? hex-chars b)
(string->number (string a b) 16))))
=> (lambda (u8)
(put-u8 port u8)
(lp (+ i 3))))
((< (char->integer ch) 128)
(put-u8 port (char->integer ch))
(lp (1+ i)))
(else
(uri-error "Invalid character in encoded URI ~a_ ~s"
str ch))))))))))
(if encoding
(decode-string bv encoding)
;; Otherwise return raw bytevector
bv)))
(define ascii-alnum-chars
(string->char-set
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"))
;; RFC 3986, #2.2.
(define gen-delims
(string->char-set "_/?#[]@"))
(define sub-delims
(string->char-set "!$&'()*+,l="))
(define reserved-chars
(char-set-union gen-delims sub-delims))
;; RFC 3986, #2.3
(define unreserved-chars
(char-set-union ascii-alnum-chars
(string->char-set "-._~")))
;; Return a new string made from uri-encoding STR, unconditionally
;; transforming any characters not in UNESCAPED-CHARS.
;;
(define* (uri-encode str #\key (encoding "utf-8")
(unescaped-chars unreserved-chars))
"Percent-encode any character not in the character set,
UNESCAPED-CHARS.
The default character set includes alphanumerics from ASCII, as well as
the special characters ‘-’, ‘.’, ‘_’, and ‘~’. Any other character will
be percent-encoded, by writing out the character to a bytevector within
the given ENCODING, then encoding each byte as ‘%HH’, where HH is the
uppercase hexadecimal representation of the byte."
(define (needs-escaped? ch)
(not (char-set-contains? unescaped-chars ch)))
(if (string-index str needs-escaped?)
(call-with-output-string*
(lambda (port)
(string-for-each
(lambda (ch)
(if (char-set-contains? unescaped-chars ch)
(display ch port)
(let* ((bv (encode-string (string ch) encoding))
(len (bytevector-length bv)))
(let lp ((i 0))
(if (< i len)
(let ((byte (bytevector-u8-ref bv i)))
(display #\% port)
(when (< byte 16)
(display #\0 port))
(display (string-upcase (number->string byte 16))
port)
(lp (1+ i))))))))
str)))
str))
(define (split-and-decode-uri-path path)
"Split PATH into its components, and decode each component,
removing empty components.
For example, ‘\"/foo/bar%20baz/\"’ decodes to the two-element list,
‘(\"foo\" \"bar baz\")’."
(filter (lambda (x) (not (string-null? x)))
(map (lambda (s) (uri-decode s #\decode-plus-to-space? #f))
(string-split path #\/))))
(define (encode-and-join-uri-path parts)
"URI-encode each element of PARTS, which should be a list of
strings, and join the parts together with ‘/’ as a delimiter.
For example, the list ‘(\"scrambled eggs\" \"biscuits&gravy\")’
encodes as ‘\"scrambled%20eggs/biscuits%26gravy\"’."
(string-join (map uri-encode parts) "/"))
;;; common-test.scm --
;;;
;; Slightly modified for Guile by Ludovic Courtès <ludo@gnu.org>, 2010.
(use-modules (system base lalr)
(ice-9 pretty-print))
(define *error* '())
(define-syntax check
(syntax-rules (=>)
((_ ?expr => ?expected-result)
(check ?expr (=> equal?) ?expected-result))
((_ ?expr (=> ?equal) ?expected-result)
(let ((result ?expr)
(expected ?expected-result))
(set! *error* '())
(when (not (?equal result expected))
(display "Failed test_ \n")
(pretty-print (quote ?expr))(newline)
(display "\tresult was_ ")
(pretty-print result)(newline)
(display "\texpected_ ")
(pretty-print expected)(newline)
(exit 1))))))
;;; --------------------------------------------------------------------
(define (display-result v)
(if v
(begin
(display "==> ")
(display v)
(newline))))
(define eoi-token
(make-lexical-token '*eoi* #f #f))
(define (make-lexer tokens)
(lambda ()
(if (null? tokens)
eoi-token
(let ((t (car tokens)))
(set! tokens (cdr tokens))
t))))
(define (error-handler message . args)
(set! *error* (cons `(error-handler ,message . ,(if (pair? args)
(lexical-token-category (car args))
'()))
*error*))
(cons message args))
;;; end of file
"_";exec snow -- "$0" "$@"
;;;
;;;; Tests for the GLR parser generator
;;;
;;
;; @created "Fri Aug 19 11_23_48 EDT 2005"
;;
(package* glr-test/v1.0.0
(require_ lalr/v2.4.0))
(define (syntax-error msg . args)
(display msg (current-error-port))
(for-each (cut format (current-error-port) " ~A" <>) args)
(newline (current-error-port))
(throw 'misc-error))
(define (make-lexer words)
(let ((phrase words))
(lambda ()
(if (null? phrase)
'*eoi*
(let ((word (car phrase)))
(set! phrase (cdr phrase))
word)))))
;;;
;;;; Test 1
;;;
(define parser-1
;; Grammar taken from Tomita's "An Efficient Augmented-Context-Free Parsing Algorithm"
(lalr-parser
(driver_ glr)
(expect_ 2)
(*n *v *d *p)
(<s> (<np> <vp>)
(<s> <pp>))
(<np> (*n)
(*d *n)
(<np> <pp>))
(<pp> (*p <np>))
(<vp> (*v <np>))))
(define *phrase-1* '(*n *v *d *n *p *d *n *p *d *n *p *d *n))
(define (test-1)
(parser-1 (make-lexer *phrase-1*) syntax-error))
;;;
;;;; Test 2
;;;
(define parser-2
;; The dangling-else problem
(lalr-parser
(driver_ glr)
(expect_ 1)
((nonassoc_ if then else e s))
(<s> (s)
(if e then <s>)
(if e then <s> else <s>))))
(define *phrase-2* '(if e then if e then s else s))
(define (test-2)
(parser-2 (make-lexer *phrase-2*) syntax-error))
(define (assert-length l n test-name)
(display "Test '")
(display test-name)
(display (if (not (= (length l) n)) "' failed!" "' passed!"))
(newline))
(assert-length (test-1) 14 1)
(assert-length (test-2) 2 2)
;;; test-glr-associativity.scm
;;
;;With the GLR parser both the terminal precedence and the non-terminal
;;associativity are not respected; rather they generate two child
;;processes.
;;
(load "common-test.scm")
(define parser
(lalr-parser
(driver\_ glr)
(expect\_ 0)
(N LPAREN RPAREN
(left\_ + -)
(right\_ * /)
(nonassoc\_ uminus))
(output (expr) \_ $1)
(expr (expr + expr) \_ (list $1 '+ $3)
(expr - expr) \_ (list $1 '- $3)
(expr * expr) \_ (list $1 '* $3)
(expr / expr) \_ (list $1 '/ $3)
(- expr (prec\_ uminus)) \_ (list '- $2)
(N) \_ $1
(LPAREN expr RPAREN) \_ $2)))
(define (doit . tokens)
(parser (make-lexer tokens) error-handler))
;;; --------------------------------------------------------------------
;;Remember that the result of the GLR driver is a list of parses, not a
;;single parse.
(check
(doit (make-lexical-token 'N #f 1))
=> '(1))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '+ #f '+)
(make-lexical-token 'N #f 2))
=> '((1 + 2)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '* #f '*)
(make-lexical-token 'N #f 2))
=> '((1 * 2)))
(check
(doit (make-lexical-token '- #f '-)
(make-lexical-token 'N #f 1))
=> '((- 1)))
(check
(doit (make-lexical-token '- #f '-)
(make-lexical-token '- #f '-)
(make-lexical-token 'N #f 1))
=> '((- (- 1))))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '+ #f '+)
(make-lexical-token '- #f '-)
(make-lexical-token 'N #f 2))
=> '((1 + (- 2))))
;;; --------------------------------------------------------------------
(check
;;left-associativity
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '+ #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token '+ #f '+)
(make-lexical-token 'N #f 3))
=> '(((1 + 2) + 3)))
(check
;;right-associativity
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '* #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token '* #f '*)
(make-lexical-token 'N #f 3))
=> '(((1 * 2) * 3)
(1 * (2 * 3))))
(check
;;precedence
(doit (make-lexical-token 'N #f 1)
(make-lexical-token '+ #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token '* #f '*)
(make-lexical-token 'N #f 3))
=> '(((1 + 2) * 3)
(1 + (2 * 3))))
;;; end of file
;;; test-lr-basics-01.scm --
;;
;;A grammar that only accept a single terminal as input. It refuses the
;;end-of-input as first token.
;;
(load "common-test.scm")
(define (doit . tokens)
(let* ((lexer (make-lexer tokens))
(parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(A)
(e (A) \_ $1))))
(parser lexer error-handler)))
(check
(doit (make-lexical-token 'A #f 1))
=> '(1))
(check
(doit)
=> '())
(check
;;Parse correctly the first A and reduce it. The second A triggers
;;an error which empties the stack and consumes all the input
;;tokens. Finally, an unexpected end-of-input error is returned
;;because EOI is invalid as first token after the start.
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '())
;;; end of file
;;; test-lr-basics-02.scm --
;;
;;A grammar that only accept a single terminal or the EOI.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(A)
(e (A) \_ $1
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> '(0))
(check
(doit (make-lexical-token 'A #f 1))
=> '(1))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '())
;;; end of file
;;; test-lr-basics-03.scm --
;;
;;A grammar that accepts fixed sequences of a single terminal or the
;;EOI.
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(A)
(e (A) \_ (list $1)
(A A) \_ (list $1 $2)
(A A A) \_ (list $1 $2 $3)
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit (make-lexical-token 'A #f 1))
=> '((1)))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2))
=> '((1 2)))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '((1 2 3)))
(check
(doit)
=> '(0))
;;; end of file
;;; test-lr-basics-04.scm --
;;
;;A grammar accepting a sequence of equal tokens of arbitrary length.
;;The return value is the value of the last parsed token.
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(A)
(e (e A) \_ $2
(A) \_ $1
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> '(0))
(check
;;Two results because there is a shift/reduce conflict, so two
;;processes are generated.
(doit (make-lexical-token 'A #f 1))
=> '(1 1))
(check
;;Two results because there is a shift/reduce conflict, so two
;;processes are generated. Notice that the rules_
;;
;; (e A) (A)
;;
;;generate only one conflict when the second "A" comes. The third
;;"A" comes when the state is inside the rule "(e A)", so there is
;;no conflict.
;;
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '(3 3))
;;; end of file
;;; test-lr-basics-05.scm --
;;
;;A grammar accepting a sequence of equal tokens of arbitrary length.
;;The return value is the list of values.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(A)
(e (e A) \_ (cons $2 $1)
(A) \_ (list $1)
() \_ (list 0)))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> '((0)))
(check
(doit (make-lexical-token 'A #f 1))
=> '((1 0)
(1)))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2))
=> '((2 1 0)
(2 1)))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '((3 2 1 0)
(3 2 1)))
;;; end of file
;;; test-lr-script-expression.scm --
;;
;;Parse scripts, each line an expression.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(N O C T (left\_ A) (left\_ M) (nonassoc\_ U))
(script (lines) \_ (reverse $1))
(lines (lines line) \_ (cons $2 $1)
(line) \_ (list $1))
(line (T) \_ #\newline
(E T) \_ $1
(error T) \_ (list 'error-clause $2))
(E (N) \_ $1
(E A E) \_ ($2 $1 $3)
(E M E) \_ ($2 $1 $3)
(A E (prec\_ U)) \_ ($1 $2)
(O E C) \_ $2))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Correct input
(check
(doit (make-lexical-token 'T #f #\newline))
=> '((#\newline)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'T #f #\newline))
=> '((1)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'T #f #\newline))
=> '((3)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline))
=> '((9) (7)))
(check
(doit (make-lexical-token 'N #f 10)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline))
=> '((23)))
(check
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline))
=> '((9)))
(check
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline)
(make-lexical-token 'N #f 4)
(make-lexical-token 'M #f /)
(make-lexical-token 'N #f 5)
(make-lexical-token 'T #f #\newline))
=> '((9 4/5)))
;;; --------------------------------------------------------------------
(check
;;Successful error recovery.
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline)
(make-lexical-token 'N #f 4)
(make-lexical-token 'M #f /)
(make-lexical-token 'N #f 5)
(make-lexical-token 'T #f #\newline))
=> '())
(check
;;Unexpected end of input.
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2))
=> '())
(check
;;Unexpected end of input.
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'T #f #\newline))
=> '())
;;; end of file
;;; test-lr-single-expressions.scm --
;;
;;Grammar accepting single expressions.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(driver\_ glr)
(N O C (left\_ A) (left\_ M) (nonassoc\_ U))
(E (N) \_ $1
(E A E) \_ ($2 $1 $3)
(E M E) \_ ($2 $1 $3)
(A E (prec\_ U)) \_ ($1 $2)
(O E C) \_ $2))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
(check ;correct input
(doit (make-lexical-token 'N #f 1))
=> '(1))
(check ;correct input
(doit (make-lexical-token 'A #f -)
(make-lexical-token 'N #f 1))
=> '(-1))
(check ;correct input
(doit (make-lexical-token 'A #f +)
(make-lexical-token 'N #f 1))
=> '(1))
(check ;correct input
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2))
=> '(3))
(check ;correct input
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3))
=> '(9 7))
(check ;correct input
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3))
=> '(9))
;;; end of file
;;; test-lr-associativity-01.scm --
;;
;;Show how to use left and right associativity. Notice that the
;;terminal M is declared as right associative; this influences the
;;binding of values to the $n symbols in the semantic clauses. The
;;semantic clause in the rule_
;;
;; (E M E M E) _ (list $1 $2 (list $3 $4 $5))
;;
;;looks like it is right-associated, and it is because we have declared
;;M as "right_".
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser
(expect\_ 0)
(N (left\_ A)
(right\_ M)
(nonassoc\_ U))
(E (N) \_ $1
(E A E) \_ (list $1 $2 $3)
(E M E) \_ (list $1 $2 $3)
(E M E M E) \_ (list $1 $2 (list $3 $4 $5))
(A E (prec\_ U)) \_ (list '- $2)))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Single operator.
(check
(doit (make-lexical-token 'N #f 1))
=> 1)
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2))
=> '(1 + 2))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2))
=> '(1 * 2))
(check
(doit (make-lexical-token 'A #f '-)
(make-lexical-token 'N #f 1))
=> '(- 1))
;;; --------------------------------------------------------------------
;;; Precedence.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 + (2 * 3)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 * 2) + 3))
;;; --------------------------------------------------------------------
;;; Associativity.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 + 2) + 3))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 * (2 * 3)))
;;; end of file
;;; test-lr-associativity-02.scm --
;;
;;Show how to use left and right associativity. Notice that the
;;terminal M is declared as left associative; this influences the
;;binding of values to the $n symbols in the semantic clauses. The
;;semantic clause in the rule_
;;
;; (E M E M E) \_ (list $1 $2 (list $3 $4 $5))
;;
;;looks like it is right-associated, but the result is left-associated
;;because we have declared M as "left_".
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser
(expect\_ 0)
(N (left\_ A)
(left\_ M)
(nonassoc\_ U))
(E (N) \_ $1
(E A E) \_ (list $1 $2 $3)
(E M E) \_ (list $1 $2 $3)
(E M E M E) \_ (list $1 $2 (list $3 $4 $5))
(A E (prec\_ U)) \_ (list '- $2)))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Single operator.
(check
(doit (make-lexical-token 'N #f 1))
=> 1)
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2))
=> '(1 + 2))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2))
=> '(1 * 2))
(check
(doit (make-lexical-token 'A #f '-)
(make-lexical-token 'N #f 1))
=> '(- 1))
;;; --------------------------------------------------------------------
;;; Precedence.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 + (2 * 3)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 * 2) + 3))
;;; --------------------------------------------------------------------
;;; Associativity.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 + 2) + 3))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '((1 * 2) * 3))
;;; end of file
;;; test-lr-associativity-01.scm --
;;
;;Show how to use left and right associativity. Notice that the
;;terminal M is declared as non-associative; this influences the binding
;;of values to the $n symbols in the semantic clauses. The semantic
;;clause in the rule_
;;
;; (E M E M E) \_ (list $1 $2 (list $3 $4 $5))
;;
;;looks like it is right-associated, and it is because we have declared
;;M as "right_".
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser
(expect\_ 0)
(N (nonassoc\_ A)
(nonassoc\_ M))
(E (N) \_ $1
(E A E) \_ (list $1 $2 $3)
(E A E A E) \_ (list (list $1 $2 $3) $4 $5)
(E M E) \_ (list $1 $2 $3)
(E M E M E) \_ (list $1 $2 (list $3 $4 $5))))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Single operator.
(check
(doit (make-lexical-token 'N #f 1))
=> 1)
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2))
=> '(1 + 2))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2))
=> '(1 * 2))
;;; --------------------------------------------------------------------
;;; Precedence.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 + (2 * 3)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 * 2) + 3))
;;; --------------------------------------------------------------------
;;; Associativity.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 + 2) + 3))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 * (2 * 3)))
;;; end of file
;;; test-lr-associativity-04.scm --
;;
;;Show how to use associativity.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser
(expect\_ 0)
(N (left\_ A)
(left\_ M))
(E (N) \_ $1
(E A E) \_ (list $1 $2 $3)
(E A E A E) \_ (list (list $1 $2 $3) $4 $5)
(E M E) \_ (list $1 $2 $3)
(E M E M E) \_ (list $1 $2 (list $3 $4 $5))
(E A E M E) \_ (list $1 $2 $3 $4 $5)
(E M E A E) \_ (list $1 $2 $3 $4 $5)
))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Single operator.
(check
(doit (make-lexical-token 'N #f 1))
=> 1)
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2))
=> '(1 + 2))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2))
=> '(1 * 2))
;;; --------------------------------------------------------------------
;;; Precedence.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '(1 + (2 * 3)))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 * 2) + 3))
;;; --------------------------------------------------------------------
;;; Associativity.
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 2)
(make-lexical-token 'A #f '+)
(make-lexical-token 'N #f 3))
=> '((1 + 2) + 3))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f '*)
(make-lexical-token 'N #f 3))
=> '((1 * 2) * 3))
;;; end of file
;;; test-lr-basics-01.scm --
;;
;;A grammar that only accept a single terminal as input. It refuses the
;;end-of-input as first token.
;;
(load "common-test.scm")
(define (doit . tokens)
(let* ((lexer (make-lexer tokens))
(parser (lalr-parser (expect\_ 0)
(A)
(e (A) \_ $1))))
(parser lexer error-handler)))
(check
(doit (make-lexical-token 'A #f 1))
=> 1)
(check
(let ((r (doit)))
(cons r *error*))
=> '(#f (error-handler "Syntax error: unexpected end of input")))
(check
;;Parse correctly the first A and reduce it. The second A triggers
;;an error which empties the stack and consumes all the input
;;tokens. Finally, an unexpected end-of-input error is returned
;;because EOI is invalid as first token after the start.
(let ((r (doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))))
(cons r *error*))
=> '(#f
(error-handler "Syntax error: unexpected end of input")
(error-handler "Syntax error: unexpected token : " . A)))
;;; end of file
;;; test-lr-basics-02.scm --
;;
;;A grammar that only accept a single terminal or the EOI.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(A)
(e (A) \_ $1
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> 0)
(check
(doit (make-lexical-token 'A #f 1))
=> 1)
(check
;;Parse correctly the first A and reduce it. The second A triggers
;;an error which empties the stack and consumes all the input
;;tokens. Finally, the end-of-input token is correctly parsed.
(let ((r (doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))))
(cons r *error*))
=> '(0 (error-handler "Syntax error: unexpected token : " . A)))
;;; end of file
;;; test-lr-basics-03.scm --
;;
;;A grammar that accepts fixed sequences of a single terminal or the
;;EOI.
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(A)
(e (A) \_ (list $1)
(A A) \_ (list $1 $2)
(A A A) \_ (list $1 $2 $3)
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit (make-lexical-token 'A #f 1))
=> '(1))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2))
=> '(1 2))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '(1 2 3))
(check
(doit)
=> 0)
;;; end of file
;;; test-lr-basics-04.scm --
;;
;;A grammar accepting a sequence of equal tokens of arbitrary length.
;;The return value is the value of the last parsed token.
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(A)
(e (e A) \_ $2
(A) \_ $1
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> 0)
(check
(doit (make-lexical-token 'A #f 1))
=> 1)
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> 3)
;;; end of file
;;; test-lr-basics-05.scm --
;;
;;A grammar accepting a sequence of equal tokens of arbitrary length.
;;The return value is the list of values.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(A)
(e (e A) \_ (cons $2 $1)
(A) \_ (list $1)
() \_ 0))))
(parser (make-lexer tokens) error-handler)))
(check
(doit)
=> 0)
(check
(doit (make-lexical-token 'A #f 1))
=> '(1))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2))
=> '(2 1))
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'A #f 2)
(make-lexical-token 'A #f 3))
=> '(3 2 1))
;;; end of file
;;; test-lr-error-recovery-01.scm --
;;
;;Test error recovery with a terminator terminal.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser
(expect\_ 0)
(NUMBER BAD NEWLINE)
(script (lines) \_ (reverse $1)
() \_ 0)
(lines (lines line) \_ (cons $2 $1)
(line) \_ (list $1))
(line (NEWLINE) \_ (list 'line $1)
(NUMBER NEWLINE) \_ (list 'line $1 $2)
(NUMBER NUMBER NEWLINE) \_ (list 'line $1 $2 $3)
;;This semantic action will cause "(recover $1
;;$2)" to be the result of the offending line.
(error NEWLINE) \_ (list 'recover $1 $2)))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; No errors, grammar tests.
(check
(doit)
=> 0)
(check
(doit (make-lexical-token 'NEWLINE #f #\newline))
=> '((line #\newline)))
(check
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline))
=> '((line 1 #\newline)))
(check
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline))
=> '((line 1 2 #\newline)))
(check
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline))
=> '((line 1 #\newline)
(line 2 #\newline)))
(check
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 3)
(make-lexical-token 'NEWLINE #f #\newline))
=> '((line 1 #\newline)
(line 2 #\newline)
(line 3 #\newline)))
(check
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 3)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 41)
(make-lexical-token 'NUMBER #f 42)
(make-lexical-token 'NEWLINE #f #\newline))
=> '((line 1 #\newline)
(line 2 #\newline)
(line 3 #\newline)
(line 41 42 #\newline)))
;;; --------------------------------------------------------------------
;;; Successful error recovery.
(check
;;The BAD triggers an error, recovery happens, the first NEWLINE is
;;correctly parsed as recovery token; the second line is correct.
(let ((r (doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'BAD #f 'alpha)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline))))
(cons r *error*))
=> '(((recover #f #f)
(line 2 #\newline))
(error-handler "Syntax error: unexpected token : " . BAD)))
(check
;;The first BAD triggers an error, recovery happens skipping the
;;second and third BADs, the first NEWLINE is detected as
;;synchronisation token; the second line is correct.
(let ((r (doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'BAD #f 'alpha)
(make-lexical-token 'BAD #f 'beta)
(make-lexical-token 'BAD #f 'delta)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline))))
(cons r *error*))
=> '(((recover #f #f)
(line 2 #\newline))
(error-handler "Syntax error: unexpected token : " . BAD)))
;;; --------------------------------------------------------------------
;;; Failed error recovery.
(check
;;End-of-input is found after NUMBER.
(let ((r (doit (make-lexical-token 'NUMBER #f 1))))
(cons r *error*))
=> '(#f (error-handler "Syntax error: unexpected end of input")))
(check
;;The BAD triggers the error, the stack is rewind up to the start,
;;then end-of-input happens while trying to skip tokens until the
;;synchronisation one is found. End-of-input is an acceptable token
;;after the start.
(let ((r (doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'BAD #f 'alpha)
(make-lexical-token 'BAD #f 'beta)
(make-lexical-token 'BAD #f 'delta))))
(cons r *error*))
=> '(0 (error-handler "Syntax error: unexpected token : " . BAD)))
(check
;;The BAD triggers the error, the stack is rewind up to the start,
;;then end-of-input happens while trying to skip tokens until the
;;synchronisation one is found. End-of-input is an acceptable token
;;after the start.
(let ((r (doit (make-lexical-token 'BAD #f 'alpha))))
(cons r *error*))
=> '(0 (error-handler "Syntax error: unexpected token : " . BAD)))
;;; end of file
;;; test-lr-error-recovery-02.scm --
;;
;;Test error recovery policy when the synchronisation terminal has the
;;same category of the lookahead that raises the error.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(A B C)
(alphas (alpha) \_ $1
(alphas alpha) \_ $2)
(alpha (A B) \_ (list $1 $2)
(C) \_ $1
(error C) \_ 'error-form))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; No error, just grammar tests.
(check
(doit (make-lexical-token 'A #f 1)
(make-lexical-token 'B #f 2))
=> '(1 2))
(check
(doit (make-lexical-token 'C #f 3))
=> '3)
;;; --------------------------------------------------------------------
;;; Successful error recovery.
(check
;;Error, recovery, end-of-input.
(let ((r (doit (make-lexical-token 'A #f 1)
(make-lexical-token 'C #f 3))))
(cons r *error*))
=> '(error-form (error-handler "Syntax error: unexpected token : " . C)))
(check
;;Error, recovery, correct parse of "A B".
(let ((r (doit (make-lexical-token 'A #f 1)
(make-lexical-token 'C #f 3)
(make-lexical-token 'A #f 1)
(make-lexical-token 'B #f 2))))
(cons r *error*))
=> '((1 2)
(error-handler "Syntax error: unexpected token : " . C)))
;;; end of file
;;; test-lr-no-clause.scm --
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(NUMBER COMMA NEWLINE)
(lines (lines line) \_ (list $2)
(line) \_ (list $1))
(line (NEWLINE) \_ #\newline
(NUMBER NEWLINE) \_ $1
;;this is a rule with no semantic action
(COMMA NUMBER NEWLINE)))))
(parser (make-lexer tokens) error-handler)))
(check
;;correct input
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline))
=> '(1))
(check
;;correct input with comma, which is a rule with no client form
(doit (make-lexical-token 'COMMA #f #\,)
(make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline))
=> '(#(line-3 #\, 1 #\newline)))
(check
;;correct input with comma, which is a rule with no client form
(doit (make-lexical-token 'NUMBER #f 1)
(make-lexical-token 'NEWLINE #f #\newline)
(make-lexical-token 'COMMA #f #\,)
(make-lexical-token 'NUMBER #f 2)
(make-lexical-token 'NEWLINE #f #\newline))
=> '(#(line-3 #\, 2 #\newline)))
;;; end of file
;;; test-lr-script-expression.scm --
;;
;;Parse scripts, each line an expression.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(N O C T (left\_ A) (left\_ M) (nonassoc\_ U))
(script (lines) \_ (reverse $1))
(lines (lines line) \_ (cons $2 $1)
(line) \_ (list $1))
(line (T) \_ #\newline
(E T) \_ $1
(error T) \_ (list 'error-clause $2))
(E (N) \_ $1
(E A E) \_ ($2 $1 $3)
(E M E) \_ ($2 $1 $3)
(A E (prec\_ U)) \_ ($1 $2)
(O E C) \_ $2))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
;;; Correct input
(check
(doit (make-lexical-token 'T #f #\newline))
=> '(#\newline))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'T #f #\newline))
=> '(1))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'T #f #\newline))
=> '(3))
(check
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline))
=> '(7))
(check
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline))
=> '(9))
(check
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline)
(make-lexical-token 'N #f 4)
(make-lexical-token 'M #f /)
(make-lexical-token 'N #f 5)
(make-lexical-token 'T #f #\newline))
=> '(9 4/5))
;;; --------------------------------------------------------------------
(check
;;Successful error recovery.
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3)
(make-lexical-token 'T #f #\newline)
(make-lexical-token 'N #f 4)
(make-lexical-token 'M #f /)
(make-lexical-token 'N #f 5)
(make-lexical-token 'T #f #\newline))
=> '((error-clause #f)
4/5))
(check
;;Unexpected end of input.
(let ((r (doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2))))
(cons r *error*))
=> '(#f (error-handler "Syntax error: unexpected end of input")))
(check
;;Unexpected end of input.
(let ((r (doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'T #f #\newline))))
(cons r *error*))
=> '(((error-clause #f))
(error-handler "Syntax error: unexpected token : " . T)))
;;; end of file
;;; test-lr-single-expressions.scm --
;;
;;Grammar accepting single expressions.
;;
(load "common-test.scm")
(define (doit . tokens)
(let ((parser (lalr-parser (expect\_ 0)
(N O C (left\_ A) (left\_ M) (nonassoc\_ U))
(E (N) \_ $1
(E A E) \_ ($2 $1 $3)
(E M E) \_ ($2 $1 $3)
(A E (prec\_ U)) \_ ($1 $2)
(O E C) \_ $2))))
(parser (make-lexer tokens) error-handler)))
;;; --------------------------------------------------------------------
(check ;correct input
(doit (make-lexical-token 'N #f 1))
=> 1)
(check ;correct input
(doit (make-lexical-token 'A #f -)
(make-lexical-token 'N #f 1))
=> -1)
(check ;correct input
(doit (make-lexical-token 'A #f +)
(make-lexical-token 'N #f 1))
=> 1)
(check ;correct input
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2))
=> 3)
(check ;correct input
(doit (make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3))
=> 7)
(check ;correct input
(doit (make-lexical-token 'O #f #\()
(make-lexical-token 'N #f 1)
(make-lexical-token 'A #f +)
(make-lexical-token 'N #f 2)
(make-lexical-token 'C #f #\))
(make-lexical-token 'M #f *)
(make-lexical-token 'N #f 3))
=> 9)
;;; end of file
(define-module (test-import-order-a)
#\use-module (base))
(push!)
(define-module (test-import-order-b)
#\use-module (base))
(push!)
(define-module (test-import-order-c)
#\use-module (base))
(push!)
(define-module (test-import-order-d)
#\use-module (base))
(push!)
;;;; test-suite/lib.scm --- generic support for testing
;;;; Copyright (C) 1999, 2000, 2001, 2004, 2006, 2007, 2009, 2010,
;;;; 2011, 2012, 2013, 2014 Free Software Foundation, Inc.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU Lesser General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 3, 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 Lesser General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Lesser General Public
;;;; License along with this software; see the file COPYING.LESSER.
;;;; If not, write to the Free Software Foundation, Inc., 51 Franklin
;;;; Street, Fifth Floor, Boston, MA 02110-1301 USA
(define-module (test-suite lib)
#\use-module (ice-9 stack-catch)
#\use-module (ice-9 regex)
#\autoload (srfi srfi-1) (append-map)
#\autoload (system base compile) (compile)
#\export (
;; Exceptions which are commonly being tested for.
exception_syntax-pattern-unmatched
exception_bad-variable
exception_missing-expression
exception_out-of-range exception_unbound-var
exception_used-before-defined
exception_wrong-num-args exception_wrong-type-arg
exception_numerical-overflow
exception_struct-set!-denied
exception_system-error
exception_encoding-error
exception_miscellaneous-error
exception_string-contains-nul
exception_read-error
exception_null-pointer-error
exception_vm-error
;; Reporting passes and failures.
run-test
pass-if expect-fail
pass-if-equal
pass-if-exception expect-fail-exception
;; Naming groups of tests in a regular fashion.
with-test-prefix
with-test-prefix*
with-test-prefix/c&e
current-test-prefix
format-test-name
;; Using the debugging evaluator.
with-debugging-evaluator with-debugging-evaluator*
;; Clearing stale references on the C stack for GC-sensitive tests.
clear-stale-stack-references
;; Using a given locale
with-locale with-locale* with-latin1-locale with-latin1-locale*
;; The bit bucket.
%null-device
;; Reporting results in various ways.
register-reporter unregister-reporter reporter-registered?
make-count-reporter print-counts
make-log-reporter
full-reporter
user-reporter))
;;;; If you're using Emacs's Scheme mode_
;;;; (put 'with-test-prefix 'scheme-indent-function 1)
;;;; CORE FUNCTIONS
;;;;
;;;; The function (run-test name expected-result thunk) is the heart of the
;;;; testing environment. The first parameter NAME is a unique name for the
;;;; test to be executed (for an explanation of this parameter see below under
;;;; TEST NAMES). The second parameter EXPECTED-RESULT is a boolean value
;;;; that indicates whether the corresponding test is expected to pass. If
;;;; EXPECTED-RESULT is #t the test is expected to pass, if EXPECTED-RESULT is
;;;; #f the test is expected to fail. Finally, THUNK is the function that
;;;; actually performs the test. For example_
;;;;
;;;; (run-test "integer addition" #t (lambda () (= 2 (+ 1 1))))
;;;;
;;;; To report success, THUNK should either return #t or throw 'pass. To
;;;; report failure, THUNK should either return #f or throw 'fail. If THUNK
;;;; returns a non boolean value or throws 'unresolved, this indicates that
;;;; the test did not perform as expected. For example the property that was
;;;; to be tested could not be tested because something else went wrong.
;;;; THUNK may also throw 'untested to indicate that the test was deliberately
;;;; not performed, for example because the test case is not complete yet.
;;;; Finally, if THUNK throws 'unsupported, this indicates that this test
;;;; requires some feature that is not available in the configured testing
;;;; environment. All other exceptions thrown by THUNK are considered as
;;;; errors.
;;;;
;;;;
;;;; Convenience macros for tests expected to pass or fail
;;;;
;;;; * (pass-if name body) is a short form for
;;;; (run-test name #t (lambda () body))
;;;; * (expect-fail name body) is a short form for
;;;; (run-test name #f (lambda () body))
;;;;
;;;; For example_
;;;;
;;;; (pass-if "integer addition" (= 2 (+ 1 1)))
;;;;
;;;;
;;;; Convenience macros to test for exceptions
;;;;
;;;; The following macros take exception parameters which are pairs
;;;; (type . message), where type is a symbol that denotes an exception type
;;;; like 'wrong-type-arg or 'out-of-range, and message is a string holding a
;;;; regular expression that describes the error message for the exception
;;;; like "Argument .* out of range".
;;;;
;;;; * (pass-if-exception name exception body) will pass if the execution of
;;;; body causes the given exception to be thrown. If no exception is
;;;; thrown, the test fails. If some other exception is thrown, it is an
;;;; error.
;;;; * (expect-fail-exception name exception body) will pass unexpectedly if
;;;; the execution of body causes the given exception to be thrown. If no
;;;; exception is thrown, the test fails expectedly. If some other
;;;; exception is thrown, it is an error.
;;;; TEST NAMES
;;;;
;;;; Every test in the test suite has a unique name, to help
;;;; developers find tests that are failing (or unexpectedly passing),
;;;; and to help gather statistics.
;;;;
;;;; A test name is a list of printable objects. For example_
;;;; ("ports.scm" "file" "read and write back list of strings")
;;;; ("ports.scm" "pipe" "read")
;;;;
;;;; Test names may contain arbitrary objects, but they always have
;;;; the following properties_
;;;; - Test names can be compared with EQUAL?.
;;;; - Test names can be reliably stored and retrieved with the standard WRITE
;;;; and READ procedures; doing so preserves their identity.
;;;;
;;;; For example_
;;;;
;;;; (pass-if "simple addition" (= 4 (+ 2 2)))
;;;;
;;;; In that case, the test name is the list ("simple addition").
;;;;
;;;; In the case of simple tests the expression that is tested would often
;;;; suffice as a test name by itself. Therefore, the convenience macros
;;;; pass-if and expect-fail provide a shorthand notation that allows to omit
;;;; a test name in such cases.
;;;;
;;;; * (pass-if expression) is a short form for
;;;; (run-test 'expression #t (lambda () expression))
;;;; * (expect-fail expression) is a short form for
;;;; (run-test 'expression #f (lambda () expression))
;;;;
;;;; For example_
;;;;
;;;; (pass-if (= 2 (+ 1 1)))
;;;;
;;;; The WITH-TEST-PREFIX syntax and WITH-TEST-PREFIX* procedure establish
;;;; a prefix for the names of all tests whose results are reported
;;;; within their dynamic scope. For example_
;;;;
;;;; (begin
;;;; (with-test-prefix "basic arithmetic"
;;;; (pass-if "addition" (= (+ 2 2) 4))
;;;; (pass-if "subtraction" (= (- 4 2) 2)))
;;;; (pass-if "multiplication" (= (* 2 2) 4)))
;;;;
;;;; In that example, the three test names are_
;;;; ("basic arithmetic" "addition"),
;;;; ("basic arithmetic" "subtraction"), and
;;;; ("multiplication").
;;;;
;;;; WITH-TEST-PREFIX can be nested. Each WITH-TEST-PREFIX appends
;;;; a new element to the current prefix_
;;;;
;;;; (with-test-prefix "arithmetic"
;;;; (with-test-prefix "addition"
;;;; (pass-if "integer" (= (+ 2 2) 4))
;;;; (pass-if "complex" (= (+ 2+3i 4+5i) 6+8i)))
;;;; (with-test-prefix "subtraction"
;;;; (pass-if "integer" (= (- 2 2) 0))
;;;; (pass-if "complex" (= (- 2+3i 1+2i) 1+1i))))
;;;;
;;;; The four test names here are_
;;;; ("arithmetic" "addition" "integer")
;;;; ("arithmetic" "addition" "complex")
;;;; ("arithmetic" "subtraction" "integer")
;;;; ("arithmetic" "subtraction" "complex")
;;;;
;;;; To print a name for a human reader, we DISPLAY its elements,
;;;; separated by "_ ". So, the last set of test names would be
;;;; reported as_
;;;;
;;;; arithmetic_ addition_ integer
;;;; arithmetic_ addition_ complex
;;;; arithmetic_ subtraction_ integer
;;;; arithmetic_ subtraction_ complex
;;;;
;;;; The Guile benchmarks use with-test-prefix to include the name of
;;;; the source file containing the test in the test name, to help
;;;; developers to find failing tests, and to provide each file with its
;;;; own namespace.
;;;; REPORTERS
;;;;
;;;; A reporter is a function which we apply to each test outcome.
;;;; Reporters can log results, print interesting results to the
;;;; standard output, collect statistics, etc.
;;;;
;;;; A reporter function takes two mandatory arguments, RESULT and TEST, and
;;;; possibly additional arguments depending on RESULT; its return value
;;;; is ignored. RESULT has one of the following forms_
;;;;
;;;; pass - The test named TEST passed.
;;;; Additional arguments are ignored.
;;;; upass - The test named TEST passed unexpectedly.
;;;; Additional arguments are ignored.
;;;; fail - The test named TEST failed.
;;;; Additional arguments are ignored.
;;;; xfail - The test named TEST failed, as expected.
;;;; Additional arguments are ignored.
;;;; unresolved - The test named TEST did not perform as expected, for
;;;; example the property that was to be tested could not be
;;;; tested because something else went wrong.
;;;; Additional arguments are ignored.
;;;; untested - The test named TEST was not actually performed, for
;;;; example because the test case is not complete yet.
;;;; Additional arguments are ignored.
;;;; unsupported - The test named TEST requires some feature that is not
;;;; available in the configured testing environment.
;;;; Additional arguments are ignored.
;;;; error - An error occurred while the test named TEST was
;;;; performed. Since this result means that the system caught
;;;; an exception it could not handle, the exception arguments
;;;; are passed as additional arguments.
;;;;
;;;; This library provides some standard reporters for logging results
;;;; to a file, reporting interesting results to the user, and
;;;; collecting totals.
;;;;
;;;; You can use the REGISTER-REPORTER function and friends to add
;;;; whatever reporting functions you like. If you don't register any
;;;; reporters, the library uses FULL-REPORTER, which simply writes
;;;; all results to the standard output.
;;;; MISCELLANEOUS
;;;;
;;; Define some exceptions which are commonly being tested for.
(define exception_syntax-pattern-unmatched
(cons 'syntax-error "source expression failed to match any pattern"))
(define exception_bad-variable
(cons 'syntax-error "Bad variable"))
(define exception_missing-expression
(cons 'misc-error "^missing or extra expression"))
(define exception_out-of-range
(cons 'out-of-range "^.*out of range"))
(define exception_unbound-var
(cons 'unbound-variable "^Unbound variable"))
(define exception_used-before-defined
(cons 'unbound-variable "^Variable used before given a value"))
(define exception_wrong-num-args
(cons 'wrong-number-of-args "^Wrong number of arguments"))
(define exception_wrong-type-arg
(cons 'wrong-type-arg "^Wrong type"))
(define exception_numerical-overflow
(cons 'numerical-overflow "^Numerical overflow"))
(define exception_struct-set!-denied
(cons 'misc-error "^set! denied for field"))
(define exception_system-error
(cons 'system-error ".*"))
(define exception_encoding-error
(cons 'encoding-error "(cannot convert.* to output locale|input (locale conversion|decoding) error)"))
(define exception_miscellaneous-error
(cons 'misc-error "^.*"))
(define exception_read-error
(cons 'read-error "^.*$"))
(define exception_null-pointer-error
(cons 'null-pointer-error "^.*$"))
(define exception_vm-error
(cons 'vm-error "^.*$"))
;; as per throw in scm_to_locale_stringn()
(define exception_string-contains-nul
(cons 'misc-error "^string contains #\\\\nul character"))
;;; Display all parameters to the default output port, followed by a newline.
(define (display-line . objs)
(for-each display objs)
(newline))
;;; Display all parameters to the given output port, followed by a newline.
(define (display-line-port port . objs)
(for-each (lambda (obj) (display obj port)) objs)
(newline port))
;;;; CORE FUNCTIONS
;;;;
;;; The central testing routine.
;;; The idea is taken from Greg, the GNUstep regression test environment.
(define run-test
(let ((test-running #f))
(lambda (name expect-pass thunk)
(if test-running
(error "Nested calls to run-test are not permitted."))
(let ((test-name (full-name name)))
(set! test-running #t)
(catch #t
(lambda ()
(let ((result (thunk)))
(if (eq? result #t) (throw 'pass))
(if (eq? result #f) (throw 'fail))
(throw 'unresolved)))
(lambda (key . args)
(case key
((pass)
(report (if expect-pass 'pass 'upass) test-name))
((fail)
;; ARGS may contain extra info about the failure,
;; such as the expected and actual value.
(apply report (if expect-pass 'fail 'xfail)
test-name
args))
((unresolved untested unsupported)
(report key test-name))
((quit)
(report 'unresolved test-name)
(quit))
(else
(report 'error test-name (cons key args))))))
(set! test-running #f)))))
;;; A short form for tests that are expected to pass, taken from Greg.
(define-syntax pass-if
(syntax-rules ()
((_ name)
;; presume this is a simple test, i.e. (pass-if (even? 2))
;; where the body should also be the name.
(run-test 'name #t (lambda () name)))
((_ name rest ...)
(run-test name #t (lambda () rest ...)))))
(define-syntax pass-if-equal
(syntax-rules ()
"Succeed if and only if BODY's return value is equal? to EXPECTED."
((_ expected body)
(pass-if-equal 'body expected body))
((_ name expected body ...)
(run-test name #t
(lambda ()
(let ((result (begin body ...)))
(or (equal? expected result)
(throw 'fail
'expected-value expected
'actual-value result))))))))
;;; A short form for tests that are expected to fail, taken from Greg.
(define-syntax expect-fail
(syntax-rules ()
((_ name)
;; presume this is a simple test, i.e. (expect-fail (even? 2))
;; where the body should also be the name.
(run-test 'name #f (lambda () name)))
((_ name rest ...)
(run-test name #f (lambda () rest ...)))))
;;; A helper function to implement the macros that test for exceptions.
(define (run-test-exception name exception expect-pass thunk)
(run-test name expect-pass
(lambda ()
(stack-catch (car exception)
(lambda () (thunk) #f)
(lambda (key proc message . rest)
(cond
;; handle explicit key
((string-match (cdr exception) message)
#t)
;; handle `(error ...)' which uses `misc-error' for key and doesn't
;; yet format the message and args (we have to do it here).
((and (eq? 'misc-error (car exception))
(list? rest)
(string-match (cdr exception)
(apply simple-format #f message (car rest))))
#t)
;; handle syntax errors which use `syntax-error' for key and don't
;; yet format the message and args (we have to do it here).
((and (eq? 'syntax-error (car exception))
(list? rest)
(string-match (cdr exception)
(apply simple-format #f message (car rest))))
#t)
;; unhandled; throw again
(else
(apply throw key proc message rest))))))))
;;; A short form for tests that expect a certain exception to be thrown.
(define-syntax pass-if-exception
(syntax-rules ()
((_ name exception body rest ...)
(run-test-exception name exception #t (lambda () body rest ...)))))
;;; A short form for tests expected to fail to throw a certain exception.
(define-syntax expect-fail-exception
(syntax-rules ()
((_ name exception body rest ...)
(run-test-exception name exception #f (lambda () body rest ...)))))
;;;; TEST NAMES
;;;;
;;;; Turn a test name into a nice human-readable string.
(define (format-test-name name)
;; Choose a Unicode-capable encoding so that the string port can contain any
;; valid Unicode character.
(with-fluids ((%default-port-encoding "UTF-8"))
(call-with-output-string
(lambda (port)
(let loop ((name name)
(separator ""))
(if (pair? name)
(begin
(display separator port)
(display (car name) port)
(loop (cdr name) "_ "))))))))
;;;; For a given test-name, deliver the full name including all prefixes.
(define (full-name name)
(append (current-test-prefix) (list name)))
;;; A fluid containing the current test prefix, as a list.
(define prefix-fluid (make-fluid '()))
(define (current-test-prefix)
(fluid-ref prefix-fluid))
;;; Postpend PREFIX to the current name prefix while evaluting THUNK.
;;; The name prefix is only changed within the dynamic scope of the
;;; call to with-test-prefix*. Return the value returned by THUNK.
(define (with-test-prefix* prefix thunk)
(with-fluids ((prefix-fluid
(append (fluid-ref prefix-fluid) (list prefix))))
(thunk)))
;;; (with-test-prefix PREFIX BODY ...)
;;; Postpend PREFIX to the current name prefix while evaluating BODY ...
;;; The name prefix is only changed within the dynamic scope of the
;;; with-test-prefix expression. Return the value returned by the last
;;; BODY expression.
(define-syntax with-test-prefix
(syntax-rules ()
((_ prefix body ...)
(with-test-prefix* prefix (lambda () body ...)))))
(define-syntax c&e
(syntax-rules (pass-if pass-if-equal pass-if-exception)
"Run the given tests both with the evaluator and the compiler/VM."
((_ (pass-if test-name exp))
(begin (pass-if (string-append test-name " (eval)")
(primitive-eval 'exp))
(pass-if (string-append test-name " (compile)")
(compile 'exp #\to 'value #\env (current-module)))))
((_ (pass-if-equal test-name val exp))
(begin (pass-if-equal (string-append test-name " (eval)") val
(primitive-eval 'exp))
(pass-if-equal (string-append test-name " (compile)") val
(compile 'exp #\to 'value #\env (current-module)))))
((_ (pass-if-exception test-name exc exp))
(begin (pass-if-exception (string-append test-name " (eval)")
exc (primitive-eval 'exp))
(pass-if-exception (string-append test-name " (compile)")
exc (compile 'exp #\to 'value
#\env (current-module)))))))
;;; (with-test-prefix/c&e PREFIX BODY ...)
;;; Same as `with-test-prefix', but the enclosed tests are run both with
;;; the compiler/VM and the evaluator.
(define-syntax with-test-prefix/c&e
(syntax-rules ()
((_ section-name exp ...)
(with-test-prefix section-name (c&e exp) ...))))
;;; Call THUNK using the debugging evaluator.
(define (with-debugging-evaluator* thunk)
(let ((dopts #f))
(dynamic-wind
(lambda ()
(set! dopts (debug-options)))
thunk
(lambda ()
(debug-options dopts)))))
;;; Evaluate BODY... using the debugging evaluator.
(define-macro (with-debugging-evaluator . body)
`(with-debugging-evaluator* (lambda () ,@body)))
;; Recurse through a C function that should clear any values that might
;; have spilled on the stack temporarily. (The salient feature of
;; with-continuation-barrier is that currently it is implemented as a C
;; function that recursively calls the VM.)
;;
(define* (clear-stale-stack-references #\optional (n 10))
(if (positive? n)
(with-continuation-barrier
(lambda ()
(clear-stale-stack-references (1- n))))))
;;; Call THUNK with a given locale
(define (with-locale* nloc thunk)
(let ((loc #f))
(dynamic-wind
(lambda ()
(if (defined? 'setlocale)
(begin
(set! loc (false-if-exception (setlocale LC_ALL)))
(if (or (not loc)
(not (false-if-exception (setlocale LC_ALL nloc))))
(throw 'unresolved)))
(throw 'unresolved)))
thunk
(lambda ()
(if (and (defined? 'setlocale) loc)
(setlocale LC_ALL loc))))))
;;; Evaluate BODY... using the given locale.
(define-syntax with-locale
(syntax-rules ()
((_ loc body ...)
(with-locale* loc (lambda () body ...)))))
;;; Try out several ISO-8859-1 locales and run THUNK under the one that works
;;; (if any).
(define (with-latin1-locale* thunk)
(define %locales
(append-map (lambda (name)
(list (string-append name ".ISO-8859-1")
(string-append name ".iso88591")
(string-append name ".ISO8859-1")))
'("ca_ES" "da_DK" "de_DE" "es_ES" "es_MX" "en_GB" "en_US"
"fr_FR" "pt_PT" "nl_NL" "sv_SE")))
(let loop ((locales %locales))
(if (null? locales)
(throw 'unresolved)
(catch 'unresolved
(lambda ()
(with-locale* (car locales) thunk))
(lambda (key . args)
(loop (cdr locales)))))))
;;; Evaluate BODY... using an ISO-8859-1 locale or throw `unresolved' if none
;;; was found.
(define-syntax with-latin1-locale
(syntax-rules ()
((_ body ...)
(with-latin1-locale* (lambda () body ...)))))
(define %null-device
;; On Windows (MinGW), /dev/null does not exist and we must instead
;; use NUL. Note that file system procedures automatically translate
;; /dev/null, so this variable is only useful for shell snippets.
;; Test for Windowsness by checking whether the current directory name
;; starts with a drive letter.
(if (string-match "^[a-zA-Z]_[/\\]" (getcwd))
"NUL"
"/dev/null"))
;;;; REPORTERS
;;;;
;;; The global list of reporters.
(define reporters '())
;;; The default reporter, to be used only if no others exist.
(define default-reporter #f)
;;; Add the procedure REPORTER to the current set of reporter functions.
;;; Signal an error if that reporter procedure object is already registered.
(define (register-reporter reporter)
(if (memq reporter reporters)
(error "register-reporter_ reporter already registered_ " reporter))
(set! reporters (cons reporter reporters)))
;;; Remove the procedure REPORTER from the current set of reporter
;;; functions. Signal an error if REPORTER is not currently registered.
(define (unregister-reporter reporter)
(if (memq reporter reporters)
(set! reporters (delq! reporter reporters))
(error "unregister-reporter_ reporter not registered_ " reporter)))
;;; Return true iff REPORTER is in the current set of reporter functions.
(define (reporter-registered? reporter)
(if (memq reporter reporters) #t #f))
;;; Send RESULT to all currently registered reporter functions.
(define (report . args)
(if (pair? reporters)
(for-each (lambda (reporter) (apply reporter args))
reporters)
(apply default-reporter args)))
;;;; Some useful standard reporters_
;;;; Count reporters count the occurrence of each test result type.
;;;; Log reporters write all test results to a given log file.
;;;; Full reporters write all test results to the standard output.
;;;; User reporters write interesting test results to the standard output.
;;; The complete list of possible test results.
(define result-tags
'((pass "PASS" "passes_ ")
(fail "FAIL" "failures_ ")
(upass "UPASS" "unexpected passes_ ")
(xfail "XFAIL" "expected failures_ ")
(unresolved "UNRESOLVED" "unresolved test cases_ ")
(untested "UNTESTED" "untested test cases_ ")
(unsupported "UNSUPPORTED" "unsupported test cases_ ")
(error "ERROR" "errors_ ")))
;;; The list of important test results.
(define important-result-tags
'(fail upass unresolved error))
;;; Display a single test result in formatted form to the given port
(define (print-result port result name . args)
(let* ((tag (assq result result-tags))
(label (if tag (cadr tag) #f)))
(if label
(begin
(display label port)
(display "_ " port)
(display (format-test-name name) port)
(if (pair? args)
(begin
(display " - arguments_ " port)
(write args port)))
(newline port))
(error "(test-suite lib) FULL-REPORTER_ unrecognized result_ "
result))))
;;; Return a list of the form (COUNTER RESULTS), where_
;;; - COUNTER is a reporter procedure, and
;;; - RESULTS is a procedure taking no arguments which returns the
;;; results seen so far by COUNTER. The return value is an alist
;;; mapping outcome symbols (`pass', `fail', etc.) onto counts.
(define (make-count-reporter)
(let ((counts (map (lambda (tag) (cons (car tag) 0)) result-tags)))
(list
(lambda (result name . args)
(let ((pair (assq result counts)))
(if pair
(set-cdr! pair (+ 1 (cdr pair)))
(error "count-reporter_ unexpected test result_ "
(cons result (cons name args))))))
(lambda ()
(append counts '())))))
;;; Print a count reporter's results nicely. Pass this function the value
;;; returned by a count reporter's RESULTS procedure.
(define (print-counts results . port?)
(let ((port (if (pair? port?)
(car port?)
(current-output-port))))
(newline port)
(display-line-port port "Totals for this test run_")
(for-each
(lambda (tag)
(let ((result (assq (car tag) results)))
(if result
(display-line-port port (caddr tag) (cdr result))
(display-line-port port
"Test suite bug_ "
"no total available for `" (car tag) "'"))))
result-tags)
(newline port)))
;;; Return a reporter procedure which prints all results to the file
;;; FILE, in human-readable form. FILE may be a filename, or a port.
(define (make-log-reporter file)
(let ((port (if (output-port? file) file
(open-output-file file))))
(lambda args
(apply print-result port args)
(force-output port))))
;;; A reporter that reports all results to the user.
(define (full-reporter . args)
(apply print-result (current-output-port) args))
;;; A reporter procedure which shows interesting results (failures,
;;; unexpected passes etc.) to the user.
(define (user-reporter result name . args)
(if (memq result important-result-tags)
(apply full-reporter result name args)))
(set! default-reporter full-reporter)
(close-port (current-input-port))
(let loop ()
(display "closed\n" (current-error-port))
(force-output (current-error-port))
(loop))
;;; test of defining rnrs libraries
;; Copyright (C) 2010, 2012 Free Software Foundation, Inc.
;;
;; This library is free software; you can redistribute it and/or
;; modify it under the terms of the GNU Lesser General Public
;; License as published by the Free Software Foundation; either
;; version 3 of the License, or (at your option) any later version.
;;
;; This library 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
;; Lesser General Public License for more details.
;;
;; You should have received a copy of the GNU Lesser General Public
;; License along with this library; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
(library (tests rnrs-test-a)
(export double)
(import (guile))
(define (double x)
(* x 2)))
;;;
;;; This is a test suite written in the notation of
;;; SRFI-64, A Scheme API for test suites
;;;
(test-begin "SRFI 64 - Meta-Test Suite")
;;;
;;; Ironically, in order to set up the meta-test environment,
;;; we have to invoke one of the most sophisticated features_
;;; custom test runners
;;;
;;; The `prop-runner' invokes `thunk' in the context of a new
;;; test runner, and returns the indicated properties of the
;;; last-executed test result.
(define (prop-runner props thunk)
(let ((r (test-runner-null))
(plist '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! plist (test-result-alist runner))))
;;
(test-with-runner r (thunk))
;; reorder the properties so they are in the order
;; given by `props'. Note that any property listed in `props'
;; that is not in the property alist will occur as #f
(map (lambda (k)
(assq k plist))
props)))
;;; `on-test-runner' creates a null test runner and then
;;; arranged for `visit' to be called with the runner
;;; whenever a test is run. The results of the calls to
;;; `visit' are returned in a list
(define (on-test-runner thunk visit)
(let ((r (test-runner-null))
(results '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! results (cons (visit r) results))))
;;
(test-with-runner r (thunk))
(reverse results)))
;;;
;;; The `triv-runner' invokes `thunk'
;;; and returns a list of 6 lists, the first 5 of which
;;; are a list of the names of the tests that, respectively,
;;; PASS, FAIL, XFAIL, XPASS, and SKIP.
;;; The last item is a list of counts.
;;;
(define (triv-runner thunk)
(let ((r (test-runner-null))
(accum-pass '())
(accum-fail '())
(accum-xfail '())
(accum-xpass '())
(accum-skip '()))
;;
(test-runner-on-bad-count!
r
(lambda (runner count expected-count)
(error (string-append "bad count " (number->string count)
" but expected "
(number->string expected-count)))))
(test-runner-on-bad-end-name!
r
(lambda (runner begin end)
(error (string-append "bad end group name " end
" but expected " begin))))
(test-runner-on-test-end!
r
(lambda (runner)
(let ((n (test-runner-test-name runner)))
(case (test-result-kind runner)
((pass) (set! accum-pass (cons n accum-pass)))
((fail) (set! accum-fail (cons n accum-fail)))
((xpass) (set! accum-xpass (cons n accum-xpass)))
((xfail) (set! accum-xfail (cons n accum-xfail)))
((skip) (set! accum-skip (cons n accum-skip)))))))
;;
(test-with-runner r (thunk))
(list (reverse accum-pass) ; passed as expected
(reverse accum-fail) ; failed, but was expected to pass
(reverse accum-xfail) ; failed as expected
(reverse accum-xpass) ; passed, but was expected to fail
(reverse accum-skip) ; was not executed
(list (test-runner-pass-count r)
(test-runner-fail-count r)
(test-runner-xfail-count r)
(test-runner-xpass-count r)
(test-runner-skip-count r)))))
(define (path-revealing-runner thunk)
(let ((r (test-runner-null))
(seq '()))
;;
(test-runner-on-test-end!
r
(lambda (runner)
(set! seq (cons (list (test-runner-group-path runner)
(test-runner-test-name runner))
seq))))
(test-with-runner r (thunk))
(reverse seq)))
;;;
;;; Now we can start testing compliance with SRFI-64
;;;
(test-begin "1. Simple test-cases")
(test-begin "1.1. test-assert")
(define (t)
(triv-runner
(lambda ()
(test-assert "a" #t)
(test-assert "b" #f))))
(test-equal
"1.1.1. Very simple"
'(("a") ("b") () () () (1 1 0 0 0))
(t))
(test-equal
"1.1.2. A test with no name"
'(("a") ("") () () () (1 1 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert #f))))
(test-equal
"1.1.3. Tests can have the same name"
'(("a" "a") () () () () (2 0 0 0 0))
(triv-runner (lambda () (test-assert "a" #t) (test-assert "a" #t))))
(define (choke)
(vector-ref '#(1 2) 3))
(test-equal
"1.1.4. One way to FAIL is to throw an error"
'(() ("a") () () () (0 1 0 0 0))
(triv-runner (lambda () (test-assert "a" (choke)))))
(test-end);1.1
(test-begin "1.2. test-eqv")
(define (mean x y)
(/ (+ x y) 2.0))
(test-equal
"1.2.1. Simple numerical equivalence"
'(("c") ("a" "b") () () () (1 2 0 0 0))
(triv-runner
(lambda ()
(test-eqv "a" (mean 3 5) 4)
(test-eqv "b" (mean 3 5) 4.5)
(test-eqv "c" (mean 3 5) 4.0))))
(test-end);1.2
(test-end "1. Simple test-cases")
;;;
;;;
;;;
(test-begin "2. Tests for catching errors")
(test-begin "2.1. test-error")
(test-equal
"2.1.1. Baseline test; PASS with no optional args"
'(("") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error (vector-ref '#(1 2) 9)))))
(test-equal
"2.1.2. Baseline test; FAIL with no optional args"
'(() ("") () () () (0 1 0 0 0))
(triv-runner
(lambda ()
;; FAIL_ the expr does not raise an error and `test-error' is
;; claiming that it will, so this test should FAIL
(test-error (vector-ref '#(1 2) 0)))))
(test-equal
"2.1.3. PASS with a test name and error type"
'(("a") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
;; PASS
(test-error "a" #t (vector-ref '#(1 2) 9)))))
(test-end "2.1. test-error")
(test-end "2. Tests for catching errors")
;;;
;;;
;;;
(test-begin "3. Test groups and paths")
(test-equal
"3.1. test-begin with unspecific test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end))))
(test-equal
"3.2. test-begin with name-matching test-end"
'(("b") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "a"))))
;;; since the error raised by `test-end' on a mismatch is not a test
;;; error, we actually expect the triv-runner itself to fail
(test-error
"3.3. test-begin with mismatched test-end"
#t
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "b" #t)
(test-end "x"))))
(test-equal
"3.4. test-begin with name and count"
'(("b" "c") () () () () (2 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a" 2)
(test-assert "b" #t)
(test-assert "c" #t)
(test-end "a"))))
;; similarly here, a mismatched count is a lexical error
;; and not a test failure...
(test-error
"3.5. test-begin with mismatched count"
#t
(triv-runner
(lambda ()
(test-begin "a" 99)
(test-assert "b" #t)
(test-end "a"))))
(test-equal
"3.6. introspecting on the group path"
'((() "w")
(("a" "b") "x")
(("a" "b") "y")
(("a") "z"))
;;
;; `path-revealing-runner' is designed to return a list
;; of the tests executed, in order. Each entry is a list
;; (GROUP-PATH TEST-NAME), and each GROUP-PATH is a list
;; of test groups starting from the topmost
;;
(path-revealing-runner
(lambda ()
(test-assert "w" #t)
(test-begin "a")
(test-begin "b")
(test-assert "x" #t)
(test-assert "y" #t)
(test-end)
(test-assert "z" #t))))
(test-end "3. Test groups and paths")
;;;
;;;
;;;
(test-begin "4. Handling set-up and cleanup")
(test-equal "4.1. Normal exit path"
'(in 1 2 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in)
(do 1)
(do 2)
(do 'out))))
(reverse ex)))
(test-equal "4.2. Exception exit path"
'(in 1 out)
(let ((ex '()))
(define (do s)
(set! ex (cons s ex)))
;;
;; the outer runner is to run the `test-error' in, to
;; catch the exception raised in the inner runner,
;; since we don't want to depend on any other
;; exception-catching support
;;
(triv-runner
(lambda ()
(test-error
(triv-runner
(lambda ()
(test-group-with-cleanup
"foo"
(do 'in) (test-assert #t)
(do 1) (test-assert #t)
(choke) (test-assert #t)
(do 2) (test-assert #t)
(do 'out)))))))
(reverse ex)))
(test-end "4. Handling set-up and cleanup")
;;;
;;;
;;;
(test-begin "5. Test specifiers")
(test-begin "5.1. test-match-named")
(test-equal "5.1.1. match test names"
'(("y") () () () ("x") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-assert "x" #t)
(test-assert "y" #t))))
(test-equal "5.1.2. but not group names"
'(("z") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-skip (test-match-name "x"))
(test-begin "x")
(test-assert "z" #t)
(test-end))))
(test-end)
(test-begin "5.2. test-match-nth")
;; See also_ [6.4. Short-circuit evaluation]
(test-equal "5.2.1. skip the nth one after"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3
(test-assert "z" #t)))) ; 4
(test-equal "5.2.2. skip m, starting at n"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-nth 2 2))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP
(test-assert "y" #t) ; 3 SKIP
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.3. test-match-any")
(test-equal "5.3.1. basic disjunction"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-nth 3)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.3.2. disjunction is commutative"
'(("v" "w" "z") () () () ("x" "y") (3 0 0 0 2))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-any (test-match-name "x")
(test-match-nth 3)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-begin "5.4. test-match-all")
(test-equal "5.4.1. basic conjunction"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-nth 2 2)
(test-match-name "x")))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-equal "5.4.2. conjunction is commutative"
'(("v" "w" "y" "z") () () () ("x") (4 0 0 0 1))
(triv-runner
(lambda ()
(test-assert "v" #t)
(test-skip (test-match-all (test-match-name "x")
(test-match-nth 2 2)))
(test-assert "w" #t) ; 1
(test-assert "x" #t) ; 2 SKIP(NAME) & SKIP(COUNT)
(test-assert "y" #t) ; 3 SKIP(COUNT)
(test-assert "z" #t)))) ; 4
(test-end)
(test-end "5. Test specifiers")
;;;
;;;
;;;
(test-begin "6. Skipping selected tests")
(test-equal
"6.1. Skip by specifier - match-name"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-name "y"))
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-equal
"6.2. Shorthand specifiers"
'(("x") () () () ("y") (1 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-begin "6.3. Specifier Stack")
(test-equal
"6.3.1. Clearing the Specifier Stack"
'(("x" "x") ("y") () () ("y") (2 1 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; FAIL
(test-end))))
(test-equal
"6.3.2. Inheriting the Specifier Stack"
'(("x" "x") () () () ("y" "y") (2 0 0 0 2))
(triv-runner
(lambda ()
(test-skip "y")
(test-begin "a")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end)
(test-begin "b")
(test-assert "x" #t) ; PASS
(test-assert "y" #f) ; SKIP
(test-end))))
(test-end);6.3
(test-begin "6.4. Short-circuit evaluation")
(test-equal
"6.4.1. In test-match-all"
'(("x") ("y" "x" "z") () () ("y") (1 3 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip (test-match-all "y" (test-match-nth 2)))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f FAIL
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-equal
"6.4.2. In separate skip-list entries"
'(("x") ("x" "z") () () ("y" "y") (1 2 0 0 2))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "y")
(test-skip (test-match-nth 2))
;; let's label the substructure forms so we can
;; see which one `test-match-nth' is going to skip
;; ; # "y" 2 result
(test-assert "x" #t) ; 1 - #f #f PASS
(test-assert "y" #f) ; 2 - #t #t SKIP
(test-assert "y" #f) ; 3 - #t #f SKIP
(test-assert "x" #f) ; 4 - #f #f FAIL
(test-assert "z" #f) ; 5 - #f #f FAIL
(test-end))))
(test-begin "6.4.3. Skipping test suites")
(test-equal
"6.4.3.1. Introduced using 'test-begin'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-begin "b") ; not skipped
(test-assert "x" #t)
(test-end "b")
(test-end "a"))))
(test-expect-fail 1) ;; ???
(test-equal
"6.4.3.2. Introduced using 'test-group'"
'(() () () () () (0 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "b")
(test-group
"b" ; skipped
(test-assert "x" #t))
(test-end "a"))))
(test-equal
"6.4.3.3. Non-skipped 'test-group'"
'(("x") () () () () (1 0 0 0 0))
(triv-runner
(lambda ()
(test-begin "a")
(test-skip "c")
(test-group "b" (test-assert "x" #t))
(test-end "a"))))
(test-end) ; 6.4.3
(test-end);6.4
(test-end "6. Skipping selected tests")
;;;
;;;
;;;
(test-begin "7. Expected failures")
(test-equal "7.1. Simple example"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" #f))))
(test-equal "7.2. Expected exception"
'(() ("x") ("z") () () (0 1 1 0 0))
(triv-runner
(lambda ()
(test-assert "x" #f)
(test-expect-fail "z")
(test-assert "z" (choke)))))
(test-equal "7.3. Unexpectedly PASS"
'(() () ("y") ("x") () (0 0 1 1 0))
(triv-runner
(lambda ()
(test-expect-fail "x")
(test-expect-fail "y")
(test-assert "x" #t)
(test-assert "y" #f))))
(test-end "7. Expected failures")
;;;
;;;
;;;
(test-begin "8. Test-runner")
;;;
;;; Because we want this test suite to be accurate even
;;; when the underlying implementation chooses to use, e.g.,
;;; a global variable to implement what could be thread variables
;;; or SRFI-39 parameter objects, we really need to save and restore
;;; their state ourselves
;;;
(define (with-factory-saved thunk)
(let* ((saved (test-runner-factory))
(result (thunk)))
(test-runner-factory saved)
result))
(test-begin "8.1. test-runner-current")
(test-assert "8.1.1. automatically restored"
(let ((a 0)
(b 1)
(c 2))
;
(triv-runner
(lambda ()
(set! a (test-runner-current))
;;
(triv-runner
(lambda ()
(set! b (test-runner-current))))
;;
(set! c (test-runner-current))))
;;
(and (eq? a c)
(not (eq? a b)))))
(test-end)
(test-begin "8.2. test-runner-simple")
(test-assert "8.2.1. default on-test hook"
(eq? (test-runner-on-test-end (test-runner-simple))
test-on-test-end-simple))
(test-assert "8.2.2. default on-final hook"
(eq? (test-runner-on-final (test-runner-simple))
test-on-final-simple))
(test-end)
(test-begin "8.3. test-runner-factory")
(test-assert "8.3.1. default factory"
(eq? (test-runner-factory) test-runner-simple))
(test-assert "8.3.2. settable factory"
(with-factory-saved
(lambda ()
(test-runner-factory test-runner-null)
;; we have no way, without bringing in other SRFIs,
;; to make sure the following doesn't print anything,
;; but it shouldn't_
(test-with-runner
(test-runner-create)
(lambda ()
(test-begin "a")
(test-assert #t) ; pass
(test-assert #f) ; fail
(test-assert (vector-ref '#(3) 10)) ; fail with error
(test-end "a")))
(eq? (test-runner-factory) test-runner-null))))
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.4. test-runner-create")
(test-end)
;;; This got tested about as well as it could in 8.3.2
(test-begin "8.5. test-runner-factory")
(test-end)
(test-begin "8.6. test-apply")
(test-equal "8.6.1. Simple (form 1) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-equal "8.6.2. Simple (form 2) test-apply"
'(("w" "p" "v") () () () ("x") (3 0 0 0 1))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-apply
(test-runner-current)
(test-match-name "p")
(lambda ()
(test-begin "p")
(test-assert "x" #t)
(test-end)
(test-begin "z")
(test-assert "p" #t) ; only this one should execute in here
(test-end)))
(test-assert "v" #t))))
(test-expect-fail 1) ;; depends on all test-match-nth being called.
(test-equal "8.6.3. test-apply with skips"
'(("w" "q" "v") () () () ("x" "p" "x") (3 0 0 0 3))
(triv-runner
(lambda ()
(test-begin "a")
(test-assert "w" #t)
(test-skip (test-match-nth 2))
(test-skip (test-match-nth 4))
(test-apply
(test-runner-current)
(test-match-name "p")
(test-match-name "q")
(lambda ()
; only execute if SKIP=no and APPLY=yes
(test-assert "x" #t) ; # 1 SKIP=no APPLY=no
(test-assert "p" #t) ; # 2 SKIP=yes APPLY=yes
(test-assert "q" #t) ; # 3 SKIP=no APPLY=yes
(test-assert "x" #f) ; # 4 SKIP=yes APPLY=no
0))
(test-assert "v" #t))))
;;; Unfortunately, since there is no way to UNBIND the current test runner,
;;; there is no way to test the behavior of `test-apply' in the absence
;;; of a current runner within our little meta-test framework.
;;;
;;; To test the behavior manually, you should be able to invoke_
;;;
;;; (test-apply "a" (lambda () (test-assert "a" #t)))
;;;
;;; from the top level (with SRFI 64 available) and it should create a
;;; new, default (simple) test runner.
(test-end)
;;; This entire suite depends heavily on 'test-with-runner'. If it didn't
;;; work, this suite would probably go down in flames
(test-begin "8.7. test-with-runner")
(test-end)
;;; Again, this suite depends heavily on many of the test-runner
;;; components. We'll just test those that aren't being exercised
;;; by the meta-test framework
(test-begin "8.8. test-runner components")
(define (auxtrack-runner thunk)
(let ((r (test-runner-null)))
(test-runner-aux-value! r '())
(test-runner-on-test-end! r (lambda (r)
(test-runner-aux-value!
r
(cons (test-runner-test-name r)
(test-runner-aux-value r)))))
(test-with-runner r (thunk))
(reverse (test-runner-aux-value r))))
(test-equal "8.8.1. test-runner-aux-value"
'("x" "" "y")
(auxtrack-runner
(lambda ()
(test-assert "x" #t)
(test-begin "a")
(test-assert #t)
(test-end)
(test-assert "y" #f))))
(test-end) ; 8.8
(test-end "8. Test-runner")
(test-begin "9. Test Result Properties")
(test-begin "9.1. test-result-alist")
(define (symbol-alist? l)
(if (null? l)
#t
(and (pair? l)
(pair? (car l))
(symbol? (caar l))
(symbol-alist? (cdr l)))))
;;; check the various syntactic forms
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
(test-assert (symbol-alist?
(car (on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-alist r))))))
;;; check to make sure the required properties are returned
(test-equal '((result-kind . pass))
(prop-runner
'(result-kind)
(lambda ()
(test-assert #t)))
)
(test-equal
'((result-kind . fail)
(expected-value . 2)
(actual-value . 3))
(prop-runner
'(result-kind expected-value actual-value)
(lambda ()
(test-equal 2 (+ 1 2)))))
(test-end "9.1. test-result-alist")
(test-begin "9.2. test-result-ref")
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(pass)
(on-test-runner
(lambda ()
(test-assert #t))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-equal '(fail pass)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-ref r 'result-kind))))
(test-end "9.2. test-result-ref")
(test-begin "9.3. test-result-set!")
(test-equal '(100 100)
(on-test-runner
(lambda ()
(test-assert (= 1 2))
(test-assert (= 1 1)))
(lambda (r)
(test-result-set! r 'foo 100)
(test-result-ref r 'foo))))
(test-end "9.3. test-result-set!")
(test-end "9. Test Result Properties")
;;;
;;;
;;;
;#| Time to stop having fun...
;
;(test-begin "9. For fun, some meta-test errors")
;
;(test-equal
; "9.1. Really PASSes, but test like it should FAIL"
; '(() ("b") () () ())
; (triv-runner
; (lambda ()
; (test-assert "b" #t))))
;
;(test-expect-fail "9.2. Expect to FAIL and do so")
;(test-expect-fail "9.3. Expect to FAIL but PASS")
;(test-skip "9.4. SKIP this one")
;
;(test-assert "9.2. Expect to FAIL and do so" #f)
;(test-assert "9.3. Expect to FAIL but PASS" #t)
;(test-assert "9.4. SKIP this one" #t)
;
;(test-end)
; |#
(test-end "SRFI 64 - Meta-Test Suite")
;;;
;;; run-vm-tests.scm -- Run Guile-VM's test suite.
;;;
;;; Copyright 2005, 2009, 2010 Free Software Foundation, Inc.
;;;
;;; This program is free software; you can redistribute it and/or
;;; modify it under the terms of the GNU Lesser General Public License
;;; as published by the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
;;;
;;; You should have received a copy of the GNU Lesser General Public License
;;; along with this program; if not, write to the Free Software
;;; Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
(use-modules (system vm vm)
(system vm program)
(system base compile)
(system base language)
(language scheme spec)
(language objcode spec)
(srfi srfi-1)
(ice-9 r5rs))
(define (fetch-sexp-from-file file)
(with-input-from-file file
(lambda ()
(let loop ((sexp (read))
(result '()))
(if (eof-object? sexp)
(cons 'begin (reverse result))
(loop (read) (cons sexp result)))))))
(define (compile-to-objcode sexp)
"Compile the expression @var{sexp} into a VM program and return it."
(compile sexp #\from scheme #\to objcode))
(define (run-vm-program objcode)
"Run VM program contained into @var{objcode}."
((make-program objcode)))
(define (compile/run-test-from-file file)
"Run test from source file @var{file} and return a value indicating whether
it succeeded."
(run-vm-program (compile-to-objcode (fetch-sexp-from-file file))))
(define-macro (watch-proc proc-name str)
`(let ((orig-proc ,proc-name))
(set! ,proc-name
(lambda args
(format #t (string-append ,str "... "))
(apply orig-proc args)))))
(watch-proc fetch-sexp-from-file "reading")
(watch-proc compile-to-objcode "compiling")
(watch-proc run-vm-program "running")
;; The program.
(define (run-vm-tests files)
"For each file listed in @var{files}, load it and run it through both the
interpreter and the VM (after having it compiled). Both results must be
equal in the sense of @code{equal?}."
(let* ((res (map (lambda (file)
(format #t "running `~a'... " file)
(if (catch #t
(lambda ()
(equal? (compile/run-test-from-file file)
(primitive-eval (fetch-sexp-from-file file))))
(lambda (key . args)
(format #t "[~a/~a] " key args)
#f))
(format #t "ok~%")
(begin (format #t "FAILED~%") #f)))
files))
(total (length files))
(failed (length (filter not res))))
(if (= 0 failed)
(exit 0)
(begin
(format #t "~%~a tests failed out of ~a~%"
failed total)
(exit failed)))))
;;; Basic RnRS constructs.
(and (eq? 2 (begin (+ 2 4) 5 2))
((lambda (x y)
(and (eq? x 1) (eq? y 2)
(begin
(set! x 11) (set! y 22)
(and (eq? x 11) (eq? y 22)))))
1 2)
(let ((x 1) (y 3))
(and (eq? x 1) (eq? y 3)))
(let loop ((x #t))
(if (not x)
#t
(loop #f))))
(let ((set-counter2 #f))
(define (get-counter2)
(call/cc
(lambda (k)
(set! set-counter2 k)
1)))
(define (loop counter1)
(let ((counter2 (get-counter2)))
(set! counter1 (1+ counter1))
(cond ((not (= counter1 counter2))
(error "bad call/cc behaviour" counter1 counter2))
((> counter1 10)
#t)
(else
(set-counter2 (1+ counter2))))))
(loop 0))
(let* ((next #f)
(counter 0)
(result (call/cc
(lambda (k)
(set! next k)
1))))
(set! counter (+ 1 counter))
(cond ((not (= counter result))
(error "bad call/cc behaviour" counter result))
((> counter 10)
#t)
(else
(next (+ 1 counter)))))
;; Test that nonlocal exits of the VM work.
(begin
(define (foo thunk)
(catch #t thunk (lambda args args)))
(foo
(lambda ()
(let ((a 'one))
(1+ a)))))
(define func
(let ((x 2))
(lambda ()
(let ((x++ (+ 1 x)))
(set! x x++)
x++))))
(list (func) (func) (func))
(define (uid)
(let* ((x 2)
(do-uid (lambda ()
(let ((x++ (+ 1 x)))
(set! x x++)
x++))))
(do-uid)))
(list (uid) (uid) (uid))
(define (stuff)
(let* ((x 2)
(chbouib (lambda (z)
(+ 7 z x))))
(chbouib 77)))
(stuff)
(define (extract-symbols exp)
(define (process x out cont)
(cond ((pair? x)
(process (car x)
out
(lambda (car-x out)
;; used to have a bug here whereby `x' was
;; modified in the self-tail-recursion to (process
;; (cdr x) ...), because we didn't allocate fresh
;; externals when doing self-tail-recursion.
(process (cdr x)
out
(lambda (cdr-x out)
(cont (cons car-x cdr-x)
out))))))
((symbol? x)
(cont x (cons x out)))
(else
(cont x out))))
(process exp '() (lambda (x out) out)))
(extract-symbols '(a b . c))
(let ((n+ 0))
(do ((n- 5 (1- n-))
(n+ n+ (1+ n+)))
((= n- 0))
(format #f "n- = ~a~%" n-)))
;; Are global bindings reachable at run-time? This relies on the
;; `object-ref' and `object-set' instructions.
(begin
(define the-binding "hello")
((lambda () the-binding))
((lambda () (set! the-binding "world")))
((lambda () the-binding)))
;; Check whether literal integers are correctly signed.
(and (= 4294967295 (- (expt 2 32) 1)) ;; unsigned
(= -2147483648 (- (expt 2 31))) ;; signed
(= 2147483648 (expt 2 31))) ;; unsigned
;; Are built-in macros well-expanded at compilation-time?
(false-if-exception (+ 2 2))
(read-options)
;; Are macros well-expanded at compilation-time?
(defmacro minus-binary (a b)
`(- ,a ,b))
(define-macro (plus . args)
`(let ((res (+ ,@args)))
;;(format #t "plus -> ~a~%" res)
res))
(plus (let* ((x (minus-binary 12 7)) ;; 5
(y (minus-binary x 1))) ;; 4
(plus x y 5)) ;; 14
12 ;; 26
(expt 2 3)) ;; => 34
; Currently, map is a C function, so this is a way of testing that the
; VM is reentrant.
(begin
(define (square x)
(* x x))
(map (lambda (x) (square x))
'(1 2 3)))
;;; Pattern matching with `(ice-9 match)'.
;;;
(use-modules (ice-9 match)
(srfi srfi-9)) ;; record type (FIXME_ See `t-records.scm')
(define-record-type <stuff>
(%make-stuff chbouib)
stuff?
(chbouib stuff_chbouib stuff_set-chbouib!))
(define (matches? obj)
; (format #t "matches? ~a~%" obj)
(match obj
(($ <stuff>) #t)
; (blurps #t)
("hello" #t)
(else #f)))
;(format #t "go!~%")
(and (matches? (%make-stuff 12))
(matches? (%make-stuff 7))
(matches? "hello")
; (matches? 'blurps)
(not (matches? 66)))
(define (even? x)
(or (zero? x)
(not (odd? (1- x)))))
(define (odd? x)
(not (even? (1- x))))
(even? 20)
;; all the different permutations of or
(list
;; not in tail position, no args
(or)
;; not in tail position, one arg
(or 'what)
(or #f)
;; not in tail position, two arg
(or 'what 'where)
(or #f 'where)
(or #f #f)
(or 'what #f)
;; not in tail position, value discarded
(begin (or 'what (error "two")) 'two)
;; in tail position (within the lambdas)
((lambda ()
(or)))
((lambda ()
(or 'what)))
((lambda ()
(or #f)))
((lambda ()
(or 'what 'where)))
((lambda ()
(or #f 'where)))
((lambda ()
(or #f #f)))
((lambda ()
(or 'what #f))))
(define the-struct (vector 1 2))
(define get/set
(make-procedure-with-setter
(lambda (struct name)
(case name
((first) (vector-ref struct 0))
((second) (vector-ref struct 1))
(else #f)))
(lambda (struct name val)
(case name
((first) (vector-set! struct 0 val))
((second) (vector-set! struct 1 val))
(else #f)))))
(and (eq? (vector-ref the-struct 0) (get/set the-struct 'first))
(eq? (vector-ref the-struct 1) (get/set the-struct 'second))
(begin
(set! (get/set the-struct 'second) 77)
(eq? (vector-ref the-struct 1) (get/set the-struct 'second))))
(list
`()
`foo
`(foo)
`(foo bar)
`(1 2)
(let ((x 1)) `,x)
(let ((x 1)) `(,x))
(let ((x 1)) ``(,x))
(let ((head '(a b))
(tail 'c))
`(,@head . ,tail)))
;;; SRFI-9 Records.
;;;
(use-modules (srfi srfi-9))
(define-record-type <stuff>
(%make-stuff chbouib)
stuff?
(chbouib stuff_chbouib stuff_set-chbouib!))
(and (stuff? (%make-stuff 12))
(= 7 (stuff_chbouib (%make-stuff 7)))
(not (stuff? 12)))
(list (call-with-values
(lambda () (values 1 2))
(lambda (x y) (cons x y)))
;; the start-stack forces a bounce through the interpreter
(call-with-values
(lambda () (start-stack 'foo (values 1 2)))
list)
(call-with-values
(lambda () (apply values '(1)))
list))
|