summaryrefslogtreecommitdiff
path: root/macros/texinfo/texinfo/js/examples/kawa/kawa.texi
blob: 0bd162001707c3ff3c569e83da0842d4a25abbc7 (plain)
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
\input texinfo.tex      @c -*-texinfo-*-
@c %**start of header
@setfilename kawa.info
@documentencoding UTF-8
@settitle The Kawa Scheme language
@setchapternewpage off
@syncodeindex fn cp
@syncodeindex vr cp
@syncodeindex pg cp
@codequoteundirected on
@codequotebacktick on
@c version: %W% %G%
@c %**end of header

@macro false{}
@code{#f}
@end macro

@macro true{}
@code{#t}
@end macro

@macro func{NAME}
@code{\NAME\}
@end macro

@macro stxdef{NAME}
@findex @i{\NAME\}
@anchor{meta-\NAME\}@var{\NAME\} @t{::=}
@end macro

@ifnotinfo
@ifnottex
@macro stxref{NAME}
@ref{meta-\NAME\, @var{\NAME\}, @var{\NAME\}}
@end macro
@end ifnottex
@end ifnotinfo
@ifinfo
@macro stxref{NAME}
@var{\NAME\}
@end macro
@end ifinfo
@iftex
@macro stxref{NAME}
@var{\NAME\}
@end macro
@end iftex

@macro stxlit{TEXT}
@code{@b{\TEXT\}}
@end macro
@macro stxlitlbrace{TEXT}
@code{@b{@{}}
@end macro

@macro arbno{THING}
\THING\@sup{*}
@end macro
@c maybe use \x2217
@c \THING\ @var{...}

@macro atleastone{THING}
\THING\@sup{+}
@end macro

@macro meta{THING}
@var{\THING\}
@end macro

@macro PerformanceNote
@emph{Performance note:}
@end macro

@macro CompatibilityNote
@emph{Compatibility:}
@end macro

@ifinfo
@macro vari{THING}
@var{\THING\1}
@end macro
@macro varii{THING}
@var{\THING\2}
@end macro
@macro variii{THING}
@var{\THING\3}
@end macro
@macro variv{THING}
@var{\THING\4}
@end macro
@end ifinfo
@ifnotinfo
@macro vari{THING}
@var{\THING\}@sub{1}
@end macro
@macro varii{THING}
@var{\THING\}@sub{2}
@end macro
@macro variii{THING}
@var{\THING\}@sub{3}
@end macro
@macro variv{THING}
@var{\THING\}@sub{4}
@end macro
@end ifnotinfo

@include version.texi

@iftex
@finalout
@end iftex
@titlepage
@title The Kawa Scheme language
@subtitle @value{UPDATED}
@sp 1
@author Per Bothner
@page
@end titlepage

@contents

@ifinfo
@format
START-INFO-DIR-ENTRY
* kawa: (kawa).         The Kawa Scheme language
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@ifnottex
@node Top, Installation, (dir), (dir)
@top The Kawa Scheme language
@end ifnottex

@c Kawa is best known as an implementation of the
@c @uref{http://www.schemers.org/,Scheme language} for the Java platform.
@c It compiles Scheme to high-performance Java bytecodes.
@c It is also a general framework for implementing dynamic languages,
@c and includes a full implementation of XQuery and the beginnings of
@c implementations of Common Lisp and Emacs Lisp (JEmacs).

Kawa is a general-purpose programming language that runs on the Java platform.
It aims to combine:
@itemize
@item
the benefits of dynamic scripting languages
(non-verbose code with less boiler-plate, fast and easy start-up,
a @uref{http://en.wikipedia.org/wiki/Read-eval-print_loop,REPL},
no required compilation step); with
@item
the benefits of traditional compiled languages (fast execution, static error detection,
modularity, zero-overhead Java platform integration).
@end itemize
It is an extension of the long-established @uref{http://www.schemers.org/,Scheme}
language, which is in the Lisp family of programming languages.
Kawa has many @ref{Features,useful features}.

Kawa is also a useful @ref{Framework,framework} for implementing
other programming languages on the Java platform.
It has many useful utility classes.

This manual describes version @value{VERSION}, updated @value{UPDATED}.
See the summary of @ref{News,recent changes}.

@c Old versions of makeinfo don't support: @ifnotdocbook
The Kawa home page (which is currently just an on-line
version of this document) is @uref{http://www.gnu.org/software/kawa/}.

@c (blank line needed above) @end ifnotdocbook

The @ref{Tutorial,Kawa tutorial} is useful to get stated.
While it is woefully incomplete, it does link to some other more in-depth
(but not Kawa-specific) Scheme tutorials.

For copyright information on the software and documentation,
see @ref{License}.

Various people and orgnizations @ref{Acknowledgements,have contributed to Kawa}.

This package has nothing to do with the defunct Kawa commercial Java IDE.

@menu
* News::                 News - Recent Changes
* Features::
* Community::
* Installation::         Building and installing Kawa
* Tutorial::             Kawa Scheme Tutorial
* Running::              Invoking, Running, and Using Kawa
* Syntax::
* Program structure::
* Control features::
* Symbols and namespaces::
* Procedures::
* Numbers::              Quantities and Numbers
* Characters and text::
* Data structures::
* Eval and Environments::
* Debugging::
* Input-Output::         Input, output, and file handling
* Types::
* Objects Classes and Modules::
* XML tools::            XML, HTML, and the web
* Miscellaneous::
* FAQs::                 Frequently Asked Questions
* Framework::            The Kawa language framework
* License::
* Overall Index::	 Index of functions, macros, concepts, and more.
@end menu

@node News
@chapter News - Recent Changes
@include news.texi

@node Features
@chapter Features

Runs on the Java platform, with no native code needed.

Extends the @uref{http://en.wikipedia.org/wiki/Scheme_%28programming_language%29,Scheme language}, following the @uref{http://r7rs.org/,R7RS} specification from 2013.
Scheme has many implementations, and is much used in research and teaching.

Programs @uref{http://per.bothner.com/blog/2010/Kawa-in-shootout/, run fast}
- roughly as fast as Java programs,
and much faster than other ``scripting languages''.
This is due to a sophisticated compiler,
compile-time transformations, type inference, and optional type declarations.

Full, convenient, and efficient access to the huge set of Java libraries
means you can access objects, methods, fields, and classes without run-time overhead.

Start-up times are fast.  You don't have to wait for a lot of
initialization.  Even if you start with source code, the parser
and compiler are fast.

@ref{Scripts} are simple Kawa source files
that can run as an application or command.  These are simple to write,
start, and run efficiently, since they're automatically
compiled before execution.

Alternatively, you can embed Kawa as a @ref{Evaluating Scheme expressions from Java,
scripting language for Java applications}.

Deployment is easy and flexible.  You just need the Kawa jar file.

@ref{Macros} and @ref{Named quasi-literals,custom named literals} make it easy
to extend the syntax and implement Domain-Specific Languages.

Kawa provides the usual @ref{REPL Console,read-eval-print loop}, as well as batch modes.

Kawa has builtin @ref{Pretty-printing,pretty-printer} support, and fancy formatting.

Kawa supports class-definition facilities, and separately-compiled modules.

You can @ref{Allocating objects,allocate and initialize objects}
with a compact ``builder'' syntax.  It works out-of-the-box
(with no run-time overhead) on many classes and APIs,
but can be customized if need be.

A library for functional @ref{Composable pictures,composable pictures}
lets you create ``picture'' objects,
display them, transform them, combine them, convert to
SVG or images, and more.
This can be ``printed'' directly in the Kawa console
(either the DomTerm console or the Swing one).

@ref{Building JavaFX applications,JavaFX programming} is simpler.

You can @ref{Building for Android,run Kawa programs on Android},
and there is special handling to make @ref{Android view construction,constructing View objects} easier.

Flexible shell-like functionality, including @ref{process literals}.

@ref{Server-side scripts,Web page scripts} are easy to write and install
with @ref{Self-configuring page scripts,self-configuring web servers},
optionally using @ref{Servlets,servlets} and @ref{XML literals}.

@ref{Arrays} and sequences have a lot of flexibility:
Arrays can be multi-dimensional;
you can use an array as an index (which generalizes slices and permutations);
you can define a lazy array using a function that maps indexes to values;
you can re-map the indexes to yield a transformed array.

Many useful features for mathematics and numerics:
@itemize
@item
The full ``numeric tower'' includes infinite-precision
rational numbers and complex numbers.
@item
Compile-time optimization of arithmetic
with the use of type declarations and inference.
@item
A @ref{Quantities,@dfn{quantity}} is a real number with a unit,
such as @code{3cm}.
@item
@ref{Quaternions} are a 4-dimensional generalization of complex numbers.
Unsigned primitive integer types (@code{ubyte}, @code{ushort},
@code{uint}, @code{ulong}) are implemented efficiently without
object allocation.
@end itemize

A @ref{Lazy evaluation,lazy value} wraps an expression which is evaluated
only when it is needed.

Kawa provides a @ref{Framework,framework} for implementing other programming languages,
and comes with incomplete support for CommonLisp, Emacs Lisp, and
EcmaScript, and
@uref{http://www.gnu.org/software/qexo/,XQuery}.

@menu
* Implemented SRFIs::
* Compatibility::        Compatibility with standards
@end menu

@node Implemented SRFIs
@section Implemented SRFIs

Kawa implements the following semi-standard SRFIs
(@uref{http://srfi.schemers.org/,Scheme Request for Implementation}):
@itemize
@item
@uref{http://srfi.schemers.org/srfi-0/srfi-0.html, SRFI 0}: Feature-based conditional expansion construct,
using @code{cond-expand} - @pxref{Syntax and conditional compilation}.
@item
@uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI 1}: List Library, if @code{(require 'list-lib)} - @pxref{SRFI-1}.
@item
@uref{http://srfi.schemers.org/srfi-2/srfi-2.html, SRFI 2}: AND-LET*: an AND with local bindings, a guarded LET* special form.
@item
@uref{http://srfi.schemers.org/srfi-4/srfi-4.html, SRFI 4}: Homogeneous numeric vector datatypes - @pxref{Uniform vectors}.
@item
@uref{http://srfi.schemers.org/srfi-6/srfi-6.html, SRFI 6}: Basic String Ports - @pxref{Ports}.
@item
@uref{http://srfi.schemers.org/srfi-8/srfi-8.html, SRFI 8}: @code{receive}: Binding to multiple values - @pxref{Multiple values}.
@item
@uref{http://srfi.schemers.org/srfi-9/srfi-9.html, SRFI 9}: Defining Record Types, using @code{define-record-type}
- @pxref{Record types}.
@item
@uref{http://srfi.schemers.org/srfi-10/srfi-10.html, SRFI 10}: @code{#,} external form for special named types.
This is deprecated for various reasons, including that it conflicts
with syntax-case @code{unsyntax}.
Better to use srfi-108 @ref{Named quasi-literals}.
@item
@uref{http://srfi.schemers.org/srfi-11/srfi-11.html, SRFI 11}: Syntax for receiving multiple values,
using @code{let-values} and @code{let*-value} - @pxref{Multiple values}.
@item
@uref{http://srfi.schemers.org/srfi-13/srfi-13.html, SRFI 13}: String Library.
Needs some polishing.
@item
@uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14}: Character-set Library - @pxref{Character sets}.
@item
@uref{http://srfi.schemers.org/srfi-16/srfi-16.html, SRFI 16}: Syntax for procedures of variable arity,
using @uref{http://srfi.schemers.org/srfi-16/srfi-16.html, @code{case-lambda}}.
@item
@uref{http://srfi.schemers.org/srfi-17/srfi-17.html, SRFI 17}: Generalized @code{set!} - @pxref{Locations}.
@item
@uref{http://srfi.schemers.org/srfi-23/srfi-23.html, SRFI 23}: Error reporting mechanism, using @code{error} - @pxref{Exceptions}.
@item
@uref{http://srfi.schemers.org/srfi-25/srfi-25.html, SRFI 25}: Multi-dimensional Array Primitives - @pxref{Arrays}.
@item
@uref{http://srfi.schemers.org/srfi-26/srfi-26.html, SRFI 26}: Notation for Specializing Parameters without Currying - @pxref{Procedures}. 
@item
@uref{http://srfi.schemers.org/srfi-28/srfi-28.html, SRFI 28}: Basic Format Strings - @pxref{Format}.
@item
@uref{http://srfi.schemers.org/srfi-30/srfi-30.html, SRFI 30}: Nested Multi-line Comments.
@item
@uref{http://srfi.schemers.org/srfi-35/srfi-35.html, SRFI 35}: Conditions.
@item
@uref{http://srfi.schemers.org/srfi-37/srfi-37.html, SRFI 37}: @uref{http://srfi.schemers.org/srfi-37/srfi-37.html,@code{args-fold} - a program argument processor}, if @code{(require 'args-fold)}.
@item
@uref{http://srfi.schemers.org/srfi-38/srfi-38.html, SRFI 38}: External Representation for Data With Shared Structure.
The @code{read-with-shared-structure} is missing, but subsumed by @code{read}.
@item
@uref{http://srfi.schemers.org/srfi-39/srfi-39.html, SRFI 39}:
@xref{Parameter objects}.
@item
@uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41}: Streams - @pxref{Streams}.
@item
@uref{http://srfi.schemers.org/srfi-45/srfi-45.html, SRFI 45}: Primitives for Expressing Iterative Lazy Algorithms - @pxref{Lazy evaluation}.
@item
@uref{http://srfi.schemers.org/srfi-60/srfi-60.html, SRFI 60}: Integers as Bits. - @pxref{Logical Number Operations}.
@item
@uref{http://srfi.schemers.org/srfi-62/srfi-62.html, SRFI 62}: S-expression comments.
@item
@uref{http://srfi.schemers.org/srfi-64/srfi-64.html, SRFI 64}: A Scheme API for test suites.
@item
@uref{http://srfi.schemers.org/srfi-69/srfi-69.html, SRFI 69}: Basic hash tables - @pxref{Hash tables}.
@item
@uref{http://srfi.schemers.org/srfi-87/srfi-87.html, SRFI 87}: @code{=>} in @code{case} clauses.
@item
@uref{http://srfi.schemers.org/srfi-88/srfi-88.html, SRFI 88}: Keyword objects - @pxref{Keywords}.
@item
@uref{http://srfi.schemers.org/srfi-95/srfi-95.html, SRFI 95}: Sorting and Merging.
@item
@uref{http://srfi.schemers.org/srfi-97/srfi-97.html, SRFI 97}: Names for SRFI Libraries.
@item
@uref{http://srfi.schemers.org/srfi-98/srfi-98.html, SRFI 98}: An interface to access environment variables
@item
@uref{http://srfi.schemers.org/srfi-101/srfi-101.html, SRFI 101}: Purely Functional Random-Access Pairs and Lists - @pxref{SRFI-101}.
@item
@uref{http://srfi.schemers.org/srfi-107/,SRFI 107}: XML reader syntax - @pxref{XML literals}.
@item
@uref{http://srfi.schemers.org/srfi-108/,SRFI 108}: Named quasi-literal constructors - @pxref{Named quasi-literals}.
@item
@uref{http://srfi.schemers.org/srfi-109/srfi-109.html, SRFI-109}: Extended string quasi-literals - @pxref{string quasi-literals}.
@item
@uref{http://srfi.schemers.org/srfi-118/srfi-118.html, SRFI-118}: Simple adjustable-size strings (@code{string-append!} and @code{string-replace!}).
@end itemize

@node Compatibility
@section Compatibility with standards

Kawa implements all the required and optional features of R7RS,
with the following exceptions.

The entire ``numeric tower" is implemented.
However, some transcendental functions only work on reals.
Integral functions do not necessarily work on
inexact (floating-point) integers.
(The whole idea of ``inexact integer" in R5RS seems rather pointless ...)

Also, @code{call-with-current-continuation} is only ``upwards" (?).
I.e. once a continuation has been exited, it cannot be invoked.
These restricted continuations can be used to implement catch/throw
(such as the examples in R4RS), but not co-routines or backtracking.

Kawa now does general tail-call elimination, but only if
you use the flag @code{--full-tail-calls}.  (Currently, the
@code{eval} function itself is not fully tail-recursive, in violation
of R5RS.)   The @code{--full-tail-calls} flag is not on by default,
partly because it is noticably slower (though I have not measured how
much), and partly I think it is more useful for Kawa to be compatible
with standard Java calling conventions and tools.
Code compiled with @code{--full-tail-calls} can call code
 compiled without it and vice versa.

Even without @code{--full-tail-calls}, if the
compiler can prove that the procedure being called is the current
function, then the tail call will be replaced by a jump.
This includes must ``obvious'' cases of calls to the
current function named using @code{define} or @code{letrec},
and many cases of mutual tail-recursion (including
state-machines using @code{letrec}).

By default, symbols are case sensitive.

Kawa implements most of the features of the expression language of DSSSL,
the Scheme-derived ISO-standard Document Style Semantics and Specification
Language for SGML.  Of the core expression language, the only features
missing are character properties, @code{external-procedure},
the time-relationed procedures, and character name escapes in
string literals.
From the full expression language, Kawa additionally is missing
@code{format-number}, @code{format-number-list}, and language objects.
Quantities, keyword values, and the expanded @code{lambda} form
(with optional and keyword parameters) are supported.

@node Community
@chapter The Kawa Community

@menu
* Reporting bugs::       Where to report bugs
* Mailing lists::        Where to discuss changes, etc
* Acknowledgements::     Acknowledgements and thanks
* Support::              Technical support for Kawa
* Projects::             Projects using Kawa
* Ideas and tasks::      Ideas and tasks for contributing to Kawa
@end menu

@node Reporting bugs
@section Reporting bugs

To report a bug or a feature request
use the @uref{https://gitlab.com/kashell/Kawa/issues,Issue Tracker}.
This does require a @uref{https://gitlab.com/,GitLab} account;
if this is a problem you can use the Savannah bug tracker.

@subsubheading Older Savannah bug tracker

The older bug tracker for Kawa on Savannah is still available,
but we request you use
the @uref{https://gitlab.com/kashell/Kawa/issues,GitLab Issue Tracker}
for new issues.

To report a bug or feature request for Kawa (including Qexo or JEmacs) through Savannah,
use the
@uref{http://savannah.gnu.org/bugs/?func=additem&group=kawa,bug-submission page}.
You can browse and comment on existing bug reports
using the @uref{http://savannah.gnu.org/bugs/?group=kawa, Kawa Bugzilla page}.

When a bug report is created or modified, mail is automatically sent to the
@email{bug-kawa@@gnu.org} list.  You can subscribe, unsubscribe, or browse
the archives through the
@uref{http://mail.gnu.org/mailman/listinfo/bug-kawa,
@code{bug-kawa} web interface}.

@node Mailing lists
@section General Kawa email and discussion

The general Kawa email list is @email{kawa@@sourceware.org}.
This mailing list is used for announcements, questions, patches,
and general discussion relating to Kawa.  If you wish to subscribe,
send a blank message request to @email{kawa-subscribe@@sourceware.org}.
To unsubscribe, send a blank message to
@email{kawa-unsubscribe@@sourceware.org}.
(If your mail is forwarded and you're not sure which email address you're
subscribed as, send mail to the address following @code{mailto:} in the
@code{List-Unsubscribe} line in the headers of the messages you get from
the list.)

You can browse the @uref{http://sourceware.org/ml/kawa/,
archive of past messages}.

There are separate mailing lists for
@uref{http://mail.gnu.org/mailman/listinfo/qexo-general, Qexo}
and @uref{http://lists.sourceforge.net/mailman/listinfo/jemacs-info,JEmacs}.

@node Acknowledgements
@section Acknowledgements and thanks

The author and project leader of Kawa is
@uref{http://per.bothner.com/,Per Bothner}
@email{per@@bothner.com}.

Kawa is a re-write of Kawa 0.2, which was a Scheme interpreter written by
R. Alexander Milowski @email{alex@@milowski.com}.

Thanks to Cygnus Solutions (now part of Red Hat) for sponsoring
the initial development of Kawa, and then transferring
their ownership interest to Per.

@subsubheading Financial support

Ean Schuessler and @uref{http://www.brainfood.com/,Brainfood}
provided financial support and encouragement.

Thanks to Chris Dean, Dean Ferreyra, and others
at @uref{http://www.mercedsystems.com/,Merced Systems} for financial
support and other contributions.

@uref{http://google.com/,Google} through their
@uref{http://code.google.com/soc/,Summer of Code} project
sponsored Charles Turner during Summer 2011 and 2012,
and sponsored Andrea Bernardini Summer 2014.

Thomas Kirk and AT&T provided financial support, and useful bug reports.

@subsubheading Various contributions

@uref{http://jcubic.pl/,Jakub Jankiewicz} contributed the Kawa logo.

Helmut Eller provided SLIME support, syntaxutils.scm, and many bug reports.

Daniel Bonniot for multiple small improvements
to gnu.bytecode and gnu.expr.

Jamison Hope for multiple contributions,
including quaternion support, the SRFI-14 implementation,
Ant improvements, and Google Summer of Code mentoring.

Jim White for Ant support and other improvements.

Bruce R. Lewis implemented @ref{KRL,,KRL} and made other contributions.

Geoff Berry: Handle Exceptions attribute.  Other improvements.

Shad Gregory improved JEmacs.

Al Petrofsky improved gnu.math printing and added some IntNum methods.

Marco Vezzoli:  SRFI-1 tailoring for Kawa.

Albert Ting - old GuiConsole code.

Christian Surlykke ported JEmacs to use SWT.

Geoff Berry for various gnu.bytecode improvements.

Ivelin Ivanov and Tom Reilly for servlet support.

Anthony Green for Fedora packaging.

Charles Turner for pretty-printer improvements,
improvements in the Common Lips support, and other changes.

Andrea Bernardini optimized the implementation of @code{case}.

Julien Rousseau and Marius Kjeldahl contributed to Android support.

Peter Lane for many documentation improvements.

@subsubheading Small fixes and improvements

Patrick Barta;
Joseph Bowbeer;
Dominique Boucher;
Alexander Bunkenburg;
Harold Carr;
Emmanuel Castro;
Álvaro Castro-Castilla;
Heather Downs;
Francisco Vides Fernández;
Nic Ferrier;
Oliver Flasch;
Weiqi Gao;
Luke Gorrie;
Mario Domenech Goulart;
Zvi Har'E;
Jeff Haynes;
Ethan Herdrick;
Joerg-Cyril Hoehle;
Elliott Hughes;
Mike Kenne;
Brian Jones;
Gerardo Jorvilleur;
Simon Josefsson (JEmacs menu);
Thomas Kirk;
Jay Krell;
Edouard Parmelan;
Walter C. Pelissero;
Rafael Jesus Alcantara Perez;
Lynn Quam;
Marcus Otto;
Terje Pedersen (some XQuery functions);
Matthias Radestock;
Ola Rinta-Koski;
Andreas Schlapbach;
Robert D. Skeels;
Benny Tsai;
Vladimir Tsichevski;
Matthieu Vachon;
Phil Walker;
Knut Wannheden;
Chris Wegrzyn.

@subsubheading Bug reports and test cases

Seth Alves;
Khairul Azhar;
Bob Bane;
Hans Boehm;
Adrián Medraño Calvo;
Brian D. Carlstrom;
Luis Casillas;
Sudarshan S Chawathe;
Ken Dickey (format tests);
Helge Dietert;
Allan Erskine;
Marc Feeley (polytype.scm);
Margus Freudenthal;
Weiqi Gao;
Andrea Girotto;
Norman Hard;
Gerardo Horvilleur;
Yaroslav Kavenchuk;
Felix S Klock II;
Francois Leygues;
Mirko Luedde;
Leonardo Valeri Manera;
Kjetil S. Matheussen;
Alex Mitchell;
Alex Moiseenko
Edouard Parmelan;
Walter C. Pelissero;
Stephen L. Peters;
François Pinard;
Bill Robinson;
Dan Stanger (Eaton Vance);
Hallvard Traetteberg;
Taylor Venable;
Alessandro Vernet;
Tony White
John Whittaker;
Robert Yokota.

@subsubheading Code ported from other packages

Kawa includes Free Software originally written for other purposes,
but incorporated into Kawa, perhaps with some porting.  A partial list:

Dorai Sitaram wrote pregexp.

The @code{rationalize} algorithm is by Alan Bawden and Marc Feeley.

Lars T Hansen wrote SRFI-11 (let-values, let*-values macros).

Olin Shivers wrote the SRFI-1 list-processing library,
and the SRFI-13 reference impementation.

John David Stone wrote SRFI-8 (receive macro)

Jussi Piitulainen wrote the SRFI-25 specification and tests.

Richard Kelsey and Michael Sperber wrote SRFI-34.

Anthony Carrico wrote the SRFI-37 reference implementation.

Panu Kalliokoski wrote the SRFI-69 reference implementation.

Donovan Kolbly wrote the srfi-64 ``meta'' testsuite.
Alex Shinn improved SRFI-64 portability.

Philip L. Bewig wrote the SRFI-41 (streams) specification and
reference implementation.

Simon Tatham wrote listsort.

Aubrey Jaffer wrote much of SLIB, some of which has been
imported into gnu.kawa.slib. He also wrote some tests we're using.

@node Support
@section Technical Support for Kawa

If you have a project that depends on Kawa or one of its component
packages, you might do well to get paid priority support from
Kawa's author.

The base price is $2400 for one year.  This entitles you to basic
support by email or phone.  Per @email{per@@bothner.com} will answer techical
questions about Kawa or its implementation, investigate bug reports, and
suggest work-arounds.  I may (at my discretion) provide fixes and
enhancements (patches) for simple problems.  Response for support
requests received during the day (California time) will normally be
within a few hours.

All support requests must come through a single designated contact
person.  If Kawa is important to your business, you probably
want at least two contact people, doubling the price.

If the support contract is cancelled (by either party), remaining
time will be prorated and refunded.

Per is also available for development projects.

@node Projects
@section Projects using Kawa

@uref{http://appinventor.mit.edu/,MIT App Inventor}
for Android (formerly Google App Inventor)
uses Kawa to translate its visual blocks language.

The @uref{http://www.narrativeandplay.org/hypedyn/,HypeDyn} hypertext
fiction authoring tool is written in Kawa. HypeDyn (pronounced "hyped
in") is a procedural hypertext fiction authoring tool for people who
want to create text-based interactive stories that adapt to reader
choice. HypeDyn is free to download and open source, and runs on
Linux, MacOS and Windows. This is a research project carried out at
the Department of Communications and New Media, National University of
Singapore.

@uref{http://www.nuecho.com,Nü Echo} develops high-performance speech
enabled applications. Nü Echo uses Kawa for the development of innovative
speech application development tools, like a complete 
@uref{http://www.nuecho.com/en/services/grammar.shtml,grammar IDE}.

@uref{http://www.mercedsystems.com/, Merced Systems@comma{} Inc.} uses Kawa
extensively in their contact center performance management product
Merced Peformance Suite.  Kawa Scheme is used for all development
and has allowed Merced to realize the large productivity gains
that come with using Scheme while still maintaining tight
integration with a large number of Java libraries.

JEmacs is included in the Kawa distribution.  It is a project to
re-implement Emacs, allowing a mix of Java, Scheme, and Emacs Lisp.
It has its own @uref{http://jemacs.sourceforge.net/,home-page}.

BRL (``the Beautiful Report Language") is a database-oriented language
to embed in HTML and other markup.
@uref{http://brl.sourceforge.net/, BRL} allows you to embed Scheme in
an HTML file on a web server.

The @uref{http://schemeway.sourceforge.net,SchemeWay Project} is a set of
@uref{http://www.eclipse.org,Eclipse} plug-ins for professional Scheme
programming. The first plugin released, SchemeScript, is a fully-featured
Scheme
editor customizable in Scheme. It embeds the Kawa Scheme system and has
many features that ease Kawa Scheme programming (like code completion on
variable names, 
class and method names, namespaces, etc).

The Health Media Research Laboratory, part of the Comprehensive Cancer
Center at the University of Michigan, is using Kawa as an integral part of
its core tailoring technologies. Java programs using Kawa libraries are used
to administer customized web-based surveys, generate tailored feedback,
validate data, and "characterize," or transform, data. Kawa code is embedded
directly in XML-formatted surveys and data dictionaries. Performance and
ease of implementation has far exceeded expectations. For more information
contact Paul R. Potts, Technical Director, Health Media Research Lab,
@code{<potts@@umich.edu>}.

Mike Dillon (@code{mdillon@@gjt.org})
did the preliminary work of creating a
Kawa plugin for jEdit. It is called SchemeShell and provides a REPL inside
of the jEdit console for executing expressions in Kawa (much as the BeanShell
plugin does with the BeanShell scripting language).
It is currently available only via CVS from:
@example
CVSROOT=:pserver:anonymous@@cvs.jedit.sourceforge.net:/cvsroot/jedit
MODULE=plugins/SchemeShell
@end example

STMicroelectronics (@code{marco.vezzoli@@st.com})
uses Kawa in a prototypal
intranet 3tier information retrieval system as a communication protocol
between server and clients, and to do server agents programming.

@ignore
The Nice Programming Language is a new open source language with a
Java-like syntax. It features multiple dispatch, parametric types,
higher-order functions, tuples, optional parameters, safe static typing
of @code{null}, ..., and the new concept of "abstract interfaces".
The Nice compiler (@code{nicec}) uses Kawa's @code{gnu.expr}
and @code{gnu.bytecode}
packages to generate Java bytecode.
You can find more about Nice at @uref{http://nice.sourceforge.net}.
For more information feel free to contact
Daniel Bonniot @email{bonniot@@users.sf.net}).
@end ignore

@node Ideas and tasks
@section Ideas and tasks for contributing to Kawa

Kawa (like other Free Software projects) has no lack of tasks and projects
to work on.  Here are some ideas.

The ones marked @i{(GSoC)} are probably most suitable for a Google
Summer of Code project, in being a reasonable size, self-contained, and not
depending on other tasks.

@subsection Run interactive process in separate Java Virtual Machine:
@i{(GSoC)}

When developing and testing it is useful for the REPL to support
hot-swapping (replacing functions on-the-fly) and debugging.
The main goal being able to smoothly reload changed modules
(files or functions), and have other modules not break.
Debugging (such as setting breakpoints) would not be a priority
for this project, but could be a follow-on project.
Skills: Should be experienced with Java, and interested in learning
about @uref{https://docs.oracle.com/javase/8/docs/technotes/guides/jvmti/index.html,JVM TI} and similar low-level parts of the platform.
Difficulty: Challenging, but you can study
how @uref{https://en.wikipedia.org/wiki/Jshell,Java-9's new jshell}
uses the JVM TI.

@subsection Better dynamic reload

@i{(GSoC - this is related to the previous item)}

Kawa does a lot of optimizations and inlining.  This conflicts
with being able to ``reload'' a module into an already-running
interactive environment.

We could add an option to load a module in ``reloadable'' mode.
Kawa already patches an old function object (a @code{ModuleMethod})
so existing references to the function get automatically updated.
However, there are problems if the ``signature'' of the function
changes - for example if the return type (declared or inferred)
becomes more general.  In those cases the best thing is to
re-compile any code that depends on the modified function.

Reloading a module that defines a class is even trickier,
at least if there are existing instances that should
work as the updated class.  We can handle the special case
where only method bodies change: In reloadable mode, each
method body is compiled to a separate function, the
actual body indirects to the function.  We must also
recognize when compiling a new version of the same
class, which requires a textual comparison between the
old and new versions, or a structural comparison
between the old class and the new code.

When it comes to top-level variables, an issue is when
to re-evaluate the initializing expression.  It is reasonable
to do so if and only if the expression is modified, which
again requires a textual comparison.

@subsection Easier Access to Native Libraries using JNA/JNR
@i{(GSoC)}

The traditional way to access native (C/C++) functions is using JNI,
but it's very awkward.
JNA and @uref{https://github.com/jnr,JNR} are @uref{http://www.oracle.com/technetwork/java/jvmls2013nutter-2013526.pdf,much easier to use}.
This project would design and implement an easy-to-use Kawa wrapper for
for JNR.  You should study existing JNR wrappers, such as that for JRuby.
Difficulty: Medium.  Need to study existing wrappers and "foreign
function interfaces" (in multiple languages) and design one suitable for Kawa.
Some Scheme (Kawa) experience would be helpful.  

@subsection Types for units

@i{(GSoC)}

Kawa supports units (such as @code{cm^2} for square centimeters)
and @ref{Quantities,quantities} (such as @code{4cm^2}).
We would like to integrate these into the type system, both
for performance and compile-time type checking.

For syntax we can use a pseudo-parameterized type @code{quantity}.  For example:
@example
(define a1 ::quantity[cm^2] 4cm^2)
(* 2.0 a1) ;; @result{} 8cm^2
(+ 2.0 a1) ;; @i{compile-time error}
@end example
The run-time type of the variable @code{a1} should be
a primitive @code{double}, without object allocation.
Of course when @code{a1} is converted to an object, we
create a @code{Quantity}, not a @code{Double}.
We can build on Kawa's existing framework for
non-standard primitive types such as @code{character} and @code{ulong}.
Skills: Need good Java experience, and somewhat familiar with the
Java Virtual Machine.
You will need to become comfortable reading <code>javap</code> output.
Difficulty: Modest.

@subsection Compiler should use class-file reading instead of reflection
The Kawa compiler currently uses reflection to determine properties
(such as exported function definitions) from referenced classes.
It would be better to read class files.
This should not be too difficult, since the @code{gnu.bytecode} library
abstracts over class information read by reflection or class reading.

@subsection Mutually dependent Java and Scheme modules

@i{(GSoC - maybe)}

We'd like a command for compiling a list of Java and Scheme
source files that may have mutual dependencies.  A good way
to do this is to hook into @code{javac}, which is quite extensible
and pluggable.

One could do something like:
@enumerate
@item
Read the ``header" of each Kawa source file, to determine the
name of the generated main class.
@item
Enter these class names into the javac tables as ``uncompleted''
classes.
@item
Start compiling the Java files.  When this requires the members
of the Kawa classes, switch to the Kawa files.  From javac,
treat these as pre-compiled .class files.  I.e. we treat the Kawa
compiler as a black box that produces Symbols in the same way as
reading class files.  At this point we should only need the
initial ``scan'' phase on Kawa.
@item
If necessary, finish compiling remaining Kawa files.
@end enumerate

This approach may not immediately provide as robust mixed-language
support as is ideal, but it is more amenable to incremental improvement
than a standalone stub-generator.

This project is good if you know or want to learn how @code{javac} works.

@subsection Use Java-7 MethodHandles and invokedynamic
Java 7 supports MethodHandles which are meant to provide better
performance (ultimately) for dynamic languages.
See @uref{http://jcp.org/en/jsr/detail?id=292,JSR 292}
and the @uref{http://openjdk.java.net/projects/mlvm/,Da Vinci Machine Project}.
Kawa makes limited use of MethodHandles, and no use of invokedynamic.
There is more to be done.  For example, we
can start by optimizing arithmetic when the types are unknown
at compile-time.  They could make implementing
generic functions (multimethods) more efficient.
At some point we want to compile lambdas in the same way
as Java 8 does. This can potentially
be more efficient than Kawa's current mechanism.

Remi Forax's @uref{https://github.com/forax/vmboiler,vmboiler} is
a small library on top of ASM that generates optimistically typed bytecodes.
It could be useful for ideas.

@anchor{task-parameterized-types}
@subsection Parameterized types
@i{(GSoC)}

Kawa has some limited support for parameterized types, but
it's not used much.  Improve type inferencing.
Support definition of parameterized classes.
Better use of parameterized types for sequence class.
Support wildcards.  
(It might be better to have wild-carding be associated with
declarations, as in Scala or @uref{http://openjdk.java.net/jeps/300,proposed for Java}, rather than uses.)
See also @uref{http://openjdk.java.net/jeps/8043488}.

@subsection Optimized function types and values using MethodHandles
@i{(GSoC)}

Kawa doesn't have true function types: Parameter and result types
are only handled for ``known'' functions.  The general case with
optional and keyword parameter is complicated, but simple
fixed-arity procedure types would be very useful.

The following syntax is suggested:
@example
procedure[(@var{T1} .. @var{Tn}) @var{Tr}]
@end example
@var{T1} through @var{T1} are types of the parameters, and
@var{Tr} is the type of the result.
For example: @code{procedure[(vector int) string]}.
We call this a typed-procedure type (in contrast to plain @code{procedure}).

If a value has a typed-procedure type then its run-time representation
is a just a @code{MethodHandle}.  If such a procedure is called,
the generated bytecode is to just call its @code{invokeExact} method.
The argument expressions are converted (and type-checked) the same
way as if we were calling a statically-known procedure.

Note that passing an @code{int} argument
of to @code{procedure[(vector int) string]} value does @emph{not}
require allocating an object to ``box'' the @code{int};
we can pass a plain @code{int} as-is.
Thus using typed-procedure types can lead to major speed-up.
For example the @code{lib-test.scm} should become much faster.

Converting a known procedure to a typed-procedure type is usually
just a matter of creating a @code{MethodHandle} that references the
method implementing the procedure.  Some glue code may be needed
if the types aren't identical, or if the procedure is a closure.

Converting a type-procedure value @code{p} to generic value (such
as untyped @code{procedure} or @code{object}) can be though of as
wrapping it in a @code{lambda}:
@example
((lambda (arg1::vector arg2::int)::string (p arg1 arg2))
@end example

Coercing a generic value or an untyped procedure to a typed-procedure would
need to generate a method whose signature matches the typed-procedure type,
and in the body of the method use a generic apply.

Coercing from one typed-procedure type to a different typed-procedure type
is a combination of the above techniques (as if converting first to object and
then to the target type), though some optimizations are worth doing.

Adding varargs support can be done later.

@c Later, we might consider merging @code{MHProcedure} and @code{PrimProcedure}.

We need a fall-back mechanism for platforms (such as Android)
that don't support @code{MethodHandle}s.  The easiest is to
just treat a typed-procedure type as plain @code{procedure} at run-time,
though we still want the compile-time type-checking,

@subsection Full continuations
@emph{Currently being worked on.}

Add support for full continuations, which is the major
feature missing for Kawa to qualify as a ``true Scheme''.
One way to implement continuations is to add a add that converts
the abstract syntax tree to continuation-passing-style, and then
expand the existing full-tail-call support to manage a stack.
There are other ways to solve the problem.
This may benefit from @ref{task-faster-tailcalls,Faster tailcalls}.

@subsection Faster tailcalls
@anchor{task-faster-tailcalls}
Make @code{--full-tailcalls} run faster.
This may depend on (or incorporate)
@ref{task-TreeList-optimization,TreeList-optimization}. 

@anchor{task-TreeList-optimization}
@subsection TreeList-optimization
The @uref{http://www.gnu.org/software/kawa/api/gnu/lists/TreeList.html,TreeList} class is a data structure for ``flattened'' trees.  It is used for
XML-style nodes, for multiple values, and for the full-tail-call API.
The basic concept is fine, but it could do with some re-thinking
to make make random-access indexing fast.  Also, support for updating
is insufficient.  (This needs someone into designing and hacking on
low-level data-structures, along with lots of profiling and testing.)

@subsection Asynchronous evaluation

C# recently added @code{asynch} and @code{await} keywords
for @uref{http://msdn.microsoft.com/en-us/vstudio/gg316360,asynchronous programming}.  Kawa's recently improved support for lazy programming
seems like a good framework for equivalent functionality:
Instead of an @code{asynch} method that returns a @code{Task<T>},
the Kawa programmer would write a function that returns a @code{lazy[T]}.
This involves some design work, and modifying the compiler to
rewrite the function body as needed.

This is related to full continuations, as the re-writing is similar.

@anchor{task-REPL-improvements}
@subsection REPL console and other REPL improvement
@emph{Currently being worked on.}

Improvements to the read-eval-print console.
In addition to a traditional Swing console,
it would be useful to support using a web browser as a remote terminal,
possibly using web-sockets.
(This allows ``printing'' HTML-expressions, which can be a useful way
to learn and experiment with web technologies.)
See @uref{http://per.bothner.com/blog/2007/ReplPane/, here} for an article
on the existing Swing REPL, along with some to-do items.
Being able to hide and show different parts of the output might be nice.
Being able to link from error messages to source might be nice.
Better handling of redefinitions is discussed 
@uref{http://per.bothner.com/blog/2009/REPL-for-JavaFX/, here in the context of JavaXF Script}; this is a general REPL issue, mostly independent of the GUI for it.

An interesting possibility is to use the @uref{http://ipython.org/,IPython}
framework.  There are existing ports for Scala: either
@uref{https://github.com/mattpap/IScala,IScala}
or @uref{https://github.com/Bridgewater/scala-notebook, Scala Notebook}.

@subsection XQuery-3.0 functionality
@i{(GSoC, for some subset)}

It would be nice to update the XQuery (Qexo) support
to some subset of @uref{http://www.w3.org/TR/xquery-30/,XQuery 3.0}.

@subsection XQuery-updates
It would be nice to support @uref{http://www.w3.org/TR/xquery-update-10/, XQuery updates}.  This depends on @ref{task-TreeList-optimization,TreeList-optimization}. 

@anchor{task-common-lisp}
@subsection Common Lisp support
Kawa supports a small subset of the Common Lisp language, but it supports
a much larger subset of core Common Lisp concepts and data structures, some
designed with Common Lisp functionality in mind.  Examples include
packages, arrays, expanded function declarations, type specifications,
and format.  A lot could be done to improve the Common Lisp support
with modest effort.  Some Common Lisp features could also be useful
for Scheme: Documentation strings (or markup) as Java annotations,
better MOP-like introspection, and generic methods a la defmethod
(i.e. with multiple definition statements, possibly in separate files,
as opposed to the current make-procedure) all come to mind.
Being able to run some existing Common Lisp code bases with
at most modest changes should be the goal.
One such package to start with might be an
@uref{http://aperiodic.net/phil/archives/Geekery/notes-on-lisp-testing-frameworks.html,existing test framework}, perhaps
@uref{http://common-lisp.net/project/bese/FiveAM.html, FivaAM}.
Full Common Lisp compatibility is nice, but let's walk before we can run.

@subsection JEmacs improvements

@i{(GSoC, for some subset)}

A lot of work is needed to make
@uref{http://jemacs.sourceforge.net/,JEmacs} useful.
One could try to import a useful package and see what works and what fails.
Or one may look at basic editing primitives.
Enhancements may be needed to core Emacs Lisp language primitives
(enhancing @ref{task-common-lisp, Common Lisp support} may help),
or to the display engine.

Emacs now supports @uref{http://www.gnu.org/software/emacs/manual/html_node/elisp/Lexical-Binding.html,lexical bindings} - we should do the same.

@subsection Improved IDE integration
There is some Kawa support for Eclipse (Schemeway), and possibly
other IDEs (NetBeans, IntelliJ).  But many improvements are
desirable.
@ref{task-REPL-improvements, REPL improvements} may be a component of this.

@subsubsection Plugin for NetBeans IDE

Kawa-Scheme support for the NetBeans IDE would be useful.
One could perhaps build on the Clojure plugin.

@subsubsection Plugin for Eclipse IDE

Kawa-Scheme support for the Eclipse IDE would be useful.
Probably makes sense to
enhance @uref{http://sourceforge.net/projects/schemeway/,SchemeWay}.
It may also make sense to build on
the @uref{http://www.eclipse.org/dltk/,Dynamic Languages Toolkit},
possibly making use of @uref{http://schemeide.sourceforge.net/,Schemeide},
though DLTk seems more oriented towards interpreted non-JVM-based languages.

@subsubsection Improve Emacs integration

@uref{http://en.wikipedia.org/wiki/SLIME, SLIME} is an Emacs mode
that provides IDE-like functionality.  It supports Kawa.

@uref{http://jdee.sourceforge.net/,JDEE} is a Java development environment,
so might have better hooks to the JVM and Java debugging architecture.

@uref{http://cedet.sourceforge.net/,CEDET} is a more general
framework of development tools.

@subsection Hop-style web programming
@uref{http://hop.inria.fr/,Hop} is an interesting design
for integrating server-side and client-side programming using
a Scheme dialect.  These ideas seem like they would port
quite well to Kawa.

@subsection String localization

@i{(GSoC)}

Support localization by extending the
@uref{http://srfi.schemers.org/srfi-109/srfi-109.html,SRFI_109}
syntax, in the manner of (and compatible with)
@uref{http://www.gnu.org/software/gettext/,GNU gettext}.
I.e. optionally specify a localization key (to use as an index
in the translation database); if there is no key specified,
default to using the literal parts of the string.

@subsection Data binding
Implement a ``bind'' mechanism similar to that
of @uref{http://docs.oracle.com/javafx/1.3/tutorials/core/dataBinding/,JavaFX Script}.
The idea is that when you initialize a variable or field,
instead of initializing it to a fixed value, you bind it to
an expression depending on other variables.
We install ``listeners'' on those variables, so when those variables
change, we update the bound variable.
This feature is useful in many applications, but the initial
focus could be GUI programming and perhaps web programming.
@c Note in general the result is a ``text'', which is a generalization
@c of a string: A text is a sequence of characters *or* other values.
@c If an embedded expression evaluates to a non-string, it is @emph{not}
@c automatically converted to a string.  Conversion to a string
@c is done on demand, for example on printing.
@c (This is similar to values in the XML data model.)

@subsection Decimal arithmetic and repeated decimals

@i{(GSoC. Possibly a bit light for a full Summer project,
but can be extended or combined with other projects.)}

Exact decimal arithmetic is a variation of exact rational arithmetic,
but may be more user-friendly.  In particular, printing using
decimals is generally nicer than fractions.
It is also sometimes useful to specify an explicit scale,
so we can distinguish 0.2 from 0.20.
We can use the Java @code{BigDecimal} class, but run into problems
with division - for example @code{(/ 1.0 3.0)}.
We should implement a subclass of @code{RatNum} that generalizes
@code{BigDecimal} to also handle repeating decimals.
We need a lexical syntax for repeating decimals.
Possible ideas: @code{0._81_} or @code{0.#81}.
If a Scheme number literal is specified as exact and has either
a decimal point or an exponent (for example @code{#e1.25}), then it should
read as an exact decimal, not a fraction.

@subsection Optional strict typing along with an explicit @code{dynamic} type

@i{(GSoC)}

Kawa currently implements ``optimistic'' typing: The compiler only
complains if an expression has no values in common with the target type
- for example, if assigning a @code{string} expression to an @code{integer}
variable.
It would be interesting to experiment with a
@code{--strict-typing} option (which would never be the default):
Strict typing would only allow ``widening'' conversions - i.e.
that the expression type be a subtype of the target type.
For example it would complain if assigning a @code{number} to an @code{integer}
unless you used an explicit cast.

To make this easier to work with we'd make use
of the @ref{dynamic-type,@code{dynamic} type}, similar to
@uref{https://msdn.microsoft.com/en-us/library/dd264736.aspx,what
@code{C#} does}: Any expression can be converted
to or from @code{dynamic} without the compiler complaining.
Similarly, if @code{x} is @code{dynamic} then @code{x:name}
is allowed by the compiler regardless of @code{name}, with all checking
being deferred to run-time.  If a variable is declared without a type,
it should default to @code{dynamic}.  The @code{dynamic} type
is represented in the VM as @code{object} but with an annotation
(like we do with @code{character}).

The type-checker might need some changes to better distinguish
implicit conversions from explicit casts.

@node Installation
@chapter Getting and installing Kawa

@menu
* Getting Kawa::
* Running Java::                Getting and running Java
* Binary distribution::         Installing and using the binary distribution
* Source distribution::         Installing and using the source distribution
@end menu

@node Getting Kawa, Running Java, , Installation
@section Getting Kawa

You can compile Kawa from the source distribution.
Alternatively, you can install the pre-compiled binary distribution.

You can get Kawa sources and binaries from the Kawa ftp site
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/},
or from a @uref{http://www.gnu.org/order/ftp.html,mirror site}.

The current release of the Kawa source code is
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.tar.gz}.
(To unpack @code{.tar.gz} files Windows users can use
@uref{http://www.7-zip.org/,7-Zip}, which is Free Software.)

The corresponding pre-compiled release
is @uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.zip}.
The most recent snapshot is
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-latest.zip}.
Instructions for using either are @ref{Binary distribution,here}.

@subsection Getting the development sources using Git

The Kawa sources are managed using a
@uref{https://gitlab.com/kashell/Kawa,git} repository.
If you want the very latest version grab
@uref{https://git-scm.com/downloads,a git client},
and then check out the source using this command:
@example
git clone https://gitlab.com/kashell/Kawa.git
@end example

After a checkout you will need to run:
@example
./autogen.sh
@end example
before proceding with instructions for @ref{Source distribution,building the source distribution}.

Once you have it checked out, you can keep it up-to-date with @code{git pull}.

You can also
@uref{https://gitlab.com/kashell/Kawa/tree/master,browse the git archive} online.

@node Running Java, Binary distribution, Getting Kawa, Installation
@section Getting and running Java

Before installing Kawa, you will need a working Java system.
The released Kawa jar file assumes Java 8 or newer.
You need to build Kawa from source if you have Java 5, Java 6,
or are targeting Android.
(Older versions of Kawa have been reported to
work with JDK from 1.1, Kaffe, Symantec Cafe, J++, and GCJ,
but these are no longer supported.)

The discussion below assumes you are using the Java Developer's Kit
(JDK) from Oracle.  You can download free copies of
@uref{http://www.oracle.com/technetwork/java/javase/downloads/index.html, JDK 8} for various platforms.

@c If you want to run Kawa on a Macintosh, see
@c @uref{http://rdsathene.org/scheme/mackawa.html}.

The program @code{java} is the Java interpreter.
The program @code{javac} is the Java compiler,
and is needed if you want to compile the source release yourself.
Both programs must be in your @code{PATH}.
If you have the JDK in directory @code{$JAVA_HOME},
and you are using a Bourne-shell compatible shell
(/bin/sh, ksh, bash, and some others) you can set @code{PATH} thus:
@example
PATH=$JAVA_HOME/bin:$PATH
export PATH
@end example

@node Binary distribution
@section Installing and using the binary distribution

The binary release comes as a @code{.zip} archive that
includes Kawa itself (as a @code{.jar} file @code{kawa-@var{version}.jar}),
some third-party helper libraries, @code{kawa} command scripts
(for GNU/Linux/Unix/MacOS or Windows),
and documentation (basically this manual).

After downloading (see @ref{Getting Kawa}), extract the files
from the @code{.zip} archive using a suitable @code{unzip} program,
which will create a directory @code{kawa-@var{version}},
with @code{lib}, @code{bin}, and @code{doc} sub-directories.
In the following, we assume the environment variable @code{KAWA_HOME}
refers to this directory:
@example
unzip ~/Downloads/kawa-@var{version}.zip
export KAWA_HOME=`pwd`/kawa-@var{version}
@end example

The binary release requires Java 8 or later.
If you have an older Java implementation, or build for a mobile
environment like Android,
then you will need to get the source distribution.

If you want to use Kawa as part of some other application,
you just need the @code{$KAWA_HOME/lib/kawa.jar}.

@subsubheading Running the @code{kawa} command

To run a Kawa script file or the Kawa read-eval-print-loop
run the Kawa application.  There are various way to do so.

The recommended way is to execute the @code{$KAWA_HOME/bin/kawa} Bash
shell script.
This should work on most Unix-like platforms that have Bash installed,
including GNU/Linux, BSD, MacOS, and Cygwin/MingW.
(Please report if you have problems.)

The script assumes that either a suitable @code{java} program is
in your @code{PATH}; or the @code{JAVA} environment variable
names a suitable @code{java} executable; or that @code{JAVA_HOME}
is set so @code{$JAVA_HOME/bin/java} is suitable.

If you want to put @code{kawa} in your search path you can of course do:
@example
PATH=$KAWA_HOME/bin:$PATH
@end example
Alternatively you can create a symbolic link in an already-searched directory.
For example:
@example
cd /usr/local/bin
ln -s $KAWA_HOME/bin/kawa kawa
@end example

The @code{bin/kawa.bat} script works on Windows.

Both scripts add some helper libraries, including support for input editing.

It is also possible to run Kawa using @code{java} directly:
@example
java -jar $KAWA_HOME/lib/kawa.jar
@end example
or:
@example
CLASSPATH=$KAWA_HOME/lib/kawa.jar
export CLASSPATH
java kawa.repl
@end example
On Windows:
@example
set classpath=%KAWA_HOME%\lib\kawa.jar
@end example

To run Kawa in a fresh window use the -w flag:
@example
kawa -w
@end example
or
@example
java kawa.repl -w
@end example

@subsubheading Reading the documentation

The file @code{doc/kawa-manual.epub} contains the Kawa documention
packaged as an electronic book, which is readable by most
e-book readers.  Plugins are also available for common browsers,
for example @uref{http://www.epubread.com,EPUBReader} for @code{firefox}.

Even easier is to invoke
@ref{browse-manual-option,@code{bin/kawa --browse-manual}}
(or on Windows: @code{bin\kawa.bat --browse-manual}).

An @code{epub} is essentially a zip archive, which you can unzip:
@example
cd $KAWA_HOME/doc
unzip kawa-manual.epub
@end example
Then you can use a plain browser
with the URL @code{file:$KAWA_HOME/doc/OEBPS/index.xhtml}.

@node Source distribution,  , Binary distribution, Installation
@section Installing and using the source distribution
The Kawa release normally comes as a gzip-compressed tar file named
@samp{kawa-@value{VERSION}.tar.gz}.
@c The same sources are available as a zip file
@c @samp{kawa-@value{VERSION}-src.zip}.
Two methods are supporting for compiling the Kawa sources;
choose whichever is most convenient for you.

One method uses the traditional GNU @code{configure} script,
followed by running @code{make}.  This works well on Unix-like
systems, such as GNU/Linux.
You can also use this method on Microsoft Windows,
with the help of tools from @uref{http://www.MinGW.org/, MinGW}
or @uref{http://www.cygwin.org/, Cygwin}.

The other method uses the @code{ant} command, a Java-based
build system released by Apache's Jakarta project.  This uses
an @code{build.xml} file in place of @code{Makefile}s, and
works on non-Unix systems such as Microsoft Windows.  However,
the @code{ant} method does not support all
the features of the @code{configure}+@code{make} method.

@subsection Build Kawa using @code{configure} and @code{make}

(See @ref{building-on-Windows-with-make,below} for some notes for building
on Microsoft Windows.)

If you have a @code{tar.gz} file, first unpack that in your build directory:
@example
tar xzf kawa-@value{VERSION}.tar.gz
cd kawa-@value{VERSION}
@end example

If you're building from the Git repository, you need to
generate @code{configure} and some other files. This is
easiest done with the @code{autogen.sh} script:
@example
./autogen.sh
@end example

Then you must configure the sources.  This you do in
the same way you configure most other GNU software.  Normally
you can just run the configure script with no arguments:

@example
./configure
@end example
The @code{configure} script takes a number of @ref{configure options,options}.

If you have installed Kawa before, make sure your @code{CLASSPATH}
does not include old versions of Kawa, or other classes that may
conflict with the new ones.

Then you need to compile all the .java source files.
Just run make:
@example
make
@end example
This assumes that @samp{java} and @samp{javac} are the java interpreter
and compiler, respectively.

It has been reported that parallel make doesn't work,
so don't use the @code{-j2} or above options.

You can now test the system by running Kawa in place:
@example
java kawa.repl
@end example

or you can run the test suite:
@example
make check
@end example

or you can install the compiled files:
@example
make install
@end example

This will install your classes into @code{$PREFIX/share/java} (and its
sub-directories).  Here @code{$PREFIX} is the directory you specified
to configure with the @code{--prefix} option, or @code{/usr/local} if you
did not specify a @code{--prefix} option.

To use the installed files, you need to set @code{CLASSPATH} so
that @code{$PREFIX/share/java/kawa.jar} is in the path:
@example
CLASSPATH=$PREFIX/share/java/kawa.jar
export CLASSPATH
@end example
This is done automatically if you use the @samp{kawa} script.

@anchor{configure options}
@cindex configure options
@subsubsection Configure options

The @code{configure} script takes a number of options.
The @code{--help} switch gives you a list of options.
The following are some of the more common or important ones.

@table @asis
@item @code{--prefix=@var{install-dir}}
@itemx @code{--prefix @var{install-dir}}
By default @code{make install} will install the compiled @code{.jar}
files info @code{/usr/local/share/java},
the @code{kawa} command into @code{/usr/local/bin},
and so on in @code{/usr/local}.
The @code{--prefix} option causes the files to be installed
under @code{@var{install-dir}} instead of @code{/usr/local}.
For example to install the @code{.jar} in @code{/opt/kawa/share/java}
and otherwise use @code{/opt/kawa} do:
@example
./configure --prefix=/opt/kawa
@end example

@item @code{--with-java-source=@var{version}}
As distributed, the Kawa source code requires Java 8.
If you only have Java 7, Java 6, or Java 5, use the @code{--with-java-source} option:
@example
./configure --with-java-source=6
@end example

Kawa no longer supports older verisons of Java (JDK 1.4 or older).
It might be possible to use a tool
like @uref{http://retroweaver.sourceforge.net/, Retroweaver}
on the Kawa @code{.jar} to fix up Java 5 dependencies.
Contact the Kawa author if you want to be a tester for this.

@item @code{--with-docbook-stylesheet[=@var{path}]}
Build the documentation (this manual) as an electronic book
(in ebook format) or a website, using
the DocBook xslt stylesheets.
(You can build the documentation without DocBook, but using
it enables nicer-looking and more functional documentation.)

The stylesheets are found using @var{path};
the file @code{@var{path}/epub3/chunk.xsl} needs to exist.
(For example, on Fedora 25 @var{path} can be @code{/usr/share/sgml/docbook/xsl-ns-stylesheets},
while on Debian use @code{/usr/share/xml/docbook/stylesheet/docbook-xsl-ns}.)

@item @code{--with-domterm}
@itemx @code{--with-domterm=@var{domterm_home}}
Compile with extra support for the @ref{Using DomTerm,DomTerm}
terminal emulator library, where @code{@var{domterm_home}}
is such that @code{@var{domterm_home}/lib/domterm.jar} exists.
(Some DomTerm support is built-in regardless.)

If you use this option along with @code{--with-javafx}
then creating a new @ref{REPL Console,REPL} window
will create a DomTerm window.

As an optional convenience, you can use the @code{domterm.jar}
in the Kawa binary distribution.

@item @code{--with-jline3}
@itemx @code{--with-jline3=@var{jline3.jar}}
Build support for using @uref{https://github.com/jline/jline3,JLine 3},
which is a library for handling console input, similar to GNU readline.
If specified, the @var{jline3.jar} is added to the classpath of the
generated @code{kawa.sh} or @code{kawa} shell program.

An advantage of @code{--with-jline3} (compared to
@code{--enable-kawa-frontend}) is that the former works without native code
(on most Unix-like platforms), and it does not require a C wrapper program.

As an optional convenience, you can use the @code{jline.jar}
in the Kawa binary distribution.

@item @code{--with-domterm}
@itemx @code{--with-domterm=@var{domterm.jar}}
Compile with extra support for the @ref{Using DomTerm,DomTerm}
terminal emulator library.  (Some DomTerm support is built-in regardless.)

If you use this option along with @code{--with-javafx}
then creating a new @ref{REPL Console,REPL} window
will create a DomTerm window.

As an optional convenience, you can use the @code{domterm.jar}
in the Kawa binary distribution.

@item @code{--with-servlet}
@itemx @code{--with-servlet=@var{servlet-jar}}
Build support for @ref{Servlets,servlets}, which are used in web servers.
This requires the @code{servlet-api.jar} (available various places including
@uref{http://tomcat.apache.org/,Tomcat} or
@uref{https://glassfish.java.net/,Glassfish}),
for @code{javax.servlet.Servlet} and related classes.
If this class isn't in your classpath, specify its location
as @code{@var{servlet-jar}}. For example:
@example
./configure --with-servlet=/path/to/servlet-api.jar 
@end example

@item @code{--enable-jemacs}
Build JEmacs (enable Emacs-like text editor) and support (a subset of)
the Emacs Lisp language.  JEmacs is a proof of concept - not really
usable or maintained.

@item @code{--with-javafx}
@itemx @code{--with-javafx=@var{javafx-jar}}
@itemx @code{--with-javafx=@var{java-home}}
Set this flag to enable the convenience features
for @ref{Building JavaFX applications,JavaFX}.
The JavaFX classes are included in JDK 8 (but not OpenJDK 8),
and you don't need to specify @code{@var{javafx-jar}} or @code{@var{java-home}}.
For JDK 7 you need to specify @code{@var{javafx-jar}}
(the path to @code{javafx.rt}) or @code{@var{java-home}}
(the value of the @code{$JAVA_HOME}).

@item @code{--with-android=@var{android-jar}}
Build for the Android platform.
This requires @ref{Building for Android,special instructons}.

@item @code{--enable-kawa-frontend}
If you have the GNU @samp{readline} library installed, you might try
adding the @samp{--enable-kawa-frontend} flag.
This will build the
@samp{kawa} front-end program, which provides input-line editing
and an input history.  You can get @samp{readline} from archives
of GNU programs, including @uref{ftp://www.gnu.org/}.

Note that using JLine, enabled by @code{--with-jline3},
is now recommended instead of using the @code{readline} frontend.

You may need to specify to @code{make} where to find
the @code{readline} include files (with @code{READLINE_INCLUDE_PATH})
and the library (with @code{READINE_LIB_PATH}).
For example on OS/X you need to do:
@example
make READLINE_INCLUDE_PATH=-I/usr/local/unix/readline/include \
     READLINE_LIB_PATH=-L/usr/local/unix/readline/lib
@end example
@end table

@anchor{building-on-Windows-with-make}
@subsubsection Building on Windows using MinGW

The Kawa @code{configure} and @code{make} process assumes Unix-like
tools, which you can get from @uref{http://mingw.org, the MinGW project}.
Download the MingGW Installation Manager, and use it to install
at least @code{mingw-developer-toolkit}.
(Also installing @code{msys-groff} avoids a minor problem
building the documentation.)

The @code{C:\MinGW\msys\1.0\msys.bat} script creates a command window
with the @code{bash} shell and the @code{PATH} set up as needed.
Alternatively, you can use the standard Windows command prompt
if you set your @code{PATH} as described in @uref{http://mingw.org/wiki/Getting_Started, here}.

@subsubsection Building on Windows using Cygwin

The free @uref{http://sourceware.org/cygwin/,Cygwin}
environment can be used for building Kawa: The Kawa configure script
recognizes Cygwin, and modifies the classpath to use Windows-style
path separators.

Beyond the base packages, you probably want to install @code{autoconf},
@code{automake}, @code{git}, @code{texinfo}, @code{groff},
@code{make}, and @code{diffutils}.

Cygwin (unlike MinGW) has a current version of @code{makeinfo}, but
an undiagnosed bug still prevents building @code{kawa.info}.
You can work around that problem with @code{touch doc/kawa.info}.

@subsection Building the documentation

@subsubsection Plain HTML documentation

You can build a plain HTML version of the documentation
(using @code{makeinfo} from the @code{texinfo} distribution):
@example
cd doc && make kawa-html/index.html
@end example

In this case, point your browser at
@code{file:/@var{kawa_srcdir}/doc/kawa-html/index.html}.

@subsubsection Fancier HTML documentation

To build the documentation in a nicer form suitable for a web-site
you need @code{makeinfo} @emph{and} the DocBook XSLT tools
(and to have run @code{configure} with
the @code{--with-docbook-stylesheet} option):
@example
cd doc && make web/index.html
@end example

You can then point your browser at @code{file:/@var{kawa_srcdir}/doc/web/index.html}.

@subsubsection Using ebook readers or the --browse-manual option

To build an @code{EPUB} file suitable for ebook readers,
as well as enabling support for the
@ref{browse-manual-option,@code{kawa --browse-manual} option}, do:

@example
cd doc && make kawa-manual.epub
@end example

This also requires the DocBook XSLT tools.

@subsubsection Building a printable PDF file

To build a @code{pdf} file suitable for printing or online viewing do:
@example
cd doc && make kawa.pdf
@end example

The resulting @code{kawa.pdf} is somewhat unsatisfactory - when viewed online,
links aren't clickable.  Furthermore, box drawing characters are missing.

@subsection Build Kawa using @code{ant}

Kawa now includes an Ant buildfile (@code{build.xml}).
@uref{http://ant.apache.org, Ant} is a part of the Apache
Jakarta project.
If you don't hava Ant installed,
get it from @uref{http://ant.apache.org/bindownload.cgi}.
The build is entirely Java based and works equally well on *nix, Windows,
and presumably most any other operating system.

Once Ant has been installed and configured (you may need to set the
@code{JAVA_HOME}, and @code{ANT_HOME} environment variables), you should
be able to change to the directory containing the @code{build.xml} file,
and invoke the @samp{ant} command.  With the default settings, a
successful build will result in a @code{kawa-@value{VERSION}.jar} in the
current directory.

There are a few Ant "targets" of interest (they can be supplied on the
Ant command line):

@table @code
@item all
This is the default, it does @code{classes} and @code{jar}.
@item classes
Compiles all the files into @code{*.class} files into the directory
specified by the @code{build.dir} property.
@item jar
Builds a jar into into the directory
specified by the @code{dist.dir} property.
@item runw
Run Kawa in a GUI window.
@item clean
Deletes all files generated by the build, including the jar.
@end table

There is not yet a @code{test} target for running the testsuite.

There are various ``properties" that control what @code{ant} does.  You can
override these on the command line or by editing the
@code{build.properties} file in the same directory as @code{build.xml}.
For example, the @code{build.dir} property tells @code{ant} where to
build temporary files, and where to leave the resulting @code{.jar}
file.  For example, to leave the generated files in the sub-directory
named @code{BUILD} do:
@example
ant -Dbuild.dir=BUILD
@end example
A sample @code{build.properties} is provided and it contains
comments explaining many of the options.

Here are a few general properties that help to customize your build:
@table @code
@item build.dir
Path to put the temporary files used for building.
@item dist.dir
Path to put the resulting jar file.
@item version.local
A suffix to add to the version label for your customized version.
@item debug
Whether (true/false) the Javac "-g" option is enabled.
@item optimize
Whether (true/false) the Javac "-O" option is enabled.
@end table

Here are some Kawa-specific ones (all @code{true}/@code{false}):
@code{with-collections}, @code{with-references}, @code{with-awt},
@code{with-swing}, @code{enable-jemacs}, and @code{enable-servlet}>
See the sample @code{build.properties} for more information on these.

If you change any of the build properties, you will generally want to do
an @samp{ant clean} before building again as the build is often not able to
notice that kind of change.  In the case of changing a directory path,
you would want to do the @code{clean} before changing the path.

A special note for NetBeans users:
For some reason the build-tools target which compiles an Ant task won't
compile with the classpath provided by NetBeans.
You may do @samp{ant build-tools} from the command line outside of NetBeans,
in which case you will not want to use the @code{clean} target as that
will delete the tool files as well.
You can use the @code{clean-build} and/or @code{clean-dist}
targets as appropriate.  Alternatively you can add @code{ant.jar} to the
@code{build-tools} classpath by copying or linking it into a @code{lib/ext}
directory in Kawa's source directory (the one containing the @code{build.xml}
file).

@ignore
@subsection Compiling Kawa to native code with GCJ

@emph{Using GCJ is no longer supported.  This section is for historial
reference, or if someone enhances GCJ enough to support Kawa.}

The GNU Compiler for the Java(tm) Programming Language
(@uref{http://gcc.gnu.org/java/,GCJ}) is part of the
GNU Compiler Collection (@uref{http://gcc.gnu.org/,GCC}).
It can compile Java source or bytecode
files into native code on supported systems.
Version 4.1 or later of GCC is recommended,
and only Intel x86-based Linux/GNU system have been tested with Kawa.

First, get and install GCC.  Set @code{PREFIX} to where
you want to install GCJ, and configure it with these options:
@example
./configure --enable-threads --enable-languages=c++,java --prefix $PREFIX
make bootstrap
make install
@end example
Make sure @code{gcj} is in your path and refers to the newly-installed
version, and if needed, set @code{LD_LIBRARY_PATH} to point to the
directory where @code{libgcj.so} was installed:
@example
PATH=$PREFIX/bin:$PATH
LD_LIBRARY_PATH=$PREFIX/lib
export LD_LIBRARY_PATH
@end example

To build Kawa, you need to specify @code{--with-gcj} to
@code{configure} which tells it to use GCJ.
@example
./configure --with-gcj --prefix $PREFIX
@end example
Then as before:
@example
make
make install
@end example

Alternatively, you can use configure option
@code{--with-gcj-dbtool}.  This allows gcj to automatically
find the kawa shared libraries from the @code{.jar} file.
@end ignore

@node Tutorial
@chapter Kawa Scheme Tutorial

@emph{This is obviously incomplete, but it may be useful,
especially if you're starting with Kawa from scratch.}
If you're new to Scheme you might also check out one of these tutorials:
Takafumi Shido's
@uref{http://www.shido.info/lisp/idx_scm_e.html,Yet Another Scheme Tutorial};
@c dead link Greg Badross @uref{http://www.cs.washington.edu/education/courses/341/99suq/lectures/scheme/,lecture notes};
Dorai Sitaram's @uref{http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-1.html,Teach Yourself Scheme in Fixnum Days}; or
Paul Wilson's @uref{ftp://ftp.cs.utexas.edu/pub/garbage/cs345/schintro-v14/schintro_toc.html,An Introduction to Scheme and its Implementation}.

@menu
* Tutorial - Introduction::      Introduction
* Tutorial - Booleans::          Booleans
* Tutorial - Numbers::           Numbers
* Tutorial - Functions::         Functions
* Tutorial - Variables::         Variables
* Tutorial - Pictures::          Pictures
* Tutorial - Sequences::         Lists and sequences
* Tutorial - Objects::           Creating and using objects
* Tutorial - Types::             Types and declarations
* Tutorial - Exceptions and errors::
* Tutorial - Classes::           Classes
* Tutorial - Other Java features::
@end menu

@node Tutorial - Introduction
@section Introduction
You've heard about all the hot scripting languages
-- you might even be tired of hearing about them.
But Kawa offers you something different than the
scripting-language @i{du-jour} can.
You may be interested in one that runs on the Java virtual machine,
either because you have to interact with other Java tools,
or because you like having access to all the Java packages out there.
Or maybe you don't care about Java, but you care about performance.
If so, let me tell you about Kawa, which is actually one of the
very oldest language implementations running on the Java Virtual Machine,
dating back to 1996.

The Kawa language is a dialect/implementation of the Scheme language.
(The Kawa project also supports other languages, including
@uref{http://www.w3.org/XML/Query,XQuery}
and @uref{http://jemacs.sourceforge.net,Emacs Lisp},
as well as tools for implementing mew programming languages,
but we won't cover that in this tutorial.)

@uref{http://www.schemers.org/,Scheme}
is an established language with many
@uref{http://community.schemewiki.org/?scheme-faq-standards#implementations,implementations},
a @uref{http://www.schemers.org/Documents/Standards/,standard} specification
(the traditional @uref{http://www.schemers.org/Documents/Standards/R5RS/,R5RS},
@uref{http://www.r6rs.org/,R6RS} which was ratified in 2007,
and @uref{http://www.r7rs.org/,R7RS} which was ratified in 2013),
and is used by universities for both teaching and research.
Scheme also has a reputation for being difficult to learn,
with a weird parenthesis-heavy syntax,
and hard-to-understand concepts like @uref{http://en.wikipedia.org/wiki/Continuation,continuations}.
Luckily, you don't need to understand continuations!
(Kawa doesn't fully implement them anyway.)

The following assumes that Kawa is already installed on your computer;
if not see these @ref{Installation,installation instructions}.
Running the @code{kawa} command in interactive mode
is a good way start learning Kawa:
@example
$ @kbd{kawa}
#|kawa:1|# @kbd{}
@end example
If you don't have @code{kawa} but you have a
Kawa ``jar'' and you have Java installed you can instead do:

@example
$ @kbd{java -jar kawa-@var{version-number}.jar}
#|kawa:1|# @kbd{}
@end example

The prompt string has the form of a Scheme comment,
to make it easier to cut-and-paste.
Kawa is expecting you type in an expression or command,
which it will evaluate, and then print out the result.
For example, a quoted string is a simple expression that evaluates to a
string value, which will print as itself, before printing the next prompt:

@example
#|kawa:1|# @kbd{"Hello, world!"}
Hello, world!
#|kawa:2|# @kbd{}
@end example
@c Thus the Kawa equivalent of the traditional
@c @uref{http://en.wikipedia.org/wiki/Hello_world,``hello world''} is trivial.

The most noticable difference from most other programming languages
is that Scheme uses ``prefix'' notation for function calls.
For example Kawa has a function @code{max} which returns the
largest value of the arguments.
Instead of @code{max(5, 7, 3)}
you write @code{(max 5 7 3)}:

@example
(max 5 7 3) @result{} 7
@end example

(We use the @code{@result{}} symbol above to indicate that
the expression @code{(max 5 7 3)} evaluates to the
value @code{7}.)

The prefix notation may feel a bit weird, but you quickly
get used to it, and it has some advantages.
One is consistency: What are special infix operators in most languages
are just regular functions in Scheme.
For example, addition is just a regular function call,
and @code{+} is just a regular function name:
@example
(+ 2.5 1.2) @result{} 3.7
@end example

The same prefix notation is used for special operations like assignments:
@example
#|kawa:1|# @kbd{(set! sqrt-of-2 (sqrt 2))}
#|kawa:2|# @kbd{sqrt-of-2}
1.4142135623730951
@end example

@node Tutorial - Booleans
@section Booleans

Scheme uses the syntax @code{#t} and @code{#f}
for Boolean true and false value, respectively.  For example, the
``less-than'' function is named @code{<}.
Its result is true if the first argument is less than the second (or, if
there are more than two arguments, that they are in increasing order):
@example
(< 3 4) @result{} #t
(< -3 -4) @result{} #f
(< 2 3 5 7 11)) @result{} #t
@end example

The @code{if} special form takes two or three sub-expressions:
It evaluates the first expression.
If that is true it evaluates the second expression;
otherwise it evaluates the third expression, if provided:
@example
(if (< 3 4) (+ 5 5) (+ 5 6)) @result{} 10
@end example

We call @code{if} a special form rather than a function,
because for a function all the arguments are evaluated before the
function is called, but in a special form that is not neceassarily the case.

In addition to @code{#t} any value except @code{#f}
counts as ``true'' when evaluating the first expression of an @code{if}:

@example
(if 0 (+ 5 5) (+ 5 6)) @result{} 11
@end example

You can use @code{and}, @code{or},
and @code{not} to create complex boolean expressions.
Of these @code{and} and @code{or}
are special forms that only evaluate as many of the sub-expressions as needed.
@example
(if (not (and (>= i 0) (<= i 9)))
    (display "error"))
@end example

You can use the @code{cond} form as an alternative to
@code{if}:
@example
(cond ((< 3 3) 'greater)
      ((> 3 3) 'less)
      (else ’equal))       @result{} equal
@end example

The null value (written as @code{#!null} in Kawa or @code{null} in Java)
is also considered as false.

@node Tutorial - Numbers
@section Numbers

@subheading Exact integers and fractions

Kawa has the usual syntax for decimal integers.
Addition, subtraction, and multiplication
are written using the usual @code{+},
@code{-}, and  @code{*},
but these are all prefix functions that take a variable number of arguments:

@example
(+ 1 2 3) @result{} 6
(- 10 3 4) @result{} (- (- 10 3) 4)  @result{} 3
(* 2 -6)  @result{} -12
@end example

Kawa has arbitrary-precision integers.

Let us implement the @uref{http://en.wikipedia.org/wiki/Factorial,factorial} function.
Type in the following (we'll look at the syntax shortly):
@example
#|kawa:1|# @kbd{(define (factorial x)}
#|(---:2|# @kbd{  (if (< x 1) 1}
#|(---:3|# @kbd{    (* x (factorial (- x 1)))))}
@end example

(The prompt changes to indicate a continuation line.)
This binds the name @code{factorial}
to a new function, with formal parameter @code{x}.
This new function is immediately compiled to Java bytecodes,
and later a JIT compiler may compile it to native code.

A few tests:
@example
#|kawa:4|# @kbd{(list (factorial 3) (factorial 4))}
(6 24)
#|kawa:5|# @kbd{(factorial 30)}
265252859812191058636308480000000
@end example

@subheading Floating-point real numbers

Given what was said above about being able to add, subtract and multiply integers,
the following may be unexpected:

@example
#|kawa:1|# (/ 2 3)
2/3
#|kawa:2|# (+ (/ 1 3) (/ 2 3))
1
@end example

In many languages, dividing two integers, as 2/3, would result in 0.  At best,
the result would be a floating point number, similar to 0.666667.  Instead,
Kawa has a @emph{rational} number type, which holds the results of divisions
@emph{exactly}, as a proper fraction.  Hence, adding one third to two thirds
will always result in exactly one.

Floating-point real numbers are known in Kawa as @emph{inexact} numbers, as
they cannot be stored exactly.  Consider:

@example
#|kawa:3|# (exact? 2/3)
#t
#|kawa:4|# (exact? 0.33333333)
#f
#|kawa:5|# (exact->inexact 2/3)
0.6666666666666666
@end example

The first two examples check numbers for being @code{exact?}; there is a
corresponding @code{inexact?} test.  The last shows how an exact number can be
converted to an inexact form.

Numbers are converted between exact and inexact versions when required
within operations or procedures:

@example
#|kawa:6|# (+ 0.33333333 2/3)
0.9999999966666666
#|kawa:7|# (inexact? (+ 0.33333333 2/3))
#t
#|kawa:8|# (sin 2/3)
0.618369803069737
@end example

@subheading Complex numbers

A @emph{complex} number is made from two parts: a @emph{real} part and an
@emph{imaginary} part.  They are written @code{2+3i}.  A complex number can
be manipulated just like other numbers:

@example
#|kawa:9|# (+ 2+3i 5+2i)
7+5i
#|kawa:10|# (* 2+3i 4-3i)
17+6i
#|kawa:11|# (integer? (+ 2+3i -3i))
#t
@end example

Notice how in the last example the result is an integer, which Kawa recognises.

Kawa also includes @ref{Quaternions,quaternion} numbers.

@subheading Units and dimensions

In many applications, numbers have a @emph{unit}.  For example, 5 might be
a number of dollar bills, a weight on a scale, or a speed.  Kawa enables us
to represent numbers as @emph{quantities}: numbers along with their unit.
For example, with weight, we might measure weight in pounds and ounces,
where an ounce is 1/16 of a pound.

Using Kawa, we can define units for our weight measurements, and specify the 
units along with numbers:

@example
#|kawa:12|# (define-base-unit pound "Weight")
#|kawa:13|# (define-unit ounce 0.0625pound)
#|kawa:14|# 3pound
3.0pound
#|kawa:15|# (+ 1pound 5ounce)
1.3125pound
@end example

In this example we define a base unit, the pound, and a unit based on it, the
ounce, which is valued at 0.0625 pounds (one sixteenth).  Numbers can then be
written along with their unit (making them quantities).  Arithmetic is possible 
with quantities, as shown in the last line, and Kawa will do the smart thing
when combining units.  In this case, 1 pound and 5 ounces is combined to make
1.3125 pounds.

@node Tutorial - Functions
@section Functions

To declare a new function use @code{define},
which has the following form:
@example
(define (@var{function-name} @var{parameter-names}) @var{body})
@end example

This creates a new function named @var{function-name},
which takes @var{parameter-names} as parameters.
When the function is called, the  @var{parameter-names}
are initialized with the actual arguments. Then @var{body}
is evaluated, and its value becomes the result of the call.

For example, in the @code{factorial} function we looked at recently,
the @var{function-name} is @code{factorial},
and the @var{parameter-names} is @code{x}:

@example
(define (factorial x)
  (if (< x 1) 1
  (* x (factorial (- x 1)))))
@end example

@subheading Anonymous functions

@c If you just evaluate a function nameA function is an actual variable you can evaluate xxx

An @emph{anonymous} function is simply a function which does not have a name.
We define an anonymous function using a @dfn{lambda expression}, which has
the following form:
@example
(lambda (@var{parameter-names}) @var{body})
@end example

The lambda expression has the @var{parameter-names} and @var{body} of a
function, but it has no name.  What is the point of this?

An important example is creating a function to act on a list, perhaps using
@code{map}.  The @code{map} function takes two parameters: the first is a
function which takes a value and returns a value; the second is a list.  Here,
we want to double every number in the list.

The usual way of doing this is to create a named function, called
@code{double}, and then apply it to a list:

@example
#|kawa:1|# (define (double x)
#|.....2|#    (* 2 x))
#|kawa:3|# (map double (list 1 2 3 4 5))
(2 4 6 8 10)
@end example

Instead, anonymous functions make it easy to create a function to work on a
list, without having to define it in advance:

@example
#|kawa:4|# (map (lambda (x) (* 2 x)) (list 1 2 3 4 5))
(2 4 6 8 10)
#|kawa:5|# (define y 3)
#|kawa:6|# (map (lambda (x) (* x y)) (list 1 2 3 4 5))
(3 6 9 12 15)
@end example

The first example shows the double example rewritten as an anonymous function.
The second example shows how the anonymous function can be changed to
fit the place in which it is used: here, the value of @var{y} determines the
value by which the list values are multiplied.

Notice that we can name our anonymous functions, in just the same way we
name any value in Kawa, using @code{define}:

@example
(define double
   (lambda (n)
       (* 2 n)))
@end example

although more frequently we use the short-hand for defining functions, which we
have already met:

@example
(define (double n)
  (* 2 n))
@end example

Anonymous functions are ``first-class values'' in Kawa, and can be passed to
other functions as arguments (like we did with @code{map}), and they can even
be created and returned by functions as results.

@subheading Optional, rest and keyword parameters

You can declare a function that takes optional arguments,
or a variable number of arguments.  You can also use keyword parameters.

The following function illustrates the use of @emph{optional} arguments.  The function
identifies an optional argument @code{z}: if the function is called with 3 arguments, @code{z}
will be bound to the third value, otherwise it will be @code{#f}.

@example
(define (addup x y #!optional z)
  (if z
    (+ x y z)
    (+ x y)))
@end example

The following examples show @code{addup} applied to 2, 3 and invalid arguments.  It is an error to
pass just one argument or more than three: @code{x} and @code{y} are compulsory, but @code{z} is
optional.

@example
#|kawa:12|# (addup 1 2)
3
#|kawa:13|# (addup 1 2 3)
6
#|kawa:14|# (addup 1)
/dev/stdin:14:1: call to 'addup' has too few arguments (1; min=2, max=3)
#|kawa:15|# (addup 1 2 3 4)
/dev/stdin:15:1: call to 'addup' has too many arguments (4; min=2, max=3)
@end example

In this example, a better way to define the function would be to include a
default value for @code{z}, for when its value is not given by the caller.
This is done as follows, with the same behavior as above:

@example
(define (addup x y #!optional (z 0))
  (+ x y z))
@end example

You can include as many optional parameters as you wish, after the @code{#!optional}.

@emph{Rest} arguments are an alternative way to pass an undefined number of
arguments to a function.  Here is @code{addup} written with rest arguments,
notice the variable name after the . (dot):

@example
(define (addup x y . args)
  (+ x y (apply + args)))
@end example

The @code{args} are simply a list of all remaining values.  The following now all work, as the
function only requires a minimum of two numbers:

@example
#|kawa:4|# (addup 1 2)
3
#|kawa:5|# (addup 1 2 3)
6
#|kawa:6|# (addup 1 2 3 4 5 6 7 8)
36
@end example

An alternative way to identify the rest args is with @code{#!rest}:

@example
(define (addup x y #!rest args)
  (+ x y (apply + args)))
@end example

Finally, it can be useful to identify parameters by name and, for this, Kawa
provides @emph{keyword} arguments.  Consider the following function:

@example
(define (vector-3d #!key x y z)
  (make-vector x y z))
#|kawa:40|# (vector-3d #:x 2 #:z 3 #:y 4)
#(2 4 3)
@end example

@code{vector-3d} is defined with three keyword arguments: @code{x}, @code{y}, and @code{z}.  When the
function is called, we identify the name for each value by writing @code{#:} at the start of the name.
This allows us to write the arguments in any order.  Keyword parameters can also be given default
values, as with optional parameters.  Keyword parameters with no default value, and no value in the caller,
will get the value @code{#f}.

In the caller, keywords are symbols with @code{#:} at the front (or @code{:} at
the end): @ref{Keywords,read more here}.

All these extended types of arguments are available both for ``named'' and for ``anonymous'' functions.
Optional, rest and keyword arguments can be mixed together, along with the usual arguments.
For details @ref{Extended formals,read more here.}

@node Tutorial - Variables
@section Variables

You can declare a variable using a @code{!} form.
This takes a variable name, and an expression.  It declares a new
variable with the given name, and gives it the value of the expression.
@example
#|kawa:1|# (! binary-kilo 1024)
#|kawa:2|# (! binary-mega (* binary-kilo binary-kilo))
#|kawa:3|# binary-mega
1048576
@end example

If you prefer, you can use @code{define} instead of @code{!}:

@example
#|kawa:1|# @kbd{(define binary-kilo 1024)}
#|kawa:2|# @kbd{(define binary-mega (* binary-kilo binary-kilo))}
#|kawa:3|# @kbd{binary-mega}
1048576
@end example

The advantage of using @code{define} is that it is portable
to other Scheme implementations.
The advantages of using @code{!} is that it is shorter;
it generalizes to patterns (see later);
and it guards against accidentally ``shadowing'' a variable
by a nested variable with the same name.

A @code{!} (or @code{define}) typed into the command-line
defines a top-level variable.

You can also declare local variables, which are variables defined for
a given block of code.  For example, in the following code @code{let}
is used to set up a local binding of @code{x} to 3: this does not affect
the outer binding of @code{x} to 5:

@example
(define x 5)

(let ((x 3))
  (display x))  @result{} 3

(display x)     @result{} 5
@end example

Alternative forms for defining local variables are
@code{let}, @code{let*}, or @code{letrec}/@code{letrec*}.

The differences are in the order in which definitions are made.
@code{let} evaluates all its definitions in the environment holding
at the start of the @code{let} statement.  In the following example,
the local variables are defined using values from the global variables:

@example
(define x 5)
(define y 2)

(let ((x (+ 2 y))  ; uses value of global y, i.e. 2
      (y (+ 3 x))) ; uses value of global x, i.e. 5
  (display (list x y)))  @result {} (4 8)
@end example

@code{let*} instead evaluates each definition in the environment holding
at the start of the @code{let*} statement, along with all @emph{previous}
local definitions. In the following example, @code{y} is now defined with the
@emph{local} value of @code{x}:

@example
(define x 5)
(define y 2)

(let* ((x (+ 2 y))  ; uses value of global y, i.e. 2
       (y (+ 3 x))) ; uses value of local x, i.e. 4
  (display (list x y)))  @result {} (4 7)
@end example

@code{letrec/letrec*} are similar, but allow the definition of recursive
functions:

@example
(letrec ((is-even? (lambda (n) (and (not (= 1 n))
                                    (or (zero? n)
                                        (is-odd? (- n 1))))))
         (is-odd? (lambda (n) (and (not (zero? n))
                                   (or (= 1 n)
                                       (is-even? (- n 1)))))))
  (display (is-even? 11)))   @result {} #f
@end example

@node Tutorial - Pictures
@section Composable pictures

The @code{pictures} library lets you create geometric shapes
and images, and combine them in interesting ways.
You first need to import the library:
@example
(import (kawa pictures))
@end example
The easiest way to use and learn the library
is with a suitable REPL, where you can type
expressions that evaluate to pictures values,
and view the resulting pictures directly on the console.
The easiest way is to start the @code{kawa} command with the @code{-w}
flag.  Alternatively, you can use
a @ref{Using DomTerm,DomTerm}-based terminal emulator
such as @code{qtdomterm} (which is shown in the image below),
and then the @code{kawa} command.

@image{images/domterm-pictures-1}

The above image shows two simple examples: a filled
circle (radius 30 pixels, color magenta), and a non-filled rotated rectangle
(color maroon 3-pixel wide strokes).

See @ref{Composable pictures} for details and more examples.

@subheading Shapes and coordinates

A @dfn{shape} is a geometrical figure consisting of
one or more curves and lines.  One kind of shape is a circle;
you can create one with the @code{circle} procedure,
specifying the radius in ``pixels''.

@example
#|kawa:1|# @kbd{(import (kawa pictures))}
#|kawa:2|# @kbd{(circle 30)}
@image{images/fill-circ-1}
@end example
It you print a shape, it will show it as a thin black curve.

A @dfn{point} has two real-numbered parts: the point's x-coordinate,
and its y-coordinate.
The x-coordinate increases as you move right along the page/screen,
while the y-coordinate increases as you move @emph{down}.
(Unlike traditional mathematics, where
the y-coordinate increases as you go up.)
The unit distance is one ``pixel'', which is defined as CSS or HTML.
You can create a point with @code{&P} operator.
For example:
@example
&P[30 20]
@end example
is a point 30 pixels right and 20 pixels down from the origin point.
To create a circle centered on that point do @code{(center 30 &P[30 20])}.

The expression @code{(rectangle &P[10 20] &P[50 40])} creates
a rectangle whose upper left corner is (10,20) and whose
lower right corner is (50,40).

A @dfn{dimension} is a pair, a width and height,
and is written:
@example
&D[@var{width} @var{height}]
@end example
In addition to being used for sizes,
a dimension is also used for relative offsets.
For example, the previous rectangle could also
be written  @code{(rectangle &P[10 20] &D[40 20])}.

You can use @code{line} to create a line.
More generally, if you specify @var{n} points you get a
@dfn{polyline} of @var{n-1} line segments:
@example
#|kawa:3|# @kbd{(line &P[10 20] &P[50 60] &P[90 0])}
@image{images/polyline-1}
@end example
The same line using dimensions for relative offsets:
@example
#|kawa:4|# @kbd{(line &P[10 20] &D[40 20] &D[40 -60])}
@end example

A @dfn{closed shape} is one whose end point is the same as its start point.
The @code{polygon} function creates one using straight line segments
@example
#|kawa:5|# @kbd{(polygon &P[10 20] &P[50 60] &P[90 0])}
@image{images/polygon-1}
@end example

@subheading Colors and filling

You can override the default color (black) using the
@code{with-paint} procedure, which takes a color and a picture
to produce a new picture:
@example
#|kawa:6|# @kbd{(with-paint 'red (circle 32))}
@end example

The first argument can be either one of the standard CSS/HTML5 color
names (such as @code{'red} or @code{'medium-slate-blue}),
or an integer representing an sRGB color, usually written
as a hex literal in the form @code{#xRRGGBB}:
@example
#|kawa:7|# @kbd{(with-paint #x0808FF (circle 32))}
@end example

The name @code{with-paint} is because the first argument
can be not just a color, but a general ``paint'', such as
a gradient or a background image.  However, we won't go into that.

If the shape is closed, you can ``fill'' its inside:
@example
(fill (circle 32))
@end example

You can change the color using @code{with-paint}:
@example
(with-paint 'goldenrod (fill (circle 32)))
@end example
or as an extra argument to @code{fill}:
@example
(fill 'goldenrod (circle 32))
@end example

draw TODO

@subheading Images
An image is a picture represented as a rectangular grid of color values.
It may be a photograph from a camera, or be created by a painting
program like Photoshop or gimp.
You can use @code{image-read} to read an image from a file,
typically a @code{.png} or @code{.jpg} file.

@example
#|kawa:10|# @kbd{(define img1 (image-read "http://pics.bothner.com/2013/Cats/06t.jpg"))}
#|kawa:11|# @kbd{img1}
@image{images/image-cat-1a}
@end example

@subheading Transforms TODO

@example
#|kawa:12|# @kbd{(scale 0.6 (rotate 30 img1))}
@image{images/image-cat-1b}
@end example

@subheading Combining and adjusting pictures TODO

@subheading Using and combining pictures TODO

@node Tutorial - Sequences
@section Lists and sequences

A @dfn{sequence} is a generalized array or list:
Zero or more values treated as a compound value.
Sequences have certain common operations, including indexing and iteration.
(@i{Technical note:} Sequences generally implement the @code{java.util.List}
interface, but Kawa will also treat strings and native
Java arrays as sequences.)

@subheading Lists

In traditional Lisp-family languages, the @dfn{list} is the
most important kind of sequence.
(Don't confuse Java's @code{List} interface with Kawa's use of the
word @i{list}.  They're related, in that a Kawa ``list'' implements
the @code{List} interface, so any @i{list} is also @code{List},
but not vice versa.)

A list is implemented as a chain of linked @dfn{pairs}.
You can create a constant list by quoting a parenthesized list:
@example
'(3 4 (10 20 30) "a string")
@end example

See @ref{Lists} for details and operations.

@subheading Vectors

A @dfn{vector} is a sequence that is implemented by storing the elements
side-by-side in memory.
A vector uses less space than a list of the same length,
and is generally more efficient than a list.

To create a vector you can use a bracketed list:
@example
(! vec1 ['A 'B 'C 'D 'E 'F])
@end example
This creates a vector of 6 symbols and binds it to @code{vec1}.
To select an element you can use the traditional
@code{vector-ref} procedure:
@example
(vector-ref vec1 3) @result{} 'D
@end example
Alternatively, in Kawa you can use function-call notation:
@example
(vec1 3) @result{} 'D
@end example

You can also create a vector using the traditional @code{vector} constructor:
@example
(! vec2 (vector 'A 'B 'C 'D 'E 'F))
@end example
There is one important difference between @code{vec1} and @code{vec2}:
You can modify @code{vec2} by changing some or all of its elements.
You can't do that for @code{vec1}.
(We say that @code{vec1} is an @dfn{immutable} or @dfn{constant} vector,
while  @code{vec1} is a @dfn{mutable} or @dfn{modifiable} vector.)
To change an element use either the traditional @code{vector-set!}
procedure, or function-call notation:
@example
(vector-set! vec2 2 'Y)
(set! (vec2 4) 'Z)
vec2 @result{} ['A 'B 'Y 'D 'Z 'F]
(vector-set! vec1 2 'Y) @result{} @i{throws exception}
@end example

See @ref{Vectors} for details and operations.

@subheading Java arrays and primitive vectors

See @ref{Array operations, Using Java arrays} for examples.

@subheading Indexing of general sequences

You can use function-call notation to index a generalized sequence,
whether it is a list, vector, any @code{java.util.List},
native Java array, or string:
@example
((list 'A 'B 'C 'D) 2)  @result{} 'C
("abcdef" 3)  @result{}  @result{}
(! farr (float[] 1.5 3 4.5))  ;; native Java array
(farr 2) @result{} 4.5
@end example

Note that indexing a list with an index @var{i} will be slow, since it
has to step through the list @var{i} times.  (So don't do that!)

@subheading Ranges

A @dfn{range} is a sequence of numbers in order,
spaced uniformly apart.  Usually, these are (exact) integers
that increase by one.  The usual notation is:
@example
[@var{start} <: @var{end}]
@end example
This is the sequence of integers starting with the integer @var{start}
(inclusive) and ending with the integer @var{end} (exclusive).
For example @code{[3 <: 7]} is the sequence @code{[3 4 5 6]}.

The @samp{<:} is a keyword; the @code{<} is a mnemonic for the
set of integers that are @code{<} the end value 6.
You can also use @code{<=:} if you want to include the upper bound:
@code{[4 <=: 8]} is @code{[4 5 6 7 8]}.

You can use @code{>=:} or @code{>:} for a decreasing range.
@code{[5 >=: 1]} or @code{[5 >: 0]} both evaluate to @code{[5 4 3 2 1]}.
You can also specifify a step value: @code{[1 by: 2 <=: 9]},
which evaluates to @code{[1 3 5 7 9]}.
(@ref{Ranges,Details here}.)

@subheading Using vector and ranges indexes

If an index is a sequence of integers,
the result is a new sequence (of the same type)
selecting only the elements matching the index values.
For example:
@example
#|kawa:2|# @kbd{(vec1 [3 5 2])}
#(D F C)
@end example
In general, @code{((V1 V2) I)} is @code{(V1 (V2 I))}.

You can use a range to create a slice - a contiguous subset of a list.
@example
#|kawa:3|# @kbd{(vec1 [2 <: 6])}
#(C D E F)
@end example

A range is different from a vector integer in that you can use
a range as the index in the LHS of a set!:

@example
#|kawa:4|# @kbd{(set! (vec1 [2 <: 4]) #(a b c d e))}
#|kawa:5|# @kbd{vec1}
#(A B a b c d e E F)
@end example

Notice how the number of replaced elements can be different
then the number of elements in the replacement value.
I.e. you can do insertion and deletion this way.

@example
#|kawa:7|# @kbd{(! str1 (string-copy "ABCDEF"))}
#|kawa:8|# @kbd{(set! (str1 [2 <: 5]) "98")}
AB98F
@end example

@node Tutorial - Objects
@section Creating and using objects

An @dfn{object} is a value that has the following features:
@itemize
@item
class - each object is an instance of a specific class,
making it part of the class hierarchy, which is an important
aspect of the type system;
@item
properties - various fields and methods, depending on the class;
@item
identity - it is distinct from all other objects,
even if all the properties are the same.
@end itemize

We later discuss @ref{Tutorial - Classes,how to write a new class}.
Here we assume you're using an existing class, which
could be written in Java or Scheme.

@subheading Creating a new object

To create a new object of class @code{T} you call @code{T} as if it
were a function, passing it the various constructor arguments:
@example
(java.io.File "src" "build.xml")
@end example

If there are keyword arguments they are used to initialize
the corresponding named properties:
@example
(! button1 (javax.swing.JButton text: "Do it!" tool-tip-text:  "do it"))
@end example
This create a new @code{JButton} object (using @code{JButton}'s
default constructor), and sets the @code{text} and @code{tool-tip-text}
properties (by calling @code{JButton}'s @code{setText}
and @code{setToolTipText} methods).
If there are constructor arguments, they must come before the keywords.

For objects that have components or elements, you
can list these at the end.  For example:
@example
(java.util.ArrayList 11 22 33)
@end example
This creates a fresh @code{java.util.ArrayList} (using the
default constructor), and then calls the @code{add} method 3 times.

If you prefer you can use the @code{make} procedure,
but that only handle simple constructor calls:
@example
(make java.io.File "src" "build.xml")
@end example

See @ref{Allocating objects} for details.

@subheading Calling instance methods

Given an object @var{obj} of a class that has a method @var{meth},
you can call it with argumens @var{v1} ... @var{v2} using @ref{Colon notation}:
@example
(@var{obj}:@var{meth} @var{v1} ... @var{v2})
@end example
For example:
@example
(button1:paintImmediately 10 10 30 20)
@end example

If you prefer, you can use the @code{invoke} procedure,
normally with a quoted method name:
@example
(invoke button1 'paintImmediately 10 10 30 20)
@end example
You need to use @code{invoke} (rather than colon notation)
if @var{obj} is a @code{Class} or a type expression, or its class
implements @code{gnu.mapping.HasNamedParts}.

See @ref{Method operations} for details.

@subheading Accessing properties

If @var{obj} has a field or property named @var{fld} you can also use colon
notation:
@example
@var{obj}:@var{fld}
@end example

You use the same syntax whether @var{fld} is an actual field in the
object, or a @dfn{property} (in the Java Beans sense).  The
latter is implemented using a getter/setter pair:
Methods named @code{get@var{F}} and  @code{set@var{F}}, respectively.
For example:
@example
button1:tool-tip-text
@end example
is equivalent to:
@example
(button1:getToolTipText)
@end example

You can also change a field or property using colon notation:
@example
(set! @var{obj}:@var{fld} @var{value})
@end example
For example:
@example
(set! button1:tool-tip-text "really do it!")
@end example
This is equivalent to:
@example
(button1:setToolTipText "really do it!")
@end example

Instead of colon notation, you can use the @code{field} procedure.

See @ref{Field operations} for details.

@subheading Static fields and methods

Kawa views static properties and methods as
properties and methods of the class itself.
To call a static method use the syntax:
@example
(@var{clas}:@var{meth} @var{v1} ... @var{vn})
@end example
For example:
@example
(java.math.BigDecimal:valueOf 12345 2) @result{} 123.45
@end example

To access a static field do @code{@var{clas}:@var{fld}}.  For example:
@example
java.awt.Color:RED
@end example

You can also use the @code{static-field} and @code{invoke-static} procedures.

@node Tutorial - Types
@section Types and declarations

A @dfn{type} is a named value for a set
of objects with related properties.
For example, @code{vector} is the type for standard Scheme vectors.
You can use a type to specify that a variable can only have
values of the specified type:

@example
#|kawa:5|# @kbd{(define v ::vector #(3 4 5))}
#|kawa:6|# @kbd{v}
#(3 4 5)
#|kawa:7|# @kbd{(set! v 12)}
/dev/stdin:7:1: warning - cannot convert literal (of type gnu.math.IntNum) to vector
Value (12) for variable 'v' has wrong type (gnu.math.IntNum) (gnu.math.IntNum cannot be cast to gnu.lists.FVector)
	at atInteractiveLevel$7.run(stdin:7)
	at gnu.expr.ModuleExp.evalModule(ModuleExp.java:302)
	at kawa.Shell.run(Shell.java:275)
	at kawa.Shell.run(Shell.java:186)
	at kawa.Shell.run(Shell.java:167)
	at kawa.repl.main(repl.java:870)
Caused by: java.lang.ClassCastException: gnu.math.IntNum cannot be cast to gnu.lists.FVector
	... 6 more
@end example

Using a type specification catches errors, and makes your programs
more readable.  It can also allow the Kawa compiler to generate code
that runs faster.

You can use a type to check that a value is an instance of the type,
using either the @code{instance?} function:

@example
(instance? #(3 4 5) vector) @result{} #t
(instance? '(3 4 5) vector) @result{} #f
@end example

As a convenience, you can use a type-name followed by a ``@code{?}'':
@example
(@var{type}? @var{val}) == (instance? @var{val} @var{type})
@end example

You can ``call'' a type as if it were a function,
which constructs a new instance of the type.
The following example shows how to construct a normal Scheme vector,
and a Java array of ints:

@example
|kawa:1|# (vector )
#()
#|kawa:2|# (instance? (vector ) vector)
#t
#|kawa:3|# (define x (int[] 1 2 3))
#|kawa:4|# x
[1 2 3]
#|kawa:5|# (instance? x int[])
#t
@end example

A fully-qualified Java class is a type name.
So are the names of Java primitive types.
So are Java array types, as shown above.

e.g. a JFrame is constructed by using its class name as a function:

@example
#|kawa:6|# (javax.swing.JFrame )
javax.swing.JFrame[frame0,0,25,0x0,invalid,hidden,layout=java.awt.BorderLayout,
title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,
rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,
layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,
flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
@end example

A type is a true run-time value:

@example
(define mytypes (list vector list string))
(instance? #(3 4 5) (car mytypes) @result{} #t
@end example

The @code{define-alias} form is useful for defining shorter names
for types, like a generalization of Java's @code{import} statement:

@example
(define-alias jframe javax.swing.JFrame)
@end example

@node Tutorial - Exceptions and errors
@section Exceptions and errors

Kawa supports the exception framework and forms
from R6RS and R7RS.  See @ref{Exceptions} for details.

@subheading Native exception handling

You can also work with native Java exceptions at a low level.

The @code{primitive-throw} procedure throws a @code{Throwable} value.
It is implemented just like Java's @code{throw}.
@example
(primitive-throw (java.lang.IndexOutOfBoundsException "bad index"))
@end example

You can catch an exception with the @code{try-catch} syntax.  For example:
@example
(try-catch
  (do-a-bunch-of-stuff)
  (ex java.lang.Throwable
    (format #f "caught ~a~%~!" ex)
    (exit)))
@end example

A @code{try-finally} does the obvious:
@example
(define (call-with-port port proc)
  (try-finally
   (proc port)
   (close-port port)))
@end example

Both @code{try-catch} and @code{try-finally} are
expression forms that can return values, while the corresponding
Java forms are statements that cannot return values.

@node Tutorial - Classes
@section Classes

See @ref{Defining new classes} for the gory details; no tutorial yet.

@node Tutorial - Other Java features
@section Other Java features

@subheading Import

The @code{import} form can be used to avoid having to write
fully-qualified class names.  For example:
@example
(import (class java.util
               Map
               (HashMap HMap)))
@end example
This defines aliases for two classes in the @code{java.util} package,
one with renaming:
@code{Map} is an alias for @code{java.util.Map},
and @code{HMap} is an alias for @code{java.util.HashMap}.

The @code{class} keyword is needed because the @code{import}
form is also used for Kawa's module system.
See @ref{importing-class-names} and @ref{Importing} for details.

@subheading Synchronized blocks

You can use a @code{synchronized} expression:

@example
(synchronized obj form1 ... formn)
@end example
This waits until it can get an exclusive lock on @var{obj}
and then evaluates @var{form1} through @var{formn}.
Unlike Java, this is an expression and returns the value of @var{formn}.

@subheading Annotations

You can write annotation declarations - see @ref{Annotations} for details.

Kawa does not yet support annotations on types,
or declaring new annotation classes.

@part Reference Documentation

@node Running
@chapter How to start up and run Kawa

The easiest way to start up Kawa is to run the @samp{kawa} program.
This finds your Java interpreter, and sets up @samp{CLASSPATH} correctly.
If you have installed Kawa such that @code{$PREFIX/bin} is in your @code{$PATH},
just do:
@example
kawa
@end example
However, @samp{kawa} only works if you have a Unix-like environment.
On some platforms, @samp{kawa} is a program that uses the GNU
@samp{readline} library to provide input line editing.

To run Kawa manually, you must start a Java Virtual Machine.
How you do this depends on the Java implementation.
For Oracle's JDK, and some other implementations, you must have the
Java evaluator (usually named @code{java}) in your @code{PATH}.
You must also make sure that the @code{kawa/repl.class} file,
the rest of the Kawa packages, and the standard Java
packages can be found by searching CLASSPATH.
@xref{Running Java}.

Then you do:
@example
java kawa.repl
@end example

In either case, you will then get the @samp{#|kawa:1|#} prompt,
which means you are
in the Kawa read-eval-print-loop.  If you type a Scheme
expression, Kawa will evaluate it.  Kawa will then print the
result (if there is a non-"void" result).

@menu
* Options::      Command-line arguments
* Scripts::      Running Command Scripts
* REPL Console:: The REPL (read-eval-print-loop) console
* Exiting::      Exiting Kawa
* Compiling::    Compiling to byte-code
@end menu

@node Options, Scripts, Running, Running
@section Command-line arguments

@cindex options
You can pass various flags to Kawa, for example:
@example
kawa -e '(display (+ 12 4))(newline)'
@end example
or:
@example
java kawa.repl -e '(display (+ 12 4))(newline)'
@end example
Either causes Kawa to print @samp{16}, and then exit.

At startup, Kawa executes an init file from the user's home
directory.
The init file is named @code{.kawarc.scm} on Unix-like systems
(those for which the file separator is @code{'/'}),
and @code{kawarc.scm} on other systems.
This is done before the read-eval-print loop
or before the first @code{-f} or @code{-c} argument.  (It is not run
for a @code{-e} command, to allow you to set options to override
the defaults.)

@subsection Argument processing

Kawa processes the command-line arguments in order.
Options (which either start with @samp{-} or contain a @samp{=})
may ``use up'' one or more command arguments.
Some of the options (@samp{-c}, @samp{-e}, @samp{-f}, @samp{-s},
@samp{-C}, @code{-w}, @samp{--}, @code{--browse-manual})
are @dfn{action options}; others set various properties.

When all the command-line arguments have been ``used up''
and if no action options have been seen,
then Kawa enters an interactive read-eval-print loop.
(If an action option has been seen, we're done.)

If the next command-line argument is not an option
(does not start with @samp{-} nor contains a @samp{=})
then we're done if we've seen an action option (and the
last action option wasn't preceded by @code{--with-arg-count}).
(Presumably any remaining arguments were command-line-arguments
used by the action option.)

Otherwise, the first remaining argument names either a
file that is read and evaluated, or a compiled class.
In the former case, the whole file is read and compiled as a module
before being loaded (unlike the @code{-f} flag which reads and
evaluates the file command by command.)
If the argument is the fully-qualified name of a class,
then the class is loaded, an instance allocated,
and its @code{run} method invoked.  If the class was compiled from
a Kawa Scheme module, then invoking @code{run} has the
effect of evaluating the module body.
The @code{command-line-arguments} vector is set to any remaining
arguments after the file/class name.
(This can be overridden with the @code{--with-arg-count} option.
Command-line processing continues if there are any further arguments.)

@subsection General options

@table @code
@item -e @var{expr}
Kawa evaluates @var{expr}, which contains one or more Scheme expressions.
Does not cause the @code{~/.kawarc.scm} init file to be run.
@item -c @var{expr}
Same as @samp{-e @var{expr}}, except that it
does cause the @code{~/.kawarc.scm} init file to be run.
@item -f @var{filename-or-url}
Kawa reads and evaluates expressions from the file named
by @var{filename-or-url}.  If the latter is @samp{-},
standard input is read (with no prompting).  Otherwise,
it is equivalent to evaluating @samp{(load "@var{filename-or-url}")}.
The @var{filename-or-url} is interpreted as a URL
if it is absolute - it starts with a "URI scheme" like @code{http:}.
@item -s
@itemx --
The remaining arguments (if any) are passed to @samp{command-line-arguments}
and (the @code{cdr} of) @code{(command-line}),
and an interactive read-eval-print loop is started.
This uses the same "console" as where you started up Kawa;
use @samp{-w} to get a new window.
@item --script @var{filename-or-url}
@itemx --script@var{N} @var{filename-or-url}
The global variable @samp{command-line-arguments} is set to the remaining
arguments (if any).
Kawa reads and evaluates expressions from the file named
by @var{filename-or-url}.
If @code{script} is followed by an integer @var{N},
then @var{N} lines are skipped first.

Skipping some initial lines is useful if you want to have a non-Kawa
preamble before the actual Kawa code.
One use for this is for Kawa shell scripts (@pxref{Scripts}).

@item -w
@itemx -w@var{sub-option}
Creates a new top-level window, and runs an interactive read-eval-print
in the new window.  See @ref{New-Window}.
Same as @code{-e (scheme-window #t)}.
You can specify multiple @samp{-w} options, and also use @samp{-s}.
@item --help
Prints out some help.
@item --version
Prints out the Kawa version number, and then exits.

If Kawa was built with a @code{.git} repository present,
also prints the result of @code{git describe}.
@anchor{browse-manual-option}
@item --browse-manual
@itemx --browse-manual=@var{command}
Browse a local copy of the documentation (this manual).

This creates a mini web-server that reads
from @code{doc/kawa-manual.epub}, which is
included in the binary distributions, but not built by default from source.

If no @var{command} is specified, creates a new window or tab
in your default web browser.
If @var{command} is a string containing @code{%U},
then Kawa replaces @code{%U} with a URL that references itself,
and then executes the resulting command.
If @var{command} does not contain @code{%U}, then
@var{command} becomes @var{command}@code{" %U"}.
For example to use the Firefox browser to browse the manual do either of:
@example
kawa --browse-manual=firefox
kawa --browse-manual="firefox %U"
@end example

@item --server @var{portnum}
Start a server listening from connections on the specified @var{portnum}.
Each connection using the Telnet protocol causes a new read-eval-print-loop
to start.  This option allows you to connect using any
Telnet client program to a remote "Kawa server".
@item --with-arg-count=@var{argc}
This option is used before an action option (such as @code{-f}).
The @var{argc} arguments after the action become the
value of the @code{command-line-arguments} during the action.
When the action is finished, command-line-processing resumes
after skipping the @var{argc} arguments.

For example:
@example
$ kawa -f a.scm -f b.scm x y
@end example
When evaluating @code{a.scm} the @code{command-line-arguments}
by default is @emph{all} the remaining arguments: @code{["-f" "b.scm" "x" "y"]}.
Then @code{b.scm} is evaluated with @code{command-line-arguments}
set to @code{["x" "y"]}

@example
$ kawa --with-arg-count=0 -f a.scm -f b.scm x y
@end example
In this case @code{a.scm} is evaluated with @code{command-line-arguments}
set to the empty vector @code{[]}, and then @code{b.scm} is evaluated with @code{command-line-arguments}
set to @code{["x" "y"]}

@example
$ kawa --with-arg-count=4 -f a.scm -f b.scm x y
@end example
In this case @code{a.scm} is evaluated with @code{command-line-arguments}
set to @code{["-f" "b.scm" "x" "y"]}. Since command-line processing
skips the arguments specified by @code{--with-arg-count=4},
in this case @code{b.scm} is not evaluated.
@end table

@subsection Options for language selection

@table @code
@item --scheme
Set the default language to Scheme.
(This is the default unless you select another language,
or you name a file with a known extension on the command-line.)
@item --r5rs
@itemx --r6rs
@itemx --r7rs
Provide better compatibility with the specified Scheme standards.
(This is a work-in-progress.)
For example @code{--r6rs} aims to disable Kawa extensions
that conflict with R6RS.  It does not aim to disable all extensions,
only incompatible extensions.
These extensions disable the colon operator and keyword literals,
as well as the use of initial @samp{@@} as a splicing operator.
The ``@code{l}'' exponent suffix of a number literal creates a
floating-point double, rather than a @code{BigInteger}.
Selecting @code{--r5rs} makes symbols by default
case-insensitive.
@item --elisp
@itemx --emacs
@itemx --emacs-lisp
Set the default language to Emacs Lisp.
(The implementation is quite incomplete.)
@item --lisp
@itemx --clisp
@itemx --clisp
@itemx --commonlisp
@itemx --common-lisp
Set the default language to CommonLisp.
(The implementation is @emph{very} incomplete.)
@item --krl
Set the default language to KRL.  See @ref{KRL}.
@item --brl
Set the default language to KRL, in BRL-compatibility mode.  See @ref{KRL}.
@item --xquery
Set the default language to the draft XML Query language.
See the @uref{http://www.gnu.org/software/qexo/,Kawa-XQuery page}
for more information.
@item --xslt
Set the default language to XSLT (XML Stylesheet Language Transformations).
(The implementation is @emph{very} incomplete.)
See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
for more information.
@item --pedantic
Try to follow the approprate language specification to the letter,
even in corner cases, and even if it means giving up some
Kawa convenience features.  This flag so far only affects
the XQuery parser, but that will hopefully change.
@end table

@subsection Options for warnings and errors

@table @code
@cindex @code{--warn-@var{whatever}}
@cindex @code{--no-warn-@var{whatever}}
@pindex @code{warn-undefined-variable}
@item --warn-undefined-variable
Emit a warning if the code references a variable which is neither in
lexical scope nor in the compile-time dynamic (global) environment.
This is useful for catching typos.
(A @code{define-variable} form can be used to silence warnings.
It declares to the compiler that a variable is to be resolved dynamically.)
This defaults to on;
to turn it off use the @code{--no-warn-undefined-variable} flag.
@pindex warn-unknown-member
@item --warn-unknown-member
Emit a warning if the code references a named member (field or method)
for which there is no match in the compile-time type of the receiver.
This defaults to on;
to turn it off use the @code{--no-warn-unknown-member} flag.
@pindex warn-invoke-unknown-method
@item --warn-invoke-unknown-method
Emit a warning if the @code{invoke} function calls a named method
for which there is no matching method in the compile-time type of the receiver.
This defaults to the value of @code{--warn-unknown-member},
to turn it off use the @code{--no-warn-invoke-unknown-method} flag.
@pindex warn-unused
@item --warn-unused
Emit a warning if a variable is unused or code never executed. This defaults
to on; to turn it off use the @code{--no-warn-unused} flag.
@cindex warn-unreachable
@item --warn-unreachable
Emit a warning if the code can never be executed. This defaults to on;
to turn it off use the @code{--no-warn-unreachable} flag.
@cindex warn-void-used
@item --warn-void-used
Emit a warning if an expression depends on an expression
that is void (always has zero values), including call to @code{void}
functions and method.  Also warn if an expression depends on a
conditional (@code{if}) that has no ``else'' clause.
Examples include using the value of @code{set-car!} as
an argument to a function, or to initialize a variable.
This defaults to on;
to turn it off use the @code{--no-warn-void-used} flag.
@pindex warn-as-error
@item --warn-as-error
Treat a compilation warning as if it were an error and halt compilation.
@end table

An option can be followed by a value, as
in @code{--warn-invoke-unknown-method=no}.
For boolean options, the values @code{yes}, @code{true}, @code{on}, or @code{1}
enable the option, while @code{no}, @code{false}, @code{off},
or @code{0} disable it.
You can also negate an option by prefixing it with @code{no-}:
The option @code{--no-warn-unknown-member}
is the same as @code{--warn-unknown-member=no}.

These options can also be used in the module source, using
@code{module-compile-options} or @code{with-compile-options}.
(In that case they override the options on the command line.)

@subsection Options for setting variables

@table @code
@item @var{name}=@var{value}
Set the global variable with the specified @var{name} to the given @var{value}.
The type of the @var{value} is currently unspecified; the plan is for it
to be like XQuery's @dfn{untyped atomic} which can be coerced as needed.
@item @{@var{namespace-uri}@}@var{local-name}=@var{value}
Set the global variable with the specified namespace uri and
namespace-local name to the given value.
@end table

These options are processed when invoking the @code{kawa}
application (i.e. the @code{kawa.repl} application).
If you want a Kawa application compiled with @code{--main}
to process these these assignments, call the
@code{process-command-line-assignments} utility function.

@table @code
@item -D@var{variable-name}=@var{variable-value}
Sets the JVM property @var{variable-name} to @var{variable-value},
using the @code{setProperty} method of @code{java.lang.System}.
@end table

@subsection Options for the REPL console

@table @asis
@item @code{--console}
@itemx @code{--no-console}
Usually Kawa can detect when the standard input port is a ``console''
or ``terminal'', but these are useful for overriding that detection.
The @code{--console} flag is useful when the standard input is a pipe,
but you want to direct Kawa to treat it as an interactive terminal.
The @code{--no-console} flag was useful for older pre-Java-6
implementations that did not have the @code{java.lang.Console} class.
@item @code{console:type=}@var{console-types}
@itemx @code{console:use-jline=}[@code{yes}|@code{no}]
@itemx @code{console:jline-mouse=}[@code{yes}|@code{no}]
See the @ref{REPL Console} section.
@item @code{console:prompt1=@var{prompt1}}
@itemx @code{console:prompt2=@var{prompt2}}
Initialize @ref{input-prompt1,@code{input-promp1} and @code{input-prompt2}}, respectively.
@end table
See also the @code{--output-format} flag.

@subsection Options for controlling output formatting

@cindex @code{--output-format}
@table @code
@item --output-format @var{format}
@itemx --format @var{format}
Change the default output format to that specified by @var{format}.
See @ref{Named output formats} for more information and a list.
@end table

@table @code
@item out:base=@var{integer}
The number base (radix) to use by default when printing rational numbers.
Must be an integer between 2 and 36, and the default is of course 10.
For example the option @code{out:base=16} produces hexadecimal output.
Equivalent to setting the @code{*print-base*} variable.
@item out:radix=no|yes
If true, prints an indicator of the radix used when printing rational numbers.
The default is @code{no}.
Equivalent to setting the @code{*print-radix*} variable.
@item out:doctype-system=@var{system-identifier}
If @code{out:doctype-system} is specified then a @code{DOCTYPE} declaration
is written before writing a top-level XML element, using
the specified @var{system-identifier}.
@item out:doctype-public=@var{public-identifier}
Ignored unless  @code{out:doctype-system} is also specified,
in which case the @var{public-identifier} is written
as the public identifiers of the @code{DOCTYPE} declaration.
@item out:xml-indent=@var{kind}
Controls whether extra line breaks and indentation are added
when printing XML.
If @var{kind} is @code{always} or @code{yes} then newlines and
appropriate indentation are added before and after each element.
If @var{kind} is @code{pretty} then the pretty-printer is used
to only add new lines when an element otherwise won't fit on a single line.
If @var{kind} is @code{no} (the default) then no extra line breaks
or indentation are added.
@item out:line-length=@var{columns}
@itemx out:right-margin=@var{columns}
Specifies the maximum number of number of columns in a line
when the pretty-printer decides where to break a line.
(The two options are equivalent.)
@end table

@subsection Options for compiling and optimizing

@table @code
@item --target @var{version}
The @var{version} can be a JDK or Java specification version:
@code{5}, @code{6}, or @code{7}.
The JDK versions @code{1.5} and @code{1.6} are equivalent to @code{5}
or @code{6}, respectively.
Specify a JVM (classfile) version to target.  This is useful
if (for example) you use Java 6, but want to create @code{.class} files
that can run on Java 5.  In that case specify @code{--target 5}.
@end table

The following options control which calling conventions are used:
@table @code
@item --full-tailcalls
Use a calling convention that supports proper tail recursion.
@item --no-full-tailcalls
Use a calling convention that does not support proper tail recursion.
Self-tail-recursion (i.e. a recursive call to the current function)
is still implemented correctly, assuming that the called function
is known at compile time.
@item --no-inline
Disable inlining of known functions and methods.
The generated code runs slower, but you can more reliably trace procedures.
Normally Kawa will assume that a procedure @code{fn}
declared using a @code{(define (fn args) body)} form is constant,
assuming it isn't modified in the current module.  However, it is
possible some other module might modify the binding of @code{fn}.
You can use the @code{--no-inline} to disable the assumption that @code{fn}
is constant.
@end table

The default is currently @code{--no-full-tailcalls} because
it is usually faster.
It is also closer to the Java call model, so may be better for people
primarily interested in using Kawa for scripting Java systems.

Both calling conventions can co-exist:  Code compiled
with @code{--full-tailcalls} can call code compiled
with @code{--no-full-tailcalls} and vice versa.

These options can also be used in the module source, using
@code{module-compile-options} or @code{with-compile-options}.
(In that case they override the options on the command line.)

The options @samp{-C}, @samp{-d}, @samp{-T}, @samp{-P}, @samp{--main}
@samp{--applet}, and @code{--servlet} are used to compile a Scheme file;
see @ref{Files compilation}.
The options @samp{--module-static}, @code{--module-nonstatic},
@code{--no-module-static}, and @code{--module-static-run}
control how a module is mapped to a Java class; see @ref{static-or-non-modules}.
The option @samp{--connect @var{portnum}} is only used by
the @samp{kawa} front-end program.

@subsection Options for debugging

The following options are useful if you want to debug or understand
how Kawa works.
@table @code
@item --debug-dump-zip
Normally, when Kawa loads a source file, or evaluates a non-trivial expression,
it generates new internal Java classes but does not write them out.  This
option asks it to write out generated classes in a @samp{.zip} archive
whose name has the prefix @samp{kawa-zip-dump-}.
@item --debug-print-expr
Kawa translates source language forms into an internal @code{Expression}
data structure.  This option causes that data structure to be written out
in a readable format to the standard output.
@item --debug-print-final-expr
Similar to the previous option, but prints out the @code{Expression} after
various transformations and optimizations have been done, and just before
code generation.
@item --debug-syntax-pattern-match
Prints logging information to standard error when a @code{syntax-rules}
or @code{syntax-case} pattern matches.
@item --debug-error-prints-stack-trace
Prints a stack trace with any error found during compilation.
@item --debug-warning-prints-stack-trace
Prints a stack trace with any warning found during compilation.
@end table

@subsection Options for web servers

JDK 6 (or later) includes a complete web server library.

@table @code
@item --http-auto-handler @var{context-path} @var{appdir}
Register a web application handler that uses files
in the directory @var{appdir} to handle HTTP (web) requests
containing the given @var{context-path}.  That is it handles
requests that start with @code{http://localhost:@var{port}@var{context-path}}.
(This assumes the @var{context-path} starts with a @code{/}.)
@xref{Self-configuring page scripts}.
@item --http-start @var{port}
Start the web server, listing on the specified @var{port}.
@end table

@subsection Options for the JVM

The @code{kawa} front-end can pass options to the @code{java} launcher,
using @code{-J} or @code{-D} options.
These must be given @emph{before} any other arguments.
For example:
@example
kawa -J-Xms48m -Dkawa.command.name=foo foo.scm
@end example
is equivalent to (ignoring classpath issues):
@example
java -Xms48m -Dkawa.command.name=foo kawa.repl foo.scm
@end example
You can also pass a @code{-D} option (but not a @code{-J} option) after the
class name, in which case it is processed by the Kawa command-line processor
rather than the @code{java} launcher.  The effect is normally the same.

@table @code
@item -J@var{jvm-option}
Passes the @var{jvm-option} to the @code{java} command,
before the class-name (@code{kawa.repl}) and Kawa options.
@item -D@var{variable-name}=@var{variable-value}
Sets the JVM property @var{variable-name} to @var{variable-value}.
Equivalent to @code{-J-D@var{variable-name}=@var{variable-value}}.
@end table

@node Scripts
@section Running Command Scripts

If you write a Kawa application, it is convenient to be able
to execute it directly (from the command line or clicking an icon, say),
without have to explicitly run @code{kawa} or @code{java}.
On Unix-like systems the easiest way to do this is to
write a small shell script that runs your Kawa application.

For modest-sized applications it is convenient if the shell script
and the Kawa code can be in the same file.
Unix-like systems support a mechanism where a @dfn{script} can
specify a program that should execute it.  The convention
is that the first line of the file should start with the two characters
@samp{#!} followed by the absolute path of the program that should
process (interpret) the script.

(Windows has @dfn{batch files}, which are similar.)

This convention works well for script languages that use @samp{#}
to indicate the start of a comment, since the interpreter will
automatically ignore the line specifying the interpreter filename.
Scheme, however, uses @samp{#} as a multi-purpose prefix,
and Kawa specifically uses @samp{#!} as a prefix for
various @ref{Special named constants} such as @code{#!optional}.

Kawa does recognize the three-character sequence @samp{#!/} at the
beginning of a file as special, and ignores it.
Here is an example:
@example
#!/usr/local/bin/kawa
(format #t "The command-line was:~@{ ~w~@}~%" (command-line))
@end example

If you copy this text to a file named @code{/home/me/bin/scm-echo},
set the execute permission, and make sure it is in your @code{PATH},
then you can execute it just by naming it on command line:
@example
$ chmod +x /home/me/bin/scm-echo
$ PATH=/home/me/bin:$PATH
$ scm-env a b
The command-line was: "/home/me/bin/scm-echo" "a" "b"
@end example
The system kernel will automatically execute @code{kawa}, passing it the
filename as an argument.

Note that the full path-name of the @code{kawa} interpreter
must be hard-wired into the script.  This means you may have to edit
the script depending on where Kawa is installed on your system.
Another possible problem is that the interpreter must be an
actual program, not a shell script. Depending on how you configure
and install Kawa, @code{kawa} can be a real program or a script.
You can avoid both problems by the @code{env} program, available on
most modern Unix-like systems:

@example
#!/usr/bin/env kawa
(format #t "The command-line was:~@{ ~w~@}~%" (command-line))
@end example

This works the same way, but assumes @code{kawa} is in the
command @code{PATH}.

@subsection Setting kawa options in the script

If you need to specify extra arguments to @code{kawa},
you can run arbitrary shell command inside Scheme block comments.
Here is an example:
@example
#!/bin/sh
#|
exec kawa out:base=16 out:radix=yes "$0" "$*"
|#
(format #t "The command-line is:~@{ ~w~@}.~%" (command-line))
(display "It has ")
(display (apply + (map string-length (command-line))))
(display " characters.")
(newline)
@end example

The trick is to hide the shell code from Kawa inside
a @code{#|...|#} block-comment.  The start of the block comment
is a line starting with a @code{#}, so it is treated as a comment by the shell.
You can then invoke @code{kawa} (or @code{java} directly)
as you prefer, setting up class-path and jars as needed,
and passing whatever arguments you want.
(The shell replaces the @code{"$0"} by the name of the script, and
replaces the @code{"$@@"} by the remaining arguments passed to the script.)
You need to make sure the shell finishes before it reaches
the end of the block comment or the Scheme code, which would confuse it.
The example uses @code{exec}, which tells the shell to @emph{replace}
itself by @var{kawa};
an alternative is to use the shell @code{exit} command.

If you copy the above file to @code{/tmp/sch-echo} and make
that file executable, you can run it directly:
@example
$ /tmp/scm-echo "a b" "c d"
The command-line is: "/tmp/scm-echo" "a b c d".
It has #x14 characters.
@end example

When the Kawa reader sees the initial @code{#/} it sets
the command name to the file name, so it can be used by a future
call to @code{(command-name)}.  If you want to override
this you can use the @code{-Dkawa.command.name=@var{name}} option.

Using comments this way has the advantage that you have the
option of running the script ``manually'' if you prefer:
@example
$ kawa /tmp/scm-echo out:base=8 "x y"
The command-line is: "/tmp/scm-echo" "out:base=8" "x y".
It has 26 characters.
@end example

@subsection Other ways to pass options using meta-arg or --script

An argument consisting of just a @code{\} (backslash)
causes Kawa to read the @emph{second} line looking for
options.  (Quotes and backslashes work like in the shell.)
These replace the backslash in the command line.

This is a less verbose mechanism, but it requires an
absolute path to @code{kawa}, due to shell limitations.

@example
#!/usr/bin/kawa \
  --scheme --full-tailcalls
(format #t "The command-line is:~@{ ~w~@}.~%" (command-line))
@end example

In this case the effective command line received by Kawa will
be @code{--scheme}, @code{--full-tailcalls}, followed by the
script filename, followed by other arguments specified when
running the script.

The backslash used this way originated in
@uref{http://www.scsh.net, scsh} where it is called the @dfn{meta-arg}.
(Unlike scsh, Kawa's @code{#!} is not a block comment,
but a rest-of-line, though the backslash causes the following line
to also be skipped.) 

An alternative method is to use the @code{--script2} option,
which tells Kawa to execute the script after ignoring
the initial two lines.  For example:

@example
#!/bin/sh
exec kawa --commonlisp out:base=16 --script2 "$0" "$@@"
(setq xx 20) (display xx) (newline)
@end example

This is slightly more compact than using block-comments as shown earlier,
but it has the disadvantage that you can't explicitly
use @code{kawa} or @code{java} to run the script unless you
make sure to pass it the @code{--script2} option.

@subsection Scripts for compiled code
If you compile your Kawa application to class files (or better:
a @code{jar} file), you probably still want to write a small
shell script to set things up.  Here is one method:

@example
#!/bin/sh
export CLASSPATH=/my/path
exec kawa -Dkawa.command.name="$0" foo "$@@"
@end example

Using the @code{kawa} front-end is a convenience, since it automatically
sets up the paths for the Kawa classes, and (if enabled) it
provides readline support for the default input port.

Setting the @code{kawa.command.name} property to @code{"$0"}
(the filename used to invoke the script) enables
@code{(command-line}) to use the script name as the command name.

You can invoke @code{java} directly, which is necessary when
running a @code{jar} file:

@example
#!/bin/sh
exec java -cp /path/to/kawa -Dkawa.command.name="$0" foo.jar "$@@"
@end example

@ignore
(It is in principle possible to compile a Kawa application to
``a native executable'', for example using @code{gcj}.
However, this is no longer supported, as gcj is no longer
being actively developed.)
@end ignore

@node REPL Console
@section The REPL (read-eval-print-loop) console

The read-eval-print-loop (REPL) console is a convenient way to
do simple programming, test out things, and experiment.
As the name implies, the REPL repeatedly (in a loop)
prints out a prompt, reads an input command, evaluates it, then prints the result.

The REPL is started when you invoke the @code{kawa} command
with no arguments.  For example:

@example
$ @kbd{kawa}
#|kawa:1|# @kbd{(define pi (* 2 (asin 1)))}
#|kawa:2|# @kbd{(list pi (sqrt pi))}
(3.141592653589793 1.7724538509055159)
#|kawa:3|# @kbd{}
@end example

The colors and styles used for the prompt and the user input
depend on user preference and the capabilities of the console device.
(If you read this on a color screen you should see pale green for the
prompt and pale yellow for the user input;
this matches the defaults for the DomTerm console.)

You can @ref{Prompts,change the prompt string} if you want.
The default format depends on the (programming) language used;
the one shown above is used for Scheme.
It has the form of a comment, which can be convenient for copying
and pasting lines.

You can @ref{Named output formats,change the output formatting} with
the @code{--output-format} command-line option.

The basic console has few frills, but should work in any enviroment
where you have a console or terminal.  It has no dependencies,
except the kawa @code{.jar} file (and Java):
@example
$ @kbd{java kawa-@value{VERSION}.jar}
#|kawa:2|# @kbd{}
@end example

On rare occason you may need to specify the @code{--console} flag.

@subsection Input line editing and history

When typing a command in a console it is helpful to go back
and correct mistakes, repeat and edit previous commands, and so on.
How well you can do this varies a lot depending on which tools you use.
Kawa delegates input editing to an external tool.
The recommended and default input-editing tool is
the @uref{https://github.com/jline/jline3,JLine3 library},
which is bundled with the Kawa binary distribution.

JLine3 handles the normal editing comands, including arrow keys
for moving around in the input, and deleting with backspace or delete.
In general, JLine3 uses the same keybindings as GNU readline,
which are based on Emacs key-bindings.

You can use the up-arrow to move to previous commands in the
input history and down-arrow to go forwards.
Control-R (``reverse search'' searches backwards in the history
for a previous command that contains the search string.

Multi-line commands are treated as a unit by JLine3:
If Kawa determines that input is ``incomplete'' it will
ask for continuation lines - and you can go back and edit previous
lines in the same command.
You can explicitly create a multi-line command with Escape-Space.
An entry in the command history may be multiple lines.

Tab-completion works for Kawa-Scheme identifiers: If you type TAB
after an identifier, Kawa will present a list of possible completions.

There are multiple alternatives to using JLine3.
You can use GNU readline (if you configured with @code{--enable-kawa-frontend}).
You can use a front-end program like @code{rlfe} or @code{fep}.
You can use Emacs shell or scheme mode.
You can also use DomTerm in line-edit mode, where the browser handles
the editing.

@table @asis
@item @code{console:use-jline=}[@code{yes}|@code{no}]
Disable (with @code{no}) or enable (with @code{yes}, which is the default)
input line editing with JLine.
@item @code{console:console:jline-mouse=}[@code{yes}|@code{no}]
Enable (with @code{yes}) mouse click reporting from
most xterm-like terminals to JLine, which means you
can move the input cursor with the mouse.
This is disabled by default because it conflicts with other useful mouse
actions (text selection using drag; middle-button paste; right-button
context menu; and wheel mouse scrolling).
If you enable mouse-reporting, on most terminals you can get the
standard behavior when pressing the shift key.  E.g. to enable selection,
drag with the shift key pressed.  (However, mouse-wheel scrolling
may not work even with shift pressed.)
@end table

@anchor{New-Window}
@subsection Running a Command Interpreter in a new Window

Instead of using an existing terminal window for Kawa's REPL console,
you can request a new window.
The command-line options @code{-w} creates a new window.
Kawa also creates a new window when it needs to create a REPL
(for example if invoked with no options) and it is not running
in a console.

You have a number of options for how the window appears and
what it supports, controlled by text following @code{-w}.
All except @code{-wswing} (and @code{-wconsole}) use DomTerm,
so they depend on some kind of web browser technology.
All except @code{-wswing} by default use  JLine3 input editing,
if available.

@table @asis
@item @code{-w}
Pick the default/preferred console implementation.
You can specify your preference with the @code{console:type=} option,
which is followed by one of the options below (without the @code{"-w"} prefix),
It can also be list of options separated by semi-colons, in which
case they are tried in order.

The current default (it may change) is as if you specified:
@example
console:type="google-chrome;browser;javafx;swing;console"
@end example

@item @code{-wbrowser}
Creates a Kawa window or tab in your preferred desktop browser.
Kawa starts a builtin HTTP and WebSocket server to communicate with the browser.
@item @code{-wbrowser=@var{command}}
Uses @var{command} to display the Kawa REPL.
The @var{command} should include the pattern @code{%U}, which Kawa replaces
with a URL that it listens to.
(Alternatively, it can use the pattern @code{%W}, which Kawa replaces
with the port number of its WebSocket server.  However, this feature may be removed.)
If the is no @code{%} in the @var{command}, Kawa add @code{" %U"}.
Thus @code{-wbrowser=firefox} is the same as @code{-wbrowser="firefox %U"}.
@item @code{-wgoogle-chrome}
Creates a new Google Chrome window in ``app mode'' - i.e. with no location or menu bar.
This is the same as @code{-wbrowser="google-chrome --app=%U"}.
@item @code{-wqtdomterm}
Uses the @code{QtDomTerm} application.
Same as @code{-wbrowser="qtdomterm --connect localhost:%W"}, where @code{%W}
is the port of the WebSocke server that Kawa starts.
@item @code{-wjavafx}
Creates a new window using JavaFX WebView, which runs in the same JVM as Kawa.
While this doesn't currently have much in the way of Kawa-specific menus
or other features, it has the most potential for adding them in the future.
However, it does require JavaFX, which is not always available,
and which does not see a lot of love from Oracle. (It uses an old version of WebKit.)
@item @code{-wswing}
Create a console using the Swing toolkit.
This is the old implementation of @code{-w}.
It is deprecated because it only supports the builtin Swing line editing.
(I.e. neither DomTerm or JLine3 features are available, though
``printing'' @ref{Composable pictures,pictures} does work.)
@item @code{-wserve}
@itemx @code{-wserve=}@var{port}
Starts up an HTTP server (along with a WebSocket server),
but does not automatically create any browser windows.
Instead you can use any modern browser to load @code{http://localhost:@var{port}/}.
If @var{port} is not specified, the systems selects it (and prints it out).
@item @code{-wconsole}
Same as @code{"--"} - i.e. it uses the existing console.
@item @code{console:type=}@var{preference-list}
Specify the behavior of plain @code{-w}.
@end table

@anchor{Using DomTerm}
@subsection Using DomTerm

@uref{http://domterm.org,DomTerm} is a family of terminal emulators that use
the DomTerm JavaScript library.

You can either have Kawa start DomTerm:
@example
$ kawa @var{options} -w
@end example
or start a DomTerm terminal emulator and have it start Kawa:
@example
$ domterm kawa @var{options} --
@end example
(You can also start a shell in a @code{domterm} window, and then start @code{kawa}.)

Either approach works and both give you the benefits of DomTerm:
@itemize
@item
A xterm/ansi-compatible terminal emulator,
which means you can use (for example) JLine3 for input editing.
@item
You can ``print'' images, @ref{Composable pictures,pictures}, or HTML elements.
@item
Pretty-printing is handled by the terminal,
which means line-breaking is re-computed when window width changes.
@item
Hide/show buttons allow you to temporarily hide/unhide the output from a specific command.
@item
You can save a session as an HTML file,
which can be viewed later.
(Still with dynamic line-breaking and pretty-printing, as well as working hide/show buttons.)
The file is actually XHTML, so it can be processed with XML-reading tools.
@item
Distinct styles for prompts, input, error output and regular output,
which can be customized with CSS.
@end itemize

For now it is recommended to use both DomTerm and JLine3.

@deffn Procedure domterm-load-stylesheet stylesheet [name]
The string @var{stylesheet} should be a literal CSS stylesheet
which is downloaded into the current DomTerm console.
The new stylesheet is given the attribute @code{name=@var{name}},
where @var{name} defaults to @code{"Kawa"}.  If there is an
existing stylesheey whose @code{name} attribute is @var{name},
it is replaced.
In this example we change the background color to light gray:
@example
(domterm-load-stylesheet "div.domterm @{ background-color: lightgray@}")
@end example
@end deffn

@node Exiting
@section Exiting Kawa
Kawa normally keeps running as long as there is an active
read-eval-print loop still awaiting input or there is an unfinished
other computation (such as requested by a @samp{-e} or @samp{-f} option).

To close a read-eval-print-loop, you can type the special
literal @code{#!eof} at top level.  This is recognized as end-of-file.
Typing an end-of-file character (normally ctrl-D under Unix)
should also work, but that depends on your operating system
and terminal interface.

If the read-eval-print-loop
is in a new window, you can select @samp{Close} from the @samp{File} menu.

To exit the entire Kawa session, call the
@ref{Exiting the current process,@code{exit} procedure} (with 0 or 1 integer arguments).

@node Compiling, , , Running
@section Compiling to byte-code

All Scheme functions and source files are invisibly compiled
into internal Java byte-codes.
(A traditional interpreter is used for macro-expansion.
Kawa used to also interpret ``simple'' expressions in interactive mode,
but always compiling makes things more consistent, and allows for
better stack traces on errors.)

To save speed when loading large Scheme source files, you probably
want to pre-compile them and save them on your local disk.
There are two ways to do this.

You can compile a Scheme source file to a single archive file.
You do this using the @code{compile-file} function.
The result is a single file that you can move around and @code{load}
just like the @code{.scm} source file.  You just specify the name
of the archive file to the @code{load} procedure.
Currently, the archive is a "zip" archive and has extension ".zip";
a future release will probably use "Java Archive" (jar) files.
The advantage of compiling to an archive is that it is simple
and transparent.

Alternatively, you can compile a Scheme source file to a
collection of @samp{.class} files.
You then use the standard Java class loading mechanism to load the code.
The compiled class files do have to be installed somewhere
in the @code{CLASSPATH}.

@menu
* Files compilation::           Compiling to a set of .class files
* Archive compilation::         Compiling to an archive file
* Compiling using Ant::
* Application compilation::     Compiling to a standalone application
* Applet compilation::          Compiling to an applet
* Compiling to executable::     Compiling to a native executable
@end menu

@node Files compilation
@subsection Compiling to a set of .class files

Invoking @samp{kawa} (or @samp{java kawa.repl}) with
the @samp{-C} flag will compile
a @samp{.scm} source file into one or more @samp{.class} files:
@example
kawa --main -C myprog.scm
@end example

You run it as follows:
@example
kawa [-d @var{outdirectory}] [-P @var{prefix}] [-T @var{topname}] [--main | --applet | --servlet] -C @var{infile} ...
@end example

Note the @samp{-C} must come last, because @samp{Kawa} processes the
arguments and options in order,

Here:
@table @code
@item -C @var{infile} ...
The Scheme source files we want to compile.
@item -d @var{outdirectory}
The directory under which the resulting @samp{.class} files will be.
The default is the current directory.
@item -P @var{prefix}
A string to prepend to the generated class names.
The default is the empty string.
@item -T @var{topname}
The name of the "top" class - i.e. the one that contains the code
for the top-level expressions and definitions.
The default is generated from the @var{infile} and @var{prefix}.
@item --main
Generate a @code{main} method so that the resulting "top" class can
be used as a stand-alone application. @xref{Application compilation}.
@item --applet
The resulting class inherits from @code{java.applet.Applet},
and can be used as an applet.  @xref{Applet compilation}.
@item --servlet
The resulting class implements @code{javax.servlet.http.HttpServlet},
and can be used as a servlet in a servlet container like Tomcat.
@end table

When you actually want to load the classes, the @var{outdirectory}
must be in your @samp{CLASSPATH}.
You can use the @code{require} syntax or the @code{load} function to load the code,
by specifying the top-level class, either as a file name
(relative to @var{outdirectory}) or as a class name.
E.g. if you did:
@example
kawa -d /usr/local/share/java -P my.lib. -T foo -C foosrc.scm
@end example
you can use either:
@example
(require my.lib.foo)
@end example
or:
@example
(load "my.lib.foo")
@end example
Using @code{require} is preferred as it imports the definitions
from @code{my.lib.foo} into the compile-time environment,
while @code{load} only imports the definitions into the run-time environment.

If you are compiling a Scheme source file (say @samp{foosrc.scm})
that uses macros defined in some other file (say @samp{macs.scm}),
you need to make sure the definitions are visible to the compiler.
One way to do that is with the @samp{-f}:
@example
kawa -f macs.scm -C foosrc.scm
@end example

Many of the options @ref{Options,,described earlier} are
relevant when compiling.  Commonly used options include language selection,
the @code{--warn-xxx} options, and @code{--full-tailcalls}.

@node Archive compilation
@subsection Compiling to an archive file

@deffn Procedure compile-file source-file compiled-archive
Compile the @var{source-file}, producing a @code{.zip} archive
@var{compiled-file}.


For example, to byte-compile a file @samp{foo.scm} do:
@example
(compile-file "foo.scm" "foo")
@end example

This will create @samp{foo.zip}, which contains
byte-compiled JVM @code{.class} files.
You can move this file around, without worrying about class paths.
To load the compiled file, you can later @code{load} the
named file, as in either @code{(load "foo")} or @code{(load "foo.zip")}.
This should have the same effect as
loading @samp{foo.scm}, except you will get the faster byte-compiled versions.
@end deffn

@node Compiling using Ant
@subsection Compiling using Ant
@cindex kawac
Many Java projects use @uref{http://ant.apache.org, Ant}
for building Java projects.  Kawa includes a @code{<kawac>}
Ant task that simplifies compiling Kawa source files to classes.
See the @code{build.xml} in the Kawa source distribution for examples.
See the @uref{ant-kawac.html, @code{kawac} task documentation} for details.

@node Application compilation
@subsection Compiling to a standalone application

A Java application is a Java class with a special method
(whose name is @code{main}).  The application can be invoked directly
by naming it in the Java command.
If you want to generate an application from a Scheme program,
create a Scheme source file with the definitions you need, plus
the top-level actions that you want the application to execute. 

For example, assuming your Scheme file is 
@code{MyProgram.scm}, you  have two ways at your disposal to 
compile this Scheme program to a standalone application:
@enumerate
@item
Compile
in the regular way described in the previous section, but add the
@code{--main} option.
@example
kawa --main -C MyProgram.scm
@end example

The @code{--main} option will compile all Scheme programs
received in arguments to standalone applications.
@item
Compile
in the regular way decribed in the previous section, but add the 
@code{main: #t} module compile option to your module.
@example
;; MyProgram.scm
(module-name <myprogram>)
(module-compile-options main: #t)
@end example

@example
kawa -C MyProgram.scm
@end example

This way you can compile multiple Scheme programs at once, and
still control which one(s) will compile to standalone application(s).
@end enumerate

Both methods will create a @code{MyProgram.class} which you can either
@code{load} (as described in the previous section), or invoke as an application:
@example
java MyProgram [@var{args}]
@end example
Your Scheme program can access the command-line arguments @var{args}
by using the global variable @samp{command-line-arguments},
or the R6RS function @samp{command-line}.

If there is no explicit @code{module-export} in a module compiled
with @code{--main} then no names are exported.  (The default
otherwise is for all names to be exported.)

@node Applet compilation, Compiling to executable, Application compilation, Compiling
@subsection Compiling to an applet
An applet is a Java class that inherits from @code{java.applet.Applet}.
The applet can be downloaded and run in a Java-capable web-browser.
To generate an applet from a Scheme program, write the Scheme
program with appropriate definitions of the functions @samp{init},
@samp{start}, @samp{stop} and @samp{destroy}.  You must declare these
as zero-argument functions with a @code{<void>} return-type.

Here is an example, based on the scribble applet in Flanagan's
"Java Examples in a Nutshell" (O'Reilly, 1997):
@example
(define-private last-x 0)
(define-private last-y 0)

(define (init) :: void
  (let ((applet (this)))
    (applet:addMouseListener
     (object (java.awt.event.MouseAdapter)
	     ((mousePressed e)
	      (set! last-x (e:getX))
	      (set! last-y (e:getY)))))
    (applet:addMouseMotionListener
     (object (java.awt.event.MouseMotionAdapter)
	     ((mouseDragged e)
	      (let ((g (applet:getGraphics))
		    (x (e:getX))
		    (y (e:getY)))
		(g:drawLine last-x last-y x y)
		(set! last-x x)
		(set! last-y y)))))))

(define (start) :: void (format #t "called start.~%~!"))
(define (stop) :: void (format #t "called stop.~%~!"))
(define (destroy) :: void (format #t "called destroy.~%~!"))
@end example

You compile the program with the @samp{--applet} flag in addition to the
normal @samp{-C} flag:
@example
java kawa.repl --applet -C scribble.scm
@end example

You can then create a @samp{.jar} archive containing your applet:
@example
jar cf scribble.jar scribble*.class
@end example

Finally, you create an @samp{.html} page referencing your applet
and its support @code{jar}s:
@example
<html><head><title>Scribble testapp</title></head>
<body><h1>Scribble testapp</h1>
You can scribble here:
<br>
<applet code="scribble.class" archive="scribble.jar, kawa-@value{VERSION}.jar" width=200 height=200>
Sorry, Java is needed.</applet>
</body></html>
@end example

The problem with using Kawa to write applets is that the Kawa @code{.jar}
file is quite big, and may take a while to download over a network connection.
Some possible solutions:

@itemize
@item
Try to strip out of the Kawa @code{.jar} any classes your
applet doesn't need.
@item
Java 2 provides a mechanism to install a @uref{http://java.sun.com/docs/books/tutorial/ext/basics/download.html,
download extension}.
@item
Consider some alternative to applets, such as
@uref{http://java.sun.com/products/javawebstart/,Java Web Start}.
@end itemize

@node Compiling to executable, , Applet compilation, Compiling
@subsection Compiling to a native executable

In the past it was possible to compile a Scheme program to native code using GCJ.
However, using GCJ with Kawa is no longer supported,
as GCJ is no longer being actively maintained.

@ignore
You can compile your Scheme program to native code using GCJ,
as long as you have built Kawa using GCJ.

First, you need to compile the Scheme code to a set of @code{.class} files;
see @ref{Files compilation}.
@example
kawa --main -C myprog.scm
@end example

Then to create an executable @code{myprog} do:
@example
gckawa --main=myprog myprog*.class -o myprog
@end example

The @code{gckawa} is a simple shell script that calls @code{gcj}.
The reason for the wildcard in @code{myprog*.class} is that sometimes
Kawa will generate some helper classes in addition to @code{myprog.class}.
The @code{--main} option tell @code{gcj} which class contains
the @code{main} method it should use.  The @code{-o} option names
the resulting executable program.  The @code{-lkawa} option tells
the linker it should link with the kawa shared library, and
the @code{-L$PREFIX/bin} option tells the linker where it can
find that library.
@end ignore

@node Syntax
@chapter Syntax

@menu
* Syntax notation::
* Lexical and datum syntax::
* Lexical syntax::
* Datum syntax::
* Hash-prefixed forms::
* Primitive expression syntax::
* Colon notation:: Property access using colon notation
* Bodies::
* Syntax and conditional compilation::
* Macros::
* Named quasi-literals::
@end menu

@node Syntax notation, Lexical and datum syntax, , Syntax
@section Notation

The formal syntax for Kawa Scheme is written in an extended @acronym{BNF}.
Non--terminals are written @var{like-this}.  Case is insignificant
for non--terminal names.
Literal text (terminals) are written @stxlit{like this}.

All spaces in the grammar are for legibility.
@c  @meta{Empty} stands for the empty string.

The following extensions to @acronym{BNF} are used to make the
description more concise: @arbno{@meta{thing}} or @meta{thing}@code{...}
both mean zero or more occurrences of @meta{thing},
and @atleastone{@meta{thing}} means at least one @meta{thing}.

Some non-terminal names refer to the Unicode scalar values of the same
name: @meta{character-tabulation} (U+0009), @meta{linefeed} (U+000A),
@meta{carriage-return} (U+000D), @meta{line-tabulation} (U+000B),
@meta{form-feed} (U+000C), @meta{space} (U+0020), @meta{next-line}
(U+0085), @meta{line-separator} (U+2028), and @meta{paragraph-separator}
(U+2029).

@node Lexical and datum syntax, Lexical syntax, Syntax notation, Syntax
@section Lexical and datum syntax

The syntax of Scheme code is organized in three levels:

@enumerate
@item
the @emph{lexical syntax} that describes how a program text is split
into a sequence of lexemes,

@item
the @emph{datum syntax}, formulated in terms of the lexical syntax, that
structures the lexeme sequence as a sequence of @emph{syntactic data},
where a syntactic datum is a recursively structured entity,

@item
the @emph{program syntax} formulated in terms of the datum syntax,
imposing further structure and assigning meaning to syntactic data.
@end enumerate

Syntactic data (also called @emph{external representations}) double as a
notation for objects, and the @func{read} and
@func{write} procedures can be used for reading and writing syntactic data,
converting between their textual representation and the corresponding
objects.  Each syntactic datum represents a corresponding
@emph{datum value}.  A syntactic datum can be used in a program to obtain the
corresponding datum value using @code{quote}.
@c FIXME (@ref{base expressions quotation}).

Scheme source code consists of syntactic data and (non--significant)
comments.  Syntactic data in Scheme source code are called @emph{forms}.
(A form nested inside another form is called a @emph{subform}.)
Consequently, Scheme's syntax has the property that any sequence of
characters that is a form is also a syntactic datum representing some
object.  This can lead to confusion, since it may not be obvious out of
context whether a given sequence of characters is intended to be a
representation of objects or the text of a program.  It is also a source
of power, since it facilitates writing programs such as interpreters or
compilers that treat programs as objects (or vice versa).

A datum value may have several different external representations.  For
example, both @code{#e28.000} and @code{#x1c} are syntactic data
representing the exact integer object 28, and the syntactic data
@code{(8 13)}, @code{( 08 13 )}, @code{(8 . (13 . ()))} all represent a
list containing the exact integer objects 8 and 13.  Syntactic data that
represent equal objects (in the sense of @func{equal?})
are always equivalent as forms of a program.

Because of the close correspondence between syntactic data and datum
values, we sometimes uses the term @emph{datum} for either a
syntactic datum or a datum value when the exact meaning is apparent from
the context.

@c An implementation must not extend the lexical or datum syntax in any
@c way, with one exception: it need not treat the syntax
@c @code{#!<identifier>}, for any <identifier> (@ref{lex syntax
@c identifiers}) that is not @code{r6rs}, as a syntax violation, and it may
@c use specific @code{#!}--prefixed identifiers as flags indicating that
@c subsequent input contains extensions to the standard lexical or datum
@c syntax.  The syntax @code{#!r6rs} may be used to signify that the input
@c afterward is written with the lexical syntax and datum syntax described
@c by this report.  @code{#!r6rs} is otherwise treated as a comment;
@c @ref{lex syntax whitespace and comments}.

@node Lexical syntax, Datum syntax, Lexical and datum syntax, Syntax
@section Lexical syntax

The lexical syntax determines how a character sequence is split into a
sequence of lexemes, omitting non--significant portions such as comments
and whitespace.  The character sequence is assumed to be text according
to the @uref{http://unicode.org/,Unicode standard}.
Some of the lexemes, such as
identifiers, representations of number objects, strings etc., of the
lexical syntax are syntactic data in the datum syntax, and thus
represent objects.  Besides the formal account of the syntax, this
section also describes what datum values are represented by these
syntactic data.

The lexical syntax, in the description of comments, contains a forward
reference to @meta{datum}, which is described as part of the datum
syntax.  Being comments, however, these @meta{datum}s do not play a
significant role in the syntax.

Case is significant except in representations of booleans, number
objects, and in hexadecimal numbers specifying Unicode scalar values.
For example, @code{#x1A} and @code{#X1a} are equivalent.  The identifier
@code{Foo} is, however, distinct from the identifier @code{FOO}.

@subsection Formal account

@noindent
@var{Interlexeme-space} may occur on either side of any lexeme, but not
within a lexeme.

@meta{Identifier}s, @code{.}, @meta{number}s, @meta{character}s, and
@meta{boolean}s, must be terminated by a @meta{delimiter} or by the end
of the input.

@c The following two characters are reserved for future extensions to the
@c language: @code{@{ @}}

@display
@stxdef{lexeme} @stxref{identifier} | @var{boolean} | @stxref{number}
         | @var{character} | @stxref{string}
         | @stxlit{(} |  @stxlit{)} |  @stxlit{[} |  @stxlit{]} |  @stxlit{#(}
         | @stxlit{'} | @stxlit{`} | @stxlit{,} | @stxlit{,@@} | @stxlit{.}
         | @stxlit{#'} |  @stxlit{#`} |  @stxlit{#,} |  @stxlit{#,@@}
@stxdef{delimiter} @stxlit{(} |  @stxlit{)} |  @stxlit{[} | @stxlit{]} | @stxlit{"} | @stxlit{;} | @stxlit{#}
         | @stxref{whitespace}
@end display

((UNFINISHED))

@subsection Line endings

Line endings are significant in Scheme in single--line comments
and within string literals.
In Scheme source code, any of the line endings in @meta{line-ending}
marks the end of a line.  Moreover, the two--character line endings
@meta{carriage-return} @meta{linefeed} and @meta{carriage-return}
@meta{next-line} each count as a single line ending.

In a string literal, a @meta{line-ending} not preceded by a @code{\}
stands for a linefeed character, which is the standard line--ending
character of Scheme.

@subsection Whitespace and comments

@display
@stxdef{intraline-whitespace} @var{space} | @var{character-tabulation}
@stxdef{whitespace}  @stxref{intraline-whitespace}
         | @var{linefeed} | @var{line-tabulation} | @var{form-feed}
         | @var{carriage-return} | @var{next-line}
         | @i{any character whose category is Zs, Zl, or Zp}
@stxdef{line-ending} @var{linefeed} | @var{carriage return}
         | @var{carriage-return} @var{linefeed} | @var{next-line}
         | @var{carriage-return} @var{next-line} | @var{line-separator}
@stxdef{comment}  @stxlit{;} all subsequent characters up to a @var{line-ending}
                or @var{paragraph-separator}
         | @stxref{nested-comment}
         | @stxlit{#;} @stxref{interlexeme-space} @stxref{datum}
         | @stxref{shebang-comment}
@stxdef{nested-comment}  @stxlit{#|} @stxref{comment-text} @stxref{comment-cont}* @stxlit{|#}
@stxdef{comment-text} character sequence not containing @stxlit{#|} or @stxlit{|#}
@stxdef{comment-cont} @stxref{nested-comment} @stxref{comment-text}
@stxdef{atmosphere} @stxref{whitespace} | @stxref{comment}
@stxdef{interlexeme-space} @arbno{@var{atmosphere}}
@end display

As a special case the characters @stxlit{#!/} are treated as starting a comment,
but only at the beginning of file.  These characters are used on
Unix systems as an @uref{http://en.wikipedia.org/wiki/Shebang_(Unix), Shebang interpreter directive}.
The Kawa reader skips the entire line.
If the last non-whitespace character is @stxlit{@backslashchar{}}
(backslash) then the following line is also skipped, and so on.
@display
@stxdef{shebang-comment} @stxlit{#!} @var{absolute-filename} text up to non-escaped @var{line-ending}
@end display

@noindent
@emph{Whitespace} characters are spaces, linefeeds, carriage returns,
character tabulations, form feeds, line tabulations, and any other
character whose category is Zs, Zl, or Zp.  Whitespace is used for
improved readability and as necessary to separate lexemes from each
other.  Whitespace may occur between any two lexemes, but not within a
lexeme.  Whitespace may also occur inside a string, where it is
significant.

The lexical syntax includes several comment forms.  In all cases,
comments are invisible to Scheme, except that they act as delimiters,
so, for example, a comment cannot appear in the middle of an identifier
or representation of a number object.

A semicolon (@code{;}) indicates the start of a line comment.  The
comment continues to the end of the line on which the semicolon appears.

Another way to indicate a comment is to prefix a @stxref{datum}
with @code{#;}, possibly with
@meta{interlexeme-space} before the @meta{datum}.  The comment consists
of the comment prefix @code{#;} and the @meta{datum} together.  This
notation is useful for ``commenting out'' sections of code.

Block comments may be indicated with properly nested @code{#|} and
@code{|#} pairs.
@example
#|
   The FACT procedure computes the factorial of a
   non-negative integer.
|#
(define fact
  (lambda (n)
    ;; base case
    (if (= n 0)
        #;(= n 1)
        1       ; identity of *
        (* n (fact (- n 1))))))
@end example

@c The lexeme @code{#!r6rs}, which signifies that the program text that
@c follows is written with the lexical and datum syntax described in this
@c report, is also otherwise treated as a comment.

@subsection Identifiers

@display
@stxdef{identifier} @stxref{initial} @stxref{subsequent}*
         | @stxref{peculiar-identifier}
@stxdef{initial} @stxref{constituent} | @stxref{special-initial}
         | @stxref{inline-hex-escape}
@stxdef{letter} @stxlit{a} | @stxlit{b} | @stxlit{c} | ... | @stxlit{z}
         | @stxlit{A} | @stxlit{B} | @stxlit{C} | ... | @stxlit{Z}
@stxdef{constituent} @stxref{letter}
         | @i{any character whose Unicode scalar value is greater than
             127, and whose category is Lu, Ll, Lt, Lm, Lo, Mn,
             Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co}
@stxdef{special-initial} @stxlit{!} | @stxlit{$} | @stxlit{%} | @stxlit{&} | @stxlit{*} | @stxlit{/} | @stxlit{<} | @stxlit{=}
         | @stxlit{>} | @stxlit{?} | @stxlit{^} | @stxlit{_} | @stxlit{~}
@stxdef{subsequent} @stxref{initial} | @stxref{digit}
         | @i{any character whose category is Nd, Mc, or Me}
         | @stxref{special-subsequent}
@stxdef{digit} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7} | @stxlit{8} | @stxlit{9}
@stxdef{oct-digit} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7}
@stxdef{hex-digit} @stxref{digit}
         | @stxlit{a} | @stxlit{A} | @stxlit{b} | @stxlit{B} | @stxlit{c} | @stxlit{C} | @stxlit{d} | @stxlit{D} | @stxlit{e} | @stxlit{E} | @stxlit{f} | @stxlit{F}
@stxdef{special-subsequent} @stxlit{+} | @stxlit{-} | @stxlit{.} | @stxlit{@@}
@stxdef{escape-sequence} @stxref{inline-hex-escape}
         | @stxlit{\\}@stxref{character-except-x}
         | @stxref{multi-escape-sequence}
@stxdef{inline-hex-escape} @stxlit{\\x}@stxref{hex-scalar-value}@stxlit{;}
@stxdef{hex-scalar-value} @stxref{hex-digit}+
@stxdef{multi-escape-sequence} @stxlit{|}@arbno{@stxref{symbol-element}}@stxlit{|}
@stxdef{symbol-element}  @i{any character except} @stxlit{|} @i{or} @stxlit{@backslashchar{}}
         | @stxref{inline-hex-escape} | @stxref{mnemonic-escape} | @stxlit{@backslashchar{}|}

@stxdef{character-except-x} @i{any character except @code{x}}
@stxdef{peculiar-identifier} @stxlit{+} | @stxlit{-} | @stxlit{...} | @stxlit{->} @arbno{@var{subsequent}}
@end display

Most identifiers allowed by other programming languages are also
acceptable to Scheme.  In general, a sequence of letters, digits, and
``extended alphabetic characters'' is an identifier when it begins with
a character that cannot begin a representation of a number object.  In
addition, @code{+}, @code{-}, and @code{...} are identifiers, as is a
sequence of letters, digits, and extended alphabetic characters that
begins with the two--character sequence @code{->}.  Here are some
examples of identifiers:

@example
lambda         q                soup
list->vector   +                V17a
<=             a34kTMNs         ->-
the-word-recursion-has-many-meanings
@end example

Extended alphabetic characters may be used within identifiers as if they
were letters.  The following are extended alphabetic characters:

@example
! $ % & * + - . / < = > ? @@ ^ _ ~
@end example

Moreover, all characters whose Unicode scalar values are greater than
127 and whose Unicode category is Lu, Ll, Lt, Lm, Lo, Mn, Mc, Me, Nd,
Nl, No, Pd, Pc, Po, Sc, Sm, Sk, So, or Co can be used within
identifiers.  In addition, any character can be used within an
identifier when specified using an @meta{escape-sequence}.  For example,
the identifier @code{H\x65;llo} is the same as the identifier
@code{Hello}.

Kawa supports two additional non-R6RS ways of making
identifiers using special characters, both taken from Common Lisp:
Any character (except @code{x}) following a backslash is treated
as if it were a @var{letter};
as is any character between a pair of vertical bars.

@c , and the identifier @code{\x3BB;} is the same as the
@c identifier $\lambda$.

Identifiers have two uses within Scheme programs:
@itemize
@item
Any identifier may be used as a @ref{variable-reference,,variable}
or as a @ref{macro-reference,,syntactic keyword}.
@item
When an identifier appears as or with in @ref{literal-expression,,literal},
it is being used to denote a @ref{Simple symbols,,symbol}.
@end itemize

In contrast with older versions of Scheme, the syntax distinguishes
between upper and lower case in identifiers and in characters
specified via their names, but not in numbers, nor in inline hex
escapes used in the syntax of identifiers, characters, or strings.
The following directives give explicit control over case folding.

@deffn Syntax #!fold-case
@deffnx Syntax #!no-fold-case

These directives may appear anywhere comments are permitted and are
treated as comments, except that they affect the reading of subsequent
data.  The @code{#!fold-case} directive causes the @code{read}
procedure to case-fold (as if by @code{string-foldcase}) each
identifier and character name subsequently read from the same
port. The @code{#!no-fold-case} directive causes the @code{read}
procedure to return to the default, non-folding behavior.
@end deffn

Note that colon @code{:} is treated specially for
@ref{Colon notation, colon notation} in Kawa Scheme,
though it is a @var{special-initial} in standard Scheme (R6RS).

@subsection Numbers

((INCOMPLETE))

@display
@stxdef{number} ((TODO))
  | @stxref{quantity}
@stxdef{decimal} @stxref{digit}+ @stxref{optional-exponent}
  | @stxlit{.} @stxref{digit}+ @stxref{optional-exponent}
  | @stxref{digit}+ @stxlit{.} @stxref{digit}+ @stxref{optional-exponent}
@end display

@display
@stxdef{optional-exponent} @i{empty}
  | @stxref{exponent-marker} @stxref{optional-sign} @stxref{digit}+
@stxdef{exponent-marker} @stxlit{e} | @stxlit{s} | @stxlit{f} | @stxlit{d} | @stxlit{l}
@end display
The letter used for the exponent in a floating-point literal determines
its type:
@table @asis
@item @stxlit{e}
Returns a @code{gnu.math.DFloat} - for example @code{12e2}.
Note this matches the default when there is no @stxref{exponent-marker}.
@item @stxlit{s} or @stxlit{f}
Returns a primitive @code{float} (or @code{java.lang.Float}
when boxed as an object) - for example @code{12s2} or @code{12f2}.
@item @stxlit{d}
Returns a primitive @code{double} (or @code{java.lang.Double} when boxed)
- for example @code{12d2}.
@item @stxlit{l}
Returns a @code{java.math.BigDecimal} - for example @code{12l2}.
@end table
@display
@stxdef{optional-sign} @i{empty} | @stxlit{+} | @stxlit{-}
@stxdef{digit-2} @stxlit{0} | @stxlit{1}
@stxdef{digit-8} @stxlit{0} | @stxlit{1} | @stxlit{2} | @stxlit{3} | @stxlit{4} | @stxlit{5} | @stxlit{6} | @stxlit{7}
@stxdef{digit-10} @stxref{digit}
@stxdef{digit-16} @stxref{digit-10} | @stxlit{a} | @stxlit{b} | @stxlit{c} | @stxlit{d} | @stxlit{e} | @stxlit{f}
@end display

@node Datum syntax, Hash-prefixed forms, Lexical syntax, Syntax
@section Datum syntax

The datum syntax describes the syntax of syntactic data in terms of a
sequence of @meta{lexeme}s, as defined in the lexical syntax.

The following grammar describes the syntax of syntactic data in terms of
various kinds of lexemes defined in the grammar in section ``Lexical
Syntax'':

@display
@stxdef{datum} @stxref{defining-datum}
         | @stxref{nondefining-datum}
         | @stxref{defined-datum}
@stxdef{nondefining-datum} @stxref{lexeme-datum}
         | @stxref{compound-datum}

@stxdef{lexeme-datum} @stxref{boolean} | @meta{number}
         | @stxref{character} | @stxref{string} | @stxref{symbol}
@stxdef{symbol} @stxref{identifier}
@stxdef{compound-datum} @stxref{list} | @stxref{vector} | @stxref{uniform-vector} | @stxref{array-literal} | @stxref{extended-string-literal} | @stxref{xml-literal}
@stxdef{list} @stxlit{(}@stxref{datum}*@stxlit{)}
         | @stxlit{(}@atleastone{@stxref{datum}} @stxlit{.} @stxref{datum}@stxlit{)}
         | @stxref{abbreviation}
@stxdef{vector} @stxlit{#(}@arbno{@stxref{datum}}@stxlit{)}
@end display
@c FIXME: add to abbrev-prefix: @stxlit{#,} | @stxlit{#,@@}

@anchor{datum labels}
@subsection Datum labels

@display
@stxdef{datum-label} @stxlit{#}@stxref{indexnum}@stxlit{=}
@stxdef{defining-datum} @atleastone{@stxref{datum-label}}@stxref{nondefining-datum}
@stxdef{defined-datum} @stxlit{#}@stxref{indexnum}@stxlit{#}
@stxdef{indexnum} @atleastone{@stxref{digit}}
@end display

The lexical syntax @code{#@meta{n}=@meta{datum}} reads the
same as @meta{datum}, but also results in @meta{datum} being
labelled by @meta{n}, which must a sequence of digits.

The lexical syntax @code{#@meta{n}#} serves as a reference to some
object labelled by @code{#@meta{n}=}; the result is the same object
(in the sense of @code{eq?}) as the @code{#@meta{n}=}.

Together, these syntaxes permit the notation of structures
with shared or circular substructure.

@example
(let ((x (list 'a 'b 'c)))
  (set-cdr! (cddr x) x)
  x)    @result{} #0=(a b c . #0#)
@end example

The scope of a datum label is the portion of the outermost
datum in which it appears that is to the right of the label.
Consequently, a reference @code{#@meta{n}#} can occur
only after a label @code{#@meta{n}=};
it is an error to attempt a forward reference.
In addition, it is an error if the reference appears as the labelled
object itself (as in @code{#@meta{n}=#@var{n}#}), because the object
labelled by @code{#@var{n}=} is not well defined in this case.



@subsection Abbreviations

@display
@stxdef{abbreviation} @stxref{r6rs-abbreviation} | @stxref{kawa-abbreviation}
@stxdef{r6rs-abbreviation} @stxref{abbrev-prefix} @stxref{datum}
@stxdef{abbrev-prefix} @stxlit{'} | @stxlit{`} | @stxlit{,} | @stxlit{,@@}
         | @stxlit{#'} | @stxlit{#`}
@stxdef{kawa-abbreviation} XXX
@end display

The following abbreviations are expanded at read-time:

@table @asis
@item @stxlit{'}@meta{datum}     
means @stxlit{(quote} @meta{datum}@stxlit{)}.

@item @stxlit{`}@meta{datum}     
means @stxlit{(quasiquote} @meta{datum}@stxlit{)}.

@item @stxlit{,}@meta{datum}
means @stxlit{(unquote} @meta{datum}@stxlit{)}.

@item @stxlit{,@@}@meta{datum}     
means @stxlit{(unquote-splicing} @meta{datum}@stxlit{)}.

@item @stxlit{#'}@meta{datum}     
means @stxlit{(syntax} @meta{datum}@stxlit{)}.

@item @stxlit{#`}@meta{datum}     
means @stxlit{(quasisyntax} @meta{datum}@stxlit{)}.

@item @stxlit{#,}@meta{datum}
means @stxlit{(unsyntax} @meta{datum}@stxlit{)}.
This abbreviation is currently only recognized when nested inside an explicit
@stxlit{#`}@meta{datum} form,
because of a conflict with SRFI-10 named constructors.

@item @stxlit{#,@@}@meta{datum}
means @stxlit{(unsyntax-splicing} @meta{datum}@stxlit{)}.

@item @meta{datum1}@stxlit{:}@meta{datum2}
means @stxlit{($lookup$} @meta{datum1} @stxlit{(quasiquote} @meta{datum2}@stxlit{))}.
@xref{Colon notation}.

@item @stxlit{[}@meta{expression} ...@stxlit{]}
means @stxlit{($bracket-list$} @meta{expression} ...@stxlit{)}.

@item @meta{operator}@stxlit{[}@meta{expression} ...@stxlit{]}
means @stxlit{($bracket-apply$} @meta{operator} @meta{expression} ...@stxlit{)}.

@end table

@node Hash-prefixed forms
@section Hash-prefixed forms

A number of different special forms are indicated by an
initial hash (number) symbols (@code{#}).
Here is a table summarizing them.

Case is ignored for the character followed the @code{#}.
Thus @code{#x} and @code{#X} are the same.

@table @asis
@item @stxlit{#:}@var{keyword}
Guile-style @ref{Keywords,keyword} syntax.
@item @stxlit{#\\}
@ref{meta-character, Character literals, Character literals}.
@item @stxlit{#!}
@xref{Special named constants}.
@item @stxlit{#`}@var{datum}
Equivalent to @code{(quasisyntax @var{datum})}.
Convenience syntax for syntax-case macros.
@item @stxlit{#'}@var{datum}
Equivalent to @code{(syntax @var{datum})}.
Convenience syntax for syntax-case macros.
@item @stxlit{#,}@var{datum}
Equivalent to @code{(unsyntax @var{datum})}.
Currently only recognized when inside a @code{#`@var{template}} form. 
Convenience syntax for syntax-case macros.
@item @stxlit{#,(}@var{name} @var{datum} ...@stxlit{)}
Special named constructors.
This syntax is deprecated, because it conflicts with @code{unsyntax}.
It is only recognized when @emph{not} in a @code{#`@var{template}} form.
@item @stxlit{#,@@}@var{datum}
Equivalent to @code{(unsyntax-splicing @var{datum})}.
@item @stxlit{#(}
A vector.
@item @stxlit{#|}
Start of nested-comment.
@item @stxlit{#/}@var{regex}@stxlit{/}
@xref{Regular expressions}.
@item @stxlit{#<}
@xref{XML literals}.
@item @stxlit{#;}@var{datum}
A datum comment - the @var{datum} is ignored.
(An @var{interlexeme-space} may appear before the @var{datum}.)
@item @stxlit{#}@var{number}@stxlit{=}@var{datum}
A reference definition, allowing cyclic and shared structure.
Equivalent to the @var{datum}, but also defines an association between
the integer @var{number} and that @var{datum}, which can be
used by a subsequent @code{#@var{number}#} form.
@item @stxlit{#}@var{number}@stxlit{#}
A back-reference, allowing cyclic and shared structure.
@item @stxlit{#}@var{R}@stxlit{a}@var{datum}
An @ref{array-literals,array literal},
for a multi-dimensional array of rank @var{R}.
@item @stxlit{#b}
A binary (base-2) number.
@item @stxlit{#d}
A decimal (base-10) number.
@item @stxlit{#e}
A prefix to treat the following number as exact.
@item @stxlit{#f}
@itemx @stxlit{#false}
The standard boolean false object.
@item @stxlit{#f}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
A uniform vector of floating-point numbers.
The parameter @var{n} is a precision, which can be 32 or 64.
@xref{Uniform vectors}.
@item @stxlit{#i}
A prefix to treat the following number as inexact.
@item @stxlit{#o}
An octal (base-8) number.
@item @stxlit{#}@var{base}@stxlit{r}
A number in the specified @var{base} (radix).
@item @stxlit{#s}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
A uniform vector of signed integers.
The parameter @var{n} is a precision, which can be 8, 16, 32, or 64.
@xref{Uniform vectors}.
@item @stxlit{#t}
@itemx @stxlit{#true}
The standard boolean true object.
@item @stxlit{#u}@var{n}@stxlit{(}@var{number} ...@stxlit{)}
A uniform vector of unsigned integers.
The parameter @var{n} is a precision, which can be 8, 16, 32, or 64.
@xref{Uniform vectors}.
@item @stxlit{#x}
A hexadecimal (base-16) number.
@end table

The follow named constructor forms are supported:

@table @asis
@item @stxlit{#,(path} @var{path}@stxlit{)}
@item @stxlit{#,(filepath} @var{path}@stxlit{)}
@item @stxlit{#,(URI} @var{path}@stxlit{)}
@item @stxlit{#,(symbol} @var{local-name} [@var{uri} [@var{prefix}]]@stxlit{)}
@itemx @stxlit{#,(symbol} @var{local-name} @var{namespace}@stxlit{)}
@item @stxlit{#,(namespace} @var{uri} [@var{prefix}]@stxlit{)}
@item @stxlit{#,(duration} @var{duration}@stxlit{)}
@end table

@node Primitive expression syntax
@section Primitive expression syntax

@display
@stxdef{expression} @stxref{literal-expression} | @stxref{variable-reference}
  | @stxref{procedure-call} | TODO
@end display

@anchor{literal-expression}
@subsection Literal expressions

@display
@stxdef{literal-expression} @stxlit{(quote} @stxref{datum}@stxlit{)}
  | @stxlit{'} @stxref{datum}
  | @var{constant} 
@stxdef{constant} @var{number} | @meta{boolean} | @meta{character} | @meta{string}
@end display

@code{(quote @var{datum})} evaluates to @var{datum},
which may be any external representation of a Scheme object.
This notation is used to include literal constants in Scheme code.
@example
(quote a)               @result{}  a 
(quote #(a b c))        @result{}  #(a b c)
(quote (+ 1 2))         @result{}  (+ 1 2)
@end example

@code{(quote @var{datum})} may be abbreviated as @code{'@var{datum}}.
The two notations are equivalent in all respects.
@example
’a                      @result{}  a
’#(a b c)               @result{}  #(a b c)
’()                     @result{}  ()
’(+ 1 2)                @result{}  (+ 1 2)
’(quote a)              @result{}  (quote a)
’’a                     @result{}  (quote a)
@end example

Numerical constants, string constants, character constants,
bytevector constants, and boolean constants evaluate to
themselves; they need not be quoted.

@example
145932          @result{}  145932
#t              @result{}  #t
"abc"           @result{}  "abc"
@end example
@c #vu8(2 24 123)  @result{} #vu8(2 24 123)

Note that @ref{Keywords,keywords} need to be quoted,
unlike some other Lisp/Scheme dialect, including Common Lisp,
and earlier versions of Kawa.  (Kawa currently evaluates a non-quoted
keyword as itself, but that will change.)

@anchor{variable-reference}
@subsection Variable references

@display
@stxdef{variable-reference} @stxref{identifier}
@end display
An expression consisting of a variable is a variable reference if it is
not a macro use (see below).  The value of the variable reference is the
value stored in the location to which the variable is bound.  It is a
syntax violation to reference an unbound variable.

The following example assumes the base library has been
imported:

@example
(define x 28)
x   @result{}  28
@end example

@subsection Procedure calls

@display
@stxdef{procedure-call} @stxlit{(}@stxref{operator} @stxref{operand} @dots{})
@stxdef{operator} @stxref{expression}
@stxdef{operand} @stxref{expression}
  | @stxref{keyword} @stxref{expression}
  | @code{@@} @stxref{expression}
  | @code{@@:} @stxref{expression}
@end display

A procedure call consists of expressions for the procedure to be called
and the arguments to be passed to it, with enclosing parentheses.  A
form in an expression context is a procedure call if @meta{operator} is
not an identifier bound as a syntactic keyword.

When a procedure call is evaluated, the operator and operand expressions
are evaluated (in an unspecified order) and the resulting procedure is
passed the resulting arguments.

@example
(+ 3 4)                @result{}  7
((if #f + *) 3 4)      @result{}  12
@end example

The syntax @stxref{keyword} @var{expression} is a @dfn{keyword argument}.
This is a mechanism for specifying arguments using a name rather than position,
and is especially useful for procedures with many optional paramaters.
Note that @stxref{keyword} must be literal, and cannot be the
result from evaluating a non-literal expression.
(This is a change from previous versions of Kawa,
and is different from Common Lisp and some other Scheme dialects.)

An expression prefixed by @code{@@} or @code{@@:} is
a splice argument.  The following expression must evaluate to an
``argument list'' (see @ref{Application and Arguments Lists} for details);
each element in the argument
becomes a separate argument when call the @var{operator}.
(This is very similar to the ``spread'' operator is EcmaScript 6.)

@node Colon notation
@section Property access using colon notation

The @dfn{colon notation} accesses named parts (properties) of a value.
It is used to get and set fields, call methods, construct compound symbols,
and more.
Evaluating the form @code{@var{owner}:@var{property}}
evaluates the @code{@var{owner}} then it extracts the named @code{@var{property}} of the result.

@display
@stxdef{property-access-abbreviation} @stxref{property-owner-expression}@stxlit{:}@stxref{property-name}
@stxdef{property-owner-expression} @stxref{expression}
@stxdef{property-name} @stxref{identifier} | @stxlit{,}@stxref{expression}
@end display

The @var{property-name} is usually a literal name,
but it can be an unquoted @var{expression} (i.e. following a @code{,}),
in which case the name is evaluated at run-time.
No separators are allowed on either side of the colon.

The input syntax @code{@var{owner}:@var{part}} is translated by
the Scheme reader to the internal representation @code{($lookup$ @var{owner} (quasiquote @var{part}))}.

@subsection Part lookup rules

Evaluation proceeds as follows.
First @var{property-owner-expression} is
evaluated to yield an @var{owner} object.
Evaluating the @var{property-name} yields a @var{part} name,
which is a simple symbol: Either
the literal @var{identifier}, or the result of evaluating the
property-name @var{expression}.
If the @var{expression} evaluates to a string, it is converted to
a symbol, as if using @code{string->symbol}.

@itemize
@item
If the @var{owner} implements @code{gnu.mapping.HasNamedParts},
then the result is that of invoking the @code{get} method of the @var{owner}
with the @var{part} name as a parameter.

As a special case of this rule, if @var{owner} is a
@code{gnu.mapping.Namespace}, then the result is the
@ref{Namespaces,compound symbol in that namespace}.
@item
If @var{owner} is a @code{java.lang.Class} or a @code{gnu.bytecode.ObjectType},
the result is the static member named @var{part}
(i.e. a static field, method, or member class).
@item
If @var{owner} is a @code{java.lang.Package} object, we get the member
class or sub-package named @var{part}.
@item
Otherwise, we look for a named member (instance member or field).

Note you can't use colon notation to invoke instance methods
of a @code{Class}, because it will match a previous rule.
For example if you want to invoke the @code{getDeclaredMethod}
method of the @code{java.util.List} , you can't write @code{(java.util.List:getDeclaredMethod} because that will look for a static method in @code{java.util.List}.
@end itemize

If the colon form is on the left-hand-side of an assignment (@code{set!}),
then the named part is modified as appropriate.

@c We will look into examples and details below.
@c @subsection The @code{HasNamedParts} case
@c @subsection Static parts of classes and packages
@c @subsection Instance parts

@subsection Specific cases

Some of these are deprecated;
more compact and readable forms are usually preferred.

@subsubsection Invoking methods

@display
@stxlit{(}@var{instance}@stxlit{:}@stxref{method-name} @var{arg} ...@stxlit{)}
@stxlit{(}@var{class}@stxlit{:}@stxref{method-name} @var{instance} @var{arg} ...@stxlit{)}
@stxlit{(}@var{class}@stxlit{:}@stxref{method-name} @var{arg} ...@stxlit{)}
@stxlit{(*:}@stxref{method-name} @var{instance} @var{arg} ...@stxlit{)}
@end display

For details @pxref{Method operations}.

@subsubsection Accessing fields

@display
@var{class}@stxlit{:}@stxref{field-name}
@var{instance}@stxlit{:}@stxref{field-name}
@stxlit{(}@var{prefix}@stxlit{:.}@stxref{field-name} @var{instance}@stxlit{)}
@end display

For details @pxref{Field operations}.

@subsubsection Type literal

@display
@stxlit{(}@stxref{type}@stxlit{:<>)}
@end display
Returns the @var{type}.
Deprecated; usually you can just write:
@example
@var{type}
@end example

@subsubsection Type cast

@display
@stxlit{(}@stxref{type}@stxlit{:}@stxlit{@atchar{}} @stxref{expression}@stxlit{)}
@end display
Performs a cast.
Deprecated; usually you can just write:
@example
->@var{type}
@end example

@subsubsection Type test

@display
@stxlit{(}@stxref{type}@stxlit{:instanceof?} @stxref{expression}@stxlit{)}
@end display

Deprecated; usually you can just write:
@example
(@var{type}? @var{expression})
@end example

@subsubsection New object construction

@display
@stxlit{(}@stxref{type}@stxlit{:new} @var{arg} ...@stxlit{)}
@end display

Deprecated; usually you can just write:
@display
@stxlit{(}@stxref{type} @var{arg} ...@stxlit{)}
@end display

@subsubsection Getting array length

@display
@stxref{expression}@stxlit{:length}
@stxlit{(}@stxref{expression}@stxlit{:.length)}
@end display


@node Bodies
@section Programs and Bodies

@anchor{program units}
@subheading Program units

A @meta{program-unit} consists of a sequence of definitions and expressions.

@display
@stxdef{program-unit} @atleastone{@stxref{library-definition}} [@stxref{statements}]
  | @stxref{statements}
@stxdef{statements} @atleastone{@stxref{statement}}
@stxdef{statement} @var{definition} | @stxref{expression} | @stxlit{(begin} @arbno{@stxref{statement}} @stxlit{)}
@end display

Typically a @meta{program-unit} corresponds to a single source file
(i.e.a named file in the file system).  Evaluating a @meta{program-unit}
first requires the Kawa processor to analyze
the whole @meta{program-unit} to determine which names are defined by the
definitions, and then evaluates each @meta{statement} in order in the context
of the defined names.  The value of an @meta{expression} is normally
discarded, but may be printed out instead, depending on the evaluating context.

The read-eval-print-loop (REPL) reads one or more lines until it gets
a valid @meta{program-unit}, and evaluates it as above, except that the
values of expressions are printed to the console (as if using the
@code{display} function).  Then the REPL reads and evaluates
another @meta{program-unit}, and so on. A definition in an earlier
@meta{program-unit} is remembered and is visible in a later @meta{program-unit}
unles it is overridden.

@cindex encoding specifier
@cindex coding specifier
A comment in the first 2 lines of a source file may contain an encoding
specification.  This can be used to tell the reader what kind of character
set encoding is used for the file.  This only works for a character
encoding that is compatible with ASCII (in the sense that if the
high-order bit is clear then it's an ASCII character),
and that are no non-ASCI characters in the lines upto and including
the encoding specification.
A basic example is:
@example
;; -*- coding: utf-8 -*-
@end example
In general any string that matches the following regular expression works:
@example
coding[:=]\s*([-a-zA-Z0-9]+)
@end example

@subheading Libraries

@anchor{implicit library}
A @meta{program-unit} may contain @meta{library-definitions}.
In addition, any @meta{statements} in @meta{program-unit} comprise
an @dfn{implicit library}, in that it can be given a name, and referenced
from other libraries.
Certain names defined in the @meta{program-unit} can be exported,
and then they can be imported by other libraries.
For more information @pxref{Module classes}.

It is recommended but not required that:
@itemize
@item
There should be at most one @meta{library-definition} in a @meta{program-unit}.
@item
The @meta{library-name} of the @meta{library-definition} should
match the name of the source file.  For example:
@example
(define-library (foo bar) ...)
@end example
should be in a file named @code{foo/bar.scm}.
@item
If there is a @meta{library-definition}, there should
be no extra @meta{statements} - i.e no implicit library definition.
(It is disallowed to @code{export} any definitions from the
implicit library if there is also a @meta{library-definition}.)
@end itemize
Following these recommendations makes it easier to locate
and organize libraries.
However, having multiple libraries in a single @meta{program-unit}
is occasionally useful for source distribution and for testing.

@subheading Bodies

The @meta{body} of a @func{lambda}, @func{let}, @func{let*},
@func{let-values}, @func{let*-values}, @func{letrec}, or @func{letrec*}
expression, or that of a definition with a body consists of zero or more
definitions or expressions followed by a final expression.
(Standard Scheme requires that all definitions precede all expressions.)

@display
@stxdef{body} @arbno{@stxref{statement}}
@end display

Each identifier defined by a definition is local to the @meta{body}.
That is, the identifier is bound, and the region of the binding is the
entire @meta{body}.
Example:

@example
(let ((x 5))
  (define foo (lambda (y) (bar x y)))
  (define bar (lambda (a b) (+ (* a b) a)))
  (foo (+ x 3)))
@result{} 45
@end example

When @func{begin}, @func{let-syntax}, or @func{letrec-syntax} forms
occur in a body prior to the first expression, they are spliced into the
body.  Some or all of the body, including portions wrapped in
@func{begin}, @func{let-syntax}, or @func{letrec-syntax} forms, may be
specified by a macro use.

An expanded @meta{body} containing variable definitions can be
converted into an equivalent @func{letrec*} expression.
(If there is a definition following expressions you may need to
convert the expressions to dummy definitions.)     For example,
the @func{let} expression in the above example is equivalent to

@example
(let ((x 5))
  (letrec* ((foo (lambda (y) (bar x y)))
            (bar (lambda (a b) (+ (* a b) a))))
    (foo (+ x 3))))
@end example


@node Syntax and conditional compilation
@section Syntax and conditional compilation

@subheading Feature testing

@deffn Syntax cond-expand @arbno{@stxref{cond-expand-clause}} [@stxlit{(else} command-or-definition*@stxlit{)}]
@display
@stxdef{cond-expand-clause} @stxlit{(}@var{feature-requirement} @var{command-or-definition}*@stxlit{)}
@findex @i{fff-rec}
@stxdef{feature-requirement} @stxref{feature-identifier}
  | @stxlit{(and} @arbno{@stxref{feature-requirement}}@stxlit{)}
  | @stxlit{(or} @arbno{@stxref{feature-requirement}}@stxlit{)}
  | @stxlit{(not} @stxref{feature-requirement}@stxlit{)}
  | @stxlit{(library} @stxref{library-name}@stxlit{)}
@stxdef{feature-identifier} a symbol which is the name or alias of a SRFI
@end display

The @code{cond-expand} form tests for the existence of features at
macro-expansion time. It either expands into the body of one of its
clauses or signals an error during syntactic
processing. @code{cond-expand} expands into the body of the first clause
whose feature requirement is currently satisfied; the @code{else}
clause, if present, is selected if none of the previous clauses is
selected.

The implementation has a set of
feature identifiers which are ``present'', as well as a set
of libraries which can be imported.
The value of a
@meta{feature-requirement} is determined by replacing each
@meta{feature-identifier} by @code{#t} if it is present
(and @code{#f} otherwise);
replacing @code{(library @meta{library-name})}
by @code{#t} if @meta{library-name} is importable (and @code{#f} otherwise);
and then evaluating the resulting expression as a Scheme boolean expression
under the normal interpretation of @code{and}, @code{or}, and @code{not}.

Examples:
@example
(cond-expand
    ((and srfi-1 srfi-10)
     (write 1))
    ((or srfi-1 srfi-10)
     (write 2))
    (else))
@end example

@example
(cond-expand
  (command-line
   (define (program-name) (car (argv)))))
@end example

The second example assumes that @code{command-line} is an alias for some
feature which gives access to command line arguments. Note that an error
will be signaled at macro-expansion time if this feature is not present.

You can use @code{java-6}, @code{java-7}, @code{java-8},
or @code{java-9} to check if the underlying Java
is a specific version or newer.
For example the name @code{java-7} matches for
either Java 7, Java 8, or newer, as
reported by @code{System} property @code{"java.version"}.

You can use @code{class-exists:@var{ClassName}} to check
if @code{@var{ClassName}} exists at compile-time.
The identifier @code{class-exists:org.example.MyClass}
is roughly equivalent to the test @code{(library (org example MyClass))}.
(The latter has some special handling for @code{(srfi ...)} as well
as builtin Kawa classes.)
@end deffn

@deffn Procedure features
Returns a list of feature identifiers which @code{cond-expand}
treats as true.
This not a complete list - for example @code{class-exists:@var{ClassName}}
feature identifiers are not included.
It is an error to modify this list.
Here is an example of what @code{features} might return:
@example
(features)  @result{}
(complex exact-complex full-unicode java-7 java-6 kawa
 ratios srfi-0 srfi-4 srfi-6 srfi-8 srfi-9 srfi-11
 srfi-16 srfi-17 srfi-23 srfi-25 srfi-26 srfi-28 srfi-30
 srfi-39 string-normalize-unicode threads)
@end example
@end deffn

@subheading File inclusion

@anchor{include}
@anchor{include-relative}
@deffn Syntax include @atleastone{path}
@deffnx Syntax include-relative @atleastone{path}
@deffnx Syntax include-ci @atleastone{path}
These take one or more path names expressed as string literals,
find corresponding files, read the contents of the files in the specified order
as if by repeated applications of @code{read}, and effectively
replace the @code{include} with a @code{begin} form
containing what was read from the files.

You can control the search path used for @code{include}
by setting the @code{kawa.include.path} property.  For example:
@example
$ kawa -Dkawa.include.path="|:/opt/kawa-includes"
@end example
The special @code{"|"} path element means to search
relative to the directory containing the including source file.
The default search path is @code{"|:."} which means to first
search the directory containing the including source file,
and then search the directory specified by @code{(current-path)}.

The search path for @code{include-relative} prepends @code{"|"}
before the search path used by @code{include}, so it always
searches first the directory containing the including source file.
Note that if the default search path is used then @code{include}
and @code{include-relative} are equivalent; there is only a difference
if the @code{kawa.include.path} property changes the default.

Using @code{include-ci} is like @code{include}, except that it reads each
file as if it began with the @code{#!fold-case} directive.
@end deffn

@node Macros
@section Macros
@anchor{macro-reference}

Libraries and top--level programs can define and use new kinds of
derived expressions and definitions called @emph{syntactic abstractions}
or @emph{macros}.  A syntactic abstraction is created by binding a
keyword to a @emph{macro transformer} or, simply, @emph{transformer}.

The transformer determines how a use of the macro (called a @emph{macro
use}) is transcribed into a more primitive form.

Most macro uses have the form:

@example
(@meta{keyword} @meta{datum} @dots{})
@end example
@noindent
where @meta{keyword} is an identifier that uniquely determines the kind
of form.  This identifier is called the @emph{syntactic keyword}, or
simply @emph{keyword}.  The number of @meta{datum}s and the syntax of
each depends on the syntactic abstraction.

Macro uses can also take the form of improper lists, singleton
identifiers, or @func{set!} forms, where the second subform of the
@func{set!} is the keyword:

@example
(@meta{keyword} @meta{datum} @dots{} . @meta{datum})
@meta{keyword}
(set! @meta{keyword} @meta{datum})
@end example

The @func{define-syntax}, @func{let-syntax} and @func{letrec-syntax}
forms create bindings for keywords, associate them with macro
transformers, and control the scope within which they are visible.

The @func{syntax-rules} and @func{identifier-syntax} forms create
transformers via a pattern language.  Moreover, the @func{syntax-case}
form allows creating transformers via arbitrary Scheme code.

Keywords occupy the same name space as variables.  That is, within the
same scope, an identifier can be bound as a variable or keyword, or
neither, but not both, and local bindings of either kind may shadow
other bindings of either kind.

Macros defined using @func{syntax-rules} and @func{identifier-syntax}
are ``hygienic'' and ``referentially transparent'' and thus preserve
Scheme's lexical scoping.

@itemize
@item 
If a macro transformer inserts a binding for an identifier (variable or
keyword) not appearing in the macro use, the identifier is in effect
renamed throughout its scope to avoid conflicts with other identifiers.

@item 
If a macro transformer inserts a free reference to an identifier, the
reference refers to the binding that was visible where the transformer
was specified, regardless of any local bindings that may surround the
use of the macro.
@end itemize

Macros defined using the @func{syntax-case} facility are also hygienic
unless @func{datum->syntax} is used.

Kawa supports most of the @code{syntax-case} feature.

Syntax definitions are valid wherever definitions are.
They have the following form:

@deffn Syntax define-syntax keyword @stxref{transformer-spec}
The @var{keyword} is a identifier, and @var{transformer-spec}
is a function that maps syntax forms to syntax forms,
usually an instance of @code{syntax-rules}.
If the @code{define-syntax} occurs at the top level, then the top-level
syntactic environment is extended by binding the @var{keyword}
to the specified transformer, but existing references to any top-level
binding for @var{keyword} remain unchanged.  Otherwise, it is an
@dfn{internal syntax definition}, and is local to the @var{body}
in which it is defined.

@example
(let ((x 1) (y 2))
   (define-syntax swap!
     (syntax-rules ()
       ((swap! a b)
        (let ((tmp a))
          (set! a b)
          (set! b tmp)))))
   (swap! x y)
   (list x y))  @result{} (2 1)
@end example

Macros can expand into definitions in any context that permits them.
However, it is an error for a definition to define an identifier
whose binding has to be known in order to determine the meaning
of the definition itself, or of any preceding definition that belongs
to the same group of internal definitions.
@end deffn

@deffn Syntax define-syntax-case name @stxlit{(}literals@stxlit{)} @stxlit{(}pattern expr@stxlit{)} ...
A convenience macro to make it easy to define @code{syntax-case}-style macros.
Defines a macro with the given @var{name} and list of @var{literals}.
Each @var{pattern} has the form of a @code{syntax-rules}-style pattern,
and it is matched against the macro invocation syntax form.
When a match is found, the corresponding @var{expr} is evaluated.
It must evaluate to a syntax form,
which replaces the macro invocation.
@example
(define-syntax-case macro-name (literals)
  (pat1 result1)
  (pat2 result2))
@end example
is equivalent to:
@example
(define-syntax macro-name
  (lambda (form)
    (syntax-case form (literals)
      (pat1 result1)
      (pat2 result2))))
@end example
@end deffn

@deffn Syntax define-macro @stxlit{(}name lambda-list@stxlit{)} form ...
@emph{This form is deprecated.}
Functionally equivalent to @code{defmacro}.
@end deffn

@deffn Syntax defmacro name lambda-list form ...
@emph{This form is deprecated.}
Instead of
@example
(defmacro (@var{name} ...)
  (let ... `(... ,@var{exp} ...)))
@end example
you should probably do:
@example
(define-syntax-case @var{name} ()
  ((_ ...) (let #`(... #,@var{exp} ...))))
@end example
and instead of
@example
(defmacro (@var{name} ... @var{var} ...) `(... @var{var} ...))
@end example
you should probably do:
@example
(define-syntax-case @var{name} ()
  ((_ ... @var{var} ...) #`(... @var{var} ...))
@end example

Defines an old-style macro a la Common Lisp,
and installs @code{(lambda @var{lambda-list} @var{form} ...)}
as the expansion function for @var{name}.
When the translator sees an application of @var{name},
the expansion function is called with the rest of the application
as the actual arguments.  The resulting object must be a Scheme
source form that is futher processed (it may be repeatedly macro-expanded).
@end deffn

@deffn Procedure gentemp
Returns a new (interned) symbol each time it is called.
The symbol names are implementation-dependent.
(This is not directly macro-related, but is often used in conjunction
with @code{defmacro} to get a fresh unique identifier.)
@end deffn

@deffn Procedure expand form
The result of evaluating @var{form} is treated as a Scheme expression,
syntax-expanded to internal form, and then converted back to (roughly)
the equivalent expanded Scheme form.

This can be useful for debugging macros.

To access this function, you must first @code{(require 'syntax-utils)}.
@example
(require 'syntax-utils)
(expand '(cond ((> x y) 0) (else 1))) @result{} (if (> x y) 0 1)
@end example
@end deffn

@subsection Pattern language

A @meta{transformer-spec} is an expression that evaluates to a
transformer procedure, which takes an input form and returns a
resulting form.  You can do general macro-time compilation with such a
procedure, commonly using @code{syntax-case} (which is documented
in the R6RS library specification).
However, when possible it is better to use the simpler
pattern language of @code{syntax-rules}:

@display
@stxdef{transformer-spec}
  @stxlit{(syntax-rules (} @arbno{@stxref{tr-literal}} @stxlit{)} @arbno{@stxref{syntax-rule}}@stxlit{)}
  | @stxlit{(syntax-rules} @stxref{ellipsis} @stxlit{(} @arbno{@stxref{tr-literal}} @stxlit{)} @arbno{@stxref{syntax-rule}}@stxlit{)}
  | @stxref{expression}
@stxdef{syntax-rule} @stxlit{(}@stxref{list-pattern} @stxref{syntax-template}@stxlit{)}
@stxdef{tr-literal} @stxref{identifier}
@stxdef{ellipsis} @stxref{identifier}
@end display

An instance of @code{syntax-rules} produces a new
macro transformer by specifying a sequence of hygienic
rewrite rules. A use of a macro whose keyword is associated
with a transformer specified by @code{syntax-rules} is matched
against the patterns contained in the @meta{syntax-rule}s
beginning with the leftmost syntax rule . When a match is
found, the macro use is transcribed hygienically according
to the template.
The optional @meta{ellipsis} species a symbol used to indicate
repetition; it defaults to @code{...} (3 periods).

@display
@stxdef{syntax-pattern}
  @stxref{identifier} | @stxref{constant} | @stxref{list-pattern} | @stxref{vector-pattern}
@stxdef{list-pattern} @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  | @stxlit{(} @stxref{syntax-pattern} @arbno{@stxref{syntax-pattern}} @stxlit{.} @stxref{syntax-pattern} @stxlit{)}
  | @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  | @stxlit{(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{.} @stxref{syntax-pattern}@stxlit{)}
@stxdef{vector-pattern} @stxlit{#(} @arbno{@stxref{syntax-pattern}} @stxlit{)}
  | @stxlit{#(} @arbno{@stxref{syntax-pattern}} @stxref{syntax-pattern} @stxref{ellipsis} @arbno{@stxref{syntax-pattern}} @stxlit{)}
@end display

An identifier appearing within a pattern can be an underscore
(@code{_}), a literal identifier listed in the list of @meta{tr-literal}s,
or the @meta{ellipsis}. All other identifiers appearing within a
pattern are pattern variables.

The outer @var{syntax-list} of the pattern in a @meta{syntax-rule}
must start with an identifier. It is not involved in the matching and
is considered neither a pattern variable nor a literal identifier.

Pattern variables match arbitrary input elements and are
used to refer to elements of the input in the template.
It is an error for the same pattern variable to appear more
than once in a @meta{syntax-pattern}.

Underscores also match arbitrary input elements but are
not pattern variables and so cannot be used to refer to
those elements. If an underscore appears in the literals
list, then that takes precedence and underscores in the
pattern match as literals. Multiple underscores can
appear in a @meta{syntax-pattern}.

Identifiers that appear in @code{(@arbno{@meta{tr-literal}})} are interpreted
as literal identifiers to be matched against corresponding
elements of the input. An element in the input matches a
literal identifier if and only if it is an identifier and either
both its occurrence in the macro expression and its occurrence
in the macro definition have the same lexical binding,
or the two identifiers are the same and both have no lexical
binding.

A subpattern followed by ellipsis can match zero or
more elements of the input, unless ellipsis appears in the
literals, in which case it is matched as a literal.

More formally, an input expression @var{E} matches a pattern @var{P}
if and only if:
@itemize @bullet
@item
@var{P} is an underscore (@stxlit{_}); or
@item
@var{P} is a non-literal identifier; or
@item
@var{P} is a literal identifier and @var{E} is an identifier with the
same binding; or
@item
@var{P} is a list @stxlit{(}@var{P@sub{1}} ... @var{P@sub{n}}@stxlit{)} and
@var{E} is a list of @var{n} elements
that match @var{P@sub{1}} through @var{P@sub{n}}, respectively; or
@item
@var{P} is an improper list
@stxlit{(}@var{P@sub{1}} ... @var{P@sub{n}} @stxlit{.} @var{P@sub{n+1}}@stxlit{)} and
@var{E} is a list or improper list of @var{n} or more elements that
match @var{P@sub{1}} through @var{P@sub{n}}, respectively,
and whose @var{n}th tail matches @var{P@sub{n+1}}; or
@item
@var{P} is of the form
@stxlit{(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}}@stxlit{)} where @var{E} is a proper list of @var{n} elements,
 the first @var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
respectively, whose
next @var{n-k-l} elements each match @var{P@sub{e}}, and whose remaining
@var{l} elements match @var{P@sub{k+1}} through @var{P@sub{k+l}}; or
@item
@var{P} is of the form
@stxlit{(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}} @stxlit{.} @var{P@sub{x}}@stxlit{)}
where @var{E} is a list or improper list of @var{n} elements,
the first @var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
whose next @var{n-k-l} elements each match @var{P@sub{e}}, and whose
remaining @var{l} elements match @var{P@sub{k+1}} through @var{P@sub{k+l}},
and whose @var{n}th and final @code{cdr} matches @var{P@sub{x}}; or
@item
@var{P} is a vector of the form
@stxlit{#(}@var{P@sub{1}} ... @var{P@sub{n}}@stxlit{)} and @var{E} is a
vector of @var{n} elements that match @var{P@sub{1}} through @var{P@sub{n}}; or
@item
@var{P} is of the form
@stxlit{#(}@var{P@sub{1}} ... @var{P@sub{k}} @var{P@sub{e}} @var{ellipsis} @var{P@sub{k+1}} ... @var{P@sub{k+l}}@stxlit{)}
where @var{E} is a vector of @var{n} elements the first
@var{k} of which match @var{P@sub{1}} through @var{P@sub{k}},
whose next @var{n-k-l} elements each match @var{P@sub{e}},
and whose remaining @var{l} elements match @var{P@sub{k+1}}
through @var{P@sub{k+l}}; or
@item
@var{P} is a constant and E is equal to @var{P} in the sense of the
@code{equal?} procedure.
@end itemize

It is an error to use a macro keyword, within the scope of
its binding, in an expression that does not match any of
the patterns.
@display
@stxdef{syntax-template} @stxref{identifier} | @stxref{constant}
   | @stxlit{(}@arbno{@stxref{template-element}}@stxlit{)}
   | @stxlit{(}@stxref{template-element} @arbno{@stxref{template-element}} @stxlit{.} @stxref{syntax-template} @stxlit{)}
   | @stxlit{(} @stxref{ellipsis} @stxref{syntax-template}@stxlit{)}
@stxdef{template-element} @stxref{syntax-template} [@stxref{ellipsis}]
@end display

When a macro use is transcribed according to the template
of the matching @meta{syntax-rule}, pattern variables that occur
in the template are replaced by the elements they match in
the input. Pattern variables that occur in subpatterns followed
by one or more instances of the identifier @meta{ellipsis} are
allowed only in subtemplates that are followed by as many
instances of @meta{ellipsis} . They are replaced in the output by
all of the elements they match in the input, distributed as
indicated. It is an error if the output cannot be built up
as specified.

Identifiers that appear in the template but are not pattern
variables or the identifier @meta{ellipsis} are inserted into the output
as literal identifiers. If a literal identifier is inserted as a
free identifier then it refers to the binding of that identifier
within whose scope the instance of @code{syntax-rules} appears.
If a literal identifier is inserted as a bound identifier then
it is in effect renamed to prevent inadvertent captures of
free identifiers.

A template of the
form @stxlit{(}@meta{ellipsis} @meta{template}@stxlit{)} is
identical to @meta{template}, except that @meta{ellipses}
within the template have no special meaning.
That is, any @meta{ellipses} contained within
@meta{template} are treated as ordinary identifiers. In particular,
the template @stxlit{(}@meta{ellipsis}  @meta{ellipsis}@stxlit{)}
produces a single @meta{ellipsis}. This allows syntactic
abstractions to expand into code containing ellipses.

@example
(define-syntax be-like-begin
  (syntax-rules ()
    ((be-like-begin name)
     (define-syntax name
       (syntax-rules ()
         ((name expr (... ...))
          (begin expr (... ...))))))))

(be-like-begin sequence)
(sequence 1 2 3 4) @result{} 4
@end example

@subsection Identifier predicates

@deffn Procedure {identifier?} @var{obj}
Return @true{} if @var{obj} is an identifier, i.e., a syntax object
representing an identifier, and @false{} otherwise.

The @func{identifier?} procedure is often used within a fender to verify
that certain subforms of an input form are identifiers, as in the
definition of @code{rec}, which creates self--contained recursive
objects, below.

@example
(define-syntax rec
  (lambda (x)
    (syntax-case x ()
      ((_ x e)
       (identifier? #'x)
       #'(letrec ((x e)) x)))))

(map (rec fact
       (lambda (n)
         (if (= n 0)                 
             1
             (* n (fact (- n 1))))))
     '(1 2 3 4 5))    @result{} (1 2 6 24 120)
 
(rec 5 (lambda (x) x))  @result{} exception
@end example
@end deffn


The procedures @func{bound-identifier=?} and @func{free-identifier=?}
each take two identifier arguments and return @true{} if their arguments
are equivalent and @false{} otherwise.  These predicates are used to
compare identifiers according to their @emph{intended use} as free
references or bound identifiers in a given context.

@deffn Procedure {bound-identifier=?} @vari{id} @varii{id}
@vari{id} and @varii{id} must be identifiers.

The procedure @func{bound-identifier=?} returns @true{} if a binding for
one would capture a reference to the other in the output of the
transformer, assuming that the reference appears within the scope of the
binding, and @false{} otherwise.

In general, two identifiers are @func{bound-identifier=?} only if both
are present in the original program or both are introduced by the same
transformer application (perhaps implicitly, see @func{datum->syntax}).

The @func{bound-identifier=?} procedure can be used for detecting
duplicate identifiers in a binding construct or for other preprocessing
of a binding construct that requires detecting instances of the bound
identifiers.
@end deffn

@deffn Procedure {free-identifier=?} @vari{id} @varii{id}
@vari{id} and @varii{id} must be identifiers.

The @func{free-identifier=?} procedure returns @true{} if and only if
the two identifiers would resolve to the same binding if both were to
appear in the output of a transformer outside of any bindings inserted
by the transformer.  (If neither of two like--named identifiers resolves
to a binding, i.e., both are unbound, they are considered to resolve to
the same binding.)

Operationally, two identifiers are considered equivalent by
@func{free-identifier=?} if and only the topmost matching substitution
for each maps to the same binding or the identifiers have the same name
and no matching substitution.

The @func{syntax-case} and @func{syntax-rules} forms internally use
@func{free-identifier=?} to compare identifiers listed in the literals
list against input identifiers.

@example
(let ((fred 17))
  (define-syntax a
    (lambda (x)
      (syntax-case x ()
        ((_ id) #'(b id fred)))))
  (define-syntax b
    (lambda (x)
      (syntax-case x ()
        ((_ id1 id2)
         #`(list
             #,(free-identifier=? #'id1 #'id2)
             #,(bound-identifier=? #'id1 #'id2))))))
  (a fred))
    @result{} (#t #f)
@end example

The following definition of unnamed @func{let} uses
@func{bound-identifier=?} to detect duplicate identifiers.

@example
(define-syntax let
  (lambda (x)
    (define unique-ids?
      (lambda (ls)
        (or (null? ls)
            (and (let notmem? ((x (car ls)) (ls (cdr ls)))
                   (or (null? ls)
                       (and (not (bound-identifier=? x (car ls)))
                            (notmem? x (cdr ls)))))
                 (unique-ids? (cdr ls))))))
    (syntax-case x ()
      ((_ ((i v) ...) e1 e2 ...)
       (unique-ids? #'(i ...))
       #'((lambda (i ...) e1 e2 ...) v ...)))))
@end example

The argument @code{#'(i ...)} to @func{unique-ids?} is guaranteed to be
a list by the rules given in the description of @func{syntax} above.

With this definition of @func{let}:

@example
(let ((a 3) (a 4)) (+ a a))    @result{} @i{syntax error}
@end example

However,
@example
(let-syntax
  ((dolet (lambda (x)
            (syntax-case x ()
              ((_ b)
               #'(let ((a 3) (b 4)) (+ a b)))))))
  (dolet a))
@result{} 7
@end example

@noindent
since the identifier @code{a} introduced by @func{dolet} and the
identifier @code{a} extracted from the input form are not
@func{bound-identifier=?}.

Rather than including @code{else} in the literals list as before, this
version of @func{case} explicitly tests for @code{else} using
@func{free-identifier=?}.

@example
(define-syntax case
  (lambda (x)
    (syntax-case x ()
      ((_ e0 ((k ...) e1 e2 ...) ...
          (else-key else-e1 else-e2 ...))
       (and (identifier? #'else-key)
            (free-identifier=? #'else-key #'else))
       #'(let ((t e0))
           (cond
            ((memv t '(k ...)) e1 e2 ...)
            ...
            (else else-e1 else-e2 ...))))
      ((_ e0 ((ka ...) e1a e2a ...)
          ((kb ...) e1b e2b ...) ...)
       #'(let ((t e0))
           (cond
            ((memv t '(ka ...)) e1a e2a ...)
            ((memv t '(kb ...)) e1b e2b ...)
            ...))))))
@end example

With either definition of @func{case}, @code{else} is not recognized as
an auxiliary keyword if an enclosing lexical binding for @code{else}
exists.  For example,

@example
(let ((else @false{}))
  (case 0 (else (write "oops"))))    @result{} @i{syntax error}
@end example

@noindent
since @code{else} is bound lexically and is therefore not the same
@code{else} that appears in the definition of @func{case}.
@end deffn

@subsection Syntax-object and datum conversions

@deffn Procedure {syntax->datum} @var{syntax-object}
@deffnx {Deprecated procedure} {syntax-object->datum} @var{syntax-object}
Strip all syntactic information from a syntax object and returns the
corresponding Scheme datum.

Identifiers stripped in this manner are converted to their symbolic
names, which can then be compared with @func{eq?}.  Thus, a predicate
@code{symbolic-identifier=?} might be defined as follows.

@example
(define symbolic-identifier=?
  (lambda (x y)
    (eq? (syntax->datum x)
         (syntax->datum y))))
@end example
@end deffn

@deffn Procedure {datum->syntax} @var{template-id} @var{datum} [@var{srcloc}]
@deffnx {Deprecated procedure} {datum->syntax-object} @var{template-id} @var{datum}
@var{template-id} must be a template identifier and @var{datum} should
be a datum value.

The @func{datum->syntax} procedure returns a syntax-object
representation of @var{datum} that contains the same contextual
information as @var{template-id}, with the effect that the syntax object
behaves as if it were introduced into the code when @var{template-id}
was introduced.

If @var{srcloc} is specified (and neither @code{#f} or @code{#!null}),
it specifies the file position (including line number) for the result.
In that case it should be a syntax object representing
a list; otherwise it is currently ignored, though future extensions
may support other ways of specifying the position.

The @func{datum->syntax} procedure allows a transformer to ``bend''
lexical scoping rules by creating @emph{implicit identifiers} that
behave as if they were present in the input form, thus permitting the
definition of macros that introduce visible bindings for or references
to identifiers that do not appear explicitly in the input form.  For
example, the following defines a @func{loop} expression that uses this
controlled form of identifier capture to bind the variable @code{break}
to an escape procedure within the loop body.  (The derived
@func{with-syntax} form is like @func{let} but binds pattern variables.)

@example
(define-syntax loop
  (lambda (x)
    (syntax-case x ()
      ((k e ...)
       (with-syntax
           ((break (datum->syntax #'k 'break)))
         #'(call-with-current-continuation
             (lambda (break)
               (let f () e ... (f)))))))))

(let ((n 3) (ls '()))
  (loop
    (if (= n 0) (break ls))
    (set! ls (cons 'a ls))
    (set! n (- n 1))))
@result{} (a a a)
@end example

Were @code{loop} to be defined as:

@example
(define-syntax loop
  (lambda (x)
    (syntax-case x ()
      ((_ e ...)
       #'(call-with-current-continuation
           (lambda (break)
             (let f () e ... (f))))))))
@end example

@noindent
the variable @code{break} would not be visible in @code{e ...}.

The datum argument @var{datum} may also represent an arbitrary Scheme
form, as demonstrated by the following definition of @func{include}.

@example
(define-syntax include
  (lambda (x)
    (define read-file
      (lambda (fn k)
        (let ((p (open-file-input-port fn)))
          (let f ((x (get-datum p)))
            (if (eof-object? x)
                (begin (close-port p) '())
                (cons (datum->syntax k x)
                      (f (get-datum p))))))))
    (syntax-case x ()
      ((k filename)
       (let ((fn (syntax->datum #'filename)))
         (with-syntax (((exp ...)
                        (read-file fn #'k)))
           #'(begin exp ...)))))))
@end example

@code{(include "filename")} expands into a @func{begin} expression
containing the forms found in the file named by @code{"filename"}.  For
example, if the file @file{flib.ss} contains:

@example
(define f (lambda (x) (g (* x x))))
@end example

@noindent
and the file @file{glib.ss} contains:

@example
(define g (lambda (x) (+ x x)))
@end example

@noindent
the expression:

@example
(let ()
  (include "flib.ss")
  (include "glib.ss")
  (f 5))
@end example

@noindent
evaluates to @code{50}.

The definition of @func{include} uses @func{datum->syntax} to convert
the objects read from the file into syntax objects in the proper lexical
context, so that identifier references and definitions within those
expressions are scoped where the @func{include} form appears.

Using @func{datum->syntax}, it is even possible to break hygiene
entirely and write macros in the style of old Lisp macros.  The
@func{lisp-transformer} procedure defined below creates a transformer
that converts its input into a datum, calls the programmer's procedure
on this datum, and converts the result back into a syntax object scoped
where the original macro use appeared.

@example
(define lisp-transformer
  (lambda (p)
    (lambda (x)
      (syntax-case x ()
        ((kwd . rest)
         (datum->syntax #'kwd
           (p (syntax->datum x))))))))
@end example
@end deffn

@subsection Signaling errors in macro transformers

@deffn Syntax syntax-error message @arbno{args}
The @meta{message} and @meta{args} are treated similary as for
the @code{error} procedure.  However, the error is reported
when the @code{syntax-error} is expanded.
This can be used as a @code{syntax-rules}
template for a pattern that is an invalid use of the
macro, which can provide more descriptive error messages.
The @meta{message} should be a string literal, and the @var{args}
arbitrary (non-evalualted) expressions providing additional information.

@example
(define-syntax simple-let
  (syntax-rules ()
    ((_ (head ... ((x . y) val) . tail)
       body1 body2 ...)
     (syntax-error "expected an identifier but got" (x . y)))
    ((_ ((name val) ...) body1 body2 ...)
     ((lambda (name ...) body1 body2 ...)
      val ...))))
@end example
@end deffn

@deffn Procedure report-syntax-error location message
This is a procedure that can be called at macro-expansion time
by a syntax transformer function.
(In contrast @code{syntax-error} is a syntax form used in the
expansion result.)
The @var{message} is reported as a compile-time error message.
The @var{location} is used for the source location (file name and
line/column numbers): In general it can be a @code{SourceLocator} value;
most commonly it is a syntax object for a sub-list of the input form
that is erroneous.
The value returned by @code{report-syntax-error} is an
instance of @code{ErrorExp}, which supresses further compilation.

@example
(define-syntax if
  (lambda (x)
    (syntax-case x ()
                 ((_ test then)
                  (make-if-exp #'test #'then #!null))
                 ((_ test then else)
                  (make-if-exp #'test #'then #'else))
                 ((_ e1 e2 e3 . rest)
                  (report-syntax-error #'rest
                   "too many expressions for 'if'"))
                 ((_ . rest)
                  (report-syntax-error #'rest
                   "too few expressions for 'if'")))))
@end example
In the above example, one could use the source form @code{x} for the
location, but using @code{#'rest} is more accurate.  Note that the following
is incorrect, because @code{e1} might not be a pair, in which case
we don't have location information for it (due to a Kawa limitation):
@example
    (syntax-case x ()
                 ...
                 ((_ e1)
                  (report-syntax-error
                   #'e1 ;; @i{poor location specifier}
                   "too few expressions for 'if'")))))
@end example
@end deffn

@subsection Convenience forms

@deffn Syntax with-syntax ((@var{pattern} @stxref{expression}) @dots{}) @stxref{body}
The @func{with-syntax} form is used to bind pattern variables, just as
@func{let} is used to bind variables.  This allows a transformer to
construct its output in separate pieces, then put the pieces together.

Each @var{pattern} is identical in form to a @func{syntax-case}
pattern.  The value of each @var{expression} is computed and
destructured according to the corresponding @var{pattern}, and pattern
variables within the @var{pattern} are bound as with
@func{syntax-case} to the corresponding portions of the value within
@var{body}.

The @func{with-syntax} form may be defined in terms of
@func{syntax-case} as follows.

@example
(define-syntax with-syntax
  (lambda (x)
    (syntax-case x ()
      ((_ ((p e0) ...) e1 e2 ...)
       (syntax (syntax-case (list e0 ...) ()
                 ((p ...) (let () e1 e2 ...))))))))
@end example

The following definition of @func{cond} demonstrates the use of
@func{with-syntax} to support transformers that employ recursion
internally to construct their output.  It handles all @func{cond} clause
variations and takes care to produce one-armed @func{if} expressions
where appropriate.

@example
(define-syntax cond
  (lambda (x)
    (syntax-case x ()
      ((_ c1 c2 ...)
       (let f ((c1 #'c1) (c2* #'(c2 ...)))
         (syntax-case c2* ()
           (()
            (syntax-case c1 (else =>)
             (((else e1 e2 ...) #'(begin e1 e2 ...))
              ((e0) #'e0)
              ((e0 => e1)
               #'(let ((t e0)) (if t (e1 t))))
              ((e0 e1 e2 ...)
               #'(if e0 (begin e1 e2 ...)))))
           ((c2 c3 ...)
            (with-syntax ((rest (f #'c2 #'(c3 ...))))
              (syntax-case c1 (=>)
                ((e0) #'(let ((t e0)) (if t t rest)))
                ((e0 => e1)
                 #'(let ((t e0)) (if t (e1 t) rest)))
                ((e0 e1 e2 ...)
                 #'(if e0 
                        (begin e1 e2 ...)
                        rest)))))))))))
@end example
@end deffn

@deffn Syntax quasisyntax @var{template}
@deffnx {Auxiliary Syntax} unsyntax
@deffnx {Auxiliary Syntax} unsyntax-splicing
The @func{quasisyntax} form is similar to @func{syntax}, but it allows
parts of the quoted text to be evaluated, in a manner similar to the
operation of @func{quasiquote}.

Within a @func{quasisyntax} @var{template}, subforms of @func{unsyntax}
and @func{unsyntax-splicing} forms are evaluated, and everything else is
treated as ordinary template material, as with @func{syntax}.

The value of each @func{unsyntax} subform is inserted into the output in
place of the @func{unsyntax} form, while the value of each
@func{unsyntax-splicing} subform is spliced into the surrounding list or
vector structure.  Uses of @func{unsyntax} and @func{unsyntax-splicing}
are valid only within @func{quasisyntax} expressions.

A @func{quasisyntax} expression may be nested, with each
@func{quasisyntax} introducing a new level of syntax quotation and each
@func{unsyntax} or @func{unsyntax-splicing} taking away a level of
quotation.  An expression nested within @emph{n} @func{quasisyntax}
expressions must be within @emph{n} @emph{unsyntax} or
@func{unsyntax-splicing} expressions to be evaluated.

As noted in @stxref{abbreviation}, @code{#`@var{template}} is equivalent to
@code{(quasisyntax @var{template})}, @code{#,@var{template}} is
equivalent to @code{(unsyntax @var{template})}, and
@code{#,@@@var{template}} is equivalent to @code{(unsyntax-splicing
@var{template})}.  @emph{Note} that for backwards compatibility,
you should only use @code{#,@var{template}} inside a literal @code{#`@var{template}} form.

The @func{quasisyntax} keyword can be used in place of
@func{with-syntax} in many cases.  For example, the definition of
@func{case} shown under the description of @func{with-syntax} above can
be rewritten using @func{quasisyntax} as follows.

@example
(define-syntax case
  (lambda (x)
    (syntax-case x ()
      ((_ e c1 c2 ...)
       #`(let ((t e))
           #,(let f ((c1 #'c1) (cmore #'(c2 ...)))
               (if (null? cmore)
                   (syntax-case c1 (else)
                     ((else e1 e2 ...)
                      #'(begin e1 e2 ...))
                     (((k ...) e1 e2 ...)
                      #'(if (memv t '(k ...))
                            (begin e1 e2 ...))])
                   (syntax-case c1 ()
                     (((k ...) e1 e2 ...)
                      #`(if (memv t '(k ...))
                            (begin e1 e2 ...)
                            #,(f (car cmore)
                                  (cdr cmore))))))))))))
@end example
                          
@c ((Unknown if this works))
@c Uses of @func{unsyntax} and @func{unsyntax-splicing} with zero or more
@c than one subform are valid only in splicing (list or vector) contexts.
@c @code{(unsyntax @var{template} @dots{})} is equivalent to
@c @code{(unsyntax @var{template}) ...}, and @code{(unsyntax-splicing
@c @var{template} ...)} is equivalent to @code{(unsyntax-splicing
@c @var{template}) ...}.  These forms are primarily useful as intermediate
@c forms in the output of the @func{quasisyntax} expander.
@c 
@c @quotation
@c @emph{Note:} Uses of @func{unsyntax} and @func{unsyntax-splicing} with
@c zero or more than one subform enable certain idioms, such as
@c @code{#,@@#,@@}, which has the effect of a doubly indirect splicing when
@c used within a doubly nested and doubly evaluated @func{quasisyntax}
@c expression.
@c @end quotation
@end deffn

@quotation
@emph{Note:} Any @func{syntax-rules} form can be expressed with
@func{syntax-case} by making the @func{lambda} expression and
@func{syntax} expressions explicit, and @func{syntax-rules} may be
defined in terms of @func{syntax-case} as follows.

@example
(define-syntax syntax-rules
  (lambda (x)
    (syntax-case x ()
      ((_ (lit ...) ((k . p) t) ...)
       (for-all identifier? #'(lit ... k ...))
       #'(lambda (x)
           (syntax-case x (lit ...)
             ((_ . p) #'t) ...))))))
@end example
@end quotation

@node Named quasi-literals
@section Named quasi-literals

Traditional Scheme has only a few kinds of values,
and thus only a few builtin kinds of literals.
Modern Scheme allows defining new types,
so it is desirable to have a mechanism for defining literal values
for the new types.

Consider the @code{@ref{URI-type,,URI}} type.
You can create a new instance of a @code{URI} using a
constructor function:
@example
(URI "http://example.com/")
@end example
This isn't too bad, though the double-quote characters are an ugly distraction.
However, if you need to construct the string it gets messy:
@example
(URI (string-append base-uri "icon.png"))
@end example

Instead use can write:
@example
&URI@{http://example.com/@}
@end example
or:
@example
&URI@{&[base-uri]icon.png@}
@end example

This syntax is translated by the Scheme reader
to the more familiar but more verbose equivalent forms:
@example
($construct$:URI "http://example.com/")
($construct$:URI $<<$ base-uri $>>$ "icon.png")
@end example
So for this to work there just needs to be a definition
of @code{$construct$:URI}, usually a macro.
Normal scope rules apply; typically you'd define @code{$construct$:URI} in
a module.

The names @code{$<<$} and @code{$>>$} are bound to unique zero-length strings.
They are used to allow the implementation of @code{$construct$:URI}
to determine which arguments are literal and which come from
escaped expressions.

If you want to define your own @code{$construct$:@var{tag}},
or to read motivation and details, see the
@uref{http://srfi.schemers.org/srfi-108/srfi-108.html, SRFI 108} specification.

@display
@stxdef{extended-datum-literal}
    @stxlit{&} @stxref{cname} @stxlit{@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
  | @stxlit{&} @stxref{cname} @stxlit{[} @arbno{@stxref{expression}} @stxlit{]@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
@stxdef{cname} @stxref{identifier}
@stxdef{named-literal-part}
    @i{any character except} @stxlit{&}@i{,} @stxlit{@lbracechar{}} @i{or} @stxlit{@rbracechar{}}
  | @stxlit{@lbracechar{}} @atleastone{@stxref{named-literal-part}} @stxlit{@rbracechar{}}
  | @stxref{char-ref}
  | @stxref{entity-ref}
  | @stxref{special-escape}
  | @stxref{enclosed-part}
  | @stxref{extended-datum-literal}
@end display

@c FIXME May rename: Control structure
@node Program structure
@chapter Program structure

See @ref{program units} for some notes on
structure of an entire source file.

@menu
* Boolean values::
* Conditionals::
* Variables and Patterns::
* Definitions::
* Local binding constructs::
* Lazy evaluation::
* Threads::
* Exceptions::           Exception handling
@end menu

@node Boolean values
@section Boolean values

The standard boolean objects for true and false are written as @code{#t} and @code{#f}.
Alternatively, they may be written @code{#true} and @code{#false},
respectively.

@display
@stxdef{boolean} @stxlit{#t} | @stxlit{#f} | @stxlit{#true} | @stxlit{#false}
@end display

What really matters,
though, are the objects that the Scheme conditional expressions (@code{if},
@code{cond}, @code{and}, @code{or}, @code{when}, @code{unless}, @code{do})
treat as true or
false. The phrase ``a true value'' (or sometimes just ``true'')
means any object treated as true by the conditional expressions, and the phrase ``a false value'' (or ``false'') means any
object treated as false by the conditional expressions.

Of all the ``proper Scheme'' values, only @code{#f} counts as false in
conditional expressions. All other Scheme values, including @code{#t},
count as true.  A @var{test-expression} is an expression evaluated
in this manner for whether it is true or false.

In addition the null value @code{#!null} (in Java written as @code{null})
is also considered false.  Also, if you for some strange reason create a
fresh @code{java.lang.Boolean} object whose @code{booleanValue()}
returns @code{false}, that is also considered false.

@emph{Note:} Unlike some other dialects of Lisp, Scheme distinguishes
@code{#f} and the empty list from each other and from the symbol
@code{nil}.

Boolean constants evaluate to themselves, so they do not
need to be quoted in programs.

@example
#t       @result{}  #t
#true    @result{}  #t
#f       @result{}  #f
#false   @result{}  #f
'#f      @result{}  #f
@end example

@deffn Type boolean
The type of boolean values.
As a type conversion, a true value is converted to @code{#t},
while a false value is converted to @code{#f}.
Represented as a primitive Java @code{boolean}
or @code{kawa.lang.Boolean} when converted to an object.
@end deffn

@deffn Procedure boolean? obj
The @code{boolean?} predicate returns @code{#t} if @var{obj}
is either @code{#t} or @code{#f}, and returns @code{#f} otherwise.
@example
(boolean? #f)   @result{}  #t
(boolean? 0)    @result{}  #f
(boolean? '())  @result{}  #f
@end example
@end deffn

@deffn Procedure not obj
The @code{not} procedure returns @code{#t} if @var{obj} is false,
and returns @code{#f} otherwise.

@example
(not #t)         @result{}  #f
(not 3)          @result{}  #f
(not (list 3))   @result{}  #f
(not #f)         @result{}  #t
(not ’())        @result{}  #f
(not (list))     @result{}  #f
(not ’nil)       @result{}  #f
@end example
@end deffn

@deffn Procedure boolean=? boolean1 boolean2 boolean3 ...
Returns @code{#t} if all the arguments are booleans and all are @code{#t}
or all are @code{#f}.
@end deffn

@node Conditionals
@section Conditionals

@display
@stxdef{test-expression} @stxref{expression}
@stxdef{consequent} @stxref{expression}
@stxdef{alternate} @stxref{expression}
@end display

@deffn Syntax if @stxref{test-expression} @stxref{consequent} @stxref{alternate}
@deffnx Syntax if @stxref{test-expression} @stxref{consequent}

An @func{if} expression is evaluated as follows:
first, @meta{test-expression} is
evaluated.  If it yields a true value, then @meta{consequent} is
evaluated and its values are returned.  Otherwise @meta{alternate} is
evaluated and its values are returned.  If @meta{test} yields @false{}
and no @meta{alternate} is specified, then the result of the expression
is unspecified.

@example
(if (> 3 2) 'yes 'no)          @result{} yes
(if (> 2 3) 'yes 'no)          @result{} no
(if (> 3 2)
    (- 3 2)
    (+ 3 2))                   @result{} 1
(if #f #f)                     @result{} unspecified
@end example

The @meta{consequent} and @meta{alternate} expressions are in tail
context if the @func{if} expression itself is.
@end deffn

@deffn Syntax cond @atleastone{@stxref{cond-clause}}
@deffnx Syntax cond @arbno{@stxref{cond-clause}} @stxlit{(else} @meta{expression}@dots{}@stxlit{)} 

@display
@stxdef{cond-clause} @stxlit{(}@stxref{test-expression} @stxref{body}@stxlit{)}
    | @stxlit{(}@meta{test} @stxlit{=>} @meta{expression}@stxlit{)}
@end display

A @func{cond} expression is evaluated by evaluating the @meta{test-expression}s
of successive @meta{cond-clause}s in order until one of them
evaluates to a true value.  When a @meta{test-expression} evaluates to a true
value, then the remaining @meta{expression}s in its @meta{cond-clause}
are evaluated in order, and the results of the last @meta{expression} in
the @meta{cond-clause} are returned as the results of the entire
@func{cond} expression.
If the selected @meta{cond-clause} contains only the @meta{test-expression} and no
@meta{expression}s, then the value of the @meta{test-expression} is returned as the
result.  If the selected @meta{cond-clause} uses the @code{=>} alternate
form, then the @meta{expression} is evaluated.  Its value must be a
procedure.  This procedure should accept one argument; it is called on
the value of the @meta{test-expression} and the values returned by this procedure
are returned by the @func{cond} expression.

If all @meta{test-expression}s evaluate to @false{}, and there is no @code{else}
clause, then the conditional expression returns unspecified values; if
there is an @code{else} clause, then its @meta{expression}s are
evaluated, and the values of the last one are returned.

@example
(cond ((> 3 2) 'greater)
      ((< 3 2) 'less))         @result{} greater

(cond ((> 3 3) 'greater)
      ((< 3 3) 'less)
      (else 'equal))           @result{} equal

(cond ('(1 2 3) => cadr)
      (else #f))               @result{} 2
@end example

For a @meta{cond-clause} of one of the following forms:
@example
(@meta{test} @arbno{@stxref{expression}})
(else @stxref{expression} @arbno{@stxref{expression}})
@end example

@noindent
the last @meta{expression} is in tail context if the @func{cond} form
itself is.  For a @meta{cond clause} of the form:

@example
(@meta{test} => @meta{expression})
@end example

@noindent
the (implied) call to the procedure that results from the evaluation of
@meta{expression} is in tail context if the @func{cond} form itself
is.
@end deffn

@deffn Syntax case @stxref{case-key} @atleastone{@stxref{case-clause}}
@deffnx Syntax case @stxref{case-key} @arbno{@stxref{case-clause}} @stxref{case-else-clause} 

@display
@stxdef{case-key} @stxref{expression}
@stxdef{case-clause} @stxlit{((}@arbno{@stxref{datum}}@stxlit{)} @atleastone{@stxref{expression}}@stxlit{)}
    | @stxlit{((}@arbno{@stxref{datum}}@stxlit{)} @stxlit{=>} @stxref{expression}@stxlit{)}
@stxdef{case-else-clause} @stxlit{(else}  @atleastone{@stxref{expression}}@stxlit{)}
    | @stxlit{(else =>} @stxref{expression}@stxlit{)}
@end display

Each @meta{datum} is an external representation of some object.
Each @meta{datum} in the entire @code{case} expression should be distinct.

A @func{case} expression is evaluated as follows.

@enumerate
@item
The @meta{case-key} is evaluated and its result is compared using
@func{eqv?} against the data represented by the @meta{datum}s of
each @meta{case-clause} in turn, proceeding in order from left to
right through the set of clauses.

@item
If the result of evaluating @meta{case-key} is equivalent to a datum of a
@meta{case-clause}, the corresponding @meta{expression}s are evaluated
from left to right and the results of the last expression in the
@meta{case-clause} are returned as the results of the @func{case}
expression.  Otherwise, the comparison process continues.
@item
If the result of evaluating @meta{key} is different from every datum in
each set, then if there is an @meta{case-else-clause} its expressions are
evaluated and the results of the last are the results of the @func{case}
expression; otherwise the result of @func{case} expression is unspecified.
@end enumerate

If the selected @meta{case-clause} or @meta{case-else-clause}
uses the @code{=>} alternate
form, then the @meta{expression} is evaluated. It is an error if
its value is not a procedure accepting one argument. This
procedure is then called on the value of the @meta{key} and the
values returned by this procedure are returned by the @code{case}
expression.

@example
(case (* 2 3)
  ((2 3 5 7) 'prime)
  ((1 4 6 8 9) 'composite))    @result{} composite
(case (car '(c d))
  ((a) 'a)
  ((b) 'b))                    @result{} unspecified
(case (car '(c d))
  ((a e i o u) 'vowel)
  ((w y) 'semivowel)
  (else => (lambda (x) x)))    @result{} c
@end example

The last @meta{expression} of a @meta{case clause} is in tail context if
the @func{case} expression itself is.
@end deffn

@anchor{def-match}
@deffn Syntax match @stxref{match-key} @stxref{expression} @atleastone{@stxref{match-clause}}
The @code{match} form is a generalization of @code{case} using @stxref{pattern}s,
@display
@stxdef{match-key} @stxref{expression}
@stxdef{match-clause}
  @stxlit{(} @stxref{pattern} [@stxref{guard}] @stxref{body} @stxlit{)}
@end display
The @var{match-key} is evaluated,
Then the @var{match-clause}s are tried in order.
The first @var{match-clause} whose @var{pattern} matches (and
the @var{guard}, if any, is true), is selected,
and the corresponding @var{body} evaluated.
It is an error if no @var{match-clause} matches.
@example
(match value
  (0 (found-zero))
  (x #!if (> x 0) (found-positive x))
  (x #!if (< x 0) (found-negative x))
  (x::symbol (found-symbol x))
  (_ (found-other)))
@end example

One @code{case} feature is not (yet) directly supported by @code{match}:
Matching against a list of values.
However, this is easy to simulate using a guard using @code{memq},
@code{memv}, or @code{member}:
@example
;; compare similar example under case
(match (car '(c d))
  (x #!if (memv x '(a e i o u)) ’vowel)
  (x #!if (memv x '(w y)) ’semivowel)
  (x x))
@end example
@end deffn

@deffn Syntax and @stxref{test-expression} @dots{}

If there are no @meta{test-expression}s, @true{} is returned.  Otherwise, the
@meta{test-expression} are evaluated from left to right until a
@meta{test-expression} returns @false{} or the last @meta{test-expression} is reached.  In the
former case, the @func{and} expression returns @false{} without
evaluating the remaining expressions.  In the latter case, the last
expression is evaluated and its values are returned.

@example
(and (= 2 2) (> 2 1))          @result{}  #t
(and (= 2 2) (< 2 1))          @result{}  #f
(and 1 2 'c '(f g))            @result{}  (f g)
(and)                          @result{}  #t
@end example

The @func{and} keyword could be defined in terms of @func{if} using
@func{syntax-rules} as follows:

@example
(define-syntax and
  (syntax-rules ()
    ((and) #t)
    ((and test) test)
    ((and test1 test2 ...)
     (if test1 (and test2 ...) #t))))
@end example

The last @meta{test-expression} is in tail context if the @func{and}
expression itself is.
@end deffn

@deffn Syntax or @stxref{test-expression} @dots{}
If there are no @meta{test-expression}s, @false{} is returned.  Otherwise, the
@meta{test-expression}s are evaluated from left to right until a
@meta{test-expression} returns a true value @var{val} or the last
@meta{test-expression} is
reached.  In the former case, the @func{or} expression returns @var{val}
without evaluating the remaining expressions.  In the latter case, the
last expression is evaluated and its values are returned.

@example
(or (= 2 2) (> 2 1))           @result{} #t
(or (= 2 2) (< 2 1))           @result{} #t
(or #f #f #f)                  @result{} #f
(or '(b c) (/ 3 0))            @result{} (b c)
@end example

The @func{or} keyword could be defined in terms of @func{if} using
@func{syntax-rules} as follows:

@example
(define-syntax or
  (syntax-rules ()
    ((or) #f)
    ((or test) test)
    ((or test1 test2 ...)
     (let ((x test1))
       (if x x (or test2 ...))))))
@end example

The last @meta{test-expression} is in tail context if the @func{or}
expression itself is.
@end deffn


@deffn Syntax when @stxref{test-expression} form...
If @var{test-expression} is true, evaluate each @var{form} in order,
returning the value of the last one.
@end deffn

@deffn Syntax unless @stxref{test-expression} form...
If @var{test-expression} is false, evaluate each @var{form} in order,
returning the value of the last one.
@end deffn

@node Variables and Patterns
@section Variables and Patterns

An identifier can name either a type of syntax or a location
where a value can be stored. An identifier that names a
type of syntax is called a @dfn{syntactic keyword}
(informally called a @dfn{macro}), and is said to be
@dfn{bound} to a transformer for that syntax. An identifier that
names a location is called a @dfn{variable} and is said to be @dfn{bound}
to that location. The set of all visible bindings in effect at
some point in a program is known as the @dfn{environment} in
effect at that point. The value stored in the location to
which a variable is bound is called the variable’s value.
By abuse of terminology, the variable is sometimes said
to name the value or to be bound to the value. This is
not quite accurate, but confusion rarely results from this
practice.

Certain expression types are used to create new kinds of
syntax and to bind syntactic keywords to those new syntaxes,
while other expression types create new locations
and bind variables to those locations. These expression
types are called @dfn{binding constructs}.
Those that bind syntactic keywords are discussed in @ref{Macros}.
The most fundamental of the variable binding constructs is the
@ref{meta-lambda-expression,@code{lambda} expression},
because all other variable binding constructs
can be explained in terms of @code{lambda} expressions.
Other binding constructs include the @ref{Definitions,@code{define} family},
and the @ref{Local binding constructs,@code{let} family}.

Scheme is a language with block structure. To each place
where an identifier is bound in a program there corresponds
a @dfn{region} of the program text within which the binding is visible.
The region is determined by the particular binding construct that
establishes the binding; if the binding is
established by a @code{lambda} expression, for example, then its
region is the entire @code{lambda} expression. Every mention of
an identifier refers to the binding of the identifier that established
the innermost of the regions containing the use.

If there is no binding of the identifier whose region contains the use,
then the use refers to the binding for the
variable in the global environment, if any;
if there is no binding for the identifier, it is said to be @dfn{unbound}.

@subsection Patterns

The usual way to bind variables is to match an incoming
value against a @dfn{pattern}.  The pattern contains variables
that are bound to some value derived from the value.
@example
(! [x::double y::double] (some-expression))
@end example
In the above example, the pattern @code{[x::double y::double]}
is matched against the incoming value that results from
evaluating @code{(some-expression)}.
That value is required to be a two-element sequence.
Then the sub-pattern @code{x::double} is matched against
element 0 of the sequence, which means it is coerced to a @code{double}
and then the coerced value is matched against the sub-pattern @code{x}
(which trivially succeeds).  Similarly, @code{y::double} is matched
against element 1.

The syntax of patterns is a work-in-progress. (The focus until now
has been in designing and implementing how patterns work in general,
rather than the details of the pattern syntax.)

@display
@stxdef{pattern} @stxref{identifier}
  | @stxlit{_}
  | @stxref{pattern-literal}
  | @stxlit{'}@stxref{datum}
  | @stxref{pattern} @stxlit{::} @stxref{type}
  | @stxlit{[} @arbno{@stxref{lpattern}} @stxlit{]}
@stxdef{lpattern} @stxref{pattern}
  | @stxlit{@@} @stxref{pattern}
  | @stxref{pattern} @stxlit{...}
  | @stxref{guard}
@stxdef{pattern-literal}
    @stxref{boolean} | number | @stxref{character} | @stxref{string}
@stxdef{guard} @stxlit{#!if} @stxref{expression}
@end display

This is how the specific patterns work:

@table @asis
@item @stxref{identifier}
This is the simplest and most common form of pattern.
The @var{identifier} is bound to a new variable
that is initialized to the incoming value.

@item @stxlit{_}
This pattern just discards the incoming value.
It is equivalent to a unique otherwise-unused @var{identifier}.

@item @stxref{pattern-literal}
Matches if the value is @code{equal?} to the @var{pattern-literal}.

@item @stxlit{'}@stxref{datum}
Matches if the value is @code{equal?} to the quoted @var{datum}.

@item @stxref{pattern} @stxlit{::} @stxref{type}
The incoming value is coerced to a value of the specified @var{type},
and then the coerced value is matched against the sub-@var{pattern}.
Most commonly the sub-@var{pattern} is a plain @var{identifier},
so the latter match is trivial.

@item @stxlit{[} @arbno{@stxref{lpattern}} @stxlit{]}
The incoming value must be a sequence (a list, vector or similar).
In the case where each sub-pattern is a plain @var{pattern},
then the number of sub-patterns must match the size of the sequence, and
each sub-pattern is matched against the corresponding element of the sequence.
More generally, each sub-pattern may match zero or more consequtive
elements of the incoming sequence.

@item @stxlit{#!if} @stxref{expression}
No incoming value is used.  Instead the @var{expression} is evaluated.
If the result is true, matching succeeds (so far);
otherwise the match fails.
This form is called a @uref{https://en.wikipedia.org/wiki/Guard_(computer_science),@dfn{guard}}.
@end table

@node Definitions
@section Definitions

A variable definition binds one or more identifiers and specifies
an initial value for each of them. The simplest kind of
variable definition takes one of the following forms:

@deffn Syntax ! @stxref{pattern} @stxref{expression}
Evaluate @stxref{expression}, and match the result against @var{pattern}.
Defining variables in @stxref{pattern} becomes bound in the
current (surrounding) scope.

This is similar to @code{define-constant} except generalized to a @var{pattern}.
@end deffn

@deffn Syntax define name [@stxlit{::} @stxref{type}] @stxref{expression}
Evaluate the @var{expression}, optionally converting it to @var{type},
and bind the @var{name} to the result.
@end deffn

@deffn Syntax define (name @stxref{formal-arguments}) @arbno{(@stxref{annotation} | @stxref{option-pair})} @stxref{opt-return-type} @stxref{body}
@deffnx Syntax define (name @stxlit{.} @stxref{rest-arg}) @arbno{(@stxref{annotation} | @stxref{option-pair})} @stxref{opt-return-type} @stxref{body}

Bind the @var{name} to a function definition.  The form:
@example
(define (@var{name} @stxref{formal-arguments}) @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body})
@end example
is equivalent to:
@example
(define @var{name} (lambda @stxref{formal-arguments}) name: @var{name} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}))
@end example
while the form:
@example
(define (@var{name} . @stxref{rest-arg}) @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body})
@end example
is equivalent to:
@example
(define @var{name} (lambda @stxref{rest-arg}) name: @var{name} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}))
@end example

You can associate @ref{Annotations,annotations} with @var{name}.
A field annotation will be associated with the generated field;
a method annotation will be associated with the generated method(s).
@end deffn

In addition to @code{define} (which can take an optional type specifier),
Kawa has some extra definition forms.

@deffn Syntax define-private name [@stxlit{::} @stxref{type}] value
@deffnx Syntax define-private (name formals) body
Same as @code{define}, except that @code{name} is not exported.
@end deffn

@deffn Syntax define-constant name [@stxlit{::} @stxref{type}] value
@deffnx Syntax define-early-constant name [:: type] value
Defines @var{name} to have the given @var{value}.
The value is readonly, and you cannot assign to it.
(This is not fully enforced.)

If @code{define-early-constant} is used
@emph{or} the @var{value} is a compile-time constant,
then the compiler will create a @code{final} field with
the given name and type, and evaluate @var{value}
in the module's class initializer (if the definition
is static) or constructor (if the definition is non-static),
before other definitions and expressions.
Otherwise, the @var{value} is evaluated in the module body
where it appears.

If the @var{value} is a compile-time constant,
then the definition defaults to being static.
@end deffn

@deffn Syntax define-variable name [@stxlit{::} @stxref{type}] [init]
If @var{init} is specified and @var{name} does not have a global variable
binding, then @var{init} is evaluated, and @var{name} bound to the result.
Otherwise, the value bound to @var{name} does not change.
(Note that @var{init} is not evaluated
if @var{name} does have a global variable binding.)

Also, declares to the compiler that @var{name} will be looked up
in the per-thread dynamic environment. This can be useful for shutting up
warnings from @code{--warn-undefined-variable}.

This is similar to the Common Lisp @code{defvar} form.
However, the Kawa version is (currently) only allowed at module level.
@end deffn

For @code{define-namespace} and @code{define-private-namespace}
see @ref{Namespaces}.

@node Local binding constructs
@section Local binding constructs

The binding constructs @code{let}, @code{let*}, @code{letrec},
and @code{letrec*} give Scheme a block structure, like Algol 60.
The syntax of these four constructs
is identical, but they differ in the regions they establish
for their variable bindings. In a @code{let} expression, the initial
values are computed before any of the variables become
bound; in a @code{let*} expression, the bindings and evaluations
are performed sequentially; while in @code{letrec} and @code{letrec*}
expressions, all the bindings are in effect while their initial
values are being computed, thus allowing mutually recursive definitions.
@c The let-values and let*-values con-
@c structs are analogous to let and let* respectively, but
@c are designed to handle multiple-valued expressions, bind-
@c ing different identifiers to the returned values.

@deffn Syntax let @stxlit{((}@stxref{pattern} @var{init}@stxlit{)} ...@stxlit{)} @stxref{body}
Declare new local variables as found in the @meta{pattern}s.
Each @var{pattern} is matched against the corresponding @var{init}.
The @var{init}s are evaluated in the current environment (in left-to-right
onder), the @var{variable}s in the @var{patterns}s are bound to fresh
locations holding the matched results,
the @var{body} is evaluated in the extended environment, and the values of
the last expression of body are returned.
Each binding of a variable has @var{body} as its region.

@example
(let ((x 2) (y 3))
  (* x y)) @result{} 6
@end example

@example
(let ((x 2) (y 3))
  (let ((x 7)
        (z (+ x y)))
    (* z x)))   @result{} 35
@end example

An example with a non-trivial pattern:

@example
(let (([a::double b::integer] (vector 4 5)))
  (cons b a))  @result{} (5 . 4.0)
@end example
@end deffn

@deffn Syntax let* @stxlit{((}@stxref{pattern} init@stxlit{)} ...@stxlit{)} @stxref{body}

The @code{let*} binding construct is similar to @code{let},
but the bindings are performed sequentially from left to
right, and the region of a @var{variable}s in a @var{pattern}
is that part of the @code{let*} expression to the right of
the @var{pattern}. Thus the second pattern is matched in an environment
in which the bindings from the first pattern are visible, and so on.

@example
(let ((x 2) (y 3))
  (let* ((x 7)
         (z (+ x y)))
    (* z x)))  @result{} 70
@end example
@end deffn

@deffn Syntax letrec @stxlit{((}variable [@stxlit{::} @stxref{type}] init@stxlit{)} ...@stxlit{)} @stxref{body}
@deffnx Syntax letrec* @stxlit{((}variable [@stxlit{::} @stxref{type}] init@stxlit{)} ...@stxlit{)} @stxref{body}
The @var{variable}s are bound to fresh locations,
each @var{variable} is assigned in left-to-right order
to the result of the corresponding @var{init},
the @var{body} is evaluated in the resulting environment,
and the values of the last expression in body are returned.
Despite the left-to-right evaluation and assignment order, each binding of a
@var{variable} has the entire @code{letrec} or @code{letrec*}
expression as its region,
making it possible to define mutually recursive procedures.

In Kawa @code{letrec} is defined as the same as @code{letrec*}.
In standard Scheme the order of evaluation of the @var{init}s
is undefined, as is the order of assignments.
If the order matters, you should use @code{letrec*}.

If it is not possible to evaluate each @var{init} without assigning
or referring to the value of the corresponding @var{variable}
or the variables that follow it, it is an error.
@example
(letrec ((even?
          (lambda (n)
            (if (zero? n)
                #t
                (odd? (- n 1)))))
         (odd?
          (lambda (n)
            (if (zero? n)
                #f
                (even? (- n 1))))))
  (even? 88))
     @result{} #t
@end example
@end deffn

@node Lazy evaluation
@section Lazy evaluation

@dfn{Lazy evaluation} (or call-by-need) delays evaluating an expression until it
is actually needed; when it is evaluated, the result is saved so
repeated evaluation is not needed.
@uref{http://en.wikipedia.org/wiki/Lazy_evaluation,Lazy evaluation}
is a technique that can make some algorithms easier to express compactly
or much more efficiently, or both.  It is the normal evaluation mechanism
for strict functional (side-effect-free) languages such as
@uref{http://www.haskell.org,Haskell}.
However, automatic lazy evaluation is awkward to combine with side-effects
such as input-output.  It can also be difficult to implement
lazy evaluation efficiently, as it requires more book-keeping.

Kawa, like other Schemes, uses ``eager evaluation'' - an expression
is normally evaluated immediately, unless it is wrapped in a special form.
Standard Scheme has some basic building blocks for ``manual''
lazy evaluation, using an explicit @code{delay} operator to
indicate that an expression is to be evaluated lazily,
yielding a @dfn{promise},
and a @code{force} function to force evaluation of a promise.
This functionality is enhanced in
@uref{http://srfi.schemers.org/srfi-45/srfi-45.html, SRFI 45},
in R7RS-draft (based on SRFI 45),
and @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41} (lazy lists aka streams).

Kawa makes lazy evaluation easier to use, by @dfn{implicit forcing}:
The promise is automatically evaluated (forced) when used in a
context that requires a normal value, such as arithmetic needing a number.
Kawa enhances lazy evaluation in other ways, including
support for safe multi-threaded programming.

@subsection Delayed evaluation

@deffn Syntax delay @stxref{expression}
The @code{delay} construct is used together with the procedure
@code{force} to implement @emph{lazy evaluation} or @emph{call by need}.

The result of @code{(delay @var{expression})} is a
@emph{promise} which at some point in the future may be asked (by the
@func{force} procedure) to evaluate @var{expression}, and deliver the
resulting value.  The effect of @var{expression} returning multiple
values is unspecified.
@end deffn

@deffn Syntax delay-force @stxref{expression}
@deffnx Syntax lazy @stxref{expression}
The @code{delay-force} construct is similar to @code{delay}, but it is expected
that its argument evaluates to a promise.
(Kawa treats a non-promise value as if it were a forced promise.)
The returned
promise, when forced, will evaluate to whatever the original
promise would have evaluated to if it had been forced.

The expression @code{(delay-force @meta{expression})} is
conceptually similar to @code{(delay (force @meta{expression}))}, with
the difference that forcing the result of @code{delay-force} will
in effect result in a tail call to @code{(force @meta{expression})}, while
forcing the result of @code{(delay (force @meta{expression}))} might
not. Thus iterative lazy algorithms that might result in a
long series of chains of @code{delay} and @code{force} can be rewritten
using delay-force to prevent consuming unbounded space
during evaluation.

Using @code{delay-force} or @code{lazy} is equivalent.
The name @code{delay-force} is from R7RS; the name @code{lazy}
is from the older SRFI-45.
@end deffn

@deffn Procedure eager obj
Returns a promise that when forced will return @var{obj}.
It is similar to @code{delay}, but does not delay its argument;
it is a procedure rather than syntax.

The Kawa implementation just returns @var{obj} as-is.
This is because Kawa treats as equivalent
a value and forced promise evaluating to the value.
@end deffn

@deffn Procedure force promise
The @func{force} procedure forces the value of @var{promise}.
As a Kawa extension, if the @var{promise} is not a promise (a value that
does not implement @code{gnu.mapping.Lazy}) then the argument is returned unchanged.
If no value has been computed for the promise, then a value is computed and
returned.  The value of the promise is cached (or ``memoized'') so that
if it is forced a second time, the previously computed value is
returned.
@example
(force (delay (+ 1 2)))                @result{}  3

(let ((p (delay (+ 1 2))))
  (list (force p) (force p)))          @result{}  (3 3)

(define integers
  (letrec ((next
            (lambda (n)
              (cons n (delay (next (+ n 1)))))))
    (next 0)))
(define head 
  (lambda (stream) (car (force stream)))) 
(define tail 
  (lambda (stream) (cdr (force stream)))) 

(head (tail (tail integers)))          @result{}  2
@end example

The following example is a mechanical transformation of
a lazy stream-filtering algorithm into Scheme. Each call
to a constructor is wrapped in @code{delay}, and each argument
passed to a deconstructor is wrapped in @code{force}. The use
of @code{(lazy ...)} instead of @code{(delay (force ...))} around
the body of the procedure ensures that an ever-growing
sequence of pending promises does not exhaust the heap.

@example
(define (stream-filter p? s)
  (lazy
   (if (null? (force s))
       (delay ’())
       (let ((h (car (force s)))
             (t (cdr (force s))))
         (if (p? h)
             (delay (cons h (stream-filter p? t)))
             (stream-filter p? t))))))

(head (tail (tail (stream-filter odd? integers))))
    @result{} 5
@end example

@end deffn

@deffn Procedure force* promise
Does @code{force} as many times as necessary to produce a non-promise.
(A non-promise is a value that does not implement @code{gnu.mapping.Lazy},
or if it does implement @code{gnu.mapping.Lazy} then forcing the value
using the @code{getValue} method yields the receiver.)

The @code{force*} function is a Kawa extension.
Kawa will add implicit calls to @code{force*}
in most contexts that need it, but you can also call it explicitly.
@end deffn

The following examples are not intended to illustrate good
programming style, as @code{delay}, @code{lazy}, and @code{force} are mainly
intended for programs written in the functional style.
However, they do illustrate the property that only one value is
computed for a promise, no matter how many times it is
forced.

@example
(define count 0)
(define p
  (delay (begin (set! count (+ count 1))
                (if (> count x)
                    count
                    (force p)))))
(define x 5)
p                  @result{} @emph{a promise}
(force p)          @result{} 6
p                  @result{} @emph{a promise, still}
(begin (set! x 10)
       (force p))  @result{} 6
@end example                                                                                                                                                                   

@subsection Implicit forcing

If you pass a promise as an argument to a function like @code{sqrt}
if must first be forced to a number.  In general, Kawa does this
automatically (implicitly) as needed, depending on the context.
For example:
@example
(+ (delay (* 3 7)) 13)   @result{} 34
@end example

Other functions,
like @code{cons} have no problems with promises, and automatic forcing
would be undesirable.

Generally, implicit forcing happens for arguments that require a
specific type, and does not happen for arguments that work on
@emph{any} type (or @code{Object}).

Implicit forcing happens for:
@itemize
@item
arguments to arithmetic functions;
@item
the sequence and the index in indexing operations, like @code{string-ref};
@item
the operands to @code{eqv?} and @code{equal?} are forced,
though the operands to @code{eq?} are not;
@item
port operands to port functions;
@item
the value to be emitted by a @code{display} but @emph{not} the
value to be emitted by a @code{write};
@item
the function in an application.
@end itemize

Type membership tests, such as the @code{instance?} operation,
generally do not force their values.

The exact behavior for when implicit forcing happens is a work-in-progress:
There are certainly places where implicit forcing doesn't happen while
it should; there are also likely to be places where implicit forcing
happens while it is undesirable.

Most Scheme implementations are such that a forced promise behaves differently
from its forced value, but some Scheme implementions are such that there is no
means by which a promise can be operationally distinguished
from its forced value.
Kawa is a hybrid: Kawa tries to minimize the difference between
a forced promise and its forced value, and may freely optimize
and replace a forced promise with its value.

@subsection Blank promises

A @dfn{blank promise} is a promise that doesn't (yet) have
a value @emph{or} a rule for calculating the value.
Forcing a blank promise will wait forever, until some
other thread makes the promise non-blank.

Blank promises are useful as a synchronization mechanism -
you can use it to safely pass data from one thread (the producer)
to another thread (the consumer).  Note that you can only
pass one value for a given promise: To pass multiple values, you
need multiple promises.

@example
(define p (promise))
(future ;; Consumer thread
  (begin
    (do-stuff)
    (define v (force promise)) ; waits until promise-set-value!
    (do-stuff-with v)))
;; Producer thread
... do stuff ...
(promise-set-value! p (calculate-value))
@end example

@deffn Constructor promise
Calling @code{promise} as a zero-argument constructor
creates a new blank promise.

This calls the constructor for @code{gnu.mapping.Promise}.
You can also create a non-blank promise, by setting one
of the @code{value}, @code{alias}, @code{thunk}, or @code{exception} properties.
Doing so is equivalent to calling @code{promise-set-value!},
@code{promise-set-alias!}, @code{promise-set-thunk!}, or
@code{promise-set-exception!} on the resulting promise.
For example: @code{(delay exp)} is equivalent to:
@example
(promise thunk: (lambda() exp))
@end example
@end deffn

The following four procedures require that their first arguments
be blank promises.  When the procedure returns, the promise is
no longer blank, and cannot be changed.  This is because a
promise is conceptually a placeholder for a single ``not-yet-known'' value;
it is not a location that can be assigned multiple times.
The former enables clean and safe (``declarative") use of multiple threads;
the latter is much trickier.

@deffn Procedure promise-set-value! promise value
Sets the value of the @var{promise} to @var{value},
which makes the @var{promise} forced.
@end deffn

@deffn Procedure promise-set-exception! promise exception
Associate @var{exception} with the @var{promise}.
When the @var{promise} is forced the @var{exception} gets thrown.
@end deffn

@deffn Procedure promise-set-alias! promise other
Bind the @var{promise} to be an alias of @var{other}.
Forcing @var{promise} will cause @var{other} to be forced.
@end deffn

@deffn Procedure promise-set-thunk! promise thunk
Associate @var{thunk} (a zero-argument procedure) with the @var{promise}.
The first time the @var{promise} is forced will causes the
@var{thunk} to be called, with the result (a value or an exception)
saved for future calls.
@end deffn

@deffn Procedure make-promise obj
The @code{make-promise} procedure returns a promise which,
when forced, will return @var{obj}. It is similar to @code{delay}, but
does not delay its argument: it is a procedure rather than
syntax. If @var{obj} is already a promise, it is returned.

Because of Kawa's implicit forcing, there is seldom a
need to use @code{make-promise}, except for portability.
@end deffn

@subsection Lazy and eager types

@deffn Type promise[T]
This parameterized type is the type of promises that evaluate to
an value of type @code{T}.
It is equivalent to the Java interface @code{gnu.mapping.Lazy<T>}.
The implementation class for promises is usually @code{gnu.mapping.Promise},
though there are other classes that implement @code{Lazy},
most notably @code{gnu.mapping.Future}, used for futures,
which are promises evaluated in a separate thread.
@end deffn

Note the distinction between the types @code{integer}
(the type of actual (eager) integer values), and @code{promise[integer]}
(the type of (lazy) promises that evaluate to integer).
The two are compatible: if a @code{promise[integer]} value is provided
in a context requiring an @code{integer} then it is automatically
evaluated (forced).  If an @code{integer} value is provided
in context requiring a @code{promise[integer]}, that conversion is basically
a no-op (though the compiler may wrap the @code{integer}
in a pre-forced promise).

In a fully-lazy language there would be no distinction, or
at least the promise type would be the default.  However, Kawa is
a mostly-eager language, so the eager type is the default.
This makes efficient code-generation easier: If an expression
has an eager type, then the compiler can generate code that
works on its values directly, without having to check for laziness.

@node Threads
@section Threads

There is a very preliminary interface to create parallel threads.
The interface is similar to the standard @code{delay}/@code{force},
where a thread is basically the same as a promise, except that
evaluation may be in parallel.

@deffn Syntax future expression
Creates a new thread that evaluates @var{expression}.

(The result extends @code{java.lang.Thread} and
implements @code{gnu.mapping.Lazy}.)
@end deffn

@deffn Procedure force thread
The standard @code{force} function is generalized to also work
on threads.  It waits for the thread's @var{expression} to finish
executing, and returns the result.
@end deffn

@deffn Procedure runnable function
Creates a new @code{Runnable} instance from a function.
Useful for passing to Java code that expects a @code{Runnable}.
You can get the result (a value or a thrown exception) using the
@code{getResult} method.
@end deffn

@deffn Syntax synchronized object form ...
Synchronize on the given @var{object}.  (This means getting an
exclusive lock on the object, by acquiring its @dfn{monitor}.)
Then execute the @var{form}s while holding the lock.
When the @var{form}s finish (normally or abnormally by throwing
an exception), the lock is released.
Returns the result of the last @var{form}.
Equivalent to the Java @code{synchronized} statement,
except that it may return a result.
@end deffn

@node Exceptions
@section Exception handling
An @dfn{exception} is an object used to signal an error or
other exceptional situation.  The program or run-time system
can @dfn{throw} the exception when an error is discovered.
An exception handler is a program construct that registers
an action to handle exceptions when the handler is active.

If an exception is thrown and not handled then the
read-eval-print-loop will print a stack trace, and bring
you back to the top level prompt.
When not running interactively, an unhandled exception
will normally cause Kawa to be exited.

In the Scheme exception model (as of R6RS and R7RS),
exception handlers are one-argument procedures that determine
the action the program takes when an exceptional situation is signaled.
The system implicitly maintains a
current exception handler in the dynamic environment.
The program raises an exception by invoking the current
exception handler, passing it an object encapsulating information
about the exception. Any procedure accepting
one argument can serve as an exception handler and any
object can be used to represent an exception.

The Scheme exception model is implemented on top of the Java VM's
native exception model where the only objects that
can be thrown are instances of @code{java.lang.Throwable}.
Kawa also provides direct access to this native model,
as well as older Scheme exception models.

@deffn Procedure with-exception-handler handler thunk
It is an error if @var{handler} does not accept one argument.
It is also an error if @var{thunk} does not accept zero arguments.
The @code{with-exception-handler} procedure returns the results
of invoking @var{thunk}. The @var{handler} is installed as the current
exception handler in the dynamic environment used for the
invocation of @var{thunk}.

@example
(call-with-current-continuation
  (lambda (k)
   (with-exception-handler
    (lambda (x)
     (display "condition: ")
     (write x)
     (newline)
     (k 'exception))
    (lambda ()
     (+ 1 (raise ’an-error))))))
       @result{} exception
       @i{and prints} condition: an-error
@end example

@example
(with-exception-handler
 (lambda (x)
  (display "something went wrong\n"))
 (lambda ()
  (+ 1 (raise ’an-error))))
    @i{prints} something went wrong
@end example

After printing, the second example then raises another exception.

@PerformanceNote{} The @var{thunk} is inlined if it is a
lambda expression.  However, the @var{handler} cannot be inlined
even if it is a lambda expression, because it could be called by
@code{raise-continuable}.  Using the @code{guard} form is
usually more efficient.
@end deffn

@deffn Procedure raise obj
Raises an exception by invoking the current exception handler on @var{obj}.
The handler is called with the same dynamic
environment as that of the call to raise, except that the
current exception handler is the one that was in place when
the handler being called was installed. If the handler returns,
then @var{obj} is re-raised in the same dynamic environment as the handler.

If @var{obj} is an instance of @code{java.lang.Throwable},
then @code{raise} has the same effect as @code{primitive-throw}.
@end deffn

@deffn Procedure raise-continuable obj
Raises an exception by invoking the current exception handler on @var{obj}.
The handler is called with the same dynamic
environment as the call to @code{raise-continuable}, except
that: (1) the current exception handler is the one that was
in place when the handler being called was installed, and
(2) if the handler being called returns, then it will again
become the current exception handler.
If the handler returns, the values it returns become the values
returned by the call to @code{raise-continuable}.

@example
(with-exception-handler
  (lambda (con)
    (cond
      ((string? con)
       (display con))
      (else
       (display "a warning has been issued")))
    42)
  (lambda ()
    (+ (raise-continuable "should be a number")
       23)))
      @i{prints:} should be a number
      @result{} 65
@end example
@end deffn

@deffn Syntax guard @var{variable} @atleastone{@stxref{cond-clause}} @stxref{body}
The @meta{body} is evaluated with an exception handler that binds
the raised object to @var{variable} and, within the scope of that binding,
evaluates the clauses as if they were the clauses of a @code{cond} expression.
That implicit @code{cond} expression is evaluated with
the continuation and dynamic environment of the @code{guard}
expression. If every cond-clause’s test evaluates to @code{#f}
and there is no @code{else} clause, then @code{raise-continuable} is
invoked on the raised object within the dynamic environment of the
original call to @code{raise} or @code{raise-continuable},
except that the current exception handler is that of the
@code{guard} expression.

@example
(guard (condition
         ((assq 'a condition) => cdr)
         ((assq 'b condition)))
  (raise (list (cons 'a 42))))
      @result{} 42
@end example

@example
(guard (condition
         ((assq 'a condition) => cdr)
         ((assq 'b condition)))
  (raise (list (cons 'b 23))))
      @result{} (b . 23)
@end example

@PerformanceNote{} Using @code{guard} is moderately efficient:
there is some overhead compared to using native exception handling,
but both the @var{body} and the handlers in the @var{cond-clause}
are inlined.
@end deffn

@deffn Procedure dynamic-wind in-guard thunk out-guard
All three arguments must be 0-argument procedures.
First calls @var{in-guard}, then @var{thunk}, then @var{out-guard}.
The result of the expression is that of @var{thunk}.
If @var{thunk} is exited abnormally (by throwing an exception or
invoking a continuation), @var{out-guard} is called.

If the continuation of the dynamic-wind is re-entered (which
is not yet possible in Kawa), the @var{in-guard} is called again.

This function was added in R5RS.
@end deffn

@deffn Procedure read-error? obj
Returns #t if @var{obj} is an object raised by the @code{read} procedure.
(That is if @var{obj} is a @code{gnu.text.SyntaxException}.)

@end deffn
@deffn Procedure file-error? obj
Returns #t if @var{obj} is an object raised by inability to open an input
or output port on a file.
(This includes @code{java.io.FileNotFoundException} as well
as certain other exceptions.)
@end deffn

@subsection Simple error objects

@deffn Procedure error message obj ...
Raises an exception as if by calling @code{raise}
on a newly allocated @dfn{simple error object},
which encapsulates the information provided by @var{message}
(which should a string), as well as any @var{obj} arguments,
known as the irritants.

The string representation of a simple error object is as if calling
@code{(format "#<ERROR ~a~@{ ~w~@}>" @var{message} @var{irritants})}.
(That is the @var{message} is formatted as if with @code{display}
while each irritant @var{obj} is formatted as if with @code{write}.)

This procedure is part of SRFI-23, and R7RS.
It differs from (and is incompatible with) R6RS's @code{error} procedure.
@end deffn

@deffn Procedure error-object? obj
Returns @code{#t} if @var{obj} is a simple error object.
Specifically, that @var{obj} is an instance of @code{kawa.lang.NamedException}.
Otherwise, it returns @code{#f}.
@end deffn

@deffn Procedure error-object-message error-object
Returns the message encapsulated by error-object,
which must be a simple error object.
@end deffn

@deffn Procedure error-object-irritants error-object
Returns a list of the irritants (other arguments)
encapsulated by error-object, which must be a simple error object.
@end deffn

@subsection Named exceptions

These functions associate a symbol with exceptions
and handlers: A handler catches an exception if the symbol matches.

@deffn Procedure catch key thunk 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:

@example
(handler key args ...)
@end example

@var{key} may be a symbol.  The @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}.
@end deffn

@deffn Procedure throw key arg ...
Invoke the catch form matching @var{key}, passing the @var{arg}s to the
current @var{handler}.  

If the key is a symbol it will match catches of the same
symbol or of @code{#t}.

If there is no handler at all, an error is signaled.
@end deffn

@subsection Native exception handling

@deffn Procedure primitive-throw exception
Throws the @var{exception}, which must be an instance of a sub-class
of @code{java.lang.Throwable}.
@end deffn

@deffn Syntax try-finally body handler
Evaluate @var{body}, and return its result.
However, before it returns, evaluate @var{handler}.
Even if @var{body} returns abnormally (by throwing an exception),
@var{handler} is evaluated.

(This is implemented just like Java's @code{try}-@code{finally}.
However, the current implementation does not duplicate the @var{handler}.)
@end deffn

@deffn Syntax try-catch body handler ...
Evaluate @var{body}, in the context of the given @var{handler} specifications.
Each @var{handler} has the form:
@example
@var{var} @var{type} @var{exp} ...
@end example
If an exception is thrown in @var{body}, the first @var{handler}
is selected such that the thrown exception is an instance of
the @var{handler}'s @var{type}. If no @var{handler} is selected,
the exception is propagated through the dynamic execution context
until a matching @var{handler} is found.  (If no matching @var{handler}
is found, then an error message is printed, and the computation terminated.)

Once a @var{handler} is selected,
the @var{var} is bound to the thrown exception, and the @var{exp} in
the @var{handler} are executed.  The result of the @code{try-catch}
is the result of @var{body} if no exception is thrown, or the
value of the last @var{exp} in the selected @var{handler} if an
exception is thrown.

(This is implemented just like Java's @code{try}-@code{catch}.)
@end deffn

@node Control features
@chapter Control features

@menu
* Mapping functions::
* Multiple values::
@end menu

@node Mapping functions
@section Mapping functions

The procedures @code{string-for-each} and @code{string-map}
are documented under @ref{Strings}.

The procedure @code{string-cursor-for-each} is documented under @ref{String Cursor API}.

@deffn Procedure map @var{proc} sequence@sub{1} sequence@sub{2} ...
@deffnx Procedure for-each @var{proc} sequence@sub{1} sequence@sub{2} ...
The @code{map} procedure applies @var{proc} element-wise to the elements
of the @var{sequence}s and returns a list of the results, in order.
The dynamic order in which @var{proc} is applied to
the elements of the @var{sequence}s is unspecified.

The @code{for-each} procedure does the same,
but is executed for the side-effects of @var{proc}, whose result (if any)
is discarded.
Unlike @code{map}, @code{for-each} is guaranteed to call @var{proc}
on the elements of the @var{sequences}s in order from the first element(s)
to the last.
The value returned by @code{for-each} is the void value.

Each @var{sequence} must be a generalized sequence.
(Traditionally, these arguments were restricted to lists,
but Kawa allows sequences, including vectors, Java arrays, and strings.)
If more than one @var{sequence} is given and not all
@var{sequence}s have the same length, the procedure terminates when the
shortest @var{sequence} runs out.
The @var{sequence}s can be infinite (for example circular lists),
but it is an error if all of them are infinite.

The @var{proc} must be a procedure that accepts as many arguments
as there are @var{sequence} arguments.
It is an error for @var{proc} to mutate any of the @var{sequence}s.
In the case of @code{map}, @var{proc} must return a single value.

@example
(map cadr '((a b) (d e) (g h)))
    @result{} (b e h)

(map (lambda (n) (expt n n))
     '(1 2 3 4 5))
    @result{} (1 4 27 256 3125)

(map + ’(1 2 3) ’(4 5 6 7))  @result{} (5 7 9)

(let ((count 0))
  (map (lambda (ignored)
         (set! count (+ count 1))
         count)
       '(a b)))
    @result{} (1 2) @i{or} (2 1)
@end example

The result of @code{map} is a list, even if the arguments are non-lists:
@example
(map +
     #(3 4 5)
     (float[] 0.5 1.5))
    @result{} (3.5 5.5)
@end example

To get a vector result, use @code{vector-map}.

@example
(let ((v (make-vector 5)))
  (for-each (lambda (i)
              (vector-set! v i (* i i)))
            '(0 1 2 3 4))
  v)
    @result{}  #(0 1 4 9 16)
@end example

A string is considered a sequence of @code{character} values
(not 16-bit @code{char} values):

@example
(let ((v (make-vector 10 #\-)))
  (for-each (lambda (i ch)
              (vector-set! v i ch))
            [0 <: ]
            "Smile 😃!")
   v)
    @result{} #(#\S #\m #\i #\l #\e #\space #\x1f603 #\! #\- #\-)
@end example

@PerformanceNote{} These procedures are pretty well optimized.
For each @var{sequence} the compiler will by default create an
iterator.
@c FUTURE (This can be done without object allocation XXXX)
However, if the type of the @var{sequence} is known, the compiler will
inline the iteration code.
@end deffn

@deffn Procedure vector-map @var{proc} @vari{sequence} @varii{sequence} @dots{}
Same as the @code{map} procedure, except the result is a vector.
(Traditionally, these arguments were restricted to vectors,
but Kawa allows sequences, including lists, Java arrays, and strings.)

@example
(vector-map cadr '#((a b) (d e) (g h)))
    @result{} #(b e h)

(vector-map (lambda (n) (expt n n))
            '#(1 2 3 4 5))
    @result{} #(1 4 27 256 3125)

(vector-map + '#(1 2 3) ’#(4 5 6 7))
    @result{} #(5 7 9)

(let ((count 0))
  (vector-map
    (lambda (ignored)
      (set! count (+ count 1))
      count)
    '#(a b)))
    @result{} #(1 2) @i{or} #(2 1)
@end example
@end deffn

@deffn Procedure vector-for-each @var{proc} @vari{vector} @varii{vector} @dots{}
Mostly the same as @code{for-each},
however the arguments should be generalized vectors.
Specifically, they should implement @code{java.util.List}
(which both regular vectors and uniform vectors do).
The @var{vectors} should also be efficiently indexable.

(Traditionally, these arguments were restricted to vectors,
but Kawa allows sequences, including lists, Java arrays, and strings.)

@example
(let ((v (make-list 5)))
  (vector-for-each
    (lambda (i) (list-set! v i (* i i)))
    '#(0 1 2 3 4))
  v)
    @result{} (0 1 4 9 16)
@end example
@end deffn

@node Multiple values
@section Multiple values

The multiple-value feature was added in R5RS.

@deffn Procedure values object ...
Delivers all of its arguments to its continuation.
@end deffn

@deffn Procedure call-with-values producer consumer
Calls its @var{producer} argument with no arguments and a
continuation that, when passed some values, calls the
@var{consumer} procedure with those values as arguments.

@example
(call-with-values (lambda () (values 4 5))
                  (lambda (a b) b))
                         @result{} 5

(call-with-values * -)   @result{} -1
@end example

@PerformanceNote{} If either the @var{producer} or @var{consumer} is a
fixed-arity lambda expression, it is inlined.
@end deffn

@deffn Syntax define-values @stxref{formals} @stxref{expression}
It is an error if a variable appears more than once in the
set of @meta{formals}.

The @meta{expression} is evaluated, and the @meta{formals}
are bound to the return values in the same way that the @meta{formals} in
a @code{lambda} expression are matched to the arguments in a procedure call.

@example
(define-values (x y) (integer-sqrt 17))
(list x y)    @result{} (4 1)
(let ()
  (define-values (x y) (values 1 2))
  (+ x y))
              @result{}  3
@end example
@end deffn

@deffn Syntax let-values @stxlit{((}@stxref{formals} @stxref{expression}@stxlit{)} ...@stxlit{)} @stxref{body}
Each @var{formals} should be a formal arguments list, as for a @code{lambda}.

The @var{expression}s are evaluated in the current environment, the
variables of the @var{formals} are bound to fresh locations, the return
values of the @var{expression}s are stored in the variables, the
@var{body} is evaluated in the extended environment, and the values of
the last expression of @var{body} are returned. The @var{body} is a
"tail body", cf section 3.5 of the R5RS.

The matching of each @var{formals} to values is as for the matching of
@var{formals} to arguments in a @code{lambda} expression, and it is an
error for an @var{expression} to return a number of values that does not
match its corresponding @var{formals}.
@example
(let-values (((a b . c) (values 1 2 3 4)))
  (list a b c))            @result{} (1 2 (3 4)) 

(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let-values (((a b) (values x y))
               ((x y) (values a b)))
    (list a b x y)))       @result{} (x y a b)
@end example
@end deffn

@deffn Syntax let*-values @stxlit{((}@stxref{formals} @stxref{expression}@stxlit{)} ...@stxlit{)} @stxref{body}

Each @var{formals} should be a formal arguments list as for a
@code{lambda} expression.

@code{let*-values} is similar to @code{let-values}, but the bindings are
performed sequentially from left to right, and the region of a binding
indicated by (@var{formals} @var{expression}) is that part of the
@code{let*-values} expression to the right of the binding. Thus the
second binding is done in an environment in which the first binding is
visible, and so on.
@example
(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let*-values (((a b) (values x y))
                ((x y) (values a b)))
    (list a b x y)))       @result{} (x y x y)
@end example
@end deffn

@deffn Syntax receive @stxref{formals} @stxref{expression} @stxref{body}
This convenience
form (from @uref{http://srfi.schemers.org/srfi-8/srfi-8.html, SRFI-8})
is equivalent to:
@example
(let-values ((@var{formals} @var{expression})) @var{body})
@end example
For example:
@example
(receive a (values 1 2 3 4)
  (reverse a)) @result{} (4 3 2 1)

(receive (a b . c) (values 1 2 3 4)
  (list a b c))            @result{} (1 2 (3 4)) 

(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (receive (a b) (values x y)
    (receive (x y) (values a b)
      (list a b x y))))    @result{} (x y x y)
@end example
@end deffn

@deffn Procedure values-append arg1 ...
The values resulting from evaluating each argument are appended
together.
@end deffn

@node Symbols and namespaces
@chapter Symbols and namespaces

An identifier is a name that appears in a program.

A symbol is an object representing a string that cannot be
modified. This string is called the symbol's name. Unlike strings, two
symbols whose names are spelled the same way are indistinguishable.
A symbol is immutable (unmodifiable) and normally viewed as atomic.
Symbols are useful for many applications; for instance, they may be
used the way enumerated values are used in other languages.

In addition to the simple symbols of standard Scheme, Kawa
also has compound (two-part) symbols.

@menu
* Simple symbols::
* Namespaces::
* Keywords::
* Special named constants::
@end menu

@node Simple symbols, Namespaces, , Symbols and namespaces
@section Simple symbols

Simple symbols have no properties other than their name, an immutable string.
They have the useful property that two simple symbols
are identical (in the sense of @func{eq?}, @func{eqv?} and
@func{equal?}) if and only if their names are spelled the same way.  A
symbol literal is formed using @func{quote}.

@deffn Procedure {symbol?} @var{obj}
Return @true{} if @var{obj} is a symbol, @false{} otherwise.

@example
(symbol? 'foo)          @result{} #t
(symbol? (car '(a b)))  @result{} #t
(symbol? "bar")         @result{} #f
(symbol? 'nil)          @result{} #t
(symbol? '())           @result{} #f
(symbol? #f)            @result{} #f
@end example
@end deffn

@deffn Procedure {symbol->string} @var{symbol}
Return the name of @var{symbol} as an immutable string.

@example
(symbol->string 'flying-fish)                   @result{}  "flying-fish"
(symbol->string 'Martin)                        @result{}  "Martin"
(symbol->string (string->symbol "Malvina"))     @result{}  "Malvina"
@end example
@end deffn

@deffn Procedure {string->symbol} @var{string}
Return the symbol whose name is @var{string}.

@example
(eq? 'mISSISSIppi 'mississippi)
@result{} #f

(string->symbol "mISSISSIppi")
@result{} the symbol with name "mISSISSIppi"

(eq? 'bitBlt (string->symbol "bitBlt"))
@result{} #t

(eq? 'JollyWog (string->symbol (symbol->string 'JollyWog)))
@result{} #t

(string=? "K. Harper, M.D."
          (symbol->string (string->symbol "K. Harper, M.D.")))
@result{} #t
@end example
@end deffn

@node Namespaces, Keywords, Simple symbols, Symbols and namespaces
@section Namespaces and compound symbols

Different applications may want to use the same symbol
to mean different things.  To avoid such @dfn{name clashes}
we can use @dfn{compound symbols}, which have two string parts:
a @dfn{local name} and a @dfn{namespace URI}.
The namespace-uri can be any string, but it is
recommended that it have the form of an absolute
@uref{http://en.wikipedia.org/wiki/Uniform_Resource_Identifier,URI}.
It would be too verbose to write the full URI all the
time, so one usually uses a @dfn{namespace prefix}
(namespace alias) as a short local alias to refer to a
namespace URI.

Compound symbols are usually written using the infix colon operator:
@example
@var{prefix}@stxlit{:}@var{local-name}
@end example
where @var{prefix} is a namespace alias bound
to some (lexically-known) namespace URI.

Compound symbols are used for namespace-aware XML processing.

@subsection Namespace objects

A @dfn{namespace} is a mapping from strings to symbols.
The string is the local-name of the resulting symbol.
A namespace is similar to a Common Lisp @dfn{package}.

A namespace has a namespace-uri, which a string;
it is recommended that it have the form of an absolute URI.
A namespace may optionally have a prefix, which is a string used
when printing out symbols belonging to the namespace.
(If you want ``equivalent symbols'' (i.e. those that have the same
local-name and same uri) to be the identical symbol object, then
you should use namespaces whose prefix is the empty string.)

@deffn Constructor namespace name [prefix]
Return a namespace with the given @var{name} and @var{prefix}.
If no such namespace exists, create it.
The @var{namespace-name} is commonly a URI, especially when working with XML,
in which case it is called a @var{namespace-uri}.  However, any non-empty
string is allowed.
The prefix can be a string or a simple symbol.
(If a symbol is used, then the symbol's local-name is used.)
The default for @var{prefix} is the empty string.
Multiple calls with the same arguments will yield the same namespace object.
@end deffn

The reader macro @code{#,namespace} is equivalent to the
@code{namespace} function, but it is invoked at read-time:
@example
#,(namespace "http://www.w3.org/1999/XSL/Transform" xsl)
(eq? #,(namespace "foo") (namespace "foo")) @result{} #t
@end example

The form @code{(,#namespace "" "")} returns the default @dfn{empty namespace},
which is used for simple symbols.

@deffn Procedure namespace-uri namespace
Return the namespace-uri of the argument @var{namespace}, as a string.
@end deffn

@deffn Procedure namespace-prefix namespace
Return the namespace prefix of the argument @var{namespace}, as a string.
@end deffn

@subsection Compound symbols

A compound symbol is one that belongs to a namespace other than the
default empty namespace, and (normally) has a non-empty namespace uri.
(It is possible for a symbol to belong to a non-default namespace
and have an empty namespace uri, but that is not recommended.)

@deffn Constructor symbol local-name namespace-spec
@deffnx Constructor symbol local-name [uri [prefix]]
Construct a symbol with the given @var{local-name} and namespace.
If @var{namespace-spec} is a namespace object, then find (or, if needed,
construct) a symbol with the given @var{local-name} belonging to the
namespace.  Multiple calls to @code{symbol} with the same namespace
and @var{local-name} will yield the same symbol object.

If uri is a string (optionally followed by a prefix),
then:
@example
(symbol lname uri [prefix])
@end example
is equivalent to:
@example
(symbol lname (namespace uri [prefix]))
@end example

Using @code{#t} for the @var{namespace-spec} is equivalent to
using the empty namespace @code{#,(namespace "")}.

Using @code{#!null} or @code{#f} for the @var{namespace-spec}
creates an @var{uninterned} symbol, which does not belong to
any namespace.
@end deffn

@deffn Procedure symbol-local-name symbol
Return the local name of the argument symbol, as an immutable string.
(The string is interned, except in the case of an uninterned symbol.)
@end deffn

@deffn Procedure symbol-prefix symbol
Return the prefix of the argument symbol, as an immutable
(and interned) string.
@end deffn

@deffn Procedure symbol-namespace-uri symbol
Return the namespace uri of the argument symbol, as an immutable
(and interned) string.
@end deffn

@deffn Procedure symbol-namespace symbol
Return the namespace object (if any) of the argument symbol.
Returns @code{#!null} if the symbol is uninterned.
@end deffn

@deffn Procedure {symbol=?} @vari{symbol} @varii{symbol} @variii{symbol} @dots{}
Return @true{} if the symbols are equivalent as symbols,
i.e., if their local-names and namespace-uris are the same.
They may have different values of @code{symbol-prefix} and @code{symbol-namespace}.
If a symbol is uninterned (or is @code{#!null}) then @code{symbol=?}
returns the same result as @code{eq?}.
@end deffn

Two symbols are @code{equal?} or @code{eqv?} if they're @code{symbol=?}.

@subsection Namespace aliases

A namespace is usually referenced using a shorter @dfn{namespace alias},
which is is a lexical definition that binds a namespace prefix
to a namespace object (and thus a namespace uri).
This allows using compound symbols as identifiers in Scheme programs.

@deffn Syntax define-namespace name namespace-name
Defines @var{name} as a @dfn{namespace prefix} - a lexically scoped
"nickname" for the namespace
whose full name is @var{namespace-name}, which should be a non-empty
string literal.
It is customary for the string have syntactic form of
an absolute @uref{http://en.wikipedia.org/wiki/Uniform_Resource_Identifier,URI},
but any non-empty string is acceptable and is used without
further interpretation.

Any symbols in the scope of this definitions that contain a colon, and
where the part before the colon matches the @var{name} will be
treated as being in the package/namespace whose global unique name
is the @var{namespace-name}.

Has mostly the same effect as:
@example
(define-constant @var{name} #,(namespace @var{namespace-name})
@end example

However, using @code{define-namespace} (rather than @code{define-constant})
is recommended if you want to use compound symbols as names of
variables, especially local variables, or if you want to quote
compound symbols.

Note that the prefix is only visible lexically: it is not
part of the namespace, or thus indirectly the symbols, and
so is not available when printing the symbol.
You might consider using @code{define-xml-namespace} as an alternative.

A namespace is similar to a Common Lisp package,
and the @var{namespace-name} is like the name of the package.
However, a namespace alias belongs to the lexical scope,
while a Common Lisp package nickname is global
and belongs to the package itself.

If the namespace-name starts with the string @code{"class:"}, then the
@var{name} can be used for invoking Java methods
(@pxref{Method operations}) and accessing fields (@pxref{Field operations}).

You can use a namespace as an abbreviation or renaming of a
class name, but as a matter of style @code{define-alias} is preferred.
@end deffn

@deffn Syntax define-private-namespace name namespace-name
Same as @code{define-namespace}, but the prefix @var{name}
is local to the current module.
@end deffn

For example, you might have a set of a geometry definitions
defined under the namespace-uri @code{"http://foo.org/lib/geometry"}:

@example
(define-namespace geom "http://foo.org/lib/geometry")
(define (geom:translate x y)
  (java.awt.geom.AffineTransform:getTranslateInstance x y))
(define geom:zero (geom:translate 0 0))
geom:zero
  @result{} AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
@end example

You could have some other definitions for complex math:
@example
(define-namespace complex "http://foo.org/lib/math/complex")
(define complex:zero +0+0i)
@end example

You can use a namespace-value directly in a compound name:
@example
(namespace "http://foo.org/lib/geometry"):zero
  @result{} AffineTransform[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
@end example

The variation @code{define-xml-namespace} is used for @ref{Creating XML nodes}.

@deffn Syntax define-xml-namespace prefix "namespace-uri"
Defines a namespace with prefix @var{prefix} and URI @var{namespace-uri}.
This is similar to @code{define-namespace} but with two important differences:
@itemize
@item
Every symbol in the namespace automatically maps to
an element-constructor-type, as with  the @code{html} namespace.
@item
The @var{prefix} is a component of the namespace object, and
hence indirectly of any symbols belongining to the namespace.
@end itemize

Thus the definition is roughly equivalent to:
@example
(define-constant @var{name} #,(namespace @var{namespace-name name})
@end example
along with an infinite set of definitions, for every possible @var{tag}:
@example
(define (name:@var{tag} . rest) (apply make-element 'name:@var{tag} rest))
@end example

@end deffn

@example
$ kawa --output-format xml
#|kawa:1|# @kbd{(define-xml-namespace na "Namespace1")}
#|kawa:2|# @kbd{(define-xml-namespace nb "Namespace1")}
#|kawa:3|# @kbd{(define xa (na:em "Info"))}
#|kawa:4|# @kbd{xa}
<na:em xmlns:na="Namespace1">Info</na:em>
#|kawa:5|# @kbd{(define xb (nb:em "Info"))}
#|kawa:6|# @kbd{xa}
<nb:em xmlns:nb="Namespace1">Info</nb:em>
@end example

Note that the prefix is part of the qualified name
(it is actually part of the namespace object),
and it is used when printing the tag.
Two qualified names (symbols) that have the same
local-name and the same namespace-name are considered
equal, even if they have different prefix.  You can think of
the prefix as annotation used when printing, but not
otherwise part of the ``meaning'' of a compound symbol.
They are the same object if they also have the same prefix.
This is an important difference from traditional Lisp/Scheme symbols,
but it is how XML QNames work.
@example
#|kawa:7|# (instance? xb na:em)
true
#|kawa:8|# (eq? 'na:em 'nb:em)
false
#|kawa:9|# (equal? 'na:em 'nb:em)
true
#|kawa:10|# (eqv? 'na:em 'nb:em)
true
@end example
(Note that @code{#t} is printed as @code{true} when using XML formatting.)

The predefined @code{html} prefix could be defined thus:
@example
(define-xml-namespace html "http://www.w3.org/1999/xhtml")
@end example

@node Keywords, Special named constants, Namespaces, Symbols and namespaces
@section Keywords

Keywords are similar to symbols.
They are used mainly for specifying keyword arguments.

Historically keywords have been self-evaluating (you did not need to
quote them).  This has changed: you must quote a keyword if you
want a literal keyword value, and not quote it if it is used
as a keyword argument.

@display
@stxdef{keyword} @stxref{identifier}@stxlit{:}
  | @stxlit{#:}@stxref{identifier}
@end display

The two syntaxes have the same meaning: The former is nicer-looking;
the latter is more portable (and required if you use the
@code{--r7rs} command-line flag).

@quotation
@emph{Details:}
In r7rs and other Scheme standards the colon character
does not have any special meaning, so @code{foo:} or @code{foo:bar}
are just regular identifiers.  Therefore some other Scheme variants
that have keywords (including Guile and Racket) use the @code{#:} syntax.
Kawa has some hacks so that @emph{most}
standard Scheme programs that have colons in identifiers will work.
However, for best compatibility, use the @code{--r7rs} command-line flag
(which turns colon into a regular character in a symbol), and the
@code{#:} syntax.
@end quotation

A keyword is a single token; therefore no whitespace is allowed between
the @var{identifier} and the colon or after the @code{#:};
these characters are not considered part of the name of the keyword.

@deffn Procedure keyword? obj
Return @code{#t} if @var{obj} is a keyword, and otherwise returns @code{#f}.
@end deffn

@deffn Procedure keyword->string keyword
Returns the name of @var{keyword} as a string.
The name does not include the final @code{#\:}.
@end deffn

@deffn Procedure string->keyword string
Returns the keyword whose name is @var{string}.
(The @var{string} does not include a final @code{#\:}.)
@end deffn

@node Special named constants, , Keywords, Symbols and namespaces
@section Special named constants

@defvr Constant #!optional
Special self-evaluating literal used in lambda parameter lists
before optional parameters.
@end defvr

@defvr Constant #!rest
Special self-evaluating literal used in lambda parameter lists
before the rest parameter.
@end defvr

@defvr Constant #!key
Special self-evaluating literal used in lambda parameter lists
before keyword parameters.
@end defvr

@defvr Constant #!eof
The end-of-file object.

Note that if the Scheme reader sees this literal at top-level,
it is returned literally.  This is indistinguishable from
coming to the end of the input file.  If you do not want to end reading,
but want the actual value of @code{#!eof}, you should quote it.
@end defvr

@defvr Constant #!void
The void value.  Same as @code{(values)}.
If this is the value of an expression in a read-eval-print loop,
nothing is printed.
@end defvr

@defvr Constant #!null
The Java @code{null} value.  This is not really a Scheme value,
but is useful when interfacing to low-level Java code.
@end defvr

@node Procedures, Numbers, Symbols and namespaces, Top
@chapter Procedures

@menu
* Application and Arguments Lists::
* Procedure properties::
* Generic procedures::
* Extended formals::
* Partial application::
@end menu

@node Application and Arguments Lists
@section Application and Arguments Lists

When a procedure is called, the actual argument expression are evaluated,
and the resulting values becomes the actual argument list.
This is then matched against the formal parameter list
(in the procedure definition), and assuming they match,
the procedure body is called.

@subsection Arguments lists

An argument list has three parts:
@itemize @bullet
@item
Zero or more @dfn{prefix arguments}, each of which is a value.
These typically get bound to named required or optional formal parameters,
but can also get bound to patterns.
@item
Zero or more @dfn{keyword arguments}, each of which is a keyword
(an identifier specified with keyword syntax) combined with a value.
These are bound to either named keyword formal parameters, or
bundled in with a rest parameter.
@item
Zero or more @dfn{postfix arguments}, each of which is a value.
These are usually bound to a ``rest'' formal parameter, which
receives any remaining arguments.

If there are no keyword arguments, then it ambiguous where
prefix arguments and and where postfix arguments start.
This is normally not a problem: the called procedure can
split them up however it wishes.
@end itemize

Note that all keyword arguments have to be grouped together:
It is not allowed to have a keyword argument followed by a plain
argument followed by a keyword argument.

The argument list is constructed by evaluating the each @stxref{operand}
of the @stxref{procedure-call} in order:
@table @asis
@item @var{expression}
The @var{expression} is evaluated, yielding a single value
that becomes a prefix or postfix argument.
@item @var{keyword} @var{expression}
The @var{expression} is evaluated.  The resulting value combined
with the @var{keyword} becomes a keyword argument.
@item @stxlit{@@}@var{expression}
The @var{expression} is evaluated.
The result must be a sequence - a list, vector, or primitive array.
The values of the sequence are appended to the resulting argument list.
Keyword arguments are not allowed.
@item @stxlit{@@:}@var{expression}
The @var{expression} is evaluted.
The result can be a sequence;
a hash table (viewed as a collection of (keyword,value) pairs);
or an @dfn{explicit argument list} object, which is a sequence of values
@emph{or} keyword arguments.
The values and keyword arguments
are appended to the resulting argument list, though subject to the restriction
that keyword arguments must be adjacent in the resulting argument list.
@end table

@subsection Explicit argument list objects

Sometimes it is useful to create an argument list out of
pieces, take argument lists apart, iterate over them,
and generally treat an argument list as an actual first-class value.

Explicit argument list objects can take multiple forms.
The simplest is a sequence: a list, vector, or primitive array.
Each element of the list becomes a value in the resulting argument list.

@example
(define v1 '(a b c))
(define v2 (int[] 10 11 12 13))
(list "X" @@v1 "Y" @@v2 "Z")
  @result{} ("X" a b c "Y" 10 11 12 13 "Z")
@end example

Things get more complicated once keywords are involved.
An explicit argument list with keywords is only allowed
when using the @code{@@:} splicing form,
not the @code{@@} form.  It can be either
a hash table (anything the implement @code{java.util.Map}
or the types @code{arglist} or @code{argvector}.

@quotation
@emph{Design note:} An argument list with keywords is straightforward
in Common Lisp and some Scheme implementations (including order versions of
Kawa): It's just a list some of whose @code{car} cells are keyword objects.
The problem with this model is neither a human or the compiler can
reliably tell when an argument is a keyword, since any variable
might have been assigned a keyword.  This limits performance and
error checking.
@end quotation

A hash table (anything the implement @code{java.util.Map})
whose keys are strings or keyword objects is
interpreted as a sequence of keyword arguments,
using the hash-table keys and values.

@deffn Type argvector
@deffnx Constructor argvector @arbno{@stxref{operand}}
List of arguments represented as an immutable vector.
A keyword argument takes two elements in this vector:
A keyword object, followed by the value.

@example
(define v1 (argvector 1 2 k1: 10 k2: 11 98 99))
(v1 4) @result{} 'k2
(v1 5) @result{} 11
@end example
When @code{v1} is viewed as a vector it
is equivalent to @code{(vector 1 2 'k1: 10 'k2: 11 98 99)}.
(Note in this case the keywords need to be quoted, since
the @code{vector} constructor does not take keyword arguments.)
However, the @code{argvector} ``knows'' which arguments
are actually keyword arguments, and can be examined using the
@code{(kawa arglist)} library discussed below:

@example
(arglist-key-count (argvector 1 x: 2 3)) @result{} 1
(arglist-key-count (argvector 1 'x: 2 3)) @result{} 0
(arglist-key-count (vector 1 'x: 2 3)) @result{} 0
@end example

In this case:
@example
(fun 'a @@:v1)
@end example
is equivalent to:
@example
(fun 'a 1 2 k1: 10 k2: 11 98 99)
@end example
@end deffn

@deffn Type arglist
@deffnx Constructor arglist @arbno{@stxref{operand}}
Similar to @code{argvector}, but compatible with @code{list}.
If there are no keyword arguments, returns a plain list.
If there is at least one keyword argument creates a special
@code{gnu.mapping.ArgListPair} object that implements the
usual @code{list} properties but internally wraps a @code{argvector}.
@end deffn

@subsection Argument list library

@example
(import (kawa arglist))
@end example

In the following, @var{args} is an @code{arglist} or @code{argvector}
(or in general any object that implement @code{gnu.mapping.ArgList}).
Also, @var{args} can be a generalized list, in which case it
behaves like an @code{argvector} that has no keyword arguments.

@deffn Procedure arglist-walk args proc
Call @var{proc} once, in order, for each argument in @var{args}.
The @var{proc} is called with two arguments,
corresponding to @code{(arglist-key-ref @var{args} @var{i})}
and @code{(arglist-arg-ref @var{args} @var{i})} for each @var{i} from 0
up to @code{(arglist-arg-count @var{args})} (exclusive).
I.e. the first argument is either @code{#!null} or the keyword (as a string);
the second argument is the corresponding argument value.

@example
(define (print-arguments args #!optional (out (current-output-port)))
  (arglist-walk args
                (lambda (key value)
                  (if key (format out "key: ~a value: ~w~%" key value)
                      (format out "value: ~w~%" value)))))
@end example
@end deffn

@deffn Procedure arglist-key-count args
Return the number of keyword arguments.
@end deffn

@deffn Procedure arglist-key-start args
Number of prefix arguments, which is the number of arguments before
the first keyword argument.
@end deffn

@deffn Procedure arglist-arg-count args
Return the number of non-keyword arguments.
(The count includes neither the keywords nor the corresponding values.)
@end deffn

@deffn Procedure arglist-arg-ref args index
Get the @var{index}'th argument value.
The @var{index} counts keyword argument values, but not the keywords themselves.
@example
(arglist-arg-ref (arglist 10 11 k1: -1 19) 2) @result{} -1
(arglist-arg-ref (arglist 10 11 k1: -1 19) 3) @result{} 19
@end example
@end deffn

@deffn Procedure arglist-key-ref args index
The @var{index} counts arguments like @code{arglist-arg-ref} does.
If this is a keyword argument, return the corresponding keyword
(as a string); otherwise, return @code{#!null} (which counts are false).
@example
(arglist-key-ref (argvector 10 11 k1: -1 k2: -2 19) 3) @result{} "k2"
(arglist-key-ref (argvector 10 11 k1: -1 k2: -2 19) 4) @result{} #!null
@end example
@end deffn

@deffn Procedure arglist-key-index args key
Search for a keyword matching @var{key} (which must be an interned string).
If there is no such keyword, return -1.
Otherwise return the keyword's index as as argument to @code{arglist-key-ref}.
@end deffn

@deffn Procedure arglist-key-value args key default
Search for a keyword matching @var{key} (which must be an interned string).
If there is no such keyword, return the @var{default}.
Otherwise return the corresponding keyword argument's value.
@end deffn

@subsection Apply procedures

@deffn Procedure apply proc @arbno{argi} argrest
@var{Argrest} must be a sequence (list, vector, or string) or a
primitive Java array.
(This is an extension over standard Scheme, which requires that
@var{args} be a list.)
Calls the @var{proc} (which must be a procedure), using as arguments
the @var{argi}... values plus all the elements of @var{argrest}.

Equivalent to: @code{(}@var{proc} @arbno{@var{argi}} @code{@@}@var{argrest}@code{)}.
@end deffn

@deffn Syntax constant-fold proc arg1 ...
Same as @code{(@var{proc} @var{arg1} ...)}, unless @var{proc} and
all the following arguments are compile-time constants.
(That is:  They are either constant, or symbols that have a global
binding and no lexical binding.)  In that case, @var{proc}
is applied to the arguments at compile-time, and the result replaces
the @code{constant-fold} form.  If the application raises an exception,
a compile-time error is reported.
For example:
@example
(constant-fold vector 'a 'b 'c)
@end example
is equivalent to @code{(quote #(a b c))}, assuming @code{vector}
has not been re-bound.
@end deffn

@node Procedure properties, Generic procedures, , Procedures
@section Procedure properties

You can associate arbitrary @dfn{properties} with any procedure.
Each property is a (@var{key}, @var{value})-pair.  Usually the
@var{key} is a symbol, but it can be any object.

The system uses certain internal properties:
@code{'name} refers to the name used when a procedure is printed;
@code{'emacs-interactive} is used to implement Emacs @code{interactive}
specification;
@code{'setter} is used to associate a @code{setter} procedure.

@deffn Procedure procedure-property proc key [default]
Get the property value corresponding to the given @var{key}.
If @var{proc} has no property with the given @var{key},
return @var{default} (which defaults to @code{#f}) instead.
@end deffn

@deffn Procedure set-procedure-property! proc key value
Associate the given @var{value} with the @var{key} property of @var{proc}.
@end deffn

To change the print name of the standard @code{+} procedure (probably
not a good idea!), you could do:
@example
(set-procedure-property! + 'name 'PLUS)
@end example
Note this @emph{only} changes the name property used for printing:
@example
+ @result{} #<procedure PLUS>
(+ 2 3) @result{} 5
(PLUS 3 4) @result{} ERROR
@end example

As a matter of style, it is cleaner to use the @code{define-procedure}
form, as it is a more declarative interface.

@deffn Syntax define-procedure name [propname: propvalue] ... method ...
Defines @var{name} as a compound procedure consisting of the
specified @var{method}s, with the associated properties.
Applying @var{name} select the "best" @var{method}, and applies that.
See the following section on generic procedures.

For example, the standard @code{vector-ref} procedure specifies
one method, as well as the @code{setter} property:
@example
(define-procedure vector-ref
  setter: vector-set!
  (lambda (vector::vector k ::int)
    (invoke vector 'get k)))
@end example
@end deffn

You can also specify properties in the lambda body:

@example
(define (vector-ref vector::vector k ::int)
    setter: vector-set!
    (invoke vector 'get k))
@end example

@subsection Standard properties

@table @code
@item name
The name of a procedure (as a symbol), which is used
when the procedure is printed.
@item setter
Set the setter procedure associated with the procedure.
@item validate-apply
@itemx validate-xapply
Used during the validation phase of the compiler.
@item compile-apply
Used during the bytecode-generation phase of the compiler:
If we see a call to a known function with this property,
we can emit custom bytecode for the call.
@end table

@node Generic procedures, Extended formals, Procedure properties, Procedures
@section Generic (dynamically overloaded) procedures

A @dfn{generic procedure} is a collection of @dfn{method procedures}.
(A "method procedure" is not the same as a Java method, but
the terms are related.)
You can call a generic procedure, which selects the "closest
match" among the component method procedures:  I.e. the most specific
method procedure that is applicable given the actual arguments.

@quotation
@strong{Warning:} The current implementation of selecting the "best" method
is not reliable if there is more than one method.
It can select depending on argument count, and it can select between
primitive Java methods.  However, selecting between different Scheme
procedures based on parameter types should be considered experimental.
The main problem is we can't determine the most specific
method, so Kawa just tries the methods in order.
@end quotation

@deffn Procedure make-procedure [keyword: value]... method...
Create a generic procedure given the specific methods.
You can also specify property values for the result.

The @var{keyword}s specify how the arguments are used.
A @code{method:} keyword is optional and specifies that the following
argument is a method.
A @code{name:} keyword specifies the name of the resulting procedure,
when used for printing.
Unrecognized keywords are used to set the procedure properties of the result.
@example
(define plus10 (make-procedure foo: 33 name: 'Plus10
                            method: (lambda (x y) (+ x y 10))
                            method: (lambda () 10)))
@end example
@end deffn

@node Extended formals
@section Extended Formal Arguments List

The formal arguments list of a lambda expression has some
extensions over standard Scheme:
Kawa borrows the extended formal argument list of DSSSL,
and Kawa allows you to declare the type of the parameter.
More generally, you can use @ref{Variables and Patterns,patterns}.

@display
@stxdef{lambda-expression} @stxlit{(lambda} @stxref{formals} @arbno{@stxref{option-pair}} @stxref{opt-return-type} @stxref{body}@stxlit{)}
@stxdef{return-type} @stxref{type}
@stxdef{opt-return-type} [@stxlit{::} @stxref{type}]
@end display
where
@display
@stxdef{formals} @stxlit{(}@stxref{formal-arguments}@stxlit{)} | @stxref{rest-arg}
@end display
You can of course also use the extended format in a @ref{Definitions,@code{define}}:
@example
@b{(define (}@var{name} @var{formal-arguments}@b{)} [@var{rtype}] @var{body}@b{)}
@end example
@display
@stxdef{formal-arguments}
    @arbno{@stxref{required-or-guard}} [@stxlit{#!optional} @stxref{optional-arg} ...] (@stxref{rest-key-args} | @stxlit{.} @stxref{rest-arg})
@end display
@display
@stxdef{required-or-guard} @stxref{required-arg} |@stxref{guard}
@stxdef{rest-key-args} [@stxlit{#!rest} @stxref{rest-arg}] [@stxlit{#!key} @stxref{key-arg} ...]
  | [@stxlit{#!key} @stxref{key-arg} ...] [@stxlit{#!rest} @stxref{rest-arg}]
@stxdef{required-arg} @stxref{pattern} [@stxlit{::} @stxref{type}]
  | @stxlit{(} @stxref{pattern} @stxlit{::} @stxref{type}@stxlit{)}
@stxdef{optional-arg} @var{variable} [@stxlit{::} @stxref{type}]
  | @stxlit{(} @stxref{pattern} [@stxlit{::} @stxref{type}] [@var{initializer} [@stxref{supplied-var}]]@stxlit{)}
@stxdef{supplied-var} @var{variable}
@stxdef{key-arg} @var{variable} [@stxlit{::} @stxref{type}]
    | @stxlit{(} @var{variable} [@stxlit{::} @stxref{type}] [@var{initializer} [@stxref{supplied-var}]] @stxlit{)}
@stxdef{rest-arg} @var{variable}
@end display

When the procedure is applied to a list of actual arguments, the formal and
actual arguments are processed from left to right as follows:

@itemize
@item
The @var{required-arg}s are matched against actual (pre-keyword) arguments
in order, starting with the first actual argument.
A @var{guard} is evaluated when it appears:
If it evaluates to false, then matching fails.
It shall be an error if there are fewer pre-keyword
arguments then there are @var{req-arg}s.
@item
Next the @var{optional-arg}s are bound to remaining pre-keyword arguments.
If there are fewer remaining pre-keyword arguments than there are
@var{optional-arg}s, then the remaining @var{variable}s are bound
to the corresponding @var{initializer}.
If no @var{initializer} was specified, it defaults to @code{#f}.
(TODO: If a @var{type} is specified the default for @var{initializer}
is the default value of the @var{type}.)
The @var{initializer} is evaluated in an
environment in which all the previous formal parameters have been bound.
If a @var{supplied-var} is specified, it has type boolean,
and is set to true if there was an actual corresponding argument,
and false if the initializer was evaluated.
@item
If there is a @var{rest-arg}, it is bound to a list of all the
remaining actual arguments.  These remaining actual arguments are also
eligible to be bound to keyword arguments.   If there is no
@var{rest-arg} and there are no @var{key-arg}s, then it shall
be an error if there are any remaining actual arguments.
@item
If @code{#!key} was specified, then there shall be an even number of
remaining actual arguments.  These are interpreted as a series of pairs,
where the first member of each pair is a keyword specifying the argument name,
and the second is the corresponding value.  It shall be an error if the first
member of a pair is not a keyword.  It shall be an error if the argument name
is not the same as a variable in a @var{key-arg}s, unless there
is a @var{rest-arg}.  If the same argument name occurs more than once
in the list of actual arguments, then the first value is used.
If there is no actual argument for a particular @var{key-arg},
then the variable is bound
to the corresponding @var{initializer}, if one was specified, and
otherwise to @code{#f}.  The @var{initializer} is evaluated in an
environment in which all the previous formal parameters have been bound.
@end itemize

If a @var{type} is specified, the corresponding actual argument (or
the @var{initializer} default value) is coerced to the specified @var{type}.
In the function body, the parameter has the specified type.

If @var{rtype} (the first form of the function body) is an unbound
identifier of the form @code{<TYPE>} (that is the first character
is @samp{<} and the last is @samp{>}), then that specifies the
function's return type.  It is syntactic sugar for
@code{(as <TYPE> (begin BODY))}.

You can set the @ref{Procedure properties,properties}
of the resulting procedure using an @var{option-pair}.  For example,
to set the @code{setter} property of a procedure
to @code{my-set-car} do the following:
@example
(define my-car
  (lambda (arg) setter: my-set-car (primitive-car arg)))
@end example

@node Partial application
@section Partial application

@deffn Syntax cut slot-or-expr slot-or-expr* [@code{<...>}]
where each @var{slot-or-expr} is either an @var{expression} or
the literal symbol @code{<>}.

It is frequently necessary to specialize some of the parameters of a
multi-parameter procedure. For example, from the binary operation @code{cons}
one might want to obtain the unary operation
@code{(lambda (x) (cons 1 x))}.
This specialization of parameters is also known
as @dfn{partial application}, @dfn{operator section}, or @dfn{projection}.
The macro @code{cut} specializes some of the parameters of its first
argument. The parameters that are to show up as formal variables of the
result are indicated by the symbol @code{<>}, pronouced as "slot".
In addition, the symbol @code{<...>}, pronounced as "rest-slot", matches all
residual arguments of a variable argument procedure.

A @code{cut}-expression is transformed into
a @var{lambda expression} with as many formal variables as there are
slots in the list @var{slot-or-expr}*.
The body of the resulting @var{lambda expression} calls
the first @var{slot-or-expr} with arguments from the @var{slot-or-expr}* list
in the order they appear. In case there is a rest-slot symbol, the resulting
procedure is also of variable arity, and the body calls the first
@var{slot-or-expr} with remaining arguments provided to the actual call of the
specialized procedure.

Here are some examples:

@code{(cut cons (+ a 1) <>)} is the same as @w{@code{(lambda (x2) (cons (+ a 1) x2))}}

@code{(cut list 1 <> 3 <> 5)} is the same as @w{@code{(lambda (x2 x4) (list 1 x2 3 x4 5))}}

@code{(cut list)} is the same as @w{@code{(lambda () (list))}}

@code{(cut list 1 <> 3 <...>)} is the same as @w{@code{(lambda (x2 . xs) (apply list 1 x2 3 xs))}}

The first argument can also be a slot, as one should expect in Scheme:
@code{(cut <> a b)} is the same as @w{@code{(lambda (f) (f a b))}}
@end deffn

@deffn Syntax cute slot-or-expr slot-or-expr* [@code{<...>}]
The macro @code{cute} (a mnemonic for "cut with evaluated non-slots") is
similar to @code{cut}, but it evaluates the non-slot expressions at the
time the procedure is specialized, not at the time the specialized
procedure is called.

For example
@code{(cute cons (+ a 1) <>)} is the same as
@w{@code{(let ((a1 (+ a 1))) (lambda (x2) (cons a1 x2)))}}

As you see from comparing this example with the first example above, the
@code{cute}-variant will evaluate @code{(+ a 1)} once,
while the @code{cut}-variant will
evaluate it during every invocation of the resulting procedure.

@end deffn

@node Numbers, Characters and text, Procedures, Top
@chapter Quantities and Numbers

Kawa supports the full Scheme set of number operations with some extensions.

Kawa converts between Scheme number types
and Java number types as appropriate.

@menu
* Numerical types::
* Arithmetic operations::
* Numerical input and output::
* Quaternions::
* Quantities::
* Logical Number Operations::
* Performance of numeric operations::
@end menu

@node Numerical types
@section Numerical types

Mathematically, numbers are arranged into a tower of subtypes
in which each level is a subset of the level before it:
number; complex number; real number; rational number; integer.

For example, @code{3} is an integer. Therefore @code{3} is also a rational,
a real, and a complex number. The same is true of the
Scheme numbers that model 3. For Scheme numbers, these
types are defined by the predicates @code{number?}, @code{complex?},
@code{real?}, @code{rational?}, and @code{integer?}.

There is no simple relationship between a number’s type
and its representation inside a computer. Although most
implementations of Scheme will offer at least two different
representations of 3, these different representations denote
the same integer.

Scheme’s numerical operations treat numbers as abstract
data, as independent of their representation as possible.
Although an implementation of Scheme may use multiple
internal representations of numbers, this ought not to be
apparent to a casual programmer writing simple programs.

@deffn Type number
The type of Scheme numbers.
@end deffn

@deffn Type quantity
The type of quantities optionally with units.
This is a sub-type of @code{number}.
@end deffn

@deffn Type complex
The type of complex numbers.
This is a sub-type of @code{quantity}.
@end deffn

@deffn Type real
The type of real numbers.
This is a sub-type of @code{complex}.
@end deffn

@deffn Type rational
The type of exact rational numbers.
This is a sub-type of @code{real}.
@end deffn

@deffn Type integer
The type of exact Scheme integers.
This is a sub-type of @code{rational}.
@end deffn

Kawa allows working with expressions of ``primitive'' types,
which are supported by the JVM without object allocation,
and using builtin arithmetic.  Using these types may be much
faster, assuming the compiler is able to infer
that the variable or expression has primitive type.

@deffn Type long
@deffnx Type int
@deffnx Type short
@deffnx Type byte
These are fixed-sized primitive signed exact integer types,
of respectively 64, 32, 18, and 8 bits.
If a value of one of these types needs to be converted to an
object, the standard classes @code{java.lang.Long}, @code{java.lang.Integer},
@code{java.lang.Short}, or @code{java.lang.Byte}, respectively, are used.
@end deffn

@deffn Type ulong
@deffnx Type uint
@deffnx Type ushort
@deffnx Type ubyte
These are fixed-sized primitive unsigned exact integer types,
of respectively 64, 32, 18, and 8 bits.
These are presented at runtime using the corresponding
signed types (@code{long}, @code{int}, @code{short}, or @code{byte}).
However, for arithmetic the Kawa compiler generates code to perform the
``mathematically correct'' result, truncated to an unsigned result
rather than signed.
If a value of one of these types needs to be converted to an
object, the classes @code{gnu.math.ULong}, @code{gnu.math.UInt},
@code{gnu.math.UShort}, or  @code{gnu.math.UByte} is used.
@end deffn

@deffn Type double
@deffnx Type float
These are fixed-size primitive inexact floating-point real types,
using the standard 64-bit or 32-bit IEEE representation.
If a value of one of these types needs to be converted to an
object, the standard classes @code{java.lang.Double},
or @code{java.lang.Float} is used.
@end deffn

@subsection Exactness
@cindex exactness
It is useful to distinguish between numbers that are represented
exactly and those that might not be. For example,
indexes into data structures must be known exactly, as
must some polynomial coefficients in a symbolic algebra
system. On the other hand, the results of measurements
are inherently inexact, and irrational numbers may be approximated
by rational and therefore inexact approximations.
In order to catch uses of inexact numbers where exact numbers
are required, Scheme explicitly distinguishes
exact from inexact numbers. This distinction is orthogonal
to the dimension of type.

@cindex exact complex number
@cindex inexact complex number
A Scheme number is @dfn{exact} if it was written as an exact
constant or was derived from exact numbers using only exact operations.
A number is @dfn{inexact} if it was written as
an inexact constant, if it was derived using inexact ingredients,
or if it was derived using inexact operations. Thus
inexactness is a contagious property of a number.
In particular, an @dfn{exact complex number} has an exact real part
and an exact imaginary part; all other complex numbers
are @dfn{inexact complex numbers}.

If two implementations produce exact results for a computation
that did not involve inexact intermediate results, the
two ultimate results will be mathematically equal. This
is generally not true of computations involving inexact
numbers since approximate methods such as floating-point
arithmetic may be used, but it is the duty of the implementation
to make the result as close as practical to the
mathematically ideal result.

Rational operations such as @code{+} should always produce exact
results when given exact arguments. If the operation
is unable to produce an exact result, then it may either
report the violation of an implementation restriction or it
may silently coerce its result to an inexact value.

Except for @code{exact}, the operations described in this section
must generally return inexact results when given any inexact arguments.
An operation may, however, return an
exact result if it can prove that the value of the result is
unaffected by the inexactness of its arguments. For example,
multiplication of any number by an exact zero may
produce an exact zero result, even if the other argument is inexact.

Specifically, the expression @code{(* 0 +inf.0)} may return @code{0},
or @code{+nan.0}, or report that inexact numbers are not supported,
or report that non-rational real numbers are not supported,
or fail silently or noisily in other implementation-specific ways.

The procedures listed below will always return exact integer
results provided all their arguments are exact integers
and the mathematically expected results are representable
as exact integers within the implementation:
@code{-},
@code{*},
@code{+},
@code{abs},
@code{ceiling},
@code{denominator},
@code{exact-integer-sqrt},
@code{expt},
@code{floor},
@code{floor/},
@code{floor-quotient},
@code{floor-remainder},
@code{gcd},
@code{lcm},
@code{max},
@code{min},
@code{modulo},
@code{numerator},
@code{quotient},
@code{rationalize},
@code{remainder},
@code{square},
@code{truncate},
@code{truncate/},
@code{truncate-quotient},
@code{truncate-remainder}.

@subsection Numerical promotion and conversion

When combining two values of different numeric types,
the values are converted to the first line in the following
that subsumes (follows) both types.  The computation is done using
values of that type, and so is the result.
For example adding a @code{long} and a @code{float} converts the former
to the latter, yielding a @code{float}.

Note that @code{short}, @code{byte}, @code{ushort}, @code{ubyte}
are converted to @code{int} regardless, even in the case of
a single-operand operation, such as unary negation.
Another exception is trancendental functions (such as @code{cos}),
where integer operands are converted to @code{double}.

@itemize
@item
@code{int} subsumes @code{short}, @code{byte}, @code{ushort}, @code{ubyte}.
@item
@code{uint}
@item
@code{long}
@item
@code{ulong}
@item
@code{java.lang.BigInteger}
@item
@code{integer} (i.e. @code{gnu.math.IntNum})
@item
@code{rational} (i.e. @code{gnu.math.RatNum})
@item
@code{float}
@item
@code{double}
@item
@code{gnu.math.FloNum}
@item
@code{real} (i.e. @code{gnu.math.RealNum})
@item
@code{number}
@item
@code{complex}
@item
@code{quantity}
@end itemize

When comparing a primitive signed integer value with a primitive unsigned
integer (for example @code{<} applied to a @code{int} and a @code{ulong})
the mathemically correct result is computed, as it converting both
operands to @code{integer}.

@node Arithmetic operations
@section Arithmetic operations

@deffn Procedure {real-valued?} @var{obj}
@deffnx Procedure {rational-valued?} @var{obj}
@deffnx Procedure {integer-valued?} @var{obj}
These numerical type predicates can be applied to any kind of argument.
The @func{real-valued?} procedure returns @true{} if the object is a
number object and is equal in the sense of @code{=} to some real number
object, or if the object is a NaN, or a complex number object whose real
part is a NaN and whose imaginary part is zero in the sense of
@func{zero?}.  The @func{rational-valued?} and @func{integer-valued?}
procedures return @true{} if the object is a number object and is equal
in the sense of @code{=} to some object of the named type, and otherwise
they return @false{}.

@example
(real-valued? +nan.0)                  @result{} #t
(real-valued? +nan.0+0i)               @result{} #t
(real-valued? -inf.0)                  @result{} #t
(real-valued? 3)                       @result{} #t
(real-valued? -2.5+0.0i)               @result{} #t

(real-valued? -2.5+0i)                 @result{} #t
(real-valued? -2.5)                    @result{} #t
(real-valued? #e1e10)                  @result{} #t

(rational-valued? +nan.0)              @result{} #f
(rational-valued? -inf.0)              @result{} #f
(rational-valued? 6/10)                @result{} #t
(rational-valued? 6/10+0.0i)           @result{} #t
(rational-valued? 6/10+0i)             @result{} #t
(rational-valued? 6/3)                 @result{} #t

(integer-valued? 3+0i)                 @result{} #t
(integer-valued? 3+0.0i)               @result{} #t
(integer-valued? 3.0)                  @result{} #t
(integer-valued? 3.0+0.0i)             @result{} #t
(integer-valued? 8/4)                  @result{} #t
@end example

@quotation
@emph{Note:} These procedures test whether a given number object can be
coerced to the specified type without loss of numerical accuracy.
Specifically, the behavior of these predicates differs from the behavior
of @func{real?}, @func{rational?}, and @func{integer?} on complex number
objects whose imaginary part is inexact zero.
@end quotation

@quotation
@emph{Note:} The behavior of these type predicates on inexact number
objects is unreliable, because any inaccuracy may affect the result.
@end quotation
@end deffn

@deffn Procedure exact-integer? z
Returns @code{#t} if @var{z} is both exact and an integer; otherwise
returns @code{#f}.
@example
(exact-integer? 32)                    @result{} #t
(exact-integer? 32.0)                  @result{} #t
(exact-integer? 32/5)                  @result{} #f
@end example
@end deffn

@deffn Procedure {finite?} @var{z}
Returns @code{#t} if @var{z} is finite real number
(i.e. an infinity and not a NaN),
or if @var{z} is a complex number
whose real and imaginary parts are both finite.
@example
(finite? 3)             @result{} #t
(finite? +inf.0)        @result{} #f
(finite? 3.0+inf.0i)    @result{} #f
@end example
@end deffn

@deffn Procedure {infinite?} @var{z}
Return @code{#t} if @var{z} is
an infinite real number (@code{+int.0} or @code{-inf.0}),
or if @var{z} is a complex number where either
real or imaginary parts or both are infinite.
@example
(infinite? 5.0)         @result{} #f
(infinite? +inf.0)      @result{} #t
(infinite? +nan.0)      @result{} #f
(infinite? 3.0+inf.0i)  @result{} #t
@end example
@end deffn

@deffn Procedure {nan?} @var{z}
For a real numer returns whether its is a NaN;
for a complex number if the real or imaginary parts or both is a NaN.
@example
(nan? +nan.0)           @result{} #t
(nan? 32)               @result{} #f
(nan? +nan.0+5.0i)      @result{} #t
(nan? 1+2i)             @result{} #f
@end example
@end deffn


@deffn Procedure + @var{z} @dots{}
@deffnx Procedure * @var{z} @dots{}
These procedures return the sum or product of their arguments.

@example
(+ 3 4)                          @result{}  7
(+ 3)                            @result{}  3
(+)                              @result{}  0
(+ +inf.0 +inf.0)                @result{}  +inf.0
(+ +inf.0 -inf.0)                @result{}  +nan.0

(* 4)                            @result{}  4
(*)                              @result{}  1
(* 5 +inf.0)                     @result{}  +inf.0
(* -5 +inf.0)                    @result{}  -inf.0
(* +inf.0 +inf.0)                @result{}  +inf.0
(* +inf.0 -inf.0)                @result{}  -inf.0
(* 0 +inf.0)                     @result{}  +nan.0
(* 0 +nan.0)                     @result{}  +nan.0
(* 1.0 0)                        @result{}  0.0
@end example

For any real number object @var{x} that is neither infinite nor NaN:

@example
(+ +inf.0 @var{x})                   @result{}  +inf.0
(+ -inf.0 @var{x})                   @result{}  -inf.0
@end example

For any real number object @var{x}:

@example
(+ +nan.0 @var{x})                   @result{}  +nan.0
@end example

For any real number object @var{x} that is not an exact 0:

@example
(* +nan.0 @var{x})                   @result{}  +nan.0
@end example

@c If any of these procedures are applied to mixed non--rational real and
@c non--real complex arguments, they either raise an exception with
@c condition type @code{&implementation-restriction} or return an
@c unspecified number object.

The behavior of @code{-0.0} is illustrated by the following examples:

@example
(+  0.0 -0.0)  @result{}  0.0
(+ -0.0  0.0)  @result{}  0.0
(+  0.0  0.0)  @result{}  0.0
(+ -0.0 -0.0)  @result{} -0.0
@end example
@end deffn

@deffn Procedure - @var{z}
@deffnx Procedure - @vari{z} @varii{z} @variii{z} @dots{}
With two or more arguments, this procedures returns the difference of
its arguments, associating to the left.  With one argument, however, it
returns the negation (additive inverse) of its argument.

@example
(- 3 4)                               @result{}  -1
(- 3 4 5)                             @result{}  -6
(- 3)                                 @result{}  -3
(- +inf.0 +inf.0)                     @result{}  +nan.0
@end example

@c If this procedure is applied to mixed non--rational real and non--real
@c complex arguments, it either raises an exception with condition type
@c @code{&implementation-restriction} or returns an unspecified number
@c object.

The behavior of @code{-0.0} is illustrated by the following examples:

@example
(-  0.0)       @result{} -0.0
(- -0.0)       @result{}  0.0
(-  0.0 -0.0)  @result{}  0.0
(- -0.0  0.0)  @result{} -0.0
(-  0.0  0.0)  @result{}  0.0
(- -0.0 -0.0)  @result{}  0.0
@end example
@end deffn

@deffn Procedure / @var{z}
@deffnx Procedure / @vari{z} @varii{z} @variii{z} @dots{}
If all of the arguments are exact, then the divisors must all be
nonzero.  With two or more arguments, this procedure returns the
quotient of its arguments, associating to the left.  With one argument,
however, it returns the multiplicative inverse of its argument.

@example
(/ 3 4 5)                         @result{}  3/20
(/ 3)                             @result{}  1/3
(/ 0.0)                           @result{}  +inf.0
(/ 1.0 0)                         @result{}  +inf.0
(/ -1 0.0)                        @result{}  -inf.0
(/ +inf.0)                        @result{}  0.0
(/ 0 0)                           @result{}  exception &assertion
(/ 3 0)                           @result{}  exception &assertion
(/ 0 3.5)                         @result{}  0.0
(/ 0 0.0)                         @result{}  +nan.0
(/ 0.0 0)                         @result{}  +nan.0
(/ 0.0 0.0)                       @result{}  +nan.0
@end example

If this procedure is applied to mixed non--rational real and non--real
complex arguments, it either raises an exception with condition type
@code{&implementation-restriction} or returns an unspecified number
object.
@end deffn

@deffn Procedure floor/ x y
@deffnx Procedure truncate/ x y
@deffnx Procedure div-and-mod x y
@deffnx Procedure div0-and-mod0 x y
These procedures implement number--theoretic integer division.
They accept two real numbers @var{x} and @var{y} as operands,
where @var{y} must be nonzero.
In all cases the result is two values @var{q} (an integer) and @var{r} (a real)
that satisfy the equations:
@example
@var{x} = @var{q} * @var{y} + @var{r}
@var{q} = @var{rounding-op}(@var{x}/@var{y})
@end example
The result is inexact if either argument is inexact.

For @code{floor/} the @var{rounding-op} is the @code{floor} function (below).
@example
(floor/ 123 10)         @result{}  12 3
(floor/ 123 -10)        @result{}  -13 -7
(floor/ -123 10)        @result{}  -13 7
(floor/ -123 -10)       @result{}  12 -3
@end example

For @code{truncate/} the @var{rounding-op} is the @code{truncate} function.
@example
(truncate/ 123 10)      @result{}  12 3
(truncate/ 123 -10)     @result{}  -12 3
(truncate/ -123 10)     @result{}  -12 -3
(truncate/ -123 -10)    @result{}  12 -3
@end example

For @code{div-and-mod} the @var{rounding-op} is either @code{floor}
(if @var{y} is positive) or @code{ceiling} (if @var{y} is negative).
We have:
@example
0  <= @var{r} < |@var{y}|
@end example
@example
(div-and-mod 123 10)    @result{}  12 3
(div-and-mod 123 -10)   @result{}  -12 3
(div-and-mod -123 10)   @result{}  -13 7
(div-and-mod -123 -10)  @result{}  13 7
@end example

For @code{div0-and-mod0} the @var{rounding-op} is the @code{round} function,
and @code{r} lies within a half--open interval centered on zero.
@example
-|@var{y}/2| <= @var{r} < |@var{y}/2|
@end example

@example
(div0-and-mod0 123 10)   @result{}  12 3
(div0-and-mod0 123 -10)  @result{}  -12 3
(div0-and-mod0 -123 10)  @result{}  -12 -3
(div0-and-mod0 -123 -10) @result{}  12 -3
(div0-and-mod0 127 10)   @result{}  13 -3
(div0-and-mod0 127 -10)  @result{}  -13 -3
(div0-and-mod0 -127 10)  @result{}  -13 3
(div0-and-mod0 -127 -10) @result{}  13 3
@end example

The inconsistent naming is for historical reasons: @code{div-and-mod}
and @code{div0-and-mod0} are from R6RS, while @code{floor/} and
@code{truncate/} are from R7RS.
@end deffn

@deffn Procedure floor-quotient x y
@deffnx Procedure truncate-quotient x y
@deffnx Procedure div x y
@deffnx Procedure div0 x y
These procedures return the quotient part (first value)
of respectively @code{floor/}, @code{truncate/},
@code{div-and-mod}, and @code{div0-and-mod0}.
@end deffn

@deffn Procedure floor-remainder x y
@deffnx Procedure truncate-remainder x y
@deffnx Procedure mod x y
@deffnx Procedure mod0 x y
These procedures return the remainder part (second value)
of respectively @code{floor/}, @code{truncate/},
@code{div-and-mod}, and @code{div0-and-mod0}.

As a Kawa extension @var{y} may be zero, in which case the result is @var{x}:
@example
(mod 123 0)     @result{}  123 ;; Kawa extension
@end example
@end deffn

@deffn Procedure quotient x y
@deffnx Procedure remainder x y
@deffnx Procedure modulo x y
These are equivalent to @code{truncate-quotient},
@code{truncate-remainder}, and @code{floor-remainder}, respectively.
These are provided for backward compatibility.
@example
(remainder 13 4)     @result{} 1
(remainder -13 4)    @result{} -1
(remainder 13 -4)    @result{} 1
(remainder -13 -4)   @result{} -1
(remainder -13 -4.0) @result{} -1.0
(modulo 13 4)   @result{} 1
(modulo -13 4)  @result{} 3
(modulo 13 -4)  @result{} -4
(modulo -13 -4) @result{} -1
@end example
@end deffn

@deffn Procedure abs @var{x}
Returns the absolute value of its argument.

@example
(abs -7)                         @result{}  7
(abs -inf.0)                     @result{}  +inf.0
@end example
@end deffn

@deffn Procedure gcd @vari{n} @dots{}
@deffnx Procedure lcm @vari{n} @dots{}
These procedures return the greatest common divisor or least common
multiple of their arguments.  The result is always non--negative.
The arguments must be integers; if an argument is inexact, so is the result.

@example
(gcd 32 -36)                     @result{}  4
(gcd)                            @result{}  0
(lcm 32 -36)                     @result{}  288
(lcm 32.0 -36)                   @result{}  288.0 ; inexact
(lcm)                            @result{}  1
@end example
@end deffn

@deffn Procedure numerator @var{q}
@deffnx Procedure denominator @var{q}
These procedures return the numerator or denominator of their argument;
the result is computed as if the argument was represented as a fraction
in lowest terms.  The denominator is always positive.  The denominator
of @code{0} is defined to be @code{1}.
The arguments must be integers; if an argument is inexact, so is the result.

@example
(numerator   (/ 6 4))            @result{}  3
(denominator (/ 6 4))            @result{}  2
(denominator (inexact (/ 6 4)))        @result{}  2.0
@end example
@end deffn

@deffn Procedure floor @var{x}
@deffnx Procedure ceiling @var{x}
@deffnx Procedure truncate @var{x}
@deffnx Procedure round @var{x}
These procedures return inexact integer objects for inexact arguments
that are not infinities or NaNs, and exact integer objects for exact
rational arguments.

@table @code
@item floor
Returns the largest integer object not larger than @var{x}.

@item ceiling
Returns the smallest integer object not smaller than @var{x}.
@item truncate
Returns the integer object closest to @var{x} whose absolute value is
not larger than the absolute value of @var{x}.

@item round
Returns the closest integer object to @var{x}, rounding to even when
@var{x} represents a number halfway between two integers.
@end table

If the argument to one of these procedures is inexact, then the result
is also inexact.  If an exact value is needed, the result should be
passed to the @func{exact} procedure.

Although infinities and NaNs are not integer objects, these procedures
return an infinity when given an infinity as an argument, and a NaN when
given a NaN.

@example
(floor -4.3)                     @result{}  -5.0
(ceiling -4.3)                   @result{}  -4.0
(truncate -4.3)                  @result{}  -4.0
(round -4.3)                     @result{}  -4.0

(floor 3.5)                      @result{}  3.0
(ceiling 3.5)                    @result{}  4.0
(truncate 3.5)                   @result{}  3.0
(round 3.5)                      @result{}  4.0

(round 7/2)                      @result{}  4
(round 7)                        @result{}  7

(floor +inf.0)                   @result{}  +inf.0
(ceiling -inf.0)                 @result{}  -inf.0
(round +nan.0)                   @result{}  +nan.0
@end example
@end deffn

@deffn Procedure rationalize @vari{x} @varii{x}
The @func{rationalize} procedure returns a number object representing
the @emph{simplest} rational number differing from @vari{x} by no more
than @varii{x}.

A rational number @emph{r_1} is @emph{simpler} than another rational
number @emph{r_2} if @code{r_1 = p_1/q_1} and @code{r_2 = p_2/q_2} (in
lowest terms) and @code{|p_1| <= |p_2|} and @code{|q_1| <= |q_2|}.  Thus
@code{3/5} is simpler than @code{4/7}.

Although not all rationals are comparable in this ordering (consider
@code{2/7} and @code{3/5}) any interval contains a rational number that
is simpler than every other rational number in that interval (the
simpler @code{2/5} lies between @code{2/7} and @code{3/5}).

Note that @code{0 = 0/1} is the simplest rational of all.
@example
(rationalize (exact .3) 1/10)          @result{} 1/3
(rationalize .3 1/10)                  @result{} #i1/3  ; approximately

(rationalize +inf.0 3)                 @result{}  +inf.0
(rationalize +inf.0 +inf.0)            @result{}  +nan.0
@c (rationalize 3 +inf.0)                 @result{}  0.0
@end example

The first two examples hold only in implementations whose inexact real
number objects have sufficient precision.
@end deffn

@deffn Procedure exp @var{z}
@deffnx Procedure log @var{z}
@deffnx Procedure log @vari{z} @varii{z}
@deffnx Procedure sin @var{z}
@deffnx Procedure cos @var{z}
@deffnx Procedure tan @var{z}
@deffnx Procedure asin @var{z}
@deffnx Procedure acos @var{z}
@deffnx Procedure atan @var{z}
@deffnx Procedure atan @vari{x} @varii{x}
These procedures compute the usual transcendental functions.

The @func{exp} procedure computes the base--@var{e} exponential of
@var{z}.
The @func{log} procedure with a single argument computes the natural
logarithm of @var{z} (@strong{not} the base--10 logarithm); @code{(log
@vari{z} @varii{z})} computes the base--@varii{z} logarithm of @vari{z}.

The @func{asin}, @func{acos}, and @func{atan} procedures compute
arcsine, arccosine, and arctangent, respectively.  The two--argument
variant of @func{atan} computes:

@example
(angle (make-rectangular @varii{x} @vari{x}))
@end example

These procedures may return inexact results even when given exact
arguments.
@example
(exp +inf.0)    @result{} +inf.0
(exp -inf.0)    @result{} 0.0
(log +inf.0)    @result{} +inf.0
(log 0.0)       @result{} -inf.0
(log 0)         @result{} exception &assertion
(log -inf.0)    @result{} +inf.0+3.141592653589793i    ; approximately
(atan -inf.0)   @result{} -1.5707963267948965          ; approximately
(atan +inf.0)   @result{} 1.5707963267948965           ; approximately
(log -1.0+0.0i) @result{} 0.0+3.141592653589793i       ; approximately
(log -1.0-0.0i) @result{} 0.0-3.141592653589793i       ; approximately
                                                ; if -0.0 is distinguished
@end example
@end deffn

@deffn Procedure sinh z
@deffnx Procedure cosh z
@deffnx Procedure tanh z
@deffnx Procedure asinh z
@deffnx Procedure acosh z
@deffnx Procedure atanh z
The hyperbolic functions.
@end deffn

@deffn Procedure square z
Returns the square of @var{z}.
This is equivalent to @code{(* @var{z} @var{z})}.
@example
(square 42)    @result{} 1764
(square 2.0)   @result{} 4.0
@end example
@end deffn

@deffn Procedure sqrt @var{z}
Returns the principal square root of @var{z}.  For rational @var{z}, the
result has either positive real part, or zero real part and
non--negative imaginary part.  The value of @code{(sqrt @var{z})} could be
expressed as:

@example
e^((log z)/2)
@end example

The @func{sqrt} procedure may return an inexact result even when given
an exact argument.

@example
(sqrt -5)                   @result{}  0.0+2.23606797749979i ; approximately
(sqrt +inf.0)               @result{}  +inf.0
(sqrt -inf.0)               @result{}  +inf.0i
@end example

Note that if the argument is a primitive number (such as @code{double}) or an
instance of the corresponding boxed class (such as @code{java.lang.Double})
then we use the real-number version of @code{sqrt}:
@example
(sqrt (->double -5))        @result{}  NaN
@end example
That is, we get different a result for @code{java.lang.Double}
and @code{gnu.math.DFloNum}, even for arguments that are numerically equal
in the sense of @code{=}.
This is so that the compiler can use the @code{java.lang.Math.sqrt}
method without object allocation when the argument is a @code{double}
(and because we want @code{double} and @code{java.lang.Double} to behave
consistently).
@end deffn

@deffn Procedure exact-integer-sqrt @var{k}
The @func{exact-integer-sqrt} procedure returns two non--negative exact
integer objects @emph{s} and @emph{r} where @code{@var{k} = s^2 + r} and
@code{@var{k} < (s+1)^2}.

@example
(exact-integer-sqrt 4)  @result{} 2 0 ; two return values
(exact-integer-sqrt 5)  @result{} 2 1 ; two return values
@end example
@end deffn

@node Numerical input and output
@section Numerical input and output

@deffn Procedure number->string z [radix]

The procedure @code{number->string} takes a number and a
radix and returns as a string an external representation
of the given number in the given radix such that
@example
(let ((number number)
      (radix radix))
  (eqv? number
        (string->number (number->string number radix)
                        radix)))
@end example
is true. It is an error if no possible result makes this expression true.

If present, @var{radix} must be an exact integer
in the range 2 to 36, inclusive.
If omitted, @var{radix} defaults to 10.

If @var{z} is inexact, the @var{radix} is 10, and the above expression
can be satisfied by a result that contains a decimal point,
then the result contains a decimal point and is expressed
using the minimum number of digits (exclusive of exponent
and trailing zeroes) needed to make the above expression;
otherwise the format of the result is unspecified.

The result returned by @code{number->string} never contains an
explicit radix prefix.

@emph{Note:}
The error case can occur only when @var{z} is not a complex
number or is a complex number with a non-rational real or
imaginary part.

@emph{Rationale:} If @var{z} is an inexact number and the @var{radix} is 10,
then the above expression is normally satisfied by a result containing
a decimal point. The unspecified case allows for infinities, NaNs,
and unusual representations.

@end deffn

@deffn Procedure string->number string [radix]
Returns a number of the maximally precise representation
expressed by the given @var{string}. It is an error if @var{radix} is not
an exact integer in the range 2 to 26, inclusive.

If supplied, @var{radix} is a default radix that will be overridden
 if an explicit radix prefix is present in the string (e.g.
@code{"#o177"}). If @var{radix} is not supplied, then the default @var{radix}
is 10. If @var{string} is not a syntactically valid notation for a
number, or would result in a number that the implementation cannot represent,
then @code{string->number} returns @code{#f}.
An error is never signaled due to the content of @var{string}.

@example
(string->number "100")      @result{}  100
(string->number "100" 16)   @result{}  256
(string->number "1e2")      @result{}  100.0
(string->number "#x100" 10) @result{}  256
@end example

@end deffn


@node Quaternions
@section Quaternions

Kawa extends the Scheme numeric tower to include
@uref{http://en.wikipedia.org/wiki/Quaternion,quaternions} as a proper
superset of the complex numbers.  Quaternions provide a convenient
notation to represent
@uref{http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation,rotations in three-dimensional space},
and are therefore commonly found in applications such as computer
graphics, robotics, and spacecraft engineering.  The Kawa quaternion API
is modeled after
@uref{http://www.ccs.neu.edu/home/dorai/squat/squat.html,this} with some
additions.

A quaternion is a number that can be expressed in the form
@samp{w+xi+yj+zk}, where @code{w}, @code{x}, @code{y}, and @code{z} are
real, and @code{i}, @code{j}, and @code{k} are imaginary units
satisfying @math{i@sup{2} = j@sup{2} = k@sup{2} = ijk = -1}.  The magnitude of a
quaternion is defined to be its Euclidean norm when viewed as a point in
@math{R@sup{4}}.

The real--part of a quaternion is also called its @samp{scalar}, while
the i--part, j--part, and k--part taken together are also called its
@samp{vector}.  A quaternion with zero j--part and k--part is an
ordinary complex number. (If the i--part is also zero, then it is a
real).  A quaternion with zero real--part is called a
@samp{vector quaternion}.

The reader syntax for number literals has been extended to support both
rectangular and polar (hyperspherical) notation for quaternions.  The
rectangular notation is as above, i.e. @code{w+xi+yj+zk}.  The polar
notation takes the form @code{r@@t%u&v}, where @code{r} is the
magnitude, @code{t} is the first angle, and @code{u} and @code{v} are
two other angles called the ``colatitude'' and ``longitude''.

The rectangular coordinates and polar coordinates are related by the
equations:
@example
@var{w} = @var{r} * cos @var{t}
@var{x} = @var{r} * sin @var{t} * cos @var{u}
@var{y} = @var{r} * sin @var{t} * sin @var{u} * cos @var{v}
@var{z} = @var{r} * sin @var{t} * sin @var{u} * sin @var{v}
@end example
With either notation, zero elements may be omitted.

@deffn Procedure make-rectangular @var{w} @var{x}
@deffnx Procedure make-rectangular @var{w} @var{x} @var{y} @var{z}
These procedures construct quaternions from Cartesian coordinates.
@end deffn

@deffn Procedure make-polar @var{r} @var{t}
@deffnx Procedure make-polar @var{r} @var{t} @var{u} @var{v}
These procedures construct quaternions from polar coordinates.
@end deffn

@deffn Procedure + @var{q} @dots{}
@deffnx Procedure - @var{q} @dots{}
@deffnx Procedure * @var{q} @dots{}
@deffnx Procedure / @var{q}
@deffnx Procedure / @vari{q} @varii{q} @variii{q} @dots{}
@deffnx Procedure expt @vari{q} @varii{q}
@deffnx Procedure exp @var{q}
@deffnx Procedure log @var{q}
@deffnx Procedure sqrt @var{q}
@deffnx Procedure sin @var{q}
@deffnx Procedure cos @var{q}
@deffnx Procedure tan @var{q}
@deffnx Procedure asin @var{q}
@deffnx Procedure acos @var{q}
@deffnx Procedure atan @var{q}
All of the arithmetic and transcendental functions defined for complex
arguments have been extended to support quaternions.

Quaternion multiplication is not commutative, so there are two possible
interpretations of @code{(/ q1 q2)} which would yield different results:
either @code{(* q1 (/ q2))}, or @code{(* (/ q2) q1)}.  Division in this
implementation has been defined such that @code{(/ q1 q2 ...)} is
equivalent to @code{(* q1 (/ q2) ...)}, but it is recommended to
use reciprocals (unary @code{/}) and multiplication.
@end deffn

@deffn Procedure real-part @var{q}
Return the real--part of @var{q}.

@example
(real-part 0)          @result{}  0
(real-part -i)         @result{}  0
(real-part 1+2i-3j+4k) @result{}  1
@end example
@end deffn

@deffn Procedure imag-part @var{q}
Return the i--part of @var{q}.

@example
(imag-part 0)          @result{}  0
(imag-part -i)         @result{}  -1
(imag-part 1+2i-3j+4k) @result{}  2
@end example
@end deffn

@deffn Procedure magnitude @var{q}
Return the Euclidean norm of @var{q}.  If @var{q} is @code{a+bi+cj+dk},
then @code{(magnitude q)} is
@code{(sqrt (apply + (map square (list a b c d))))}
@end deffn

@deffn Procedure angle @var{q}
Return the angle of @var{q}.
@end deffn

@subsection The @code{(kawa quaternions)} module

The following additional functionality is made available by doing one
of:
@example
(require 'quaternions) ;; or
(import (kawa quaternions))
@end example

@deffn Alias quaternion
An alias for @code{gnu.math.Quaternion}, useful for type declarations.
@end deffn
@deffn Procedure {quaternion?} @var{x}
Return @true{} if @var{x} is a quaternion, i.e. an ordinary number, and
@false{} otherwise.

@example
(quaternion? 0)          @result{}  #t
(quaternion? -i)         @result{}  #t
(quaternion? 1+2i-3j+4k) @result{}  #t
(quaternion? 10.0m)      @result{}  #f
(quaternion? "x")        @result{}  #f
@end example
@end deffn

@deffn Procedure jmag-part @var{q}
Return the j--part of @var{q}.

@example
(jmag-part 0)          @result{}  0
(jmag-part -i)         @result{}  0
(jmag-part 1+2i-3j+4k) @result{}  -3
@end example
@end deffn
@deffn Procedure kmag-part @var{q}

@example
(kmag-part 0)          @result{}  0
(kmag-part -i)         @result{}  0
(kmag-part 1+2i-3j+4k) @result{}  4
@end example
@end deffn

@deffn Procedure complex-part @var{q}
Return the projection of @var{q} into the complex plane:
@code{(+ (real-part q) (* +i (imag-part q)))}

@example
(complex-part 0)          @result{}  0
(complex-part -i)         @result{}  -1i
(complex-part 1+2i-3j+4k) @result{}  1+2i
@end example
@end deffn
@deffn Procedure vector-part @var{q}
Return the vector--part of @var{q}.

@example
(vector-part 0)          @result{}  0
(vector-part -i)         @result{}  -1i
(vector-part 1+2i-3j+4k) @result{}  +2i-3j+4k
@end example
@end deffn

@deffn Procedure unit-quaternion @var{q}
Return a quaternion of unit magnitude with the same direction as
@var{q}.  If @var{q} is zero, return zero.  This is like a 4D version of
a signum function.

@example
(unit-quaternion 0)          @result{}  0
(unit-quaternion -i)         @result{}  -1i
(unit-quaternion 1+2i-3j+4k) @result{}  0.18257418583505536+0.3651483716701107i-0.5477225575051661j+0.7302967433402214k
@end example
@end deffn

@deffn Procedure unit-vector @var{q}
Return the vector--part of @var{q}, scaled to have magnitude 1.  If the
vector--part is zero, then return zero.

@example
(unit-vector 0)          @result{}  0
(unit-vector -i)         @result{}  -1i
(unit-vector 1+2i-3j+4k) @result{}  +0.3713906763541037i-0.5570860145311556j+0.7427813527082074k
@end example
@end deffn

@deffn Procedure colatitude @var{q}
Return the colatitude of @var{q}.
@end deffn

@deffn Procedure longitude @var{q}
Return the longitude of @var{q}.
@end deffn

@deffn Procedure {vector-quaternion?} @var{obj}
Return @true{} if @var{obj} is a vector quaternion, i.e. a quaternion
with zero real--part.
@end deffn

@deffn Procedure make-vector-quaternion @var{x} @var{y} @var{z}
Construct vector quaternion @code{xi+yj+zk}.  This is equivalent to
@code{(make-rectangular 0 x y z)}.
@end deffn

@deffn Procedure {vector-quaternion->list} @var{vq}
Return a newly allocated list of the x, y, and z components of
@var{vq}.  This is equivalent to
@code{(list (imag-part vq) (jmag-part vq) (kmag-part vq))}.
@end deffn

@deffn Procedure dot-product @vari{q} @varii{q}
For two vector quaternions @vari{q} = @code{ai+bj+ck} and @varii{q} =
@code{di+ej+fk}, return @code{ad + be + cf}.  This is equal to the
@math{R^3} dot product for vectors @math{(a,b,c)} and @math{(d,e,f)},
and is also equal to @code{(- (real-part (* q1 q2)))}.  It is an error
if either @vari{q} or @varii{q} has a non-zero real--part.
@end deffn

@deffn Procedure cross-product @vari{q} @varii{q}
For two vector quaternions @vari{q} = @code{ai+bj+ck} and @varii{q} =
@code{di+ej+fk}, return the @math{R^3} cross product for vectors
@math{(a,b,c)} and @math{(d,e,f)}, which is equal to
@code{(vector-part (* q1 q2))}.  It is an error
if either @vari{q} or @varii{q} has a non-zero real--part.
@end deffn

@deffn Procedure conjugate @var{q}
Return @code{(+ (real-part q) (* -1 (vector-part q)))}.

@example
(conjugate 0)          @result{}  0
(conjugate -i)         @result{}  +1i
(conjugate 1+2i-3j+4k) @result{}  1-2i+3j-4k
@end example
@end deffn

@subsection The @code{(kawa rotations)} module

The @code{(kawa rotations)} library provides a set of functions which
use unit quaternions to represent 3D spatial rotations.  To use these
functions, the library must be imported:
@example
(import (kawa rotations))
@end example

These functions normalize their quaternion inputs as needed to be of
length 1.

@subsubsection Rotation Representation Conversions

Conversions to and from several alternate representations of rotations
are supported.

The set of unit quaternions provides a double covering of all
possible 3D rotations: @code{q} and @code{-q} represent the same
rotation.  Most other representations also have multiple numerical
values which map to the same rotation (for example, the rotation about
@code{axis-vec} by @code{angle} is the same as the rotation about
@code{-axis-vec} by @code{-angle+2pi}).  Therefore, these functions do
not necessarily act as inverses in the sense of @func{equal?}.
Furthermore, rotations involve trigonometric functions, so there will
typically be some floating point error: @code{(acos (cos 0.1))} returns
0.09999999999999945, which is very close to 0.1 but not exact.

@subsubheading Rotation Matrices

@deffn Procedure {quaternion->rotation-matrix} @var{q}
@deffnx Procedure {rotation-matrix->quaternion} @var{m}

The @func{quaternion->rotation-matrix} procedure returns a 3x3 rotation
matrix representing the same rotation as @var{q}.  The rotation matrix
is instantiated as a @ref{Arrays,SRFI-25 multi-dimensional array} backed
by an @ref{Uniform vectors,f64vector}.

The @func{rotation-matrix->quaternion} procedure performs the reverse
operation, producing an equivalent unit quaternion for the rotation
matrix (multi-dimensional array) @var{m}.

@example
(rotation-matrix->quaternion (quaternion->rotation-matrix -1)) @result{} 1.0
@end example
@end deffn

@subsubheading Axis-Angle Representation

@deffn Procedure rotation-axis @var{q}
@deffnx Procedure rotation-angle @var{q}
@deffnx Procedure rotation-axis/angle @var{q}

The @func{rotation-axis} procedure returns the axis of rotation of the
quaternion @var{q} as a unit-length vector quaternion.  If the axis of
rotation is not well-defined (the angle of rotation is 0), then
@code{+i} is arbitrarily chosen as the axis.

The @func{rotation-angle} procedure returns the corresponding angle of
rotation.  Note that this is not the same as the result of the
@func{angle} procedure.

The @func{rotation-axis/angle} procedure returns the rotation axis and
angle as multiple values.

@example
(let* ((q 1/2+1/2i+1/2j+1/2k)
       (ar (rotation-angle q))
       (ad (java.lang.Math:toDegrees ar))
       (exact-ad (exact ad)))
  (rationalize exact-ad 1/10)) @result{} 120
@end example
@end deffn

@deffn Procedure {make-axis/angle} @var{axis-vec} @var{angle}
@deffnx Procedure {make-axis/angle} @var{axis-x} @var{axis-y} @var{axis-z} @var{angle}

The @func{make-axis/angle} procedure returns a quaternion representing
the given axis/angle rotation.  The axis is specified as either a single
vector quaternion argument @var{axis-vec}, or as three reals
@var{axis-x}, @var{axis-y}, and @var{axis-z}.
@end deffn

@deffn Procedure rotx @var{angle}
@deffnx Procedure roty @var{angle}
@deffnx Procedure rotz @var{angle}

The procedures @func{rotx}, @func{roty}, and @func{rotz} return
quaternions representing rotations about the X-, Y-, and Z-axes.
@end deffn

@subsubheading Intrinsic Angle Sets

The intrinsic angle sets represent arbitrary rotations as a sequence of
three rotations about coordinate frame axes attached to the rotating
body (i.e. the axes rotate with the body).

There are twelve possible angle sets which neatly divide into two groups
of six.  The six with same first and third axes are also known as
``Euler angles''.  The six with different first and third axes are also
known as ``Tait-Bryan angles''.

@deffn Procedure intrinsic-xyx @var{q}
@deffnx Procedure intrinsic-xzx @var{q}
@deffnx Procedure intrinsic-yxy @var{q}
@deffnx Procedure intrinsic-yzy @var{q}
@deffnx Procedure intrinsic-zxz @var{q}
@deffnx Procedure intrinsic-zyz @var{q}

These functions decompose the rotation represented by @var{q} into Euler
angles of the given set (XYX, XZX, YXY, YZY, ZXZ, or ZYZ) and returns
the three angles as multiple values.  The middle angle will be in the
range [0,pi].  If it is on the edges of that range (within 1.0E-12 of 0
or pi), such that the first and third axes are colinear, then the first
angle will be set to 0.

@example
(intrinsic-zyz (* (rotz 0.3) (roty 0.8) (rotz -0.6))) @result{} 0.3000000000000001 0.7999999999999999 -0.5999999999999999
@end example
@end deffn

@deffn Alias euler-xyx
@deffnx Alias euler-xzx
@deffnx Alias euler-yxy
@deffnx Alias euler-yzy
@deffnx Alias euler-zxz
@deffnx Alias euler-zyz
Aliases for the corresponding @code{intrinsic-} procedures.
@end deffn

@deffn Procedure intrinsic-xyz @var{q}
@deffnx Procedure intrinsic-xzy @var{q}
@deffnx Procedure intrinsic-yxz @var{q}
@deffnx Procedure intrinsic-yzx @var{q}
@deffnx Procedure intrinsic-zxy @var{q}
@deffnx Procedure intrinsic-zyx @var{q}

These functions decompose the rotation represented by @var{q} into
Tait-Bryan angles of the given set (XYZ, XZY, YXZ, YZX, ZXY, or ZYX) and
returns the three angles as multiple values.  The middle angle will be
in the range [-pi/2,pi/2].  If it is on the edges of that range, such
that the first and third axes are colinear, then the first angle will be
set to 0.
@end deffn

@deffn Alias tait-bryan-xyz
@deffnx Alias tait-bryan-xzy
@deffnx Alias tait-bryan-yxz
@deffnx Alias tait-bryan-yzx
@deffnx Alias tait-bryan-zxy
@deffnx Alias tait-bryan-zyx
Aliases for the corresponding @code{intrinsic-} procedures.
@end deffn

@deffn Procedure make-intrinsic-xyx @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-xzx @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-yxy @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-yzy @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-zxz @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-zyz @var{alpha} @var{beta} @var{gamma}

These functions return quaternions representing the given Euler angle
rotations.
@end deffn

@deffn Alias make-euler-xyx
@deffnx Alias make-euler-xzx
@deffnx Alias make-euler-yxy
@deffnx Alias make-euler-yzy
@deffnx Alias make-euler-zxz
@deffnx Alias make-euler-zyz
Aliases for the corresponding @code{make-intrinsic-} procedures.

@example
(let-values (((a b c) (euler-xyx (make-euler-xyx 1.0 0.0 2.0))))
  (list a b c)) @result{} (0.0 0.0 3.0)
@end example
@end deffn

@deffn Procedure make-intrinsic-xyz @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-xzy @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-yxz @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-yzx @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-zxy @var{alpha} @var{beta} @var{gamma}
@deffnx Procedure make-intrinsic-zyx @var{alpha} @var{beta} @var{gamma}

These functions return quaternions representing the given Tait-Bryan
angle rotations.
@end deffn

@deffn Alias make-tait-bryan-xyz
@deffnx Alias make-tait-bryan-xzy
@deffnx Alias make-tait-bryan-yxz
@deffnx Alias make-tait-bryan-yzx
@deffnx Alias make-tait-bryan-zxy
@deffnx Alias make-tait-bryan-zyx
Aliases for the corresponding @code{make-intrinsic-} procedures.
@end deffn

@subsubheading Extrinsic Angle Sets

The extrinsic angle sets represent arbitrary rotations as a sequence of
three rotations about fixed-frame axes (i.e. the axes do not rotate with
the body).

There are twelve possible extrinsic angle sets, and each is the dual of
an intrinsic set.  The extrinsic rotation about axes @code{A}, @code{B},
and @code{C} by angles @code{a}, @code{b}, and @code{c} is the same as
the intrinsic rotation about axes @code{C}, @code{B}, and @code{A} by
angles @code{c}, @code{b}, and @code{a}, with the order of the three
axes reversed.

@deffn Procedure extrinsic-xyx @var{q}
@deffnx Procedure extrinsic-xyz @var{q}
@deffnx Procedure extrinsic-xzx @var{q}
@deffnx Procedure extrinsic-zxy @var{q}
@deffnx Procedure extrinsic-yxy @var{q}
@deffnx Procedure extrinsic-yxz @var{q}
@deffnx Procedure extrinsic-yzx @var{q}
@deffnx Procedure extrinsic-yzy @var{q}
@deffnx Procedure extrinsic-zxy @var{q}
@deffnx Procedure extrinsic-zxz @var{q}
@deffnx Procedure extrinsic-zyx @var{q}
@deffnx Procedure extrinsic-zyz @var{q}

These functions decompose the rotation represented by @var{q} into
extrinsic angles of the given set and returns the three angles as
multiple values.
@end deffn

@deffn Procedure make-extrinsic-xyx @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-xyz @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-xzx @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-xzy @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-yxy @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-yxz @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-yzx @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-yzy @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-zxy @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-zxz @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-zyx @var{gamma} @var{beta} @var{alpha}
@deffnx Procedure make-extrinsic-zyz @var{gamma} @var{beta} @var{alpha}

These functions return quaternions representing the given extrinsic
angle rotations.
@end deffn

@deffn Alias rpy
@deffnx Alias make-rpy
Aliases for @func{extrinsic-xyz} and @func{make-extrinsic-xyz}.

@example
(let ((r (make-rpy 0.12 -0.23 0.34)))
  (let-values (((a b c) (tait-bryan-zyx r)))
    (list a b c))) @result{} (0.3400000000000001 -0.2300000000000001 0.12000000000000002)
@end example
@end deffn

@subsubsection Rotation Operations

@deffn Procedure rotate-vector @var{rq} @var{vq}
Applies the rotation represented by quaternion @var{rq} to the vector
represented by vector quaternion @var{vq}, and returns the rotated
vector.  This is equivalent to @code{(* rq vq (conjugate rq))} for
normalized @var{rq}.

@example
(rotate-vector +k +2i)                      @result{} -2i
(rotate-vector 1/2+1/2i+1/2j+1/2k +i+2j+3k) @result{} +3.0i+1.0j+2.0k
@end example
@end deffn

@deffn Procedure make-rotation-procedure @var{rq}
A partial application of @func{rotate-vector}.  Returns a
single-argument procedure which will take a vector quaternion argument
and rotate it by @var{rq}.  The returned procedure closes over both
@var{rq} and its conjugate, so this will likely be more efficient than
@func{rotate-vector} at rotating many vectors by the same rotation.
@end deffn

@node Quantities
@section Quantities and Units

As a super-class of numbers, Kawa also provides quantities.
A @dfn{quantity} is a product of a @dfn{unit} and a pure number.
The number part can be an arbitrary complex number.
The unit is a product of integer powers of base units,
such as meter or second.

Quantity literals have the following syntax:
@display
@stxdef{quantity} @stxref{optional-sign} @stxref{decimal} @stxref{unit-term} [@stxlit{*} @stxref{unit-term}]... [@stxlit{/} @stxref{unit-term}]
@stxdef{unit-term} @stxref{unit-name} [@stxlit{^} @stxref{digit}+]
@stxdef{unit-name} @stxref{letter}+
@end display
Some examples are @code{10pt} (10 points), @code{5s} (5 seconds),
and @code{4cm^2} (4 square centimeters).

Note the @var{quantity} syntax is not recognized by the reader.
Instead these are read as symbols.
Assuming there is no lexical binding the for the symbol, it will be
rewritten at compile-time into an expression.  For example @code{4cm^2}
is transformed into:
@example
(* 4.0 (expt unit:cm 2))
@end example

@deffn Procedure quantity? object
True iff @var{object} is a quantity.  Note that all numbers are
quantities, but not the other way round.
Currently, there are no quantities that are not numbers.
To distinguish a plain unit-less number from a quantity,
you can use @code{complex?}.
@end deffn
@c FIXME Using @code{complex?} as the test would erroneously classify
@c @code{1+j} as non-plain.  The right test would be @code{quaternion?},
@c though that requires importing the (kawa quaternions) module.

@deffn Procedure quantity->number q
Returns the pure number part of the quantity @var{q}, relative to
primitive (base) units.
If @var{q} is a number, returns @var{q}.
If @var{q} is a unit, yields the magitude of @var{q} relative to base units.
@end deffn

@deffn Procedure quantity->unit q
Returns the unit of the quantity @var{q}.
If @var{q} is a number, returns the empty unit.
@end deffn

@deffn Procedure make-quantity x unit
Returns the product of @var{x} (a pure number) and @var{unit}.
You can specify a string instead of @var{unit}, such as @code{"cm"}
or @code{"s"} (seconds).
@end deffn

@deffn Syntax define-base-unit unit-name dimension
Define @var{unit-name} as a base (primitive) unit,
which is used to measure along the specified @var{dimension}.
@example
(define-base-unit dollar "Money")
@end example
@end deffn

@deffn Syntax define-unit unit-name expression
Define @var{unit-name} as a unit (that can be used in literals)
equal to the quantity @var{expression}.
@example
(define-unit cent 0.01dollar)
@end example
The @var{unit-name} is declared in the @code{unit} namespace,
so the above is equivalent to:
@example
(define-constant unit:cent (* 0.01 unit:dollar))
@end example
@end deffn

@subheading Angles

The following angle units are dimensionless, with no base unit.

Some procedures treat a unit-less real number as if it were in radians
(which mathematicians prefer);
some procedures (such as @code{rotate}) treat a unit-less real number
as if it were in degrees
(which is common in Web and other standards).

@deffn Unit rad
A unit for angles specified in radians.
A full circle is 2*pi radians.
Note that @code{(= 1.5 1.5rad)} is true,
while @code{(eqv? 1.5 1.5rad)} is false.
@end deffn

@deffn Unit deg
A unit for angles specified in degrees.
A full circle is 360 degrees.
@end deffn

@deffn Unit grad
A unit for angles specified in gradians.
A full circle is 400 gradians.
@end deffn

@node Logical Number Operations
@section Logical Number Operations

These functions operate on the 2's complement binary representation
of an exact integer.

@deffn Procedure bitwise-not i
Returns the bit-wise logical inverse of the argument.
More formally, returns the exact integer whose two's
complement representation is the one's complement of the two's
complement representation of @var{i}.
@end deffn

@deffn Procedure  bitwise-and i ...
@deffnx Procedure bitwise-ior i ...
@deffnx Procedure bitwise-xor i ...
These procedures return the exact integer that is the bit-wise
``and'', ``inclusive or'', or ``exclusive or'' of the two's
complement representations of their arguments.
If they are passed only one argument, they return that argument.
If they are passed no arguments, they return the integer
that acts as identity for the operation: -1, 0, or 0, respectively. 
@end deffn

@deffn Procedure bitwise-if i1 i2 i3

Returns the exact integer that is the bit-wise ``if'' of the twos
complement representations of its arguments, i.e. for each bit, if it
is 1 in i1, the corresponding bit in i2 becomes the value of the
corresponding bit in the result, and if it is 0, the corresponding bit
in i3 becomes the corresponding bit in the value of the result. This
is equivaent to the following computation:
@example
(bitwise-ior (bitwise-and i1 i2)
             (bitwise-and (bitwise-not i1) i3))
@end example
@end deffn

@deffn Procedure bitwise-bit-count i
If i is non-negative, returns the number of 1 bits in the twos complement
representation of i. Otherwise it returns the result of the following
computation:
@example
(bitwise-not (bitwise-bit-count (bitwise-not i)))
@end example
@end deffn

@deffn Procedure bitwise-length i
Returns the number of bits needed to represent i if it is positive,
and the number of bits needed to represent @code{(bitwise-not @var{i})}
if it is negative, which is the exact integer that is the result of the
following computation:
@example
(do ((result 0 (+ result 1))
     (bits (if (negative? i)
               (bitwise-not i)
               ei)
           (bitwise-arithmetic-shift bits -1)))
    ((zero? bits)
     result))
@end example
This is the number of bits needed to represent @var{i} in an unsigned field.
@end deffn

@deffn Procedure bitwise-first-bit-set i
Returns the index of the least significant 1 bit in the twos complement
representation of i. If i is 0, then - 1 is returned.
@example
(bitwise-first-bit-set 0) @result{} -1
(bitwise-first-bit-set 1) @result{} 0
(bitwise-first-bit-set -4) @result{} 2
@end example
@end deffn

@deffn Procedure bitwise-bit-set? i1 i2
Returns @code{#t} if the i2'th bit (where @var{i2} must be non-negative)
is 1 in the two's complement representation of @var{i1}, and @code{#f}
otherwise. This is the result of the following computation:
@example
(not (zero?
       (bitwise-and
         (bitwise-arithmetic-shift-left 1 i2)
         i1)))
@end example
@end deffn

@deffn Procedure bitwise-copy-bit i bitno replacement-bit
Returns the result of replacing the @var{bitno}'th bit of @var{i}
by @var{replacement-bit}, where @var{bitno} must be non-negative,
and @var{replacement-bit} must be either 0 or 1.
This is the result of the following computation:
@example
(let* ((mask (bitwise-arithmetic-shift-left 1 bitno)))
  (bitwise-if mask
            (bitwise-arithmetic-shift-left replacement-bit bitno)
            i))
@end example
@end deffn

@deffn Procedure bitwise-bit-field n start end
Returns the integer formed from the (unsigned) bit-field
starting at @var{start} and ending just before @var{end}.
Same as:
@example
(let ((mask
       (bitwise-not
        (bitwise-arithmetic-shift-left -1 @var{end}))))
  (bitwise-arithmetic-shift-right
    (bitwise-and @var{n} mask)
    @var{start}))
@end example
@end deffn

@deffn Procedure bitwise-copy-bit-field to start end from
Returns the result of replacing in @var{to} the bits at positions from @var{start} (inclusive) to @var{end} (exclusive) by the bits in @var{from} from position 0 (inclusive) to position @var{end} - @var{start} (exclusive).
Both @var{start} and @var{start} must be non-negative,
and @var{start} must be less than or equal to @var{start}.

This is the result of the following computation:
@example
(let* ((mask1
         (bitwise-arithmetic-shift-left -1 start))
       (mask2
         (bitwise-not
           (bitwise-arithmetic-shift-left -1 end)))
       (mask (bitwise-and mask1 mask2)))
  (bitwise-if mask
              (bitwise-arithmetic-shift-left from
                                             start)
              to))
@end example
@end deffn

@deffn Procedure bitwise-arithmetic-shift i j
Shifts @var{i} by @var{j}.
It is a ``left'' shift if @code{@var{j}>0}, and
a ``right'' shift if @code{@var{j}<0}.
The result is equal to @code{(floor (* @var{i} (expt 2 @var{j})))}.

Examples:
@example
(bitwise-arithmetic-shift -6 -1) @result{}-3
(bitwise-arithmetic-shift -5 -1) @result{} -3
(bitwise-arithmetic-shift -4 -1) @result{} -2
(bitwise-arithmetic-shift -3 -1) @result{} -2
(bitwise-arithmetic-shift -2 -1) @result{} -1
(bitwise-arithmetic-shift -1 -1) @result{} -1
@end example
@end deffn

@deffn Procedure bitwise-arithmetic-shift-left i amount
@deffnx Procedure bitwise-arithmetic-shift-right i amount
The @var{amount} must be non-negative
The @code{bitwise-arithmetic-shift-left} procedure returns the same
result as @code{bitwise-arithmetic-shift},
and @code{(bitwise-arithmetic-shift-right @var{i} @var{amount})} returns the
same result as @code{(bitwise-arithmetic-shift @var{i} (- @var{amount}))}.

If @var{i} is a primitive integer type,
then @var{amount} must be less than the number of bits in the
promoted type of @var{i} (32 or 64).
If the type is unsigned, an unsigned (logic) shift is
done for @code{bitwise-arithmetic-shift-right},
rather than a signed (arithmetic) shift.
@end deffn

@deffn Procedure bitwise-rotate-bit-field n start end count
Returns the result of cyclically permuting in @var{n} the bits at positions
from @var{start} (inclusive) to @var{end} (exclusive) by
@var{count} bits towards the more significant bits,
@var{start} and @var{end} must be non-negative,
and @var{start} must be less than or equal to @var{end}.
This is the result of the following computation:
@example
(let* ((n     ei1)
       (width (- end start)))
  (if (positive? width)
      (let* ((count (mod count width))
             (field0
               (bitwise-bit-field n start end))
             (field1 (bitwise-arithmetic-shift-left
                       field0 count))
             (field2 (bitwise-arithmetic-shift-right
                       field0
                       (- width count)))
             (field (bitwise-ior field1 field2)))
        (bitwise-copy-bit-field n start end field))
      n))
@end example
@end deffn

@deffn Procedure bitwise-reverse-bit-field i start end
Returns the result obtained from @var{i} by reversing the order of the bits at positions from @var{start} (inclusive) to @var{end} (exclusive),
where @var{start} and @var{end} must be non-negative,
and @var{start} must be less than or equal to @var{end}.
@example
(bitwise-reverse-bit-field #b1010010 1 4) @result{}  88 ; #b1011000
@end example
@end deffn

@deffn Procedure logop op x y
Perform one of the 16 bitwise operations of @var{x} and @var{y},
depending on @var{op}.
@end deffn

@deffn Procedure logtest i j
Returns true if the arguments have any bits in common.
Same as @code{(not (zero? (bitwise-and @var{i} @var{j})))},
but is more efficient.
@end deffn

@subsection SRFI-60 Logical Number Operations

Kawa supports SRFI-60 ``Integers as Bits'' as well, although we
generally recommend using the R6RS-compatible functions instead when
possible.  Unless noted as being a builtin function, to use these you
must first @code{(require 'srfi-60)} or @code{(import (srfi :60))}
(or @code{(import (srfi :60 integer-bits))}).

@deffn Procedure logand i ...
Equivalent to @code{(bitwise-and @var{i} ...)}.  Builtin.
@end deffn

@deffn Procedure logior i ...
Equivalent to @code{(bitwise-ior @var{i} ...)}.  Builtin.
@end deffn

@deffn Procedure logxor i ...
Equivalent to @code{(bitwise-xor @var{i} ...)}.  Builtin.
@end deffn

@deffn Procedure lognot i
Equivalent to @code{(bitwise-not @var{i})}.  Builtin.
@end deffn

@deffn Procedure bitwise-merge mask i j
Equivalent to @code{(bitwise-if @var{mask} @var{i} @var{j})}.
@end deffn

@deffn Procedure any-bits-set? i j
Equivalent to @code{(logtest @var{i} @var{j})}.
@end deffn

@deffn Procedure logcount i
@deffnx Procedure bit-count i
Count the number of 1-bits in @var{i}, if it is non-negative.
If @var{i} is negative, count number of 0-bits.
Same as @code{(bitwise-bit-count @var{i})} if @var{i} is non-negative.
Builtin as @func{logcount}.
@end deffn

@deffn Procedure integer-length i
Equivalent to @code{(bitwise-length @var{i})}.  Builtin.
@end deffn

@deffn Procedure log2-binary-factors i
@deffnx Procedure first-set-bit i
Equivalent to @code{(bitwise-first-bit-set @var{i})}.
@end deffn

@deffn Procedure logbit? pos i
@deffnx Procedure bit-set? pos i
Equivalent to @code{(bitwise-bit-set? @var{i} @var{pos})}.
@end deffn

@deffn Procedure copy-bit bitno i bool
Equivalent to @code{(bitwise-copy-bit @var{i} @var{bitno} (if @var{bool} 1 0))}.
@end deffn

@deffn Procedure bit-field n start end
Equivalent to @code{(bitwise-bit-field @var{n} @var{start} @var{end})}.
@end deffn

@deffn Procedure copy-bit-field to from start end
Equivalent to @code{(bitwise-copy-bit-field @var{to} @var{start} @var{end} @var{from})}.
@end deffn

@deffn Procedure arithmetic-shift i j
Equivalent to @code{(bitwise-arithmetic-shift @var{i} @var{j})}.  Builtin.
@end deffn

@deffn Procedure ash i j
Alias for @code{arithmetic-shift}.  Builtin.
@end deffn

@deffn Procedure rotate-bit-field n count start end
Equivalent to @code{(bitwise-rotate-bit-field @var{n} @var{start} @var{end} @var{count})}.
@end deffn

@deffn Procedure reverse-bit-field i start end
Equivalent to @code{(bitwise-reverse-bit-field @var{i} @var{start} @var{end})}.
@end deffn

@deffn Procedure integer->list @var{k} [@var{length}]
@deffnx Procedure list->integer @var{list}
The @func{integer->list} procedure returns a list of @var{length}
booleans corresponding to the bits of the non-negative integer @var{k},
with @code{#t} for @code{1} and @code{#f} for @code{0}.  @var{length}
defaults to @code{(bitwise-length @var{k})}.  The list will be in order
from MSB to LSB, with the value of @code{(odd? @var{k})} in the last
car.

The @func{list->integer} procedure returns the integer corresponding to
the booleans in the list @var{list}.
The @func{integer->list} and @func{list->integer} procedures are
inverses so far as @func{equal?} is concerned.
@end deffn

@deffn Procedure booleans->integer bool1 ...
Returns the integer coded by the @var{bool1} ... arguments.
Equivalent to @code{(list->integer (list @var{bool1} ...))}.
@end deffn

@subsection Deprecated Logical Number Operations

This older function is still available, but we
recommend using the R6RS-compatible function.

@deffn Procedure bit-extract n start end
Equivalent to @code{(bitwise-bit-field @var{n} @var{start} @var{end})}.
@end deffn

@node Performance of numeric operations
@section Performance of numeric operations

Kawa can generally do a pretty good job of generating
efficient code for numeric operations, at least when
it knows or can figure out the types of the operands.

The basic operations @code{+}, @code{-}, and @code{*}
are compiled to single-instruction bytecode if both
operands are @code{int} or @code{long}.
Likewise, if both operands are floating-point (or
one is floating-point and the other is rational),
then single-instruction @code{double} or @code{float}
instructions are emitted.

A binary operation involving an infinite-precision @code{integer}
and a fixed-size @code{int} or @code{long} is normally
evaluated by expanding the latter to @code{integer}
and using @code{integer} arithmetic.  An exception is
an integer literal whose
value fits in an @code{int} or @code{long} - in that case
the operation is done using @code{int} or @code{long}
arithmetic.

In general, integer literals have amorphous type.
When used to infer the type of a variable, they have @code{integer} type:
@example
(let ((v1 0))
  ... v1 has type integer ... )
@end example
However, a literal whose value fits in the @code{int} or @code{long} range
is implicitly viewed @code{int} or @code{long} in certain contexts,
primarily method overload resolution and binary arithmetic
(as mentioned above).

The comparison functions @code{<}, @code{<=}, @code{=},
@code{>}, and @code{=>} are also optimized to single instriction
operations if the operands have appropriate type.
However, the functions @code{zero?}, @code{positive?}, and @code{negative?}
have not yet been optimized.
Instead of @code{(positive? x)} write @code{(> x 0)}.

There are a number of integer division and modulo operations.
If the operands are @code{int} or @code{long}, it is faster
to use @code{quotient} and @code{remainder} rather
than @code{div} and @code{mod} (or @code{modulo}).
If you know the first operand is non-negative and the second is positive,
then use @code{quotient} and @code{remainder}.
(If an operand is an arbitrary-precision @code{integer},
then it dosn't really matter.)

The logical operations @code{bitwise-and}, @code{bitwise-ior},
@code{bitwise-xor}, @code{bitwise-not}, @code{bitwise-arithmetic-shift-left},
@code{bitwise-arithmetic-shift-right} are compiled
to single bitcode instructions if the operands are @code{int} or @code{long}.
Avoid @code{bitwise-arithmetic-shift} if the sign of the shift is known.
If the operands are arbitrary-precision @code{integer},
a library call is needed, but run-time type dispatch is avoided.

@node Characters and text, Data structures, Numbers, Top
@chapter Characters and text

@menu
* Characters::
* Character sets::
* Strings::
* String literals::
* Unicode::              Unicode character classes and conversions
* Regular expressions::
@end menu

@node Characters
@section Characters

Characters are objects that represent human-readable characters
such as letters and digits.  More precisely, a character
represents a @uref{http://www.unicode.org/glossary/#unicode_scalar_value,
Unicode scalar value}. Each character has an integer value
in the range @code{0} to @code{#x10FFFF}
(excluding the range @code{#xD800} to @code{#xDFFF}
used for @uref{http://www.unicode.org/glossary/#surrogate_code_point, Surrogate Code Points}).

@quotation
@emph{Note:}
Unicode distinguishes
between glyphs, which are printed for humans to read, and characters,
which are abstract entities that map to glyphs (sometimes in a way
that’s sensitive to surrounding characters). Furthermore, different
sequences of scalar values sometimes correspond to the same
character. The relationships among scalar, characters, and glyphs are
subtle and complex.

Despite this complexity, most things that a literate human would call
a ``character'' can be represented by a single Unicode scalar value
(although several sequences of Unicode scalar values may represent
that same character). For example, Roman letters, Cyrillic letters,
Hebrew consonants, and most Chinese characters fall into this
category.

Unicode scalar values exclude the range @code{#xD800} to @code{#xDFFF},
which are part of the range of Unicode @dfn{code points}.
However, the Unicode code points in this range, the so-called
@dfn{surrogates}, are an artifact of the UTF-16 encoding, and can only
appear in specific Unicode encodings, and even then only in pairs that
encode scalar values.  Consequently, all characters represent code
points, but the surrogate code points do not have representations as
characters.
@end quotation

@deffn Type character
A Unicode code point - normally a Unicode scalar value,
but could be a surrogate.
This is implemented using a 32-bit @code{int}.
When an object is needed (i.e. the @dfn{boxed} representation),
it is implemented an instance of @code{gnu.text.Char}.
@end deffn

@deffn Type character-or-eof
A @code{character} or the specical @code{#!eof} value (used to indicate
end-of-file when reading from a port).
This is implemented using a 32-bit @code{int},
where the value -1 indicates end-of-file.
When an object is needed, it is implemented an instance of
@code{gnu.text.Char} or the special @code{#!eof} object.
@end deffn

@deffn Type char
A UTF-16 code unit.  Same as Java primitive @code{char} type.
Considered to be a sub-type of @code{character}.
When an object is needed, it is implemented as an instance
of @code{java.lang.Character}.  Note the unfortunate inconsistency
(for historical reasons) of @code{char} boxed as @code{Character}
vs @code{character} boxed as @code{Char}.
@end deffn

Characters are written using the notation
@code{#\}@var{character} (which stands for the given @var{character};
@code{#\x}@var{hex-scalar-value} (the character whose scalar value
is the given hex integer);
or @code{#\}@var{character-name} (a character with a given name):

@c can't use @stxlit because of slash
@display
@stxdef{character} @code{@b{#\}}@var{any-character}
        | @code{@b{#\}} @meta{character-name}
        | @code{@b{#\x}} @stxref{hex-scalar-value}
        | @code{@b{#\X}} @stxref{hex-scalar-value}
@end display

The following @meta{character-name} forms are recognized:
@table @code
@item @b{#\alarm}
@code{#\x0007} - the alarm (bell) character
@item @b{#\backspace}
@code{#\x0008}
@item @b{#\delete}
@item @b{#\del}
@item @b{#\rubout}
@code{#\x007f} - the delete or rubout character
@item @b{#\escape}
@item @b{#\esc}
@code{#\x001b}
@item @b{#\newline}
@itemx @b{#\linefeed}
@code{#\x001a} - the linefeed character
@item @b{#\null}
@itemx @b{#\nul}
@code{#\x0000} - the null character
@item @b{#\page}
@code{#\000c} - the formfeed character
@item @b{#\return}
@code{#\000d} - the carriage return character
@item @b{#\space}
@code{#\x0020} - the preferred way to write a space
@item @b{#\tab}
@code{#\x0009} - the tab character
@item @b{#\vtab}
@code{#\x000b} - the vertical tabulation character
@item @b{#\ignorable-char}
A special @code{character} value, but it is not a Unicode code point.
It is a special value returned when an index refers to the second
@code{char} (code point) of a surrogate pair, and which should be ignored.
(When writing a @code{character} to a string or file,
it will be written as one or two @code{char} values.
The exception is @code{#\ignorable-char}, for which zero 
@code{char} values are written.)
@end table

@deffn Procedure {char?} @var{obj}
Return @true{} if @var{obj} is a character, @false{} otherwise.
(The @var{obj} can be any character, not just a 16-bit @code{char}.)
@end deffn

@deffn Procedure {char->integer} @var{char}
@deffnx Procedure {integer->char} @var{sv}
@var{sv} should be a Unicode scalar value, i.e., a non--negative exact
integer object in @code{[0, #xD7FF] union [#xE000, #x10FFFF]}.
(Kawa also allows values in the surrogate range.)

Given a character, @func{char->integer} returns its Unicode scalar value
as an exact integer object.  For a Unicode scalar value @var{sv},
@func{integer->char} returns its associated character.

@example
(integer->char 32)                     @result{} #\space
(char->integer (integer->char 5000))   @result{} 5000
(integer->char #\xD800)                @result{} throws ClassCastException
@end example

@PerformanceNote{} A call to @code{char->integer} is compiled as
casting the argument to a @code{character}, and then re-interpreting
that value as an @code{int}.
A call to @code{integer->char} is compiled as
casting the argument to an @code{int}, and then re-interpreting
that value as an @code{character}.
If the argument is the right type, no code is emitted: the value is
just re-interpreted as the result type.
@end deffn

@deffn Procedure {char=?} @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure {char<?} @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure {char>?} @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure {char<=?} @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure {char>=?} @vari{char} @varii{char} @variii{char} @dots{}
These procedures impose a total ordering on the set of characters
according to their Unicode scalar values.

@example
(char<? #\z #\ß)      @result{} #t
(char<? #\z #\Z)      @result{} #f
@end example

@PerformanceNote{}  This is compiled as if converting each
argument using @code{char->integer} (which requires no code)
and the using the corresponing @code{int} comparison.
@end deffn

@deffn Procedure digit-value char
This procedure returns the numeric value (0 to 9) of its
argument if it is a numeric digit (that is, if @code{char-numeric?}
returns @code{#t}), or @code{#f} on any other character.

@example
(digit-value #\3)        @result{} 3
(digit-value #\x0664)    @result{} 4
(digit-value #\x0AE6)    @result{} 0
(digit-value #\x0EA6)    @result{} #f
@end example

@end deffn

@node Character sets
@section Character sets

Sets of characters are useful for text-processing code,
including parsing, lexing, and pattern-matching.
@uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14} specifies
a @code{char-set} type for such uses.  Some examples:

@example
(import (srfi :14 char-sets))
(define vowel (char-set #\a #\e #\i #\o #\u))
(define vowely (char-set-adjoin vowel #\y))
(char-set-contains? vowel #\y) @result{}  #f
(char-set-contains? vowely #\y) @result{}  #t
@end example

See the @uref{http://srfi.schemers.org/srfi-14/srfi-14.html, SRFI 14 specification} for details.

@deffn Type char-set
The type of character sets.
In Kawa @code{char-set} is a type that can be used in type specifiers:
@example
(define vowely ::char-set (char-set-adjoin vowel #\y))
@end example
@end deffn

Kawa uses @uref{https://en.wikipedia.org/wiki/Inversion_list,inversion lists} for an efficient implementation, using Java @code{int} arrays
to represents character ranges (inversions).
The @code{char-set-contains?} function uses binary search,
so it takes time proportional to the logarithm of the number of inversions.
Other operations may take time proportional to the number of inversions.

@node Strings
@section Strings

Strings are sequences of characters.  The @emph{length} of a string is
the number of characters that it contains, as an exact non-negative integer.
The @emph{valid indices} of a string are the
exact non-negative integers less than the length of the string.
The first character of a
string has index 0, the second has index 1, and so on.

Strings are @emph{implemented} as a sequence of 16-bit @code{char} values,
even though they're semantically a sequence of 32-bit Unicode code points.
A character whose value is greater than @code{#xffff}
is represented using two surrogate characters.
The implementation allows for natural interoperability with Java APIs.
However it does make certain operations (indexing or counting based on
character counts) difficult to implement efficiently.  Luckily one
rarely needs to index or count based on character counts;
alternatives are discussed below.

@cindex istring
@cindex mstring
There are different kinds of strings:
@itemize
@item
An @dfn{istring} is @emph{immutable}:
It is fixed, and cannot be modified.
On the other hand, indexing (e.g. @code{string-ref}) is efficient (constant-time),
while indexing of other string implementations takes time proportional
to the index.

String literals are istrings, as are the return values of
most of the procedures in this chapter.

An @dfn{istring} is an instance of the @code{gnu.lists.IString} class.

@item
An @dfn{mstring} is @emph{mutable}:
You can replace individual characters (using @code{string-set!}).
You can also change the @var{mstring}'s length by inserting
or removing characters (using @code{string-append!} or @code{string-replace!}).

An @dfn{mstring} is an instance of the @code{gnu.lists.FString} class.

@item
Any other object that implements the @code{java.lang.CharSequence} interface
is also a string.
This includes standard Java @code{java.lang.String}
and @code{java.lang.StringBuilder} objects.
@end itemize

Some of the procedures that operate on strings ignore the
difference between upper and lower case. The names of
the versions that ignore case end with “@code{-ci}” (for “case
insensitive”).

@CompatibilityNote{}
Many of the following procedures (for example @code{string-append})
return an immutable istring in Kawa,
but return a ``freshly allocated'' mutable string in
standard Scheme (include R7RS) as well as most Scheme implementations
(including previous versions of Kawa).
To get the  ``compatibility mode'' versions of those procedures
(which return mstrings),
invoke Kawa with one the @code{--r5rs}, @code{--r6rs}, or @code{--r7rs}
options, or you can @code{import} a standard library like @code{(scheme base)}.

@deffn Type string
The type of string objects.
The underlying type is the interface @code{java.lang.CharSequence}.
Immultable strings are @code{gnu.lists.IString} or @code{java.lang.String},
while mutable strings are @code{gnu.lists.FString}.
@end deffn

@subsection Basic string procedures

@deffn Procedure {string?} @var{obj}
Return @true{} if @var{obj} is a string, @false{} otherwise.
@end deffn

@deffn Procedure {istring?} @var{obj}
Return @true{} if @var{obj} is a istring (a immutable, constant-time-indexable string); @false{} otherwise.
@end deffn

@deffn Constructor string @var{char} @dots{}
Return a string composed of the arguments.
This is analogous to @var{list}.

@CompatibilityNote{} The result is an istring,
except in compatibility mode, when it is a new allocated mstring.
@end deffn

@deffn Procedure string-length @var{string}
Return the number of characters in the given @var{string} as an exact
integer object.

@PerformanceNote{} If the @var{string} is not an istring,
the calling @code{string-length} may take time proportional
to the length of the @var{string},
because of the need to scan for surrogate pairs.
@end deffn

@deffn Procedure string-ref @var{string} @var{k}
@var{k} must be a valid index of @var{string}.  The @func{string-ref}
procedure returns character @var{k} of @var{string} using zero--origin
indexing.

@PerformanceNote{} If the @var{string} is not an istring,
then calling @code{string-ref} may take time proportional
to @var{k} because of the need to check for surrogate pairs.
An alternative is to use @code{string-cursor-ref}.
If iterating through a string, use @code{string-for-each}.
@end deffn

@deffn Procedure string-null? @var{string}
Is @var{string} the empty string?
Same result as @code{(= (string-length @var{string}) 0)} but
executes in O(1) time.
@end deffn

@deffn Procedure string-every pred string [start end])
@deffnx Procedure string-any pred string [start end])

Checks to see if every/any character in @var{string} satisfies @var{pred},
proceeding from left (index @var{start}) to right (index @var{end}). These
procedures are short-circuiting: if @var{pred} returns false,
@code{string-every} does not call @var{pred} on subsequent characters;
if @var{pred} returns true, @code{string-any} does not call @var{pred}
on subsequent characters. Both procedures are ``witness-generating'':
@itemize
@item
If @code{string-every} is given an empty interval (with @var{start} = @var{end}),
it returns @code{#t}.
@item
If @code{string-every} returns true for a non-empty interval
(with @var{start} < @var{end}), the returned true value is the one returned by the final call to the predicate on
@code{(string-ref @var{string} (- @var{end} 1))}.
@item
If @code{string-any} returns true, the returned true value is the one
returned by the predicate.
@end itemize

@emph{Note:} The names of these procedures do not end with a question
mark. This indicates a general value is returned instead of a simple
boolean (@code{#t} or @code{#f}).
@end deffn

@subsection Immutable String Constructors

@deffn Procedure string-tabulate proc len

Constructs a string of size @var{len} by calling @var{proc} on
each value from 0 (inclusive) to @var{len} (exclusive) to produce
the corresponding element of the string.
The procedure @var{proc} accepts an exact integer as its argument and returns a character.
The order in which @var{proc} is called on those indexes is not specifified.

@emph{Rationale:} Although @code{string-unfold} is more general,
@code{string-tabulate} is likely to run faster for the common special
case it implements.
@end deffn

@deffn Procedure string-unfold stop? mapper successor seed [base make-final]
@deffnx Procedure string-unfold-right stop? mapper successor seed [base make-final]
This is a fundamental and powerful constructor for strings.
@itemize
@item
@var{successor} is used to generate a series of ``seed'' values from the initial seed:
@var{seed}, @code{(}@var{successor} @var{seed}@code{)}, @code{(}@var{successor}@sup{2} @var{seed}@code{)}, @code{(}@var{successor}@sup{3} @var{seed}@code{)}, ...
@item 
@var{stop?} tells us when to stop — when it returns true when applied to one of these seed values.
@item 
@var{mapper} maps each seed value to the corresponding character(s) in the result string, which are assembled into that string in left-to-right order. It is an error for @var{mapper} to return anything other than a character or string.
@item 
@var{base} is the optional initial/leftmost portion of the constructed string, which defaults to the empty string @code{""}.
It is an error if @var{base} is anything other than a character or string.
@item 
@var{make-final} is applied to the terminal seed value (on which @var{stop?} returns true) to produce the final/rightmost portion of the constructed string. It defaults to @code{(lambda (x) "")}.
It is an error for @var{make-final} to return anything other than
a character or string.
@end itemize

@code{string-unfold-right} is the same as @code{string-unfold} except the
results of @var{mapper} are assembled into the string in right-to-left order,
@var{base} is the optional rightmost portion of the constructed string, and
@var{make-final} produces the leftmost portion of the constructed string.

You can use it @code{string-unfold} to convert a list to a string,
read a port into a string, reverse a string, copy a string, and so forth.
Examples:
@example
(define (port->string p)
  (string-unfold eof-object? values
                 (lambda (x) (read-char p))
                 (read-char p)))

(define (list->string lis)
  (string-unfold null? car cdr lis))

(define (string-tabulate f size)
  (string-unfold (lambda (i) (= i size)) f add1 0))
@end example
To map @var{f} over a list @var{lis}, producing a string:
@example
(string-unfold null? (compose @var{f} car) cdr @var{lis})
@end example

Interested functional programmers may enjoy noting that @code{string-fold-right}
and @code{string-unfold} are in some sense inverses.
That is, given operations @var{knull?}, @var{kar}, @var{kdr},
@var{kons}, and @var{knil} satisfying
@example
(@var{kons} (@var{kar} x) (@var{kdr} x)) = x  and  (@var{knull?} @var{knil}) = #t
@end example
then
@example
(string-fold-right @var{kons} @var{knil} (string-unfold @var{knull?} @var{kar} @var{kdr} @var{x})) = @var{x}
@end example
and
@example
(string-unfold @var{knull?} @var{kar} @var{kdr} (string-fold-right @var{kons} @var{knil} @var{string})) = @var{string}.
@end example

This combinator pattern is sometimes called an ``anamorphism.''

@end deffn

@subsection Selection

@deffn Procedure substring @var{string} @var{start} @var{end}
@var{string} must be a string, and @var{start} and @var{end} must be
exact integer objects satisfying:

@example
0 <= @var{start} <= @var{end} <= (string-length @var{string})
@end example

The @func{substring} procedure returns a newly allocated string formed
from the characters of @var{string} beginning with index @var{start}
(inclusive) and ending with index @var{end} (exclusive).
@end deffn

@deffn Procedure string-take string nchars
@deffnx Procedure string-drop       string nchars
@deffnx Procedure string-take-right string nchars
@deffnx Procedure string-drop-right string nchars
@code{string-take} returns an immutable string containing the
first @var{nchars} of @var{string};
@code{string-drop} returns a string containing all but the first @var{nchars}
of @var{string}.
@code{string-take-right} returns a string containing the last @var{nchars}
of @var{string}; @code{string-drop-right} returns a string containing all
but the last @var{nchars} of @var{string}.

@example
(string-take "Pete Szilagyi" 6) @result{} "Pete S"
(string-drop "Pete Szilagyi" 6) @result{} "zilagyi"

(string-take-right "Beta rules" 5) @result{} "rules"
(string-drop-right "Beta rules" 5) @result{} "Beta "
@end example
It is an error to take or drop more characters than are in the string:
@example
(string-take "foo" 37) @result{} @i{error}
@end example
@end deffn

@deffn Procedure string-pad       string len [char start end]
@deffnx Procedure string-pad-right string len [char start end]
Returns an istring of length @var{len} comprised of the characters
drawn from the given subrange of @var{string},
padded on the left (right) by as many occurrences of the
character @var{char} as needed.
If @var{string} has more than @var{len} chars, it is truncated on the
left (right) to length @var{len}.
The @var{char} defaults to @code{#\space}
@example.
(string-pad     "325" 5) @result{} "  325"
(string-pad   "71325" 5) @result{} "71325"
(string-pad "8871325" 5) @result{} "71325"
@end example
@end deffn

@deffn Procedure string-trim       string [pred start end]
@deffnx Procedure string-trim-right string [pred start end]
@deffnx Procedure string-trim-both  string [pred start end]
Returns an istring obtained from the given subrange of @var{string}
by skipping over all characters on the left / on the right / on both sides that satisfy the second argument @var{pred}:
@var{pred} defaults to @code{char-whitespace?}.
@example
(string-trim-both "  The outlook wasn't brilliant,  \n\r")
    @result{} "The outlook wasn't brilliant,"
@end example
@end deffn

@subsection String Comparisons

@deffn Procedure {string=?} @vari{string} @varii{string} @variii{string} @dots{}
Return @true{} if the strings are the same length and contain the same
characters in the same positions.  Otherwise, the @func{string=?}
procedure returns @false{}.

@example
(string=? "Straße" "Strasse")    @result{} #f
@end example
@end deffn


@deffn Procedure {string<?} @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure {string>?} @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure {string<=?} @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure {string>=?} @vari{string} @varii{string} @variii{string} @dots{}
These procedures return @code{#t} if their arguments are (respectively):
monotonically increasing, monotonically decreasing,
monotonically non-decreasing, or monotonically nonincreasing.
These predicates are required to be transitive.

These procedures are the lexicographic extensions to strings of the
corresponding orderings on characters.  For example, @func{string<?} is
the lexicographic ordering on strings induced by the ordering
@func{char<?} on characters.  If two strings differ in length but are
the same up to the length of the shorter string, the shorter string is
considered to be lexicographically less than the longer string.

@example
(string<? "z" "ß")      @result{} #t
(string<? "z" "zz")     @result{} #t
(string<? "z" "Z")      @result{} #f
@end example
@end deffn

@deffn Procedure string-ci=? @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure string-ci<? @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure string-ci>? @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure string-ci<=? @vari{string} @varii{string} @variii{string} @dots{}
@deffnx Procedure string-ci>=? @vari{string} @varii{string} @variii{string} @dots{}
These procedures are similar to @func{string=?}, etc.,
but behave as if they applied @code{string-foldcase} to their arguments
before invoking the corresponding procedures without @code{-ci}.

@example
(string-ci<? "z" "Z")                   @result{} #f
(string-ci=? "z" "Z")                   @result{} #t
(string-ci=? "Straße" "Strasse")        @result{} #t
(string-ci=? "Straße" "STRASSE")        @result{} #t
(string-ci=? "ΧΑΟΣ" "χαοσ")             @result{} #t
@end example
@end deffn

@subsection Conversions

@deffn Procedure list->string @var{list}
The @func{list->string} procedure returns an istring
formed from the characters in @var{list}, in order.
It is an error if any element of @var{list} is not a character.

@CompatibilityNote{} The result is an istring,
except in compatibility mode, when it is an mstring.
@end deffn

@deffn Procedure reverse-list->string @var{list}
An efficient implementation of @code{(compose list->text reverse)}:
@example
(reverse-list->text '(#\a #\B #\c))  @result{} "cBa"
@end example
This is a common idiom in the epilogue of string-processing loops
that accumulate their result using a list in reverse order.
(See also @code{string-concatenate-reverse} for the ``chunked'' variant.)
@end deffn

@deffn Procedure string->list @var{string} [@var{start} [@var{end}]]
The @func{string->list} procedure returns a newly allocated list of the
characters of @var{string} between @var{start} and @var{end}, in order.
The @func{string->list} and @func{list->string} procedures are inverses
so far as @func{equal?} is concerned.
@end deffn

@deffn Procedure vector->string vector [start [end]]
The @code{vector->string} procedure returns a newly allocated
string of the objects contained in the elements of @var{vector}
between @var{start} and @var{end}.
It is an error if any element of @var{vector} between @var{start}
and @var{end} is not a character, or is a character forbidden in strings.
@example
(vector->string #(#\1 #\2 #\3))             @result{} "123"
(vector->string #(#\1 #\2 #\3 #\4 #\5) 2 4) @result{} "34"
@end example
@end deffn

@deffn Procedure string->vector string [start [end]]
The @code{string->vector} procedure
returns a newly created vector initialized to the elements
of the string @var{string} between @var{start} and @var{end}.
@example
(string->vector "ABC")       @result{} #(#\A #\B #\C)
(string->vector "ABCDE" 1 3) @result{} #(#\B #\C)
@end example
@end deffn

@deffn Procedure string-upcase @var{string}
@deffnx Procedure string-downcase @var{string}
@deffnx Procedure string-titlecase @var{string}
@deffnx Procedure string-foldcase @var{string}
These procedures take a string argument and return a string result.
They are defined in terms of Unicode's locale--independent case mappings
from Unicode scalar--value sequences to scalar--value sequences.  In
particular, the length of the result string can be different from the
length of the input string.  When the specified result is equal in the
sense of @func{string=?} to the argument, these procedures may return
the argument instead of a newly allocated string.

The @func{string-upcase} procedure converts a string to upper case;
@func{string-downcase} converts a string to lower case.  The
@func{string-foldcase} procedure converts the string to its case--folded
counterpart, using the full case--folding mapping, but without the
special mappings for Turkic languages.  The @func{string-titlecase}
procedure converts the first cased character of each word, and downcases
all other cased characters.

@example
(string-upcase "Hi")              @result{} "HI"
(string-downcase "Hi")            @result{} "hi"
(string-foldcase "Hi")            @result{} "hi"

(string-upcase "Straße")          @result{} "STRASSE"
(string-downcase "Straße")        @result{} "straße"
(string-foldcase "Straße")        @result{} "strasse"
(string-downcase "STRASSE")       @result{} "strasse"

(string-downcase "Σ")             @result{} "σ"
; Chi Alpha Omicron Sigma:
(string-upcase "ΧΑΟΣ")            @result{} "ΧΑΟΣ"
(string-downcase "ΧΑΟΣ")          @result{} "χαος"
(string-downcase "ΧΑΟΣΣ")         @result{} "χαοσς"
(string-downcase "ΧΑΟΣ Σ")        @result{} "χαος σ"
(string-foldcase "ΧΑΟΣΣ")         @result{} "χαοσσ"
(string-upcase "χαος")            @result{} "ΧΑΟΣ"
(string-upcase "χαοσ")            @result{} "ΧΑΟΣ"

(string-titlecase "kNock KNoCK")  @result{} "Knock Knock"
(string-titlecase "who's there?") @result{} "Who's There?"
(string-titlecase "r6rs")         @result{} "R6rs"
(string-titlecase "R6RS")         @result{} "R6rs"
@end example

Since these procedures are locale--independent, they may not be
appropriate for some locales.

@emph{Kawa Note:}  The implementation of @func{string-titlecase}
does not correctly handle the case where an initial character
needs to be converted to multiple characters, such as
``LATIN SMALL LIGATURE FL'' which should be converted to
the two letters @code{"Fl"}.

@CompatibilityNote{} The result is an istring,
except in compatibility mode, when it is an mstring.
@end deffn

@deffn Procedure string-normalize-nfd @var{string}
@deffnx Procedure string-normalize-nfkd @var{string}
@deffnx Procedure string-normalize-nfc @var{string}
@deffnx Procedure string-normalize-nfkc @var{string}
These procedures take a string argument and return a string result,
which is the input string normalized to Unicode normalization form D,
KD, C, or KC, respectively.  When the specified result is equal in the
sense of @func{string=?} to the argument, these procedures may return
the argument instead of a newly allocated string.

@example
(string-normalize-nfd "\xE9;")          @result{} "\x65;\x301;"
(string-normalize-nfc "\xE9;")          @result{} "\xE9;"
(string-normalize-nfd "\x65;\x301;")    @result{} "\x65;\x301;"
(string-normalize-nfc "\x65;\x301;")    @result{} "\xE9;"
@end example
@end deffn

@subsection Searching and matching

@deffn Procedure string-prefix-length string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
@deffnx Procedure string-suffix-length string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
Return the length of the longest common prefix/suffix of @var{string@sub{1}}
and @var{string@sub{2}}.
For prefixes, this is equivalent to their ``mismatch index''
(relative to the start indexes).

The optional @var{start}/@var{end} indexes restrict the comparison
to the indicated substrings of @var{string@sub{1}} and @var{string@sub{2}}.
@end deffn

@deffn Procedure string-prefix? string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
@deffnx Procedure string-suffix? string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
Is @var{string@sub{1}} a prefix/suffix of @var{string@sub{2}}?

The optional @var{start}/@var{end} indexes restrict the comparison
to the indicated substrings of @var{string@sub{1}} and @var{string@sub{2}}.
@end deffn

@deffn Procedure string-index       string pred [start end]
@deffnx Procedure string-index-right string pred [start end]
@deffnx Procedure string-skip        string pred [start end]
@deffnx Procedure string-skip-right  string pred [start end]

@code{string-index} searches through the given substring from the
left, returning the index of the leftmost character satisfying the
predicate @var{pred}.
@code{string-index-right} searches from the right, returning
the index of the rightmost character satisfying the predicate @var{pred}.
If no match is found, these procedures return @code{#f}.

The @var{start} and @var{end} arguments specify the beginning and end
of the search; the valid indexes relevant to the search include @var{start}
but exclude @var{end}. Beware of ``fencepost''" errors: when searching
right-to-left, the first index considered is @code{(- @var{end} 1)},
whereas when searching left-to-right, the first index considered is @var{start}.
That is, the start/end indexes describe the same half-open interval
@code{[@var{start},@var{end})}
in these procedures that they do in other string procedures.

The @code{-skip} functions are similar, but use the complement of the
criterion: they search for the first char that @emph{doesn't} satisfy
@var{pred}. To skip over initial whitespace, for example, say

@example
(substring string
            (or (string-skip string char-whitespace?)
                (string-length string))
            (string-length string))
@end example

These functions can be trivially composed with @code{string-take} and
@code{string-drop} to produce @code{take-while}, @code{drop-while},
@code{span}, and @code{break} procedures without loss of efficiency.
@end deffn

@c SRFI-13 and Guile generalizes pred to char_pred, which can be a
@c predicate, a character, or a character set. That seems
@c convenient.

@deffn Procedure string-contains       string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
@deffnx Procedure string-contains-right string@sub{1} string@sub{2} [start@sub{1} end@sub{1} start@sub{2} end@sub{2}]
Does the substring of @var{string@sub{1}} specified by @var{start@sub{1}} and @var{end@sub{1}} contain the sequence of characters given by the substring of @var{string@sub{2}} specified by @var{start@sub{2}} and @var{end@sub{2}}?

Returns @code{#f} if there is no match.
If @var{start@sub{2}} = @var{end@sub{2}}, @code{string-contains}
returns @var{start@sub{1}} but @code{string-contains-right}
returns @var{end@sub{1}}. Otherwise returns the index in @var{string@sub{1}} for the first character of the first/last match; that index lies within the half-open interval [@var{start@sub{1}},@var{end@sub{1}}), and the match lies entirely within the [@var{start@sub{1}},@var{end@sub{1}}) range of @var{string@sub{1}}.

@example
(string-contains "eek -- what a geek." "ee" 12 18) ; Searches "a geek"
    @result{} 15
@end example
Note: The names of these procedures do not end with a question mark. This indicates a useful value is returned when there is a match.


@end deffn

@subsection Concatenation and replacing

@deffn Procedure string-append @var{string} @dots{}
Returns a string whose characters form the concatenation
of the given strings.

@CompatibilityNote{} The result is an istring,
except in compatibility mode, when it is an mstring.
@end deffn

@deffn Procedure string-concatenate string-list
Concatenates the elements of @var{string-list} together into a single istring.

@emph{Rationale:} Some implementations of Scheme limit the number of
arguments that may be passed to an n-ary procedure, so the
@code{(apply string-append @var{string-list})} idiom,
which is otherwise equivalent to using this procedure, is not as portable.
@end deffn

@deffn Procedure string-concatenate-reverse string-list [final-string [end]])
With no optional arguments, calling this procedure is equivalent to
@code{(string-concatenate (reverse @var{string-list}))}.
If the optional argument @var{final-string} is specified,
it is effectively consed onto the beginning of @var{string-list}
before performing the list-reverse and string-concatenate operations.

If the optional argument @var{end} is given, only the characters up to but not including @var{end} in @var{final-string} are added to the result,
thus producing
@example
(string-concatenate 
  (reverse (cons (substring final-string 0 end)
                 string-list)))
@end example
For example:
@example
(string-concatenate-reverse '(" must be" "Hello, I") " going.XXXX" 7)
  @result{} "Hello, I must be going."
@end example

@emph{Rationale:} This procedure is useful when constructing
procedures that accumulate character data into lists of string
buffers, and wish to convert the accumulated data into a single string
when done. The optional end argument accommodates that use case when
@var{final-string} is a bob-full mutable string,
and is allowed (for uniformity) when
@var{final-string} is an immutable string.
@end deffn

@deffn Procedure string-join string-list [delimiter [grammar]]
This procedure is a simple unparser; it pastes strings together
using the @var{delimiter} string, returning an istring.

The @var{string-list} is a list of strings.
The @var{delimiter} is the string used to delimit elements; it defaults to a single space @code{" "}.

The @var{grammar} argument is a symbol that determines how the @var{delimiter}
is used, and defaults to @code{'infix}.
It is an error for @var{grammar} to be any symbol other than these four:
@table @code
@item 'infix
An infix or separator grammar: insert the delimiter between list elements. An empty list will produce an empty string.
@item 'strict-infix
Means the same as @code{'infix} if the string-list is non-empty,
but will signal an error if given an empty list.
(This avoids an ambiguity shown in the examples below.)
@item 'suffix
Means a suffix or terminator grammar: insert the @var{delimiter}
after every list element.
@item 'prefix
Means a prefix grammar: insert the @var{delimiter} before every list element.
@end table

@example
(string-join '("foo" "bar" "baz"))
         @result{} "foo bar baz"
(string-join '("foo" "bar" "baz") "")
         @result{} "foobarbaz"
(string-join '("foo" "bar" "baz") ":")
         @result{} "foo:bar:baz"
(string-join '("foo" "bar" "baz") ":" 'suffix)
         @result{} "foo:bar:baz:"

;; Infix grammar is ambiguous wrt empty list vs. empty string:
(string-join '()   ":") @result{} ""
(string-join '("") ":") @result{} ""

;; Suffix and prefix grammars are not:
(string-join '()   ":" 'suffix)) @result{} ""
(string-join '("") ":" 'suffix)) @result{} ":"
@end example

@end deffn

@deffn Procedure string-replace string@sub{1} string@sub{2} start@sub{1} end@sub{1} [start@sub{2} end@sub{2}]
Returns
@example
(string-append (substring @var{string@sub{1}} 0 @var{start@sub{1}})
               (substring @var{string@sub{2}} @var{start@sub{2}} @var{end@sub{2}})
               (substring @var{string@sub{1}} @var{end@sub{1}} (string-length @var{string@sub{1}})))
@end example
That is, the segment of characters in @var{string@sub{1}} from @var{start@sub{1}}
to @var{end@sub{1}} is replaced by the segment of characters in @var{string@sub{2}} from @var{start@sub{2}} to @var{end@sub{2}}.
If @var{start@sub{1}}=@var{end@sub{1}}, this simply splices the characters
drawn from @var{string@sub{2}} into @var{string@sub{1}} at that position.

Examples:
@example
(string-replace "The TCL programmer endured daily ridicule."
                 "another miserable perl drone" 4 7 8 22)
    @result{} "The miserable perl programmer endured daily ridicule."

(string-replace "It's easy to code it up in Scheme." "lots of fun" 5 9)
    @result{} "It's lots of fun to code it up in Scheme."

(define (string-insert s i t) (string-replace s t i i))

(string-insert "It's easy to code it up in Scheme." 5 "really ")
    @result{} "It's really easy to code it up in Scheme."

(define (string-set s i c) (string-replace s (string c) i (+ i 1)))

(string-set "String-ref runs in O(n) time." 19 #\1)
    @result{} "String-ref runs in O(1) time."
@end example
@end deffn

Also see @code{string-append!} and @code{string-replace!}
for destructive changes to a mutable string.

@subsection Mapping and folding

@deffn Procedure string-fold kons knil string [start end]
@deffnx Procedure string-fold-right kons knil string [start end]
These are the fundamental iterators for strings.

The @code{string-fold} procedure maps the @var{kons} procedure across
the given @var{string} from left to right:
@example
(... (@var{kons} @var{string}@sub{2} (@var{kons} @var{string}@sub{1} (@var{kons} @var{string}@sub{0} @var{knil}))))
@end example
In other words, string-fold obeys the (tail) recursion
@example
  (string-fold @var{kons} @var{knil} @var{string} @var{start} @var{end})
= (string-fold @var{kons} (@var{kons} @var{string}@sub{start} @var{knil}) @var{start+1} @var{end})
@end example
The @code{string-fold-right} procedure maps @var{kons} across the given
string @var{string} from right to left:
@example
(@var{kons} @var{string}@sub{0}
      (... (@var{kons} @var{string}@sub{@var{end-3}}
                 (@var{kons} @var{string}@sub{@var{end-2}}
                       (@var{kons} @var{string}@sub{@var{end-1}}
                             @var{knil})))))
@end example
obeying the (tail) recursion
@example
  (string-fold-right @var{kons} @var{knil} @var{string} @var{start} @var{end})
= (string-fold-right @var{kons} (@var{kons} @var{string}@sub{@var{end-1}} @var{knil}) @var{start} @var{end-1})
@end example
Examples:
@example
;;; Convert a string or string to a list of chars.
(string-fold-right cons '() string)

;;; Count the number of lower-case characters in a string or string.
(string-fold (lambda (c count)
                (if (char-lower-case? c)
                    (+ count 1)
                    count))
              0
              string)
@end example
The string-fold-right combinator is sometimes called a "catamorphism."
@end deffn

@deffn Procedure string-for-each @var{proc} @vari{string} @varii{string} @dots{}
@deffnx Procedure string-for-each @var{proc} @vari{string} [start [end]]
The @var{string}s must all have the same length.  @var{proc} should
accept as many arguments as there are @var{string}s.

The @var{start}-@var{end} variant is provided for compatibility
with the SRFI-13 version.  (In that case @var{start} and @var{end}
count code Unicode scalar values (@code{character} values),
not Java 16-bit @code{char} values.)

The @func{string-for-each} procedure applies @var{proc} element--wise to
the characters of the @var{string}s for its side effects, in order from
the first characters to the last.  @var{proc} is always called in the
same dynamic environment as @func{string-for-each} itself.
@c  The return values of @func{string-for-each} are unspecified.

Analogous to @func{for-each}.

@example
(let ((v '()))
  (string-for-each
    (lambda (c) (set! v (cons (char->integer c) v)))
    "abcde")
   v)
  @result{} (101 100 99 98 97)
@end example

@PerformanceNote{} The compiler generates efficient code
for @code{string-for-each}.
If @var{proc} is a lambda expression, it is inlined.
@end deffn

@deffn Procedure string-map @var{proc} @vari{string} @varii{string} @dots{}
The @code{string-map} procedure applies @var{proc} element-wise to
the elements of the strings and returns a string of the results, in order.
It is an error if @var{proc} does not accept as many arguments as there
are strings, or return other than a single character or a string.
If more than one string is given and not all strings have the same length,
@code{string-map} terminates when the shortest string runs out.
The dynamic order in
which @var{proc} is applied to the elements of the strings is unspecified.
@c If multiple returns occur from string-map, the
@c values returned by earlier returns are not mutated.

@example
(string-map char-foldcase "AbdEgH")  @result{} "abdegh"
@end example
@example
(string-map
  (lambda (c) (integer->char (+ 1 (char->integer c))))
  "HAL")
        @result{} "IBM"
@end example
@example
(string-map
  (lambda (c k)
    ((if (eqv? k #\u) char-upcase char-downcase) c))
  "studlycaps xxx"
  "ululululul")
        @result{} "StUdLyCaPs"
@end example

Traditionally the result of @var{proc} had to be a character,
but Kawa (and SRFI-140) allows the result to be a string.

@PerformanceNote{} The @code{string-map} procedure has not been
optimized (mainly because it is not very useful):
The characters are boxed, and the @var{proc} is not inlined even if
it is a lambda expression.
@end deffn

@deffn Procedure string-map-index proc string [start end]

Calls @var{proc} on each valid index of the specified substring, converts
the results of those calls into strings, and returns the concatenation
of those strings. It is an error for @var{proc} to return anything other
than a character or string. The dynamic order in which proc is called
on the indexes is unspecified, as is the dynamic order in which the
coercions are performed. If any strings returned by @var{proc} are mutated
after they have been returned and before the call to @code{string-map-index}
has returned, then @code{string-map-index} returns a string with unspecified
contents; the @var{string-map-index} procedure itself does not mutate those
strings.
@end deffn

@deffn Procedure string-for-each-index proc string [start end]

Calls @var{proc} on each valid index of the specified substring, in
increasing order, discarding the results of those calls. This is
simply a safe and correct way to loop over a substring.

Example:
@example
(let ((txt (string->string "abcde"))
      (v '()))
  (string-for-each-index
    (lambda (cur) (set! v (cons (char->integer (string-ref txt cur)) v)))
    txt)
  v) @result{} (101 100 99 98 97)
@end example
@end deffn

@deffn Procedure string-count string pred [start end]
Returns a count of the number of characters in the specified substring
of @var{string} that satisfy the predicate @var{pred}.
@end deffn

@deffn Procedure string-filter pred string [start end]
@deffnx Procedure string-remove pred string [start end]
Return an immutable string consisting of only selected characters, in order:
@code{string-filter} selects only the characters that satisfy @var{pred};
@code{string-remove} selects only the characters that @emph{not}
satisfy @var{pred}
@end deffn

@subsection Replication & splitting

@deffn Procedure string-repeat string-or-character len
Create an istring by repeating the first argument @var{len} times.
If the first argument is a character, it is as if it were wrapped with
the @code{string} constructor.
We can define string-repeat in terms of the more general @code{xsubstring}
procedure:
@example
(define (string-repeat S N)
   (let ((T (if (char? S) (string S) S)))
     (xsubstring T 0 (* N (string-length T))))
@end example
@end deffn

@deffn Procedure xsubstring string [from to [start end]]
This is an extended substring procedure that implements replicated copying of a substring.
The @var{string} is a string; @var{start} and @var{end} are optional arguments that specify a substring of @var{string},
defaulting to 0 and the length of @var{string}.
This substring is conceptually replicated both up and down the index space,
in both the positive and negative directions.
For example, if @var{string} is @code{"abcdefg"}, @var{start} is 3,
and @var{end} is 6, then we have the conceptual bidirectionally-infinite string
@example
  ...  d  e  f  d  e  f  d  e  f  d  e  f  d  e  f  d  e  f  d ...
      -9 -8 -7 -6 -5 -4 -3 -2 -1  0 +1 +2 +3 +4 +5 +6 +7 +8 +9
@end example
@code{xsubstring} returns the substring of the @var{string} beginning
at index @var{from}, and ending at @var{to}.
It is an error if @var{from} is greater than @var{to}.

If @var{from} and @var{to} are missing they default to 0 and
@var{from}+(@var{end}-@var{start}), respectively.
This variant is a generalization of using @code{substring},
but unlike @code{substring} never shares substructures that would
retain characters or sequences of characters that are substructures of
its first argument or previously allocated objects.

You can use @code{xsubstring} to perform a variety of tasks:
@itemize
@item
To rotate a string left: @code{(xsubstring "abcdef" 2 8) @result{} "cdefab"}
@item
To rotate a string right: @code{(xsubstring "abcdef" -2 4) @result{} "efabcd"}
@item
To replicate a string: @code{(xsubstring "abc" 0 7) @result{} "abcabca"}
@end itemize

Note that
@itemize
@item
The @var{from}/@var{to} arguments give a half-open range containing the
characters from index @var{from} up to, but not including, index @var{to}.
@item
The @var{from}/@var{to} indexes are not expressed in the index space of
@var{string}. They refer instead to the replicated index space of the
substring defined by @var{string}, @var{start}, and @var{end}.
@end itemize

It is an error if @var{start}=@var{end}, unless @var{from}=@var{to},
which is allowed as a special case.
@end deffn

@deffn Procedure string-split string delimiter [grammar limit start end]
Returns a list of strings representing the words contained in the substring of @var{string} from @var{start} (inclusive) to @var{end} (exclusive).
The @var{delimiter} is a string to be used as the word separator.
This will often be a single character, but multiple characters are
allowed for use cases such as splitting on @code{"\r\n"}.
The returned list will have one more item than the number of non-overlapping
occurrences of the @var{delimiter} in the string.
If @var{delimiter} is an empty string, then the returned list contains a
list of strings, each of which contains a single character.

The @var{grammar} is a symbol with the same meaning as in
the @code{string-join} procedure.
If it is @code{infix}, which is the default, processing is done as
described above, except an empty string produces the empty list;
if grammar is @code{strict-infix}, then an empty string signals an error.
The values @code{prefix} and @code{suffix} cause a leading/trailing empty string in the result to be suppressed.

If @var{limit} is a non-negative exact integer, at most that many splits occur, and the remainder of string is returned as the final element of the list (so the result will have at most limit+1 elements). If limit is not specified or is #f, then as many splits as possible are made. It is an error if limit is any other value.

To split on a regular expression, you can use SRFI 115's @code{regexp-split}
procedure.
@end deffn

@subsection String mutation

The following procedures create a mutable string,
i.e. one that you can modify.

@deffn Procedure make-string [@var{k} [@var{char}]]
Return a newly allocated mstring of @var{k} characters,
where @var{k} defaults to 0.  If @var{char} is
given, then all elements of the string are initialized to @var{char},
otherwise the contents of the @var{string} are unspecified.

The 1-argument version is deprecated as poor style, except when k is 0.

@emph{Rationale:} In many languags the most common pattern for mutable strings
is to allocate an empty string and incrementally append to it.
It seems natural to initialize the string
with @code{(make-string)}, rather than @code{(make-string 0)}.

To return an immutable string that repeats @var{k} times a character
@var{char} use @code{string-repeat}.

This is as R7RS, except the result is variable-size and we allow
leaving out @var{k} when it is zero.

@end deffn

@deffn Procedure string-copy @var{string} [@var{start} [@var{end}]]
Returns a newly allocated mutable (mstring) copy of the part of the given
@var{string} between @var{start} and @var{end}.
@end deffn

The following procedures modify a mutable string.

@deffn Procedure string-set! string k char
This procedure stores @var{char} in element @var{k} of @var{string}.

@example
(define s1 (make-string 3 #\*))
(define s2 "***")
(string-set! s1 0 #\?) @result{} @emph{void}
s1 @result{} "?**"
(string-set! s2 0 #\?) @result{} @emph{error}
(string-set! (symbol->string 'immutable) 0 #\?) @result{} @emph{error}
@end example

@PerformanceNote{} Calling @code{string-set!} may take time proportional
to the length of the string:  First it must scan for the right position,
like @code{string-ref} does. Then if the new character requires
using a surrogate pair (and the old one doesn't) then we have to make room
in the string, possibly re-allocating a new @code{char} array.
Alternatively, if the old character requires using a surrogate pair
(and the new one doesn't) then following characters need to be moved.

The function @code{string-set!} is deprecated: It is inefficient,
and it very seldom does the correct thing.  Instead, you can
construct a string with @code{string-append!}.
@end deffn

@deffn Procedure string-append! @var{string} @var{value} @dots{}
The @var{string} must be a mutable string, such as one returned
by @code{make-string} or @code{string-copy}.
The @code{string-append!} procedure extends @var{string}
by appending each @var{value} (in order) to the end of @var{string}.
Each @code{value} should be a character or a string.

@PerformanceNote{} The compiler converts a call with multiple @var{value}s
to multiple @code{string-append!} calls.
If a @var{value} is known to be a @code{character}, then
no boxing (object-allocation) is needed.

The following example shows how to efficiently process a string
using @code{string-for-each} and incrementally ``build'' a result string
using @code{string-append!}.

@example
(define (translate-space-to-newline str::string)::string
  (let ((result (make-string 0)))
    (string-for-each
     (lambda (ch)
       (string-append! result
                       (if (char=? ch #\Space) #\Newline ch)))
     str)
    result))
@end example
@end deffn

@deffn Procedure string-copy!  @var{to}  @var{at}  @var{from} [@var{start} [@var{end}]]
Copies the characters of the string @var{from} that are between
@var{start} end @var{end} into the string @var{to},
starting at index @var{at}.  The order in which characters are copied
is unspecified, except that if the source and destination overlap,
copying takes place as if the source is first copied into a
temporary string and then into the destination.
(This is achieved without allocating storage by making sure to copy in
the correct direction in such circumstances.)

This is equivalent to (and implemented as):
@example
(string-replace! to at (+ at (- end start)) from start end))
@end example

@example
(define a "12345")
(define b (string-copy "abcde"))
(string-copy! b 1 a 0 2)
b  @result{}  "a12de"
@end example
@end deffn

@deffn Procedure string-replace!  @var{dst} @var{dst-start} @var{dst-end} @var{src} [@var{src-start} [@var{src-end}]]
Replaces the characters of string @var{dst} (between @var{dst-start} and @var{dst-end}) with the characters of @var{src} (between @var{src-start} and @var{src-end}).
The number of characters from @var{src} may be different than the
number replaced in @var{dst}, so the string may grow or contract.
The special case where @var{dst-start} is equal to @var{dst-end} corresponds to
insertion; the case where @var{src-start} is equal to @var{src-end}
corresponds to deletion.
The order in which characters are copied
is unspecified, except that if the source and destination overlap,
copying takes place as if the source is first copied into a
temporary string and then into the destination.
(This is achieved without allocating storage by making sure to copy in
the correct direction in such circumstances.)
@end deffn

@deffn Procedure string-fill! @var{string} @var{fill} [@var{start} [@var{end}]]
The @code{string-fill!} procedure stores @var{fill} in the elements
of @var{string} between @var{start} and @var{end}.
It is an error if @var{fill} is not a character or is forbidden in strings.
@end deffn

@subsection Strings as sequences

@subsubsection Indexing a string

Using function-call syntax with strings is convenient
and efficient.  However, it has some ``gotchas''.

We will use the following example string:
@example
(! str1 "Smile \x1f603;!")
@end example
or if you're brave:
@example
(! str1 "Smile 😃!")
@end example

This is @code{"Smile "} followed by an emoticon (``smiling face with
open mouth'') followed by @code{"!"}.
The emoticon has scalar value @code{\x1f603} - it is not
in the 16-bit Basic Multi-language Plane,
and so it must be encoded by a surrogate pair
(@code{#\xd83d} followed by @code{#\xde03}).

The number of scalar values (@code{character}s) is 8,
while the number of 16-bits code units (@code{char}s) is 9.
The @code{java.lang.CharSequence:length} method
counts @code{char}s. Both the @code{length} and the
@code{string-length} procedures count @code{character}s.  Thus:

@example
(length str1)          @result{} 8
(string-length str1)   @result{} 8
(str1:length)          @result{} 9
@end example

Counting @code{char}s is a constant-time operation (since it
is stored in the data structure).
Counting @code{character}s depends on the representation used:
In geneeral it may take time proportional to the length of
the string, since it has to subtract one for each surrogate pair;
however the @var{istring} type (@code{gnu.lists.IString} class)
uses a extra structure so it can count characters in constant-time.

Similarly we can can index the string in 3 ways:

@example
(str1 1)              @result{} #\m :: character
(string-ref str1 1)   @result{} #\m :: character
(str1:charAt 1)       @result{} #\m :: char
@end example

Using function-call syntax when the ``function'' is a string
and a single integer argument is the same as using @code{string-ref}.

Things become interesting when we reach the emoticon:

@example
(str1 6)              @result{} #\😃 :: character
(str1:charAt 6)       @result{} #\d83d :: char
@end example

Both @code{string-ref} and the function-call syntax return the
real character, while the @code{charAt} methods returns a partial character.

@example
(str1 7)              @result{} #\! :: character
(str1:charAt 7)       @result{} #\de03 :: char
(str1 8)              @result{} @i{throws} StringIndexOutOfBoundsException
(str1:charAt 8)       @result{} #\! :: char
@end example

@subsubsection Indexing with a sequence

You can index a string with a list of integer indexes,
most commonly a range:
@example
(@var{str} [@var{i} ...])
@end example
is basically the same as:
@example
(string (@var{str} @var{i}) ...)
@end example

Generally when working with strings it is best to
work with substrings rather than individual characters:
@example
(@var{str} [@var{start} <: @var{end}])
@end example

This is equivalent to invoking the @code{substring} procedure:
@example
(substring @var{str} @var{start} @var{end})
@end example

@c not implemented yet
@c @subsubsection Assigning to a subsequence

@anchor{String Cursor API}
@subsection String Cursor API

Indexing into a string (using for example @code{string-ref})
is inefficient because of the possible presence of surrogate pairs.
Hence given an index @var{i} access normally requires linearly
scanning the string until we have seen @var{i} characters.

The string-cursor API is defined in terms of abstract ``cursor values'',
which point to a position in the string.  This avoids the linear scan.

Typical usage is:
@example
(let* ((str @var{whatever})
       (end (string-cursor-end str)))
  (do ((sc::string-cursor (string-cursor-start str)
                          (string-cursor-next str sc)))
    ((string-cursor>=? sc end))
    (let ((ch (string-cursor-ref str sc)))
      (@var{do-something-with} ch))))
@end example
Alternatively, the following may be marginally faster:
@example
(let* ((str @var{whatever})
       (end (string-cursor-end str)))
  (do ((sc::string-cursor (string-cursor-start str)
                          (string-cursor-next-quick sc)))
    ((string-cursor>=? sc end))
    (let ((ch (string-cursor-ref str sc)))
      (if (not (char=? ch #\ignorable-char))
        (@var{do-something-with} ch)))))
@end example

The API is non-standard, but is based on that in Chibi Scheme.

@deffn Type string-cursor
An abstract position (index) in a string.
Implemented as a primitive @code{int} which counts the
number of preceding code units (16-bit @code{char} values).
@end deffn

@deffn Procedure string-cursor-start str
Returns a cursor for the start of the string.
The result is always 0, cast to a @code{string-cursor}.
@end deffn

@deffn Procedure string-cursor-end str
Returns a cursor for the end of the string - one past the last valid character.
Implemented as @code{(as string-cursor (invoke @var{str} 'length))}.
@end deffn

@deffn Procedure string-cursor-ref str cursor
Return the @code{character} at the @var{cursor}.
If the @var{cursor} points to the second @code{char} of a surrogate pair,
returns @code{#\ignorable-char}.
@end deffn

@deffn Procedure string-cursor-next string cursor [count]
Return the cursor position @var{count} (default 1) character
positions forwards beyond @var{cursor}.
For each @var{count} this may add either 1 or 2
(if pointing at a surrogate pair) to the @var{cursor}.
@end deffn

@deffn Procedure string-cursor-next-quiet cursor
Increment cursor by one raw @code{char} position,
even if @var{cursor} points to the start of a surrogate pair.
(In that case the next @code{string-cursor-ref} will
return @code{#\ignorable-char}.)
Same as @code{(+ @var{cursor} 1)} but with the @code{string-cursor} type.
@end deffn

@deffn Procedure string-cursor-prev string cursor [count]
Return the cursor position @var{count} (default 1) character
positions backwards before @var{cursor}.
@end deffn

@deffn Procedure substring-cursor string [start [end]]
Create a substring of the section of @var{string}
between the cursors @var{start} and @var{end}.
@end deffn

@deffn Procedure string-cursor<? cursor1 cursor2
@deffnx Procedure string-cursor<=? cursor1 cursor2
@deffnx Procedure string-cursor=? cursor1 cursor2
@deffnx Procedure string-cursor>=? cursor1 cursor2
@deffnx Procedure string-cursor>? cursor1 cursor2
Is the position of @var{cursor1} respectively before,
before or same, same, after, or after or same, as @var{cursor2}.

@PerformanceNote{} Implemented as the corresponding @code{int} comparison.
@end deffn

@c non-chibi
@deffn Procedure string-cursor-for-each proc string [start [end]]
Apply the procedure @var{proc} to each character position in
@var{string} between the cursors @var{start} and @var{end}.
@end deffn

@node String literals
@section String literals

Kaw support two syntaxes of string literals:
The traditional, portable, qdouble-quoted-delimited literals
like @code{"this"};
and extended SRFI-109 quasi-literals like @code{&@{this@}}.

@subsection Simple string literals

@display
@stxdef{string} @stxlit{"}@arbno{@stxref{string-element}}@stxlit{"}
@stxdef{string-element} @i{any character other than} @stxlit{"} @i{or} @stxlit{@backslashchar{}}
    | @stxref{mnemonic-escape} | @stxlit{@backslashchar{}"} | @stxlit{@backslashchar{}@backslashchar{}}
    | @stxlit{@backslashchar{}}@arbno{@stxref{intraline-whitespace}}@stxref{line-ending} @arbno{@stxref{intraline-whitespace}}
    | @stxref{inline-hex-escape}
@stxdef{mnemonic-escape} @stxlit{@backslashchar{}a} | @stxlit{@backslashchar{}b} | @stxlit{@backslashchar{}t} | @stxlit{@backslashchar{}n} | @stxlit{@backslashchar{}r} | ... @i{(see below)}
@end display

A string is written as a sequence of characters enclosed
within quotation marks (@stxlit{"}).
Within a string literal, various escape sequence represent characters
other than themselves.
Escape sequences always start with a backslash (@stxlit{@backslashchar{}}):
@table @asis
@item @stxlit{@backslashchar{}a}
Alarm (bell), @code{#\x0007}.
@item @stxlit{@backslashchar{}b}
Backspace, @code{#\x0008}.
@item @stxlit{@backslashchar{}e}
Escape, @code{#\x001B}.
@item @stxlit{@backslashchar{}f}
Form feed, @code{#\x000C}.
@item @stxlit{@backslashchar{}n}
Linefeed (newline), @code{#\x000A}.
@item @stxlit{@backslashchar{}r}
Return, @code{#\x000D}.
@item @stxlit{@backslashchar{}t}
Character tabulation, @code{#\x0009}.
@item @stxlit{@backslashchar{}v}
Vertical tab, @code{#\x000B}.
@item @stxlit{@backslashchar{}C-}@meta{x}
@itemx @stxlit{@backslashchar{}^}@meta{x}
Returns the scalar value of @meta{x} masked (anded) with @code{#x9F}.
An alternative way to write the Ascii control characters:
For example @code{"\C-m"} or @code{"\^m"} is
the same as @code{"#\x000D"} (which the same as @code{"\r"}).
As a special case @code{\^?} is rubout (delete) (@code{\x7f;}).
@item @stxlit{@backslashchar{}x} @stxref{hex-scalar-value}@stxlit{;}
@itemx @stxlit{@backslashchar{}X} @stxref{hex-scalar-value}@stxlit{;}
A hex encoding that gives the scalar value of a character.
@item @stxlit{@backslashchar{}@backslashchar{}} @atleastone{@stxref{oct-digit}}
At most three octal digits that give the scalar value of a character.
(Historical, for C compatibility.)
@item @stxlit{@backslashchar{}u} @atleastone{@stxref{hex-digit}}
Exactly four hex digits that give the scalar value of a character.
(Historical, for Java compatibility.)
@item @stxlit{@backslashchar{}M-}@meta{x}
(Historical, for Emacs Lisp.)
Set the meta-bit (high-bit of single byte) of the following character @var{x}.
@item @stxlit{@backslashchar{}|}
Vertical line, @code{#\x007c}.
(Not useful for string literals, but useful for symbols.)
@item @stxlit{@backslashchar{}"}
Double quote, @code{#\x0022}.
@item @stxlit{@backslashchar{}@backslashchar{}}
Backslah, @code{#\005C}.
@item @stxlit{@backslashchar{}}@arbno{@stxref{intraline-whitespace}}@stxref{line-ending} @arbno{@stxref{intraline-whitespace}}
Nothing (ignored).  Allows you to split up a long string over multiple
lines; ignoring initial whitespace on the continuation lines allows
you to indent them.
@end table

Except for a line ending, any character outside of an escape
sequence stands for itself in the string literal. A line ending
which is preceded by  @stxlit{@backslashchar{}}@arbno{@meta{intraline-whitespace}}
expands to nothing (along with any trailing @meta{intraline-whitespace}),
and can be used to indent strings for improved legibility.
Any other line ending has the same effect as inserting a @stxlit{@backslashchar{}n}
character into the string.

Examples:
@example
"The word \"recursion\" has many meanings."
"Another example:\ntwo lines of text"
"Here’s text \
containing just one line"
"\x03B1; is named GREEK SMALL LETTER ALPHA."
@end example

@anchor{string quasi-literals}
@subsection String templates

The following syntax is a @dfn{string template} (also called
a string quasi-literal or
``@uref{http://en.wikipedia.org/wiki/Here_document, here document}''):
@example
&@{Hello &[name]!@}
@end example
Assuming the variable @code{name} evaluates to @code{"John"}
then the example evaluates to @code{"Hello John!"}.

The Kawa reader converts the above example to:
@example
($string$ "Hello " $<<$ name $>>$ "!")
@end example
See the @uref{http://srfi.schemers.org/srfi-109/srfi-109.html,SRFI-109}
specification for details.

@display
@stxdef{extended-string-literal} @stxlit{&@lbracechar{}} [@stxref{initial-ignored}] @arbno{@stxref{string-literal-part}} @stxlit{@rbracechar{}}
@stxdef{string-literal-part}  @i{any character except} @stxlit{&}, @stxlit{@lbracechar{}} @i{or} @stxlit{@rbracechar{}}
    | @stxlit{@lbracechar{}} @arbno{@stxref{string-literal-part}} @stxlit{@rbracechar{}}
    | @stxref{char-ref}
    | @stxref{entity-ref}
    | @stxref{special-escape}
    | @stxref{enclosed-part}
@end display

You can use the plain @code{"@var{string}"} syntax for
longer multiline strings, but @code{&@{@var{string}@}} has
various advantages.
The syntax is less error-prone because the start-delimiter is
different from the end-delimiter.  Also note that nested braces
are allowed: a right brace @code{@rbracechar{}} is only an end-delimiter
if it is unbalanced, so you would seldom need to escape it:
@example
&@{This has a @{braced@} section.@}
  @result{} "This has a @{braced@} section."
@end example

The escape character used for special characters is
@stxlit{&}.  This is compatible with XML syntax and @ref{XML literals}.

@subsubsection Special characters

@display
@stxdef{char-ref}
    @stxlit{&#} @atleastone{@stxref{digit}} @stxlit{;}
  | @stxlit{&#x} @atleastone{@stxref{hex-digit}}  @stxlit{;}
@stxdef{entity-ref}
    @stxlit{&} @stxref{char-or-entity-name} @stxlit{;}
@stxdef{char-or-entity-name} @meta{tagname}
@end display

You can the standard XML syntax for character references, using
either decimal or hexadecimal values. The following string has two
instances of the Ascii escape character, as either decimal 27 or hex 1B:
@example
&@{&#27;&#x1B;@} @result{} "\e\e"
@end example

You can also use the pre-defined XML entity names:
@example
&@{&amp; &lt; &gt; &quot; &apos;@} @result{} "& < > \" '"
@end example
In addition, @code{&lbrace;} @code{&rbrace;} can be used for left and
right curly brace, though you don't need them for balanced parentheses:
@example
&@{ &rbrace;_&lbrace; / @{_@} @}  @result{} " @}_@{ / @{_@} "
@end example

You can use the @uref{http://www.w3.org/2003/entities/2007/w3centities-f.ent,standard XML entity names}. For example:
@example
&@{L&aelig;rdals&oslash;yri@}
  @result{} "Lærdalsøyri"
@end example

You can also use the standard R7RS character names @code{null},
@code{alarm}, @code{backspace}, @code{tab}, @code{newline}, @code{return},
@code{escape}, @code{space}, and @code{delete}.
For example:
@example
&@{&escape;&space;@}
@end example

The syntax @code{&@var{name};} is actually syntactic sugar
(specifically reader syntax) to the variable reference
@code{$entity$:@var{name}}.
Hence you can also define your own entity names:
@example
(define $entity$:crnl "\r\n")
&@{&crnl;@} ⟹ "\r\n"
@end example

@subsubsection Multiline string literals

@example
@stxdef{initial-ignored}
    @arbno{@stxref{intraline-whitespace}} @stxref{line-ending} @arbno{@stxref{intraline-whitespace}} @stxlit{&|}
@stxdef{special-escape}
    @arbno{@stxref{intraline-whitespace}} @stxlit{&|}
  | @stxlit{&} @stxref{nested-comment}
  | @stxlit{&-} @arbno{@stxref{intraline-whitespace}} @stxref{line-ending}
@end example

A line-ending directly in the text is becomes a newline,
as in a simple string literal:
@example
(string-capitalize &@{one two three
uno dos tres
@}) @result{} "One Two Three\nUno Dos Tres\n"
@end example
However, you have extra control over layout.
If the string is in a nested expression, it is confusing
(and ugly) if the string cannot be indented to match
the surrounding context. The indentation marker @stxlit{&|}
is used to mark the end of insignificant initial whitespace.
The @code{&|} characters and all the preceding whitespace are removed.
In addition, it also suppresses an initial newline.  Specifically,
when the initial left-brace is followed by optional (invisible)
intraline-whitespace, then a newline, then optional
intraline-whitespace (the indentation), and finally the indentation
marker @code{&|} - all of which is removed from the output.
Otherwise the @code{&|} only removes initial intraline-whitespace
on the same line (and itself).

@example
(write (string-capitalize &@{
     &|one two three
     &|uno dos tres
@}) out)
    @result{} @i{prints} "One Two Three\nUno Dos Tres\n"
@end example

As a matter of style, all of the indentation lines should line up.
It is an error if there are any non-whitespace characters between
the previous newline and the indentation marker.
It is also an error to write an indentation marker before the
first newline in the literal.

The line-continuation marker @stxlit{&-} is used to suppress a newline:
@example
&@{abc&-
  def@} @result{} "abc  def"
@end example

You can write a @code{#|...|#}-style comment following a @code{&}.
This could be useful for annotation, or line numbers:
@example
&@{&#|line 1|#one two
  &#|line 2|# three
  &#|line 3|#uno dos tres
@} @result{} "one two\n three\nuno dos tres\n"
@end example

@subsubsection Embedded expressions

@example
@stxdef{enclosed-part}
    @stxlit{&} @arbno{@stxref{enclosed-modifier}} @stxlit{[} @arbno{@stxref{expression}} @stxlit{]}
  | @stxlit{&} @arbno{@stxref{enclosed-modifier}} @stxlit{(} @atleastone{@stxref{expression}} @stxlit{)}
@end example

An embedded expression has the form @code{&[@var{expression}]}.
It is evaluated, the result converted to a string (as by @code{display}),
and the result added in the result string.
(If there are multiple expressions, they are all evaluated and
the corresponding strings inserted in the result.)
@example
&@{Hello &[(string-capitalize name)]!@}
@end example

You can leave out the square brackets when the expression
is a parenthesized expression:
@example
&@{Hello &(string-capitalize name)!@}
@end example

@subsubsection Formatting

@example
@stxdef{enclosed-modifier}
  @stxlit{~} @meta{format-specifier-after-tilde}
@end example

Using @ref{Format,@code{format}} allows finer-grained control over the
output, but a problem is that the association between format
specifiers and data expressions is positional, which is hard-to-read
and error-prone. A better solution places the specifier adjacant to
the data expression:
@example
&@{The response was &~,2f(* 100.0 (/ responses total))%.@}
@end example

The following escape forms are equivalent to the corresponding
forms withput the @stxlit{~}@meta{fmt-spec}, except the
expression(s) are formatted using @code{format}:
@display
@stxlit{&~}@meta{fmt-spec}@stxlit{[}@arbno{@meta{expression}}@stxlit{]} 
@end display
Again using parentheses like this:
@display
@stxlit{&~}@meta{fmt-spec}@stxlit{(}@atleastone{@meta{expression}}@stxlit{)}
@end display
is equivalent to:
@display
@stxlit{&~}@meta{fmt-spec}@stxlit{[(}@atleastone{@meta{expression}}@stxlit{)]}
@end display

The syntax of @code{format} specifications is arcane, but it allows you
to do some pretty neat things in a compact space.
For example to include @code{"_"} between each element of
the array @code{arr} you can use the @code{~@{...~@}} format speciers:
@example
(define arr [5 6 7])
&@{&~@{&[arr]&~^_&~@}@} @result{} "5_6_7"
@end example

If no format is specified for an enclosed expression,
the that is equivalent to a @code{~a} format specifier,
so this is equivalent to:
@example
&@{&~@{&~a[arr]&~^_&~@}@} @result{} "5_6_7"
@end example
which is in turn equivalent to:
@example
(format #f "~@{~a~^_~@}" arr)
@end example

The fine print that makes this work:
If there are multiple expressions in a @code{&[...]} with
no format specifier then there is an implicit @code{~a} for
each expression.
On the other hand, if there is an explicit format specifier,
it is not repeated for each enclosed expression: it appears
exactly once in the effective format string, whether
there are zero, one, or many expressions.

@node Unicode
@section Unicode character classes and conversions

@ignore
The procedures exported by the @rsixlibrary{unicode} library provide
access to some aspects of the Unicode semantics for characters and
strings: category information, case--independent comparisons, case
mappings, and normalization.
@end ignore

Some of the procedures that operate on characters or strings ignore the
difference between upper case and lower case.  These procedures have
@code{-ci} (for ``case insensitive'') embedded in their names.


@subsection Characters

@deffn Procedure char-upcase @var{char}
@deffnx Procedure char-downcase @var{char}
@deffnx Procedure char-titlecase @var{char}
@deffnx Procedure char-foldcase @var{char}
These procedures take a character argument and return a character
result.

If the argument is an upper--case or title--case character, and if there
is a single character that is its lower--case form, then
@func{char-downcase} returns that character.

If the argument is a lower--case or title--case character, and there is
a single character that is its upper--case form, then @func{char-upcase}
returns that character.

If the argument is a lower--case or upper--case character, and there is
a single character that is its title--case form, then
@func{char-titlecase} returns that character.

If the argument is not a title--case character and there is no single
character that is its title--case form, then @func{char-titlecase}
returns the upper--case form of the argument.

Finally, if the character has a case--folded character, then
@func{char-foldcase} returns that character.  Otherwise the character
returned is the same as the argument.

For Turkic characters @code{#\x130} and @code{#\x131},
@func{char-foldcase} behaves as the identity function; otherwise
@func{char-foldcase} is the same as @func{char-downcase} composed with
@func{char-upcase}.

@example
(char-upcase #\i)               @result{}  #\I
(char-downcase #\i)             @result{}  #\i
(char-titlecase #\i)            @result{}  #\I
(char-foldcase #\i)             @result{}  #\i

(char-upcase #\ß)               @result{}  #\ß
(char-downcase #\ß)             @result{}  #\ß
(char-titlecase #\ß)            @result{}  #\ß
(char-foldcase #\ß)             @result{}  #\ß

(char-upcase #\Σ)               @result{}  #\Σ
(char-downcase #\Σ)             @result{}  #\σ
(char-titlecase #\Σ)            @result{}  #\Σ
(char-foldcase #\Σ)             @result{}  #\σ

(char-upcase #\ς)               @result{}  #\Σ
(char-downcase #\ς)             @result{}  #\ς
(char-titlecase #\ς)            @result{}  #\Σ
(char-foldcase #\ς)             @result{}  #\σ
@end example

@quotation
@emph{Note:} @func{char-titlecase} does not always return a title--case
character.
@end quotation

@quotation
@emph{Note:} These procedures are consistent with Unicode's
locale--independent mappings from scalar values to scalar values for
upcase, downcase, titlecase, and case--folding operations.  These
mappings can be extracted from @file{UnicodeData.txt} and
@file{CaseFolding.txt} from the Unicode Consortium, ignoring Turkic
mappings in the latter.

Note that these character--based procedures are an incomplete
approximation to case conversion, even ignoring the user's locale.  In
general, case mappings require the context of a string, both in
arguments and in result.  The @func{string-upcase},
@func{string-downcase}, @func{string-titlecase}, and
@func{string-foldcase} procedures perform more general case conversion.
@end quotation
@end deffn

@deffn Procedure char-ci=? @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure char-ci<? @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure char-ci>? @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure char-ci<=? @vari{char} @varii{char} @variii{char} @dots{}
@deffnx Procedure char-ci>=? @vari{char} @varii{char} @variii{char} @dots{}
These procedures are similar to @func{char=?}, etc., but operate on the
case--folded versions of the characters.

@example
(char-ci<? #\z #\Z)             @result{} #f
(char-ci=? #\z #\Z)             @result{} #f
(char-ci=? #\ς #\σ)             @result{} #t
@end example
@end deffn


@deffn Procedure char-alphabetic? @var{char}
@deffnx Procedure char-numeric? @var{char}
@deffnx Procedure char-whitespace? @var{char}
@deffnx Procedure char-upper-case? @var{char}
@deffnx Procedure char-lower-case? @var{char}
@deffnx Procedure char-title-case? @var{char}
These procedures return @true{} if their arguments are alphabetic,
numeric, whitespace, upper--case, lower--case, or title--case
characters, respectively; otherwise they return @false{}.

A character is alphabetic if it has the Unicode ``Alphabetic'' property.
A character is numeric if it has the Unicode ``Numeric'' property.  A
character is whitespace if has the Unicode ``White_Space'' property.  A
character is upper case if it has the Unicode ``Uppercase'' property,
lower case if it has the ``Lowercase'' property, and title case if it is
in the Lt general category.

@example
(char-alphabetic? #\a)          @result{}  #t
(char-numeric? #\1)             @result{}  #t
(char-whitespace? #\space)      @result{}  #t
(char-whitespace? #\x00A0)      @result{}  #t
(char-upper-case? #\Σ)          @result{}  #t
(char-lower-case? #\σ)          @result{}  #t
(char-lower-case? #\x00AA)      @result{}  #t
(char-title-case? #\I)          @result{}  #f
(char-title-case? #\x01C5)      @result{}  #t
@end example
@end deffn

@deffn Procedure char-general-category @var{char}
Return a symbol representing the Unicode general category of
@var{char}, one of @code{Lu}, @code{Ll}, @code{Lt}, @code{Lm},
@code{Lo}, @code{Mn}, @code{Mc}, @code{Me}, @code{Nd}, @code{Nl},
@code{No}, @code{Ps}, @code{Pe}, @code{Pi}, @code{Pf}, @code{Pd},
@code{Pc}, @code{Po}, @code{Sc}, @code{Sm}, @code{Sk}, @code{So},
@code{Zs}, @code{Zp}, @code{Zl}, @code{Cc}, @code{Cf}, @code{Cs},
@code{Co}, or @code{Cn}.

@example
(char-general-category #\a)         @result{} Ll
(char-general-category #\space)     @result{} Zs
(char-general-category #\x10FFFF)   @result{} Cn  
@end example
@end deffn


@subsection Deprecated in-place case modification

The following functions are deprecated; they really don't
and cannot do the right thing, because in some languages
upper and lower case can use different number of characters.

@deffn Procedure string-upcase! str
@emph{Deprecated:} Destructively modify @var{str}, replacing the letters
by their upper-case equivalents.
@end deffn

@deffn Procedure string-downcase! str
@emph{Deprecated:} Destructively modify @var{str}, replacing the letters
by their upper-lower equivalents.
@end deffn

@deffn Procedure string-capitalize! str
@emph{Deprecated:} Destructively modify @var{str}, such that the letters that start a new word
are replaced by their title-case equivalents, while non-initial letters
are replaced by their lower-case equivalents.
@end deffn

@node Regular expressions, , Unicode, Characters and text
@section Regular expressions

Kawa provides @dfn{regular expressions}, which is a convenient
mechanism for matching a string against a @dfn{pattern}
and maybe replacing matching parts.

A regexp is a string that describes a pattern. A regexp matcher tries
to match this pattern against (a portion of) another string, which we
will call the text string. The text string is treated as raw text and
not as a pattern.

Most of the characters in a regexp pattern are meant to match
occurrences of themselves in the text string. Thus, the pattern ``@code{abc}''
matches a string that contains the characters ``@code{a}'', ``@code{b}'',
``@code{c}'' in succession.

In the regexp pattern, some characters act as @dfn{metacharacters},
and some character sequences act as @dfn{metasequences}. That is, they
specify something other than their literal selves. For example, in the
pattern ``@code{a.c}'', the characters ``@code{a}'' and ``@code{c}'' do stand
for themselves but the metacharacter ``@code{.}'' can match any character
(other than newline). Therefore, the pattern ``@code{a.c}'' matches an
``@code{a}'', followed by any character, followed by a ``@code{c}''.

If we needed to match the character ``@code{.}'' itself, we @dfn{escape}
it, ie, precede it with a backslash ``@code{\}''. The character sequence
``@code{\.}'' is thus a metasequence, since it doesn’t match itself but
rather just ``@code{.}''.  So, to match ``@code{a}'' followed by a literal
``@code{.}'' followed by ``@code{c}'' we use the regexp pattern
``@code{a\.c}''.  To write this as a Scheme string literal,
you need to quote the backslash, so you need to write @code{"a\\.c"}.
Kawa also allows the literal syntax @code{#/a\.c/},
which avoids the need to double the backslashes.

You can choose between two similar styles of regular expressions.
The two differ slightly in terms of which characters act as metacharacters,
and what those metacharacters mean:
@itemize
@item
Functions starting with @code{regex-} are implemented using
the @code{java.util.regex} package.
This is likely to be more efficient, has better Unicode support and
some other minor extra features, and literal syntax @code{#/a\.c/}
mentioned above.
@item
Functions starting with @code{pregexp-} are implemented in pure Scheme
using Dorai Sitaram's ``Portable Regular Expressions for Scheme'' library.
These will be portable to more Scheme implementations, including BRL,
and is available on older Java versions.
@end itemize


@subsection Java regular expressions

The syntax for regular expressions is
@uref{http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html, documented here}.

@deffn Type regex
A compiled regular expression,
implemented as @code{java.util.regex.Pattern}.
@end deffn

@deffn Constructor regex arg
Given a regular expression pattern (as a string),
compiles it to a @code{regex} object.

@example
(regex "a\\.c")
@end example
This compiles into a pattern that matches an
``@code{a}'', followed by any character, followed by a ``@code{c}''.
@end deffn

The Scheme reader recognizes ``@code{#/}'' as the start of a
regular expression @dfn{pattern literal}, which ends with the next
un-escaped ``@code{/}''.
This has the big advantage that you don't need to double the backslashes:
@example
#/a\.c/
@end example
This is equivalent to @code{(regex "a\\.c")}, except it is
compiled at read-time.
If you need a literal ``@code{/}'' in a pattern, just escape it
with a backslash: ``@code{#/a\/c/}'' matches a ``@code{a}'',
followed by a ``@code{/}'', followed by a ``@code{c}''.

You can add single-letter @emph{modifiers} following the pattern literal.
The following modifiers are allowed:
@table @code
@item i
The modifier ``@code{i}'' cause the matching to ignore case.
For example the following pattern matches ``@code{a}'' or ``@code{A}''.
@example
#/a/i
@end example
@item m
Enables ``metaline'' mode.
Normally metacharacters ``@code{^}'' and ``@code{$}'
match at the start end end of the entire input string.
In metaline mode ``@code{^}'' and ``@code{$}'' also
match just before or after a line terminator.

Multiline mode can also be enabled by the metasequence ``@code{(?m)}''. 
@item s
Enable ``singleline'' (aka ``dot-all'') mode.
In this mode the matacharacter ``@code{.} matches any character,
including a line breaks.
This mode be enabled by the metasequence ``@code{(?s)}''.
@end table

The following functions accept a regex either as
a pattern string or a compiled @code{regex} pattern.
I.e. the following are all equivalent:
@example
(regex-match "b\\.c" "ab.cd")
(regex-match #/b\.c/ "ab.cd")
(regex-match (regex "b\\.c") "ab.cd")
(regex-match (java.util.regex.Pattern:compile "b\\.c") "ab.cd")
@end example
These all evaluate to the list @code{("b.c")}.

The following functions must be imported by doing one of:
@example
(require 'regex) ;; or
(import (kawa regex))
@end example

@deffn Procedure regex-match-positions regex string [start [end]]

The procedure @code{regex‑match‑position} takes pattern and a
text @var{string}, and returns a match if the regex matches (some part of)
the text string.

Returns @code{#f} if the regexp did not match the string;
and a list of index pairs if it did match.
@example
(regex-match-positions "brain" "bird") @result{} #f
(regex-match-positions "needle" "hay needle stack")
  @result{} ((4 . 10))
@end example

In the second example, the integers 4 and 10 identify the substring
that was matched. 4 is the starting (inclusive) index and 10 the
ending (exclusive) index of the matching substring.

@example
(substring "hay needle stack" 4 10) @result{} "needle"
@end example

In this case the return list contains only one index
pair, and that pair represents the entire substring matched by the
regexp. When we discuss subpatterns later, we will see how a single
match operation can yield a list of submatches.

@code{regex‑match‑positions} takes optional third and fourth arguments
that specify the indices of the text string within which the matching
should take place.

@example
(regex-match-positions "needle"
  "his hay needle stack -- my hay needle stack -- her hay needle stack"
  24 43)
  @result{} ((31 . 37))
@end example

Note that the returned indices are still reckoned relative to the full text string.
@end deffn

@deffn Procedure regex-match regex string [start [end]]
The procedure @code{regex‑match} is called like @code{regex‑match‑positions}
but instead of returning index pairs it returns the matching substrings:
@example
(regex-match "brain" "bird") @result{} #f
(regex-match "needle" "hay needle stack")
  @result{} ("needle")
@end example

@code{regex‑match} also takes optional third and fourth arguments,
with the same meaning as does @code{regex‑match‑positions}.
@end deffn

@deffn Procedure regex-split regex string
Takes two arguments, a @var{regex} pattern and a text @var{string},
and returns a list of substrings of the text string,
where the pattern identifies the delimiter separating the substrings.
@example
(regex-split ":" "/bin:/usr/bin:/usr/bin/X11:/usr/local/bin")
  @result{} ("/bin" "/usr/bin" "/usr/bin/X11" "/usr/local/bin")

(regex-split " " "pea soup")
  @result{} ("pea" "soup")
@end example

If the first argument can match an empty string, then the list of all
the single-character substrings is returned, plus we get
a empty strings at each end.

@example
(regex-split "" "smithereens")
  @result{} ("" "s" "m" "i" "t" "h" "e" "r" "e" "e" "n" "s" "")
@end example

(Note: This behavior is different from @code{pregexp-split}.)

To identify one-or-more spaces as the delimiter, take care to use the regexp
``@code{ +}'', not ``@code{ *}''.
@example
(regex-split " +" "split pea     soup")
  @result{} ("split" "pea" "soup")
(regex-split " *" "split pea     soup")
  @result{} ("" "s" "p" "l" "i" "t" "" "p" "e" "a" "" "s" "o" "u" "p" "")
@end example
@end deffn

@deffn Procedure regex‑replace regex string replacement
Replaces the matched portion of the text @var{string} by another a
@var{replacdement} string.
@example
(regex-replace "te" "liberte" "ty")
  @result{} "liberty"
@end example

Submatches can be used in the replacement string argument.
The replacement string can use ``@code{$@var{n}}''
as a @dfn{backreference} to refer back to the @var{n}th
submatch, ie, the substring that matched the @var{n}th
subpattern.   ``@code{$0}'' refers to the entire match.
@example
(regex-replace #/_(.+?)_/
               "the _nina_, the _pinta_, and the _santa maria_"
		"*$1*"))
  @result{} "the *nina*, the _pinta_, and the _santa maria_"
@end example
@end deffn

@deffn Procedure regex‑replace* regex string replacement
Replaces all matches in the text @var{string} by the @var{replacement} string:
@example
(regex-replace* "te" "liberte egalite fraternite" "ty")
  @result{} "liberty egality fratyrnity"
(regex-replace* #/_(.+?)_/
                "the _nina_, the _pinta_, and the _santa maria_"
                "*$1*")
  @result{} "the *nina*, the *pinta*, and the *santa maria*"
@end example
@end deffn

@deffn Procedure regex-quote pattern
Takes an arbitrary string and returns a pattern string that precisely
matches it. In particular, characters in the input string that could
serve as regex metacharacters are escaped as needed.

@example
(regex-quote "cons")
  @result{} "\Qcons\E"
@end example
@code{regex‑quote} is useful when building a composite regex
from a mix of regex strings and verbatim strings.
@end deffn

@subsection Portable Scheme regular expressions

This provides the procedures @code{pregexp}, @code{pregexp‑match‑positions},
@code{pregexp‑match}, @code{pregexp‑split}, @code{pregexp‑replace},
@code{pregexp‑replace*}, and @code{pregexp‑quote}.

Before using them, you must require them:
@example
(require 'pregexp)
@end example

These procedures have the same interface as the corresponding
@code{regex-} versions, but take slightly different pattern syntax.
The replace commands use ``@code{\}'' instead of ``@code{$}''
to indicate substitutions.
Also, @code{pregexp‑split} behaves differently from
@code{regex‑split} if the pattern can match an empty string.

See @uref{http://www.ccs.neu.edu/home/dorai/pregexp/index.html,here for details}.

@node Data structures
@chapter Data structures

@menu
* Sequences::
* Lists::
* Vectors::
* Uniform vectors::
* Bytevectors::
* Ranges::
* Streams:: Lazy lists.
* Arrays::  Multi-dimensional Arrays
* Hash tables::
@end menu

@node Sequences
@section Sequences

A @dfn{sequence} is a generalized list, consisting of zero or more values.
You can choose between a number of different kinds of sequence implementations.
Scheme traditionally has @ref{Lists,lists} and @ref{Vectors,vectors}.
Any Java class that implements @code{java.util.List} is a sequence type.
Raw Java arrays can also be viewerd as a sequence,
and strings can be viewed a sequence (or vector) of characters.
Kawa also provides @ref{Uniform vectors,uniform vectors}.

Sequence types differ in their API, but given a sequence type @var{stype}
you can construct instances of that type using the syntax:
@example
(@var{stype} @var{v0} @var{v1} .... @var{vn})
@end example
For example:
@example
(bytevector 9 8 7 6)  @result{} #u8(9 8 7 6)
@end example

For a raw Java class name @var{jname} you may need to use
the empty keyword @code{||:} to separate constructor parameters (if any)
from sequence elements, as in:
@example
(gnu.lists.U8Vector ||: 9 8 7 6)  @result{} #u8(9 8 7 6)
@end example
This syntax works with any type with a default constructor
and a 1-argument @code{add} method;
see @ref{Allocating objects} for details.
You can use the same syntax for allocating arrays,
though array creation supports @ref{Creating-new-Java-arrays,more options}.

To extract an element from Scheme sequence of type @var{stype}
there is usually a function @code{@var{stype}-ref}.  For example:
@example
(define vec1 (vector 5 6 7 8))
(vector-ref vec1 2) @result{} 7
@end example

More concisely, you can use (Kawa-specific) function call syntax:
@example
(vec1 3) @result{} 8
@end example

The index can be another sequence, which creates a new sequence
of the selected indexes:
@example
(vec1 [3 0 2 1]) @result{} #(8 5 7 6)
@end example
It is convenient to use a @ref{Ranges,@dfn{range}} to select
a sub-sequence:
@example
(vec1 [1 <=: 3]) @result{} #(6 7 8)
(vec1 [2 <:]) @result{} #(7 8)
@end example

The same function call syntax also works for raw Java arrays
(though the index is restricted to an integer, not a sequence or array):
@example
(define arr1 (long[] 4 5 6 7))
(arr1 3) @result{} 7
@end example

To assign to (replace) an element from a sequence of Scheme type @var{stype}
there is usually a function @code{@var{stype}-set!}:
@example
(vector-set! vec1 1 9)
vec1 @result{} #(5 9 7 8)
@end example

Again, you can use the function call syntax:
@example
(set! (vec1 2) 'x)
vec1 @result{} #(5 9 x 8)
@end example

@deffn Procedure length seq
Returns the number of elements of the @var{seq}.

@example
(length '(a b c))             @result{}  3
(length '(a (b) (c d e)))     @result{}  3
(length '())                  @result{}  0
(length [3 4 [] 12])          @result{}  4
(length (vector))             @result{}  0
(length (int[] 7 6))          @result{}  2
@end example

The length of a string is the number of characters (Unicode code points).
In contrast, the @code{length} @emph{method} (of the @code{CharSequence} interface)
returns the number of 16-bit code points:
@example
(length "Hello")              @result{}  5
(define str1 "Hello \x1f603;!")
(invoke str1 'length)         @result{}  9
(length str1)                 @result{}  8 ; Used to return 9 in Kawa 2.x.
(string-length str1)          @result{}  8
@end example
@end deffn

@node Lists
@section Lists

A pair (sometimes called a @dfn{dotted pair}) is a record structure
with two fields called the car and cdr fields (for historical
reasons). Pairs are created by the procedure @code{cons}. The
car and cdr fields are accessed by the procedures @code{car} and
@code{cdr}. The car and cdr fields are assigned by the procedures
@code{set-car!} and @code{set-cdr!}.

Pairs are used primarily to represent lists. A @dfn{list} can be
defined recursively as either the empty list or a pair whose
cdr is a list. More precisely, the set of lists is defined as
the smallest set @var{X} such that:
@itemize
@item
The empty list is in @var{X}.
@item
If @var{list} is in @var{X}, then any pair whose cdr field contains
@var{list} is also in @var{X}.
@end itemize

The objects in the car fields of successive pairs of a list are
the elements of the list. For example, a two-element list
is a pair whose car is the first element and whose cdr is a
pair whose car is the second element and whose cdr is the
empty list. The length of a list is the number of elements,
which is the same as the number of pairs.

The empty list is a special object of its own type. It is not
a pair, it has no elements, and its length is zero.

@emph{Note:} The above definitions imply that all lists have finite
length and are terminated by the empty list.

The most general notation (external representation) for
Scheme pairs is the “dotted” notation @code{(@var{c1} . @var{c2} )}
where @var{c1} is the value of the car field and
@var{c2} is the value of the cdr field.
For example @code{(4 . 5)} is a pair whose car is 4 and
whose cdr is 5. Note that @code{(4 . 5)} is the external representation
of a pair, not an expression that evaluates to a pair.

A more streamlined notation can be used for lists: the
elements of the list are simply enclosed in parentheses and
separated by spaces. The empty list is written @code{()}.
For example,
@example
(a b c d e)
@end example
and
@example
(a . (b . (c . (d . (e . ())))))
@end example
are equivalent notations for a list of symbols.

A chain of pairs not ending in the empty list is called an
@dfn{improper list}. Note that an improper list is not a list.
The list and dotted notations can be combined to represent
improper lists:
@example
(a b c . d)
@end example
is equivalent to
@example
(a . (b . (c . d)))
@end example

@emph{Needs to finish merging from R7RS!}

@deffn Procedure make-list k [fill]
Returns a newly allocated list of @var{k} elements.  If a second argument
is given, the each element is initialized to @var{fill}.
Otherwise the initial contents of each element is unspecified.
@example
(make-list 2 3)   @result{} (3 3)
@end example
@end deffn

@anchor{SRFI-1}
@subsection SRFI-1 list library

The @uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI-1 List Library}
is available, though not enabled by default.  To use its functions you
must @code{(require 'list-lib)} or @code{(require 'srfi-1)}.
@example
(require 'list-lib)
(iota 5 0 -0.5) @result{} (0.0 -0.5 -1.0 -1.5 -2.0)
@end example

@deffn Procedure reverse! list
The result is a list consisting of the elements of @var{list} in reverse order.
No new pairs are allocated, instead the pairs of @var{list} are re-used,
with @code{cdr} cells of @var{list} reversed in place.  Note that if @var{list}
was pair, it becomes the last pair of the reversed result.
@end deffn

@anchor{SRFI-101}
@subsection SRFI-101 Purely Functional Random-Access Pairs and Lists

@uref{http://srfi.schemers.org/srfi-101/srfi-101.html, SRFI-101}
specifies immutable (read-only) lists with fast (logarithmic) indexing
and functional
update (i.e. return a modified list).
These are implemented by a @code{RAPair} class
which extends the generic @code{pair} type, which means that most
code that expects a standard list will work on these lists as well.

@node Vectors
@section Vectors

Vectors are heterogeneous structures whose elements are indexed by
integers.  A vector typically occupies less space than a list of the
same length, and the average time needed to access a randomly chosen
element is typically less for the vector than for the list.

The @emph{length} of a vector is the number of elements that it
contains.  This number is a non--negative integer that is fixed when the
vector is created.  The @emph{valid indices} of a vector are the exact
non--negative integer objects less than the length of the vector.  The
first element in a vector is indexed by zero, and the last element is
indexed by one less than the length of the vector.

Vectors are written using the notation @code{#(@var{obj} ...)}.
For example, a vector of length 3 3 containing the number zero
in element 0, the list @code{(2 2 2 2)} in element 1, and the
string @code{"Anna"} in element 2 can be written as following:
@example
#(0 (2 2 2 2) "Anna")
@end example
Note that this is the external representation of a vector.
In Kawa, a vector datum is self-evaluating,
but for style (and compatibility with R7RS) is is suggested
you quote a vector constant:
@example
’#(0 (2 2 2 2) "Anna")  @result{} #(0 (2 2 2 2) "Anna")
@end example

Compare these different ways of creating a vector:
@table @code
@item (vector a b c)
In this case @code{a}, @code{b}, and @code{c} are expressions evaluated at
run-time and the results used to initialize a newly-allocated 3-element vector.
@item [a b c]
Same as using vector, but more concise, and results in an immutable
(non-modifiable) vector.
@item #(a b c)
This is reader syntax and creates a vector literal,
at read-time, early in compile-time.
The symbols @code{a}, @code{b}, and @code{c} are not evaluated
but instead used literally.
@item `#(,a ,b ,c)
This is reader-syntax, using quasi-quotation,
so @code{a}, @code{b}, and @code{c} are expressions evaluated at run-time.
This is equivalent to @code{[a b c]} in that it results in an immutable vector.
@end table


@deffn Type vector
The type of vector objects.
@end deffn

@deffn Constructor vector @var{obj} @dots{}
Return a newly allocated vector whose elements contain the given
arguments.  Analogous to @code{list}.

@example
(vector 'a 'b 'c)               @result{}  #(a b c)
@end example

Alternatively, you can use square-bracket syntax,
which results in an immutable vector:
@example
['a 'b 'c]               @result{}  #(a b c)
@end example
@end deffn

@deffn Procedure make-vector @var{k}
@deffnx Procedure make-vector @var{k} @var{fill}
Return a newly allocated vector of @var{k} elements.  If a second
argument is given, then each element is initialized to @var{fill}.
Otherwise the initial contents of each element is @code{#!null}.
@end deffn

@deffn Procedure vector? @var{obj}
Return @true{} if @var{obj} is a vector, @false{} otherwise.
@end deffn

@deffn Procedure vector-length @var{vector}
Return the number of elements in @var{vector} as an exact integer.

@end deffn

@deffn Procedure vector-ref @var{vector} @var{k}
It is an error if @var{k} is not a valid index of @var{vector}.
The @func{vector-ref}
procedure returns the contents of element @var{k} of @var{vector}.

@example
(vector-ref '#(1 1 2 3 5 8 13 21) 5)     @result{}  8
(vector-ref '#(1 1 2 3 5 8 13 21)
  (inexact->exact (round (* 2 (acos -1)))))
@result{} 13
@end example
@end deffn

@deffn Procedure vector-set! @var{vector} @var{k} @var{obj}
It is an error if @var{k} is not a valid index of @var{vector}.
The @func{vector-set!}
procedure stores @var{obj} in element @var{k} of @var{vector}, and
returns no values.

@example
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
  (vector-set! vec 1 '("Sue" "Sue"))
  vec)
  @result{}  #(0 ("Sue" "Sue") "Anna")

(vector-set! '#(0 1 2) 1 "doe")
  @result{}  @i{error}    ;; constant vector
@end example
@end deffn

A concise alternative to @code{vector-ref} and @code{vector-set!}
is to use function call syntax.  For example:
@example
(let ((vec (vector 0 '(2 2 2 2) "Anna")))
  (set! (vec 1) '("Sue" "Sue"))
  (list (vec 2) (vec 1)))
  @result{}  ("Anna" ("Sue" "Sue"))
@end example

@deffn Procedure vector->list @var{vector} [@var{start} [@var{end}]]
The @func{vector->list} procedure returns a newly allocated list of the
objects contained in the elements of @var{vector}
between @var{start} and @var{end}.

@example
(vector->list '#(dah dah didah))        @result{}  (dah dah didah)
(vector->list '#(dah dah didah) 1 2)    @result{}  (dah)
@end example
@end deffn

@deffn Procedure list->vector @var{list}
The @func{list->vector} procedure returns a newly created vector
initialized to the elements of the list @var{list}, in order.
@example
(list->vector '(dididit dah))           @result{}  #(dididit dah)
@end example
@end deffn

@deffn Procedure vector-copy vector [start [end]]
Returns a newly allocated copy of the elements of the given
@var{vector} between @var{start} and @var{end} . The elements of the new
vector are the same (in the sense of @code{eqv?}) as the elements
of the old.

@example
(define a #(1 8 2 8)) ; a may be immutable
(define b (vector-copy a))
(vector-set! b 0 3)   ; b is mutable
b                     @result{}      #(3 8 2 8)
(define c (vector-copy b 1 3))
c                     @result{} #(8 2)
@end example
@end deffn

@deffn Procedure vector-copy! to at from [start [end]]
Copies the elements of vector from between start and end
to vector to, starting at at. The order in which elements
are copied is unspecified, except that if the source and
destination overlap, copying takes place as if the source is first
copied into a temporary vector and then into the destination.
This can be achieved without allocating storage by making
sure to copy in the correct direction in such circumstances.

It is an error if @var{at} is less than zero or greater than the length
of @var{to}.
It is also an error if @code{(- (vector-length @var{to}) @var{at})} is less
than @code{(- @var{end} @var{start})}.

@example
(define a (vector 1 2 3 4 5))
(define b (vector 10 20 30 40 50))
(vector-copy! b 1 a 0 2)
b    @result{} #(10 1 2 40 50)
@end example
@end deffn

@deffn Procedure vector-append @var{arg}...
Creates a newly allocated vector whose elements are the
concatenation of the elements of the given arguments.
Each @var{arg} may be a vector or a list.
@example
(vector-append #(a b c) #(d e f))
    @result{} #(a b c d e f)
@end example
@end deffn

@deffn Procedure {vector-fill!} @var{vector fill} [@var{start} [@var{end}]]
Stores @var{fill} in in the elements of @var{vector}
between @var{start} and @var{end}.
@example
(define a (vector 1 2 3 4 5))
(vector-fill! a 'smash 2 4)
a  @result{} #(1 2 smash smash 5)
@end example
@end deffn

The procedures @code{vector-map} and @code{vector-for-each}
are documented in @ref{Mapping functions}.

@node Uniform vectors
@section Uniform vectors

Uniform vectors are vectors whose elements are of the same numeric type.
The are defined by @uref{http://srfi.schemers.org/srfi-4/srfi-4.html,SRFI-4}.
The type names (such as @code{s8vector}) are a Kawa extension.

@display
@stxdef{uniform-vector} @stxlit{#} @stxref{uniform-tag} @stxref{list}
@stxdef{uniform-tag} @stxlit{f32} | @stxlit{f64}
    | @stxlit{s8} | @stxlit{s16} | @stxlit{s32} | @stxlit{s64}
    | @stxlit{u8} | @stxlit{u16} | @stxlit{u32} | @stxlit{u64}
@end display

This example is a literal for a 5-element vector of unsigned short (@code{ushort}) values:
@example
(define uvec1 #u16(64000 3200 160 8 0))
@end example

Since a uniform vector is a sequence, you can use function-call
notation to index one.  For example:
@example
(uvec1 1) @result{} 3200
@end example
In this case the result is a primitive unsigned short (@code{ushort}),
which is converted to a @code{gnu.math.UShort} if an object is needed.

@deffn Type s8vector
The type of uniform vectors where each element can contain
a signed 8-bit integer.  Represented using an array of @code{byte}.
@end deffn

@deffn Type u8vector
The type of uniform vectors where each element can contain
an unsigned 8-bit integer.  Represented using an array of @code{<byte>},
but each element is treated as if unsigned.

This type is a synonym for @code{bytevector},
which has @ref{Bytevectors, extra functions}.
@end deffn

@deffn Type s16vector
The type of uniform vectors where each element can contain
a signed 16-bit integer.  Represented using an array of @code{short}.
@end deffn

@deffn Type u16vector
The type of uniform vectors where each element can contain
an unsigned 16-bit integer.  Represented using an array of @code{short},
but each element is treated as if unsigned.
@end deffn

@deffn Type s32vector
The type of uniform vectors where each element can contain
a signed 32-bit integer.  Represented using an array of @code{int}.
@end deffn

@deffn Type u32vector
The type of uniform vectors where each element can contain
an unsigned 32-bit integer.  Represented using an array of @code{int},
but each element is treated as if unsigned.
@end deffn

@deffn Type s64vector
The type of uniform vectors where each element can contain
a signed 64-bit integer.  Represented using an array of @code{long}.
@end deffn

@deffn Type u64vector
The type of uniform vectors where each element can contain
an unsigned 64-bit integer.  Represented using an array of @code{long},
but each element is treated as if unsigned.
@end deffn

@deffn Type f32vector
The type of uniform vectors where each element can contain
a 32-bit floating-point real.  Represented using an array of @code{float}.
@end deffn

@deffn Type f64vector
The type of uniform vectors where each element can contain
a 64-bit floating-point real.  Represented using an array of @code{double}.
@end deffn

@deffn Procedure s8vector? value
@deffnx Procedure u8vector? value
@deffnx Procedure s16vector? value
@deffnx Procedure u16vector? value
@deffnx Procedure s32vector? value
@deffnx Procedure u32vector? value
@deffnx Procedure s64vector? value
@deffnx Procedure u64vector? value
@deffnx Procedure f32vector? value
@deffnx Procedure f64vector? value
Return true iff @var{value} is a uniform vector of the specified type.
@end deffn

@deffn Procedure make-s8vector n [value]
@deffnx Procedure make-u8vector n [value]
@deffnx Procedure make-s16vector n [value]
@deffnx Procedure make-u16vector n [value]
@deffnx Procedure make-s32vector n [value]
@deffnx Procedure make-u32vector n [value]
@deffnx Procedure make-s64vector n [value]
@deffnx Procedure make-u64vector n [value]
@deffnx Procedure make-f32vector n [value]
@deffnx Procedure make-f64vector n [value]
Create a new uniform vector of the specified type,
having room for @var{n} elements.
Initialize each element to @var{value} if it is specified; zero otherwise.
@end deffn

@deffn Constructor s8vector value ...
@deffnx Constructor u8vector value ...
@deffnx Constructor s16vector value ..
@deffnx Constructor u16vector value ...
@deffnx Constructor s32vector value ...
@deffnx Constructor u32vector value ...
@deffnx Constructor s64vector value ...
@deffnx Constructor u64vector value ...
@deffnx Constructor f32vector value ...
@deffnx Constructor f64vector value ...
Create a new uniform vector of the specified type,
whose length is the number of @var{value}s specified,
and initialize it using those @var{value}s.
@end deffn

@deffn Procedure s8vector-length v
@deffnx Procedure u8vector-length v
@deffnx Procedure s16vector-length v
@deffnx Procedure u16vector-length v
@deffnx Procedure s32vector-length v
@deffnx Procedure u32vector-length v
@deffnx Procedure s64vector-length v
@deffnx Procedure u64vector-length v
@deffnx Procedure f32vector-length v
@deffnx Procedure f64vector-length v
Return the length (in number of elements) of the uniform vector @var{v}.
@end deffn

@deffn Procedure s8vector-ref v i
@deffnx Procedure u8vector-ref v i
@deffnx Procedure s16vector-ref v i
@deffnx Procedure u16vector-ref v i
@deffnx Procedure s32vector-ref v i
@deffnx Procedure u32vector-ref v i
@deffnx Procedure s64vector-ref v i
@deffnx Procedure u64vector-ref v i
@deffnx Procedure f32vector-ref v i
@deffnx Procedure f64vector-ref v i
Return the element at index @var{i} of the uniform vector @var{v}.
@end deffn

@deffn Procedure s8vector-set! v i x
@deffnx Procedure u8vector-set! v i x
@deffnx Procedure s16vector-set! v i x
@deffnx Procedure u16vector-set! v i x
@deffnx Procedure s32vector-set! v i x
@deffnx Procedure u32vector-set! v i x
@deffnx Procedure s64vector-set! v i x
@deffnx Procedure u64vector-set! v i x
@deffnx Procedure f32vector-set! v i x
@deffnx Procedure f64vector-set! v i x
Set the element at index @var{i} of uniform vector @var{v}
to the value @var{x}, which must be a number coercible
to the appropriate type.
@end deffn

@deffn Procedure s8vector->list v
@deffnx Procedure u8vector->list v
@deffnx Procedure s16vector->list v
@deffnx Procedure u16vector->list v
@deffnx Procedure s32vector->list v
@deffnx Procedure u32vector->list v
@deffnx Procedure s64vector->list v
@deffnx Procedure u64vector->list v
@deffnx Procedure f32vector->list v
@deffnx Procedure f64vector->list v
Convert the uniform vetor @var{v} to a list containing the elments of @var{v}.
@end deffn

@deffn Procedure list->s8vector l
@deffnx Procedure list->u8vector l
@deffnx Procedure list->s16vector l
@deffnx Procedure list->u16vector l
@deffnx Procedure list->s32vector l
@deffnx Procedure list->u32vector l
@deffnx Procedure list->s64vector l
@deffnx Procedure list->u64vector l
@deffnx Procedure list->f32vector l
@deffnx Procedure list->f64vector l
Create a uniform vector of the appropriate type, initializing it
with the elements of the list @var{l}.  The elements of @var{l}
must be numbers coercible the new vector's element type.
@end deffn

@subsection Relationship with Java arrays

Each uniform array type is implemented as an @dfn{underlying Java array},
and a length field.
The underlying type is
@code{byte[]} for @code{u8vector} or @code{s8vector};
@code{short[]} for @code{u16vector} or @code{u16vector};
@code{int[]} for @code{u32vector} or @code{s32vector};
@code{long[]} for @code{u64vector} or @code{s64vector};
@code{float[]} for @code{f32vector}; and
@code{double[]} for @code{f32vector}.
The length field allows a uniform array to only use the
initial part of the underlying array.  (This can be used
to support Common Lisp's fill pointer feature.)
This also allows resizing a uniform vector.  There is no
Scheme function for this, but you can use the @code{setSize} method:
@example
(invoke some-vector 'setSize 200)
@end example

If you have a Java array, you can create a uniform vector
sharing with the Java array:
@example
(define arr :: byte[] ((primitive-array-new byte) 10))
(define vec :: u8vector (make u8vector arr))
@end example
At this point @code{vec} uses @code{arr} for its underlying storage,
so changes to one affect the other.
It @code{vec} is re-sized so it needs a larger underlying array,
then it will no longer use @code{arr}.

@node Bytevectors
@section Bytevectors

@dfn{Bytevectors} represent blocks of binary data. They are
fixed-length sequences of bytes, where a @var{byte} is an exact
integer in the range [0, 255]. A bytevector is typically more
space-efficient than a vector containing the same values.

The length of a bytevector is the number of elements that
it contains. This number is a non-negative integer that is
fixed when the bytevector is created. The valid indexes of
a bytevector are the exact non-negative integers less than
the length of the bytevector, starting at index zero as with
vectors.

The @code{bytevector} type is equivalent to the @code{u8vector}
@ref{Uniform vectors,uniform vector} type, but is specified
by the R7RS standard.

Bytevectors are written using the notation @code{#u8(byte . . . )}.
For example, a bytevector of length 3 containing the byte
0 in element 0, the byte 10 in element 1, and the byte 5 in
element 2 can be written as following:
@example
#u8(0 10 5)
@end example
Bytevector constants are self-evaluating, so they do not
need to be quoted in programs.

@deffn Type bytevector
The type of bytevector objects.
@end deffn

@deffn Constructor bytevector @var{byte} @dots{}
Return a newly allocated bytevector whose elements contain the given
arguments.  Analogous to @code{vector}.
@example
(bytevector 1 3 5 1 3 5)  @result{}  #u8(1 3 5 1 3 5)
(bytevector)  @result{}  #u8()
@end example
@end deffn

@deffn Procedure bytevector? @var{obj}
Return @true{} if @var{obj} is a bytevector, @false{} otherwise.
@end deffn

@deffn Procedure make-bytevector k
@deffnx Procedure make-bytevector k byte
The @code{make-bytevector} procedure returns a newly allocated
bytevector of length @var{k}. If @var{byte} is given, then all elements
of the bytevector are initialized to @var{byte},
otherwise the contents of each element are unspecified.
@example
(make-bytevector 2 12) @result{} #u8(12 12)
@end example
@end deffn

@deffn Procedure bytevector-length bytevector
Returns the length of @var{bytevector} in bytes
as an exact integer.
@end deffn

@deffn Procedure bytevector-u8-ref bytevector k 
It is an error if @var{k} is not a valid index of @var{bytevector}.
Returns the @var{k}th byte of @var{bytevector}.
@example
(bytevector-u8-ref ’#u8(1 1 2 3 5 8 13 21) 5)
  @result{} 8
@end example
@end deffn

@deffn Procedure bytevector-u8-set! bytevector k byte
It is an error if @var{k} is not a valid index of @var{bytevector}.
Stores @var{byte} as the @var{k}th byte of @var{bytevector}.
@example
(let ((bv (bytevector 1 2 3 4)
  (bytevector-u8-set! bv 1 3)
  bv)
  @result{} #u8(1 3 3 4)
@end example
@end deffn

@deffn Procedure bytevector-copy bytevector [start [end]]
Returns a newly allocated bytevector containing the bytes
in @var{bytevector} between @var{start} and @var{end}.

@example
(define a #u8(1 2 3 4 5))
(bytevector-copy a 2 4))
    @result{} #u8(3 4)
@end example
@end deffn

@deffn Procedure bytevector-copy! to at from [start [end]]
Copies the bytes of bytevector@var{from} between @var{start} and @var{end}
to bytevector @var{to}, starting at @var{at}. The order in which bytes
are copied is unspecified, except that if the source and destination overlap,
copying takes place as if the source is first
copied into a temporary bytevector and then into the destination.
This is achieved without allocating storage
by making sure to copy in the correct direction in such
circumstances.

It is an error if @var{at} is less than zero or greater than the length
of @var{to}.
It is also an error if @code{(- (bytevector-length @var{to}) @var{at})}
is less than @code{(- @var{end} @var{start})}.

@example
(define a (bytevector 1 2 3 4 5))
(define b (bytevector 10 20 30 40 50))
(bytevector-copy! b 1 a 0 2)
b        @result{} #u8(10 1 2 40 50)
@end example
@end deffn

@deffn Procedure bytevector-append bytevector...
Returns a newly allocated bytevector whose elements are
the concatenation of the elements in the given bytevectors.

@example
(bytevector-append #u8(0 1 2) #u8(3 4 5))
        @result{}  #u8(0 1 2 3 4 5)
@end example
@end deffn

@subsection Converting to or from strings

@deffn Procedure utf8->string bytevector [start [end]]
This procedure decodes the bytes of a bytevector between @var{start}
and @var{end}, interpreting as a UTF-8-encoded string,
and returns the corresponding string.
It is an error for @var{bytevector} to contain invalid UTF-8 byte sequences.
@example
(utf8->string #u8(#x41))  @result{} "A"
@end example
@end deffn

@deffn Procedure utf16->string bytevector [start [end]]
@deffnx Procedure utf16be->string bytevector [start [end]]
@deffnx Procedure utf16le->string bytevector [start [end]]
These procedures interpret their <var>bytevector</var> argument as
a UTF-16 encoding of a sequence of characters,
and return an istring containing that sequence.

The bytevector subrange given to @code{utf16->string}
may begin with a byte order mark (BOM); if so, that BOM
determines whether the rest of the subrange is to be
interpreted as big-endian or little-endian; in either case,
the BOM will not become a character in the returned string.
If the subrange does not begin with a BOM, it is decoded using
the same implementation-dependent endianness used by
@code{string->utf16}.

The @code{utf16be->string} and @code{utf16le->string}
procedures interpret their inputs as big-endian or little-endian,
respectively.  If a BOM is present, it is treated as a normal
character and will become part of the result.

It is an error if @code{(- @var{end} @var{start})} is odd,
or if the bytevector subrange contains invalid UTF-16 byte sequences.
@end deffn

@deffn Procedure string->utf8 string [start [end]]
This procedure encodes the characters of a string between
@var{start} and @var{end} and returns the corresponding bytevector,
in UTF-8 encoding.
@example
(string->utf8 "λ")     @result{} " #u8(#xCE #xBB)
@end example
@end deffn

@deffn Procedure string->utf16 string [start [end]]
@deffnx Procedure string->utf16be string [start [end]]
@deffnx Procedure string->utf16le string [start [end]]
These procedures return a newly allocated (unless empty)
bytevector containing a UTF-16 encoding of the given substring.

The bytevectors returned by @code{string->utf16be}
and @code{string->utf16le}
do not contain a byte-order mark (BOM);
@code{string->utf16be}> returns a big-endian encoding,
while @code{string->utf16le} returns a little-endian encoding.

The bytevectors returned by @code{string->utf16}
begin with a BOM that declares an implementation-dependent
endianness, and the bytevector elements following that BOM
encode the given  substring using that endianness.

@emph{Rationale:}
These procedures are consistent with the Unicode standard.
Unicode suggests UTF-16 should default to big-endian, but
Microsoft prefers little-endian.
@end deffn

@node Ranges
@section Ranges

A @dfn{range} is an immutable sequence of values
that increase ``linearly'' - i.e. by a fixed amount.
Most commonly it's a sequence of consequtive integers.
An example of the syntax is @code{[3 <: 7]} which evaluates
to the sequence @code{[3 4 5 6]}.
You can specify an explicit increment with a @code{by:} option.
There are multiple ways to specify when the sequence stops.
For example @code{[3 by 2 <=: 7]} is the even numbers from
3 up to 7 (inclusive, because of the @code{<=}).

Ranges are very useful for loop indexes, or selecting a sub-sequence.
If you have a sequence @var{q} and a range @var{r}, and you
use the syntax @code{(@var{q} @var{r})} to
``apply''@var{q} with the argument @var{r},
is result is to select elements of @var{q} with indexes in @var{r}.
@example
("ABCDEFG" [1 by: 2 <: 7])  @result{} "BDF"
@end example

A range can be @dfn{unbounded}, or non-finite, if you leave off
the end value.  For example @code{[3 by: 2]} is the odd integers starting at 3.

@display
@stxdef{unbounded-range}
  @stxlit{[} @var{start-expression} @stxlit{by:} @var{step-expression} @stxlit{]}
  | @stxlit{[} @var{start-expression} @stxlit{<:} @stxlit{]}
@end display

The expression @code{[@var{start} by: @var{step}]} evaluates to an
infinite sequence of values, starting with @var{start}, and followed by
@code{(+ @var{start} @var{step})},
@code{(+ @var{start} (* 2 @var{step}))}, and so on.

The syntax @code{[@var{start-expression} <:]}
is shorthand for @code{[@var{start-expression} by: 1]}.

@display
@stxdef{bounded-range} @stxlit{[} @var{start-expression} [@stxlit{by:} @var{step-expression}] @stxref{range-end} @stxlit{]}
@stxdef{range-end} @stxlit{<:} @var{end-expression}
  | @stxlit{<=:} @var{end-expression}
  | @stxlit{>:} @var{end-expression}
  | @stxlit{>=:} @var{end-expression}
  | @stxlit{size:} @var{size-expression}
@end display

A bounded range takes an initial subsequence of the unbounded
range specified by the @var{start-expression} and optional @var{step-expression}.
The different @var{end-expression} variants provide different
ways to specify the initial subsequence.

If @code{size: @var{size}} is specified, then the resulting range
is the first @var{size} elements of unbounded sequence.

In the @code{<: @var{end}} or @code{<=: @var{end}} cases then
the sequence counts up: The @var{step} must be positive, and defaults to 1.
The resulting values are those  @var{x} such that @code{(< @var{x} @var{end})},
or  @code{(<= @var{x} @var{end})}, respectively.

In the @code{>: @var{end}} or @code{>=: @var{end}} cases then
the sequence counts down: The @var{step} must be negative, and defaults to -1.
The resulting values are those  @var{x} such that @code{(> @var{x} @var{end})},
or  @code{(>= @var{x} @var{end})}, respectively.

The @var{start-expression}, @var{step-expression}, and @var{size-expression}
must evaluate to real numbers, not necessarily integers.
For example: @code{[1 by: 0.5 <=: 3.0]} is @code{[1.0 1.5 2.0 2.5 3.0]}.

The two pseudo-ranges @code{[<:]} and @code{[>:]} are useful as
array indexes. They mean ``all of the valid indexes'' of the array being indexed.
For increasing index values use @code{[<:]}; for decreasing
index values (i.e. reversing) use @code{[>:]}.

@node Streams
@section Streams - lazy lists

Streams, sometimes called lazy lists, are a sequential data structure
containing elements computed only on demand. A stream is either null
or is a pair with a stream in its cdr. Since elements of a stream are
computed only when accessed, streams can be infinite. Once computed,
the value of a stream element is cached in case it is needed again.

@emph{Note:} These are not the same as Java 8 streams.

@example
(require 'srfi-41)
(define fibs
  (stream-cons 1
    (stream-cons 1
      (stream-map +
        fibs
        (stream-cdr fibs)))))
(stream->list 8 fibs) @result{} (1 1 2 3 5 8 13 21)
@end example

See the @uref{http://srfi.schemers.org/srfi-41/srfi-41.html, SRFI 41 specification} for details.

The Kawa implementations builds on @ref{Lazy evaluation,,promises}.
The @code{stream-null} value is a promise that evaluates to the empty list.
The result of @code{stream-cons} is an eager immutable pair whose
@code{car} and @code{cdr} properties return promises.

@node Arrays
@section Multi-dimensional Arrays

Arrays are heterogeneous data structures that generaize vectors to multiple
indexes or dimensions.  Instead of a single integer index,
there are multiple indexes:  An index is a vector of integers;
the length of a valid index sequence
is the rank or the number of dimensions of an array.

@c @example
@c (define arr1 (
@c @end example

Kawa multi-dimensional arrays follows the
by @uref{http://srfi.schemers.org/srfi-25/srfi-25.html,SRFI-25 specification},
with additions from Racket's
@uref{https://docs.racket-lang.org/math/array.html, math.array} package
and other sources.

An array whose rank is 1, and where the (single) lower bound is 0
is a sequence.
Furthermore, if such an array is simple (not created by @code{share-array})
it will be implemented using a @code{<vector>}.
Uniform vectors and strings are also arrays in Kawa.

A rank-0 array has a single value.  It is essentially a box for that
value.  Functions that require arrays may treat non-arrays
as a rank-0 array containing that value.

An array of rank 2 is frequently called a @dfn{matrix}.

Note that Kawa arrays are distinct from Java (native) arrays.
The latter is a simpler one-dimensional vector-like data structure,
which is used to implement Kawa arrays and vectors.

@deffn Procedure array? obj
Returns @code{#t} if @var{obj} is an array, otherwise returns @code{#f}.
@end deffn

@subsection Array shape

The @dfn{shape} of an array consists of bounds for each index.

@c a simple-array is either a SimpleVector or a GeneralArray
@c a generic vector implements AVector
@c a stored-array is a simple-array or a transform (view) of a simple-array

The lower bound @var{b} and the upper bound @var{e} of a dimension are
exact integers with @code{(<= @var{b} @var{e})}. A valid index along the
dimension is an exact integer @var{i} that satisfies both
@code{(<= @var{b} @var{i})} and @code{(< @var{i} @var{e})}.
The length of the array along the dimension is the difference
@code{(- @var{e} @var{b})}.
The size of an array is the product of the lengths of its dimensions.

A procedure that requires a @var{shape} accepts any of the following:
@itemize
@item
A vector of simple @ref{Ranges,ranges}, one for each
dimension, all of who are
bounded (finite), consist of integer values,
and have a @var{step} of 1.
Each range, which is usually written as @code{[@var{b} <: @var{e}]},
expresses the bounds of the corresponding dimension.
For example @code{[[0 <: 5] [2 <=: 6]]} is the shape
of a rank-2 array, where the first index can be from 0 to 5 (exclusive),
while the second index can be from 2 to 6 (inclusive).
@item
A vector of simple integers.
Each integer @var{e} is an upper bound,
and is equivalent to the range @code{[0 <: @var{e}]}.
@item
A vector consisting of a mix of integers and ranges.
@item
A rank-2 array @var{S} whose own shape is @code{[@var{r} 2]}.
For each dimension @var{k}
(where @code{(<= @var{k} 0)} and @code{(< @var{k} @var{r})}),
the lower bound @var{b@sub{k}} is @code{(S @var{k} 0)},
and the upper bound @var{e@sub{k}} is @code{(S @var{k} 1)}.
@end itemize

@deffn Procedure shape bound ...
Returns a shape. The sequence @var{bound} ... must consist of an even number
of exact integers that are pairwise not decreasing. Each pair gives the
lower and upper bound of a dimension.
If the shape is used to specify the dimensions of an array
and @var{bound} ... is the sequence @var{b0} @var{e0} ... @var{bk} @var{ek}
... of @var{n} pairs of bounds, then a valid index to the array is any
sequence @var{j0} ... @var{jk} ... of @var{n} exact integers where
each @var{jk} satisfies @code{(<= @var{bk} @var{jk})}
and @code{(< @var{jk} @var{ek})}.

The shape of a @var{d}-dimensional array is a @var{d} * 2 array
where the element at @var{k 0} contains the lower bound for an index along
dimension @var{k} and the element at @var{k 1} contains the
corresponding upper bound, where @var{k} satisfies @code{(<=  0 @var{k})}
and @code{(< @var{k} @var{d})}.

@code{(shape @@@var{bounds})}
is equivalent to:
@code{(array [2 (/ (length @var{bounds}) 2)] @@@var{bounds})}
@end deffn

@deffn Procedure array-rank array
Returns the number of dimensions of @var{array}.
@example
(array-rank
  (make-array (shape 1 2 3 4)))
@end example
Returns 2.
@end deffn

@deffn Procedure array-start array k
Returns the lower bound (inclusive) for the index along dimension @var{k}.
This is most commonly 0.
@end deffn

@deffn Procedure array-end array k
Returns the upper bound for the index along dimension @var{k}.
The bound is exclusive - i.e. the first integer higher
than the last legal index.
@end deffn

@deffn Procedure array-size array
Return the total number of elements of @var{array}.
This is the product of @code{(- (array-end @var{array} @var{k}) (array-start @var{array} @var{k}))} for every valid @var{k}.
@end deffn

@subsection Array types

@deffn Type array
@deffnx Type array@var{N}
@deffnx Type array[@var{etype}]
@deffnx Type array@var{N}[@var{etype}]

The type @code{array} matches all array values.
The type @code{array@var{N}}, where @var{N} is an integer
matches array of rank @var{N}.
For example @code{array2} matches rank-2 array - i.e. matrixes.

You can optionally specify the element type @var{etype}.
This can be a primitive type.
For example a @code{array2[double]} is a rank-2 array
whose elements are @code{double} values.
@end deffn

@anchor{array-literals}
@subsection Array literals and printing

An array literal starts with @code{#} followed by its rank,
followed by a tag that describes the underlying vector (by default @code{a}),
optionally followed by information about its shape,
and finally followed by the cells, organized into dimensions using parentheses.

For example, @code{#2a((11 12 13) (21 22 23))} is a rank-2 array (a matrix)
whose shape is @code{[2 3]} or equivalently @code{[[0 <: 2] [0 <: 3]]}.
It is pretty-printed as:
@example
╔#2a:2:3═╗
║11│12│13║
╟──┼──┼──╢
║21│22│23║
╚══╧══╧══╝
@end example

@display
@stxdef{array-literal} @stxref{array-literal-header} @stxref{datum}
@stxdef{array-literal-header} @stxlit{#} @var{rank} @stxref{vectag} @arbno{@stxref{array-bound}} 
@stxdef{array-bound} [@stxlit{@@}@var{lower}]@stxlit{:}@var{length} | @stxlit{@@}@var{lower}
@stxdef{vectag} @stxlit{a} | @stxref{uniform-tag}
@end display

The @var{vectag} specifies the type of the elements of the array.

Following the @var{vectag} you can optionally include information
about the shape: For each dimension you can optionally specify
the lower bounds (after the character @code{"@@"}),
followed by the length of the dimension (after the character @code{":"}).
The shape information is required if a lower bound is non-zero,
or any length is zero.

The @stxref{datum} contains the elements in a nested-list format:
a rank-1 array (i.e. vector) uses a single list,
a rank-2 array uses a list-of-listrs, and so on.
The elements are in lexicographic order.

A uniform u32 array of rank 2 with index ranges 2..3 and 3..4:
@example
#2u32@@2@@3((1 2) (2 3))
@end example

This syntax follow Common Lisp with
@uref{https://www.gnu.org/software/guile/manual/html_node/Array-Syntax.html,Guile
extensions}.  (Note that Guile prints rank-0 arrays with an extra
set of parentheses.  Kawa follows Common Lisp in not doing so.)

When an array is printed with the @code{write} function,
the result is an @code{array-literal}.
Printing with @code{display} formats the array in a rectangular grid
using the @code{format-array} procedure.
(Note that @code{format-array} is only used when the output is in column 0,
because Kawa has very limited support for printing rectangles.)

@deffn Procedure format-array value [element-format]
Produce a nice ``pretty'' display for @var{value}, which is usually an array.

The top line includes an @code{array-literal-header}.
The lower bound are only printed if non-zero.
The dimension lengths are printed if there is zoom, or if one of them is zero.
@example
#|kawa:34|# (! arr (array [[1 <=: 2] [1 <=: 3]]
#|.....35|#   #2a((1 2) (3 4)) 9 #2a((3 4) (5 6))
#|.....36|#   [42 43] #2a:1:3((8 7 6)) #2a((90 91) (100 101))))
#|kawa:37|# arr
╔#2a@@1:2@@1:3════╤═════════╗
║#2a═╗  │      9│#2a═╗    ║
║║1│2║  │       │║3│4║    ║
║╟─┼─╢  │       │╟─┼─╢    ║
║║3│4║  │       │║5│6║    ║
║╚═╧═╝  │       │╚═╧═╝    ║
╟───────┼───────┼─────────╢
║╔#1a:2╗│#2a:1:3│╔#2a:2:2╗║
║║42│43║│║8│7│6║│║ 90│ 91║║
║╚══╧══╝│╚═╧═╧═╝│╟───┼───╢║
║       │       │║100│101║║
║       │       │╚═══╧═══╝║
╚═══════╧═══════╧═════════╝
@end example
If @var{element-format} is specified, it is a format string used
for format each non-array:
@example
#|kawa:38|# (format-array arr "~4,2f")
╔#2a@@1:2@@1:3══╤════════════════╤═══════════════╗
║╔#2a:2:2══╗  │            9.00│╔#2a:2:2══╗    ║
║║1.00│2.00║  │                │║3.00│4.00║    ║
║╟────┼────╢  │                │╟────┼────╢    ║
║║3.00│4.00║  │                │║5.00│6.00║    ║
║╚════╧════╝  │                │╚════╧════╝    ║
╟─────────────┼────────────────┼───────────────╢
║╔#1a:2╤═════╗│╔#2a:1:3══╤════╗│╔#2a:2:2══════╗║
║║42.00│43.00║│║8.00│7.00│6.00║│║ 90.00│ 91.00║║
║╚═════╧═════╝│╚════╧════╧════╝│╟──────┼──────╢║
║             │                │║100.00│101.00║║
║             │                │╚══════╧══════╝║
╚═════════════╧════════════════╧═══════════════╝
@end example
If the rank is more than 2, then each ``layer''
is printed separated by double lines.
@example
#|kawa:42|# (array-reshape [1 <=: 24] [3 2 4])
╔#3a:3:2:4══╗
║ 1│ 2│ 3│ 4║
╟──┼──┼──┼──╢
║ 5│ 6│ 7│ 8║
╠══╪══╪══╪══╣
║ 9│10│11│12║
╟──┼──┼──┼──╢
║13│14│15│16║
╠══╪══╪══╪══╣
║17│18│19│20║
╟──┼──┼──┼──╢
║21│22│23│24║
╚══╧══╧══╧══╝
@end example
@end deffn

@subsection Array construction

See also @code{array-reshape}

@deffn Procedure array shape obj ...
Returns a new array whose shape is given by @var{shape} and the initial
contents of the elements are @var{obj} ... in row major order. The array does
not retain a reference to @var{shape}.
@end deffn

@deffn Procedure make-array shape
@deffnx Procedure make-array shape value...
Returns a newly allocated array whose shape is given by @var{shape}.
If @var{value} is provided, then each element is initialized to it.
If there is more than one @var{value}, they are used in order, starting
over then the @var{value}s are exhausted.
If there is no @var{value}, the initial contents of each element is
unspecified.  (Actually, it is the @code{#!null}.)
The array does not retain a reference to @var{shape}.

@example
#|kawa:16|# @kbd{(make-array [2 4] 1 2 3 4 5)}
╔#2a:2:4╗
║1│2│3│4║
╟─┼─┼─┼─╢
║5│1│2│3║
╚═╧═╧═╧═╝
@end example

@CompatibilityNote{} Guile has an incompatible @code{make-array} procedure.
@end deffn

@deffn Procedure build-array shape procedure
Construct a ``virtual array'' of the given @var{shape},
which uses no storage for the elements.
Instead, elements are calculated on-demand by calling @var{procedure},
which takes a single argument, an index vector.

There is no caching or memoization.

@example
#|kawa:1|# @kbd{(build-array [[10 <: 12] 3]}
#|....:2|# @kbd{  (lambda (ind)}
#|....:3|# @kbd{    (let ((x (ind 0)) (y (ind 1)))}
#|....:4|# @kbd{      (- x y))))}
#2a@@10:2:3
║10│ 9│8║
╟──┼──┼─╢
║11│10│9║
╚══╧══╧═╝
@end example
@end deffn

@deffn Procedure index-array shape
Return a new immutable array of the specified @var{shape}
where each element is the corresponding row-major index.
Same as @code{(array-reshape [0 <: @var{size}] @var{shape})}
where @var{size} is the @code{array-size} of the resulting array.

@example
#|kawa:1|# @kbd{(index-array [[1 <: 3] [2 <: 6]])}
#2a@@1:2@@2:4
║0│1│2│3║
╟─┼─┼─┼─╢
║4│5│6│7║
╚═╧═╧═╧═╝
@end example

@end deffn

@subsection Array indexing

If you ``call'' an array as it it were a function,
it is equivalent to using @code{array-index-ref},
which is generalization of @code{array-ref}.
For example, given a rank-2 array @var{arr} with integer indexes @var{i}
and @var{j}, the following all get the element of @var{arr}
at index @code{[@var{i} @var{j}]}.
@example
(@var{arr} @var{i} @var{j})
(array-index-ref @var{arr} @var{i} @var{j})
(array-ref @var{arr} @var{i} @var{j})
(array-ref @var{arr} [@var{i} @var{j}])
@end example

Using function-call notation or @code{array-index-ref}
(but not plain @code{array-ref}) you can do generalized APL-style
slicing and indirect indexing.
See under @code{array-index-ref} for examples.

@deffn Procedure array-ref array k ...
@deffnx Procedure array-ref array index
Returns the contents of the element of @var{array} at index @var{k} ....
The sequence @var{k} ... must be a valid index to @var{array}.
In the second form, @var{index} must be either a vector
(a 0-based 1-dimensional array) containing @var{k} ....
@example
(array-ref (array [2 3]
              'uno 'dos 'tres
              'cuatro 'cinco 'seis)
   1 0)
@end example
Returns @code{cuatro}.
@example
(let ((a (array (shape 4 7 1 2) 3 1 4)))
   (list (array-ref a 4 1)
         (array-ref a (vector 5 1))
         (array-ref a (array (shape 0 2)
                         6 1))))
@end example
Returns @code{(3 1 4)}.
@end deffn

@deffn Procedure array-index-ref array index ...
Generalized APL-style array indexing, where each @var{index}
can be either an array or an integer.

If each @var{index} is an integer, then the result is the same as @code{array-ref}.

Otherwise, the result is an immutable array whose rank is the sum of the ranks of
each @var{index}.  An integer is treated as rank-0 array.

If @var{marr} is the result of @code{(array-index-ref @var{arr} @var{M@sub{1}} @var{M@sub{2}} ...)} then:
@example
(@var{marr} @var{i@sub{11}} @var{i@sub{12}} ... @var{i@sub{21}} @var{i@sub{22}} ...)
@end example
is defined as:
@example
(@var{arr} (@var{M@sub{1}} @var{i@sub{11}} @var{i@sub{12}} ...) (@var{M@sub{2}} @var{i@sub{21}} @var{i@sub{22}} ...) ...)
@end example
Each @var{M@sub{k}} gets as many indexes as its rank.
If @var{M@sub{k}} is an integer, then it we use
it directly without any indexing.

Here are some examples, starting with simple indexing.
@example
#|kawa:1|# (define arr (array #2a((1 4) (0 4))
#|.....2|#                    10 11 12 13 20 21 22 23 30 31 32 33))
#|kawa:3|# arr
╔#2a@@1:3:4══╗
║10│11│12│13║
╟──┼──┼──┼──╢
║20│21│22│23║
╟──┼──┼──┼──╢
║30│31│32│33║
╚══╧══╧══╧══╝
#|kawa:4|# (arr 2 3)
23
@end example
If one index is a vector and the rest are scalar integers,
then the result is a vector:
@example
#|kawa:5|# (arr 2 [3 1])
#(23 21)
@end example
You can select a ``sub-matrix'' when all indexes are vectors:
@example
#|kawa:6|# (arr [2 1] [3 1 3])
╔#2a:2:3═╗
║23│21│23║
╟──┼──┼──╢
║13│11│13║
╚══╧══╧══╝
@end example
Using ranges for index vectors selects a rectangular sub-matrix.
@example
#|kawa:7|# (arr [1 <: 3] [1 <: 4])
╔#2a:2:3═╗
║11│12│13║
╟──┼──┼──╢
║21│22│23║
╚══╧══╧══╝
@end example
You can add new dimensions:
@example
#|kawa:8|# (arr [2 1] #2a((3 1) (3 2)))
#3a╤══╗
║23│21║
╟──┼──╢
║23│22║
╠══╪══╣
║13│11║
╟──┼──╢
║13│12║
╚══╧══╝
@end example
The pseudo-range @code{[<:]} can be used to select all the indexes
along a dimension.  To select row 2 (1-origin):
@example
#|kawa:9|# (arr 2 [<:])
#(20 21 22 23)
@end example
To reverse the order use @code{[>:]}:
@example
#|kawa:10|# (arr 2 [>:])
#(23 22 21 20)
@end example
To select column 3:
@example
#|kawa:11|# (arr [<:] 3)
#(13 23 33)
@end example
If you actually want a column matrix (i.e. with shape @code{[3 1]}
you can write can place the index in a single-element vector:
@example
#|kawa:12|# (arr [<:] [3])
#2a╗
║13║
╟──╢
║23║
╟──╢
║33║
╚══╝
@end example
To expand that column to 5 colums you can repeat the column index:
@example
#|kawa:13|# [3 by: 0 size: 5]
#(3 3 3 3 3)
#|kawa:14|# (arr [<:] [3 by: 0 size: 5])
╔#2a:3:5═╤══╤══╗
║13│13│13│13│13║
╟──┼──┼──┼──┼──╢
║23│23│23│23│23║
╟──┼──┼──┼──┼──╢
║33│33│33│33│33║
╚══╧══╧══╧══╧══╝
@end example
@end deffn

@subsection Modifying arrays

You can use @code{set!} to modify one or multiple elements.
To modify a single element:
@example
(set! (@var{arr} @var{index} ...) @var{new-value})
@end example
is equivalent to
@example
(array-set! @var{arr} @var{index} ... @var{new-value})
@end example
You can set a slice (or all of the elements).
In that case:
@example
(set! (@var{arr} @var{index} ...) @var{new-array})
@end example
is equivalent to:
@example
(array-copy! (array-index-share @var{arr} @var{index} ...) @var{new-array})
@end example

@deffn Procedure array-set! array k ... obj
@deffnx Procedure array-set! array index obj
Stores @var{obj} in the element of @var{array} at index @var{k} ....
Returns the void value.
The sequence @var{k} ... must be a valid index to @var{array}.
In the second form, @var{index} must be either a vector or a
0-based 1-dimensional array containing @var{k} ....

@example
(let ((a (make-array
            (shape 4 5 4 5 4 5))))
   (array-set! a 4 4 4 "huuhkaja")
   (array-ref a 4 4 4))
@end example
Returns @code{"huuhkaja"}.

@CompatibilityNote{} SRFI-47, Guile and Scheme-48 have @code{array-set!} with a
different argument order.
@end deffn

@deffn Procedure array-copy! dst src
@CompatibilityNote{} Guile has a @code{array-copy!} with the reversed
argument order.
@end deffn

@deffn Procedure array-fill! array value
Set all the values @var{array} to @var{value}.
@end deffn

@subsection Transformations and views

A view or transform of an array is an array @var{a@sub{2}}
whose elements come from some other array @var{a@sub{1}},
given some transform function @var{T} that maps @var{a@sub{2}} indexes
to @var{a@sub{1}} indexes.
Specifically @code{(array-ref @var{a@sub{2}} @var{indexes})}
is @code{(array-ref @var{a@sub{1}} (@var{T} @var{indexes}))}.
Modifying @var{a@sub{2}} causes @var{a@sub{1}} to be modified;
modifying @var{a@sub{1}} may modify @var{a@sub{2}}
(depending on the transform function).
The shape of @var{a@sub{2}} is in generally different than that of @var{a@sub{1}}.

@deffn Procedure array-transform array shape transform
This is a general mechanism for creating a view.
The result is a new array with the given @var{shape}.
Accessing this new array is implemented by calling the @var{transform}
function on the index vector, which must return a new index vector
valid for indexing the original @var{array}.
Here is an example (using the same @code{arr} as in
the @code{array-index-ref} example):
@example
#|kawa:1|# (define arr (array #2a((1 4) (0 4))
#|.....2|#                    10 11 12 13 20 21 22 23 30 31 32 33))
#|kawa:14|# (array-transform arr #2a((0 3) (1 3) (0 2))
#|.....15|#   (lambda (ix) (let ((i (ix 0)) (j (ix 1)) (k (ix 2)))
#|.....16|#                  [(+ i 1)
#|.....17|#                   (+ (* 2 (- j 1)) k)])))
#3a:3@@1:2:2
║10│11║
╟──┼──╢
║12│13║
╠══╪══╣
║20│21║
╟──┼──╢
║22│23║
╠══╪══╣
║30│31║
╟──┼──╢
║32│33║
╚══╧══╝
@end example

The @code{array-transform} is generalization of @code{share-array},
in that it does not require the @var{transform} to be affine.
Also note the different calling conversions for the @var{tranform}:
@code{array-transform} takes a single argument (a vector of indexes),
and returns a single result (a vector of indexes);
@code{share-array} takes one argument for each index, and returns
one value for each index.  The difference is historical.
@end deffn

@deffn Procedure array-index-share array index ...
This does the same generalized APL-style indexing
as @code{array-index-ref}.  However, the resulting array
is a modifiable view into argument @var{array}.
@end deffn

@deffn Procedure array-reshape array shape
Creates a new array @var{narray} of the given @var{shape},
such that @code{(array->vector @var{array})} and
@code{(array->vector @var{narray})} are equivalent.
I.e. the @var{i}'th element in row-major-order of @var{narray}
is the @var{i}'th element in row-major-order of @var{array}.
Hence @code{(array-size @var{narray})} (as specied from the @var{shape})
must be equal to @code{(array-size @var{array})}.
The resulting @var{narray} is a view such that modifying @var{array}
also modifies @var{narray} and vice versa.
@end deffn

@deffn Procedure share-array array shape proc
Returns a new array of @var{shape} shape that shares elements of @var{array}
through @var{proc}. The procedure @var{proc} must implement an affine
function that returns indices of @var{array} when given indices of the
array returned by @code{share-array}.
The array does not retain a reference to @var{shape}.
@example
(define i_4
   (let* ((i (make-array
                (shape 0 4 0 4)
                0))
          (d (share-array i
                (shape 0 4)
                (lambda (k)
                   (values k k)))))
      (do ((k 0 (+ k 1)))
          ((= k 4))
         (array-set! d k 1))
      i))
@end example

Note: the affinity requirement for @var{proc} means that each value must
be a sum of multiples of the arguments passed to @var{proc}, plus a constant.

Implementation note: arrays have to maintain an internal index mapping
from indices @var{k1} ... @var{kd} to a single index into a backing vector;
the composition of this mapping and @var{proc} can be recognised
as @code{(@var{+ n0} (* @var{n1} @var{k1}) ... (* @var{nd} @var{kd}))}
by setting each index in turn to 1 and others to 0,
and all to 0 for the constant term; the composition can then be compiled
away, together with any complexity that the user introduced in their
procedure.

Here is an example where the @var{array} is a uniform vector:
@example
(share-array
  (f64vector 1.0 2.0 3.0 4.0 5.0 6.0)
  (shape 0 2 0 3)
  (lambda (i j) (+ (* 2 i) j)))
  @result{}  #2f64((1.0 2.0 3.0) (4.0 5.0 6.0))
@end example
@end deffn

@deffn Procedure array-flatten array
@deffnx Procedure array->vector array
Return a vector consisting of the elements of the @var{array}
in row-major-order.

The result of @code{array-flatten} is fresh (mutable) copy, not a view.
The result of @code{array->vector} is a view: If @var{array} is mutable,
then modifying @var{array} changes the flattened result and vice versa.

If @var{array} is ``simple'',  @code{array->vector} returns the original vector.
Specifically, if @var{vec} is a vector then:
@example
(eq? @var{vec} (array->vector (array-reshape @var{vec} @var{shape})))
@end example
@end deffn

@subsection Miscellaneous

@deffn Procedure format-array value [element-format]
@end deffn

@node Hash tables
@section Hash tables

A @dfn{hashtable} is a data structure that
associates keys with values.
The hashtable has no intrinsic order for the (key, value) associations
it contains, and
supports in-place modification as the primary means of setting the contents
of a hash table.
Any object can be used as a key, provided a @dfn{hash function} and a suitable
@dfn{equivalence function} is available.
A hash function is a procedure that
maps keys to exact integer objects.

The hashtable provides key lookup and destructive update in amortised
constant time, provided that a good hash function is used. 
A hash function @var{h} is acceptable for an equivalence predicate @var{e} iff
@code{(@var{e} @var{obj1} @var{obj2})} implies
@code{(= (@var{h} @var{obj1}) (@var{h} @var{obj2}))}.
A hash function @var{h} is good for a equivalence predicate @var{e} if
it distributes the resulting hash values for non-equal objects
(by @var{e}) as uniformly as possible over the range of hash
values, especially in the case when some (non-equal) objects resemble
each other by e.g. having common subsequences. This definition is
vague but should be enough to assert that e.g. a constant function is
not a good hash function.

Kawa provides two complete sets of functions for hashtables:
@itemize
@item
The functions specified by R6RS have names starting with @code{hashtable-}
@item
The functions specified by the older
@uref{http://srfi.schemers.org/srfi-69/srfi-69.html, SRFI-69} specifiation
have names starting with @code{hash-table-}
@end itemize

Both interfaces use the same underlying datatype, so it is possible 
to mix and match from both sets.
That datatype implements @code{java.util.Map}.
@c The Kawa implementation has been optimized for performance and better
@c Java integration.  Specifically, the default hash function uses
@c the standard Java @code{hashCode} method.
Freshly-written code should probably use the R6RS functions.

@subsection R6RS hash tables

To use these hash table functions in your Kawa program you must first:

@example
(import (rnrs hashtables))
@end example

This section uses the @var{hashtable} parameter name for arguments that
must be hashtables, and the @var{key} parameter name for arguments that
must be hashtable keys.

@deffn Procedure make-eq-hashtable
@deffnx Procedure make-eq-hashtable @var{k}
Return a newly allocated mutable hashtable that accepts arbitrary
objects as keys, and compares those keys with @func{eq?}.  If an
argument is given, the initial capacity of the hashtable is set to
approximately @var{k} elements.
@end deffn


@deffn Procedure make-eqv-hashtable
@deffnx Procedure make-eqv-hashtable @var{k}
Return a newly allocated mutable hashtable that accepts arbitrary
objects as keys, and compares those keys with @func{eqv?}.  If an
argument is given, the initial capacity of the hashtable is set to
approximately @var{k} elements.
@end deffn

@deffn Procedure make-hashtable @var{hash-function} @var{equiv}
@deffnx Procedure make-hashtable @var{hash-function} @var{equiv} @var{k}
@var{hash-function} and @var{equiv} must be procedures.
@var{hash-function} should accept a key as an argument and should return
a non--negative exact integer object.  @var{equiv} should accept two
keys as arguments and return a single value.  Neither procedure should
mutate the hashtable returned by @func{make-hashtable}.

The @func{make-hashtable} procedure returns a newly allocated mutable
hashtable using @var{hash-function} as the hash function and @var{equiv}
as the equivalence function used to compare keys.  If a third argument
is given, the initial capacity of the hashtable is set to approximately
@var{k} elements.

Both @var{hash-function} and @var{equiv} should behave like pure
functions on the domain of keys.  For example, the @func{string-hash}
and @func{string=?} procedures are permissible only if all keys are
strings and the contents of those strings are never changed so long as
any of them continues to serve as a key in the hashtable.  Furthermore,
any pair of keys for which @var{equiv} returns true should be hashed to
the same exact integer objects by @var{hash-function}.

@quotation
@emph{Note:} Hashtables are allowed to cache the results of calling the
hash function and equivalence function, so programs cannot rely on the
hash function being called for every lookup or update.  Furthermore any
hashtable operation may call the hash function more than once.
@end quotation
@end deffn

@subsubsection Procedures

@deffn Procedure {hashtable?} @var{obj}
Return @true{} if @var{obj} is a hashtable, @false{} otherwise.
@end deffn

@deffn Procedure hashtable-size @var{hashtable}
Return the number of keys contained in @var{hashtable} as an exact
integer object.
@end deffn

@deffn Procedure hashtable-ref @var{hashtable} @var{key} @var{default}
Return the value in @var{hashtable} associated with @var{key}.  If
@var{hashtable} does not contain an association for @var{key},
@var{default} is returned.
@end deffn

@deffn Procedure {hashtable-set!} @var{hashtable} @var{key} @var{obj}
Change @var{hashtable} to associate @var{key} with @var{obj}, adding a
new association or replacing any existing association for @var{key}, and
returns unspecified values.
@end deffn

@deffn Procedure {hashtable-delete!} @var{hashtable} @var{key}
Remove any association for @var{key} within @var{hashtable} and returns
unspecified values.
@end deffn

@deffn Procedure {hashtable-contains?} @var{hashtable} @var{key}
Return @true{} if @var{hashtable} contains an association for @var{key},
@false{} otherwise.
@end deffn

@deffn Procedure {hashtable-update!} @var{hashtable} @var{key} @var{proc} @var{default}
@var{proc} should accept one argument, should return a single value, and
should not mutate @var{hashtable}.

The @func{hashtable-update!} procedure applies @var{proc} to the value
in @var{hashtable} associated with @var{key}, or to @var{default} if
@var{hashtable} does not contain an association for @var{key}.  The
@var{hashtable} is then changed to associate @var{key} with the value
returned by @var{proc}.

The behavior of @func{hashtable-update!} is equivalent to the following
code, but is may be (and is in Kawa) implemented more efficiently in cases
where the implementation can avoid multiple lookups of the same key:

@example
(hashtable-set!
  hashtable key
  (proc (hashtable-ref
         hashtable key default)))
@end example
@end deffn


@deffn Procedure hashtable-copy @var{hashtable}
@deffnx Procedure hashtable-copy @var{hashtable} @var{mutable}
Return a copy of @var{hashtable}.  If the @var{mutable} argument is
provided and is true, the returned hashtable is mutable; otherwise it is
immutable.
@end deffn

@deffn Procedure {hashtable-clear!} @var{hashtable}
@deffnx Procedure {hashtable-clear!} @var{hashtable} @var{k}
Remove all associations from @var{hashtable} and returns unspecified
values.

If a second argument is given, the current capacity of the hashtable is
reset to approximately @var{k} elements.
@end deffn

@deffn Procedure hashtable-keys @var{hashtable}
Return a vector of all keys in @var{hashtable}.  The order of the vector
is unspecified.
@end deffn

@deffn Procedure hashtable-entries @var{hashtable}
Return two values, a vector of the keys in @var{hashtable}, and a vector
of the corresponding values.

Example:

@example
(let ((h (make-eqv-hashtable)))
  (hashtable-set! h 1 'one)
  (hashtable-set! h 2 'two)
  (hashtable-set! h 3 'three)
  (hashtable-entries h))
@result{} #(1 2 3) #(one two three) ; two return values
@end example

@noindent
the order of the entries in the result vectors is not known.
@end deffn

@subsubsection Inspection

@deffn Procedure hashtable-equivalence-function @var{hashtable}
Return the equivalence function used by @var{hashtable} to compare keys.
For hashtables created with @func{make-eq-hashtable} and
@func{make-eqv-hashtable}, returns @func{eq?} and @func{eqv?}
respectively.
@end deffn

@deffn Procedure hashtable-hash-function @var{hashtable}
Return the hash function used by @var{hashtable}.  For hashtables
created by @func{make-eq-hashtable} or @func{make-eqv-hashtable},
@false{} is returned.
@end deffn

@deffn Procedure {hashtable-mutable?} @var{hashtable}
Return @true{} if @var{hashtable} is mutable, otherwise @false{}.
@end deffn

@subsubsection Hash functions

The @func{equal-hash}, @func{string-hash}, and @func{string-ci-hash}
procedures of this section are acceptable as the hash functions of a
hashtable only if the keys on which they are called are not mutated
while they remain in use as keys in the hashtable.

@deffn Procedure equal-hash @var{obj}
Return an integer hash value for @var{obj}, based on its structure and
current contents.  This hash function is suitable for use with
@func{equal?} as an equivalence function.
@quotation
@emph{Note:} Like @func{equal?}, the @func{equal-hash} procedure must
always terminate, even if its arguments contain cycles.
@end quotation
@end deffn

@deffn Procedure string-hash @var{string}
Return an integer hash value for @var{string}, based on its current
contents.  This hash function is suitable for use with @func{string=?}
as an equivalence function.
@end deffn

@deffn Procedure string-ci-hash @var{string}
Return an integer hash value for @var{string} based on its current
contents, ignoring case.  This hash function is suitable for use with
@func{string-ci=?} as an equivalence function.
@end deffn

@deffn Procedure symbol-hash @var{symbol}
Return an integer hash value for @var{symbol}.
@end deffn


@subsection SRFI-69 hash tables

To use these hash table functions in your Kawa program you must first:
@example
(require 'srfi-69)
@end example
or
@example
(require 'hash-table)
@end example
or
@example
(import (srfi 69 basic-hash-tables))
@end example

@subsubsection Type constructors and predicate
@deffn Procedure make-hash-table [ equal? [ hash [ size-hint]]] → hash-table

Create a new hash table with no associations.
The @var{equal?} parameter is a predicate
that should accept two keys and return a boolean telling whether they
denote the same key value; it defaults to the @code{equal?} function.

The @var{hash} parameter is a hash function, and defaults to an 
appropriate hash function
for the given @var{equal?} predicate (see the Hashing section).
However, an
acceptable default is not guaranteed to be given for any equivalence
predicate coarser than @code{equal?}, except for @code{string-ci=?}.
(The function @code{hash} is acceptable for @code{equal?}, so if you
use coarser equivalence than @code{equal?} other than @code{string-ci=?},
you must always provide the function hash yourself.)
(An equivalence predicate @var{c1} is coarser than a equivalence
predicate @var{c2} iff there exist values @var{x} and @var{y} such
that @code{(and (@var{c1} @var{x} @var{y}) (not (@var{c2} @var{x} @var{y})))}.)

The @var{size-hint} parameter can be used to suggested an approriate
initial size.  This option is not part of the SRFI-69 specification
(though it is handled by the reference implementation), so specifying
that option might be unportable.
@end deffn

@deffn Procedure hash-table? obj → boolean
A predicate to test whether a given object @var{obj} is a hash table.
@end deffn

@deffn Procedure alist->hash-table alist [ equal? [ hash [ size-hint]]] → hash-table

Takes an association list @var{alist} and creates a hash table
@var{hash-table} which maps the @code{car} of every element in
@var{alist} to the @code{cdr} of corresponding elements in
@var{alist}. The @var{equal?}, @var{hash}, and @var{size-hint}
parameters are interpreted as in @code{make-hash-table}. If some key
occurs multiple times in @var{alist}, the value in the first
association will take precedence over later ones. (Note: the choice of
using @code{cdr} (instead of @code{cadr}) for values tries to strike
balance between the two approaches: using @var{cadr} would render this
procedure unusable for @code{cdr} alists, but not vice versa.)
@end deffn

@subsubsection Reflective queries
@deffn Procedure hash-table-equivalence-function hash-table
Returns the equivalence predicate used for keys of @var{hash-table}.
@end deffn

@deffn Procedure hash-table-hash-function hash-table
Returns the hash function used for keys of @var{hash-table}.
@end deffn

@subsubsection Dealing with single elements
@deffn Procedure hash-table-ref hash-table key [ thunk ] → value
This procedure returns the value associated to @var{key} in
@var{hash-table}. If no value is associated to @var{key} and
@var{thunk} is given, it is called with no arguments and its value is
returned; if @var{thunk} is not given, an error is signalled. Given a
good hash function, this operation should have an (amortised) complexity
of O(1) with respect to the number of associations in @var{hash-table}.
@end deffn

@deffn Procedure hash-table-ref/default hash-table key default → value
Evaluates to the same value as @code{(hash-table-ref @var{hash-table}
@var{key} (lambda () @var{default}))}. Given a good hash function, this
operation should have an (amortised) complexity of O(1) with respect
to the number of associations in hash-table.
@end deffn

@deffn Procedure hash-table-set! hash-table key value → void
This procedure sets the value associated to @var{key} in
@var{hash-table}. The previous association (if any) is removed. Given
a good hash function, this operation should have an (amortised)
complexity of O(1) with respect to the number of associations in
hash-table.
@end deffn

@deffn Procedure hash-table-delete! hash-table key → void
This procedure removes any association to @var{key} in
@var{hash-table}. It is not an error if no association for the
@var{key} exists; in this case, nothing is done. Given a good hash
function, this operation should have an (amortised) complexity of O(1)
with respect to the number of associations in hash-table.
@end deffn

@deffn Procedure hash-table-exists? hash-table key → boolean
This predicate tells whether there is any association to @var{key} in
@var{hash-table}. Given a good hash function, this operation should
have an (amortised) complexity of O(1) with respect to the number of
associations in hash-table.
@end deffn

@deffn Procedure hash-table-update! hash-table key function [ thunk ] → void
Semantically equivalent to, but may be implemented more efficiently than,
the following code:
@example
(hash-table-set! @var{hash-table key}
                 (function (hash-table-ref @var{hash-table} @var{key} @var{thunk})))
@end example
@end deffn

@deffn Procedure hash-table-update!/default hash-table key function default → void
Behaves as if it evaluates to
@code{(hash-table-update! @var{hash-table} @var{key} @var{function} (lambda () @var{default}))}.
@end deffn

@subsubsection Dealing with the whole contents

@deffn Procedure hash-table-size hash-table → integer
Returns the number of associations in @var{hash-table}. This operation takes
constant time.
@end deffn

@deffn Procedure hash-table-keys hash-table → list
Returns a list of keys in @var{hash-table}.
The order of the keys is unspecified.
@end deffn

@deffn Procedure hash-table-values hash-table → list
Returns a list of values in @var{hash-table}. The order of the values is
unspecified, and is not guaranteed to match the order of keys in the
result of @code{hash-table-keys}.
@end deffn

@deffn Procedure hash-table-walk hash-table proc → void
@var{proc} should be a function taking two arguments, a key and a
value. This procedure calls @var{proc} for each association in
@var{hash-table}, giving the key of the association as key and the
value of the association as value. The results of @var{proc} are
discarded. The order in which @var{proc} is called for the different
associations is unspecified.
@end deffn

@deffn Procedure hash-table-fold hash-table f init-value → final-value
This procedure calls @var{f} for every association in @var{hash-table}
with three arguments: the key of the association key, the value of the
association value, and an accumulated value, @var{val}. The @var{val}
is @var{init-value} for the first invocation of @var{f}, and for
subsequent invocations of @var{f}, the return value of the previous
invocation of @var{f}. The value @var{final-value} returned by
@code{hash-table-fold} is the return value of the last invocation of
@var{f}. The order in which @var{f} is called for different
associations is unspecified.
@end deffn

@deffn Procedure hash-table->alist hash-table → alist
Returns an association list such that the @code{car} of each element
in @var{alist} is a key in @var{hash-table} and the corresponding
@code{cdr} of each element in @var{alist} is the value associated to
the key in @var{hash-table}. The order of the elements is unspecified.

The following should always produce a hash table with the same mappings
as a hash table @var{h}:
@example
(alist->hash-table (hash-table->alist @var{h})
                        (hash-table-equivalence-function @var{h})
                        (hash-table-hash-function @var{h}))
@end example
@end deffn

@deffn Procedure hash-table-copy hash-table → hash-table
Returns a new hash table with the same equivalence predicate, hash
function and mappings as in @var{hash-table}.
@end deffn

@deffn Procedure hash-table-merge! hash-table1 hash-table2 → hash-table
Adds all mappings in @var{hash-table2} into @var{hash-table1} and
returns the resulting hash table. This function may modify
@var{hash-table1} destructively.
@end deffn

@subsubsection Hash functions

The Kawa implementation always calls these hash functions with a single
parameter, and expects the result to be within the entire
(32-bit signed) @code{int} range, for compatibility with
standard @code{hashCode} methods.

@deffn Procedure hash object [ bound ] → integer
Produces a hash value for object in the range from 0 (inclusive) tp to
@var{bound} (exclusive).

If @var{bound} is not given, the Kawa implementation returns a value within
the range @w{@code{(- (expt 2 32))}} (inclusive)
to @w{@code{(- (expt 2 32) 1)}} (inclusive).
It does this by calling the standard @code{hashCode} method,
and returning the result as is.
(If the @var{object} is the Java @code{null} value, 0 is returned.)
This hash function is acceptable for @code{equal?}.
@end deffn

@deffn Procedure string-hash string [ bound ] → integer
The same as @code{hash}, except that the argument string must be a string.
(The Kawa implementation returns the same as the @code{hash} function.)
@end deffn

@deffn Procedure string-ci-hash string [ bound ] → integer
The same as @code{string-hash}, except that the case of characters in
string does not affect the hash value produced.
(The Kawa implementation returns the same the @code{hash} function
applied to the lower-cased @var{string}.)
@end deffn

@deffn Procedure hash-by-identity object [ bound ] → integer
The same as @code{hash}, except that this function is only guaranteed
to be acceptable for @code{eq?}.
Kawa uses the @code{identityHashCode} method of @code{java.lang.System}.
@end deffn 


@node Eval and Environments
@chapter Eval and Environments

@deffn Procedure environment @arbno{list}
This procedure returns a specifier for the environment that
results by starting with an empty environment and then
importing each @var{list}, considered as an @stxref{import-set}, into it.
The bindings of the environment represented by the specifier
are immutable, as is the environment itself.
See the @code{eval} function for examples.
@end deffn

@deffn Procedure null-environment version
This procedure returns an environment that contains no variable bindings,
but contains (syntactic) bindings for all the syntactic keywords.

The effect of assigning to a variable in this environment (such
as @code{let}) is undefined.
@end deffn

@deffn Procedure scheme-report-environment version
The @var{version} must be an exact non-negative inetger corresponding to
a version of one of the Revised@var{version} Reports on Scheme.
The procedure returns an environment that contains exactly the set of
bindings specified in the corresponding report.

This implementation supports @var{version} that is 4 or 5.

The effect of assigning to a variable in this environment (such
as @code{car}) is undefined.
@end deffn

@deffn Procedure interaction-environment
This procedure return an environment that contains implementation-defined
bindings, as well as top-level user bindings.
@end deffn

@deffn Procedure environment-bound? environment symbol
Return true @code{#t} if there is a binding for @var{symbol}
in @var{environment};  otherwise returns @code{#f}.
@end deffn

@deffn Syntax fluid-let ((variable init) ...) body ...
Evaluate the @var{init} expressions.
Then modify the dynamic bindings for the @var{variables} to the
values of the @var{init} expressions, and evaluate the @var{body} expressions.
Return the result of the last expression in @var{body}.
Before returning, restore the original bindings.
The temporary bindings are only visible in the current thread, and its
descendent threads.
@end deffn

@deffn Procedure base-uri [node]
If @var{node} is specified, returns the base-URI property
of the @var{node}.  If the @var{node} does not have the base-URI
property, returns @code{#f}.
(The XQuery version returns the empty sequence in that case.)

In the zero-argument case, returns the "base URI" of the current context.
By default the base URI is the current working directory (as a URL).
While a source file is @code{load}ed, the base URI is temporarily
set to the URL of the document.
@end deffn

@deffn Procedure eval expression [environment]
This procedure evaluates @var{expression} in the environment indicated
by @var{environment}.
The default for @var{environment} is the result
of @code{(interaction-environment)}.

@example
(eval ’(* 7 3) (environment '(scheme base)))
            @result{} 21

(let ((f (eval '(lambda (f x) (f x x))
               (null-environment 5))))
  (f + 10))
            @result{} 20

(eval '(define foo 32) (environment '(scheme base)))
            @result{} @i{error is signaled}
@end example
@end deffn

@deffn Procedure load path [environment]
@deffnx Procedure load-relative path [environment]
The @var{path} can be an (absolute) URL or a filename
of a source file, which is read and evaluated line-by-line.
The @var{path} can also be a fully-qualified class name.
(Mostly acts like the @code{-f} command-line option,
but with different error handling.)
Since @code{load} is a run-time function it doesn't know
about the enclosing lexical environment, and the latter
can't know about definitions introduced by @code{load}.
For those reasons it is highly recommended that you use instead use
@code{@ref{require, require}} or @code{@ref{include, include}}.

Evaluation is done in the specified @var{environment},
which defauls to result of @code{(interaction-environment)}.

The @code{load-relative} procedure is like @code{load},
except that @var{path} is a
URI that is relative to the context's current base URI.
@end deffn

@menu
* Locations::
* Parameter objects::
@end menu

@node Locations, Parameter objects, , Eval and Environments
@section Locations

A @dfn{location} is a place where a value can be stored.
An @dfn{lvalue} is an expression that refers to a location.
(The name "lvalue" refers to the fact that the left operand
of @code{set!} is an lvalue.)
The only kind of lvalue in standard Scheme is a @dfn{variable}.
Kawa also allows @dfn{computed lvalues}.  These are procedure
calls used in "lvalue context", such as the left operand of @code{set!}.

You can only use procedures that have an associated @dfn{setter}.
In that case, @code{(set! (f arg ...) value)}
is equivalent to @code{((setter f) arg ... value)}
Currently, only a few procedures have associated @code{setter}s,
and only builtin procedures written in Java can have @code{setter}s.

For example:
@example
(set! (car x) 10)
@end example
is equivalent to:
@example
((setter car) x 10)
@end example
which is equivalent to:
@example
(set-car! x 10)
@end example

@deffn Procedure setter procedure
Gets the "setter procedure" associated with a "getter procedure".
Equivalent to @code{(procedure-property @var{procedure} 'setter)}.
By convention, a setter procedure takes the same parameters as
the "getter" procedure, plus an extra parameter that is the
new value to be stored in the location specified by the parameters.
The expectation is that following
@code{((setter @var{proc}) @var{args} ... @var{value})} then
the value of @code{(@var{proc} @var{args} ...)} will be @var{value}.

The @code{setter} of @code{setter} can be used to set the
@code{setter} property.
For example the Scheme prologue effectively does the following:
@example
(set! (setter vector-set) vector-set!)
@end example
@end deffn

Kawa also gives you access to locations as first-class values:

@deffn Syntax location lvalue
Returns a location object for the given @var{lvalue}.
You can get its value (by applying it, as if it were a procedure),
and you can set its value (by using @code{set!} on the application).
The @var{lvalue} can be a local or global variable, or a procedure
call using a procedure that has a @code{setter}.
@example
(define x 100)
(define lx (location x))
(set! (lx) (cons 1 2)) ;; set x to (1 . 2)
(lx)  ;; returns (1 . 2)
(define lc (location (car x)))
(set! (lc) (+ 10 (lc)))
;; x is now (11 . 2)
@end example
@end deffn

@deffn Syntax define-alias variable lvalue
Define @var{variable} as an alias for @var{lvalue}.
In other words, makes it so that @code{(location @var{variable})}
is equivalent to @code{(location @var{lvalue})}.
This works both top-level and inside a function.
@end deffn

@deffn Syntax define-private-alias variable lvalue
Same as @code{define-alias}, but the @var{variable}
is local to the current module.
@end deffn

Some people might find it helpful to think of a location
as a settable @dfn{thunk}.  Others may find it useful to
think of the @code{location} syntax as similar to the C @samp{&} operator;
for the @samp{*} indirection operator, Kawa uses procedure application.

You can use @code{define-alias} to define a shorter type synonym,
similar to Java's  @code{import TypeName} (single-type-import) declaration:
@example
(define-alias StrBuf java.lang.StringBuffer)
@end example

@node Parameter objects, , Locations, Eval and Environments
@section Parameter objects

A parameter object is a procedure that is bound to a location,
and may optionally have a conversion procedure.
The procedure accepts zero or one argument.
When the procedure is called with zero arguments,
the content of the location is returned.
On a call with one argument the content of the location
is updated with the result of applying the parameter object's conversion
procedure to the argument.

Parameter objects are created with the @code{make-parameter} procedure
which takes one or two arguments. The second argument is a one
argument conversion procedure. If only one argument is passed to
make-parameter the identity function is used as a conversion
procedure.
A new location is created and asociated with the 
parameter object. The initial content of the location is the
result of applying the conversion procedure to the first argument of
make-parameter.

Note that the conversion procedure can be used for guaranteeing the
type of the parameter object's binding and/or to perform some
conversion of the value.

The @code{parameterize} special form, when given a parameter object
and a value, binds the parameter
object to a new location for the dynamic extent of its body.
The initial content of the location is the result of
applying the parameter object's conversion procedure to the value. The
@code{parameterize} special form behaves analogously to @code{let}
when binding more than one parameter object (that is the order of
evaluation is unspecified and the new bindings are only visible in the
body of the parameterize special form).

When a new thread is created using @code{future} or @code{runnable}
then the child thread inherits initial values from its parent.
Once the child is running, changing the value in the child does not
affect the value in the parent or vice versa.
(In the past this was not the case: The child would share a location
with the parent except within a @code{parameterize}.
This was changed to avoid unsafe and inefficient coupling between threads.)

Note that @code{parameterize} and @code{fluid-let} have similar
binding and sharing behavior.
The difference is that @code{fluid-let} modifies locations
accessed by name, while @code{make-parameter} and @code{parameterize}
create anonymous locations accessed by calling a parameter procedure.

The R5RS procedures @code{current-input-port} and @code{current-output-port}
are parameter objects.

@deffn Procedure make-parameter init [converter]

Returns a new parameter object which is bound in the global dynamic
environment to a location containing the value returned by the call
@code{(@var{converter} @var{init})}. If the conversion procedure
converter is not specified the identity function is used instead.

The parameter object is a procedure which accepts zero or one
argument. When it is called with no argument, the content of the
location bound to this parameter object in the current dynamic
environment is returned. When it is called with one argument, the
content of the location is set to the result of the call
@code{(@var{converter} @var{arg})}, where @var{arg} is the argument
passed to the parameter object, and an unspecified value is returned.

@example
(define radix
  (make-parameter 10))

(define write-shared
  (make-parameter
    #f
    (lambda (x)
      (if (boolean? x)
          x
          (error "only booleans are accepted by write-shared")))))

(radix)           @result{}  10
(radix 2)
(radix)           @result{}  2
(write-shared 0)  gives an error

(define prompt
  (make-parameter
    123
    (lambda (x)
      (if (string? x)
          x
          (with-output-to-string (lambda () (write x)))))))

(prompt)       @result{}  "123"
(prompt ">")
(prompt)       @result{}  ">"
@end example
@end deffn

@anchor{parameterize-syntax}
@deffn Syntax parameterize ((expr1 expr2) ...) @stxref{body}
The expressions @var{expr1} and @var{expr2} are evaluated in an
unspecified order. The value of the @var{expr1} expressions must be
parameter objects. For each @var{expr1} expression and in an
unspecified order, the local dynamic environment is extended with a
binding of the parameter object @var{expr1} to a new location whose
content is the result of the call @code{(@var{converter} @var{val})},
where @var{val} is the value of @var{expr2} and @var{converter} is the
conversion procedure of the parameter object. The resulting dynamic
environment is then used for the evaluation of @var{body} (which
refers to the R5RS grammar nonterminal of that name). The result(s) of
the parameterize form are the result(s) of the @var{body}.

@example
(radix)                                              @result{}  2
(parameterize ((radix 16)) (radix))                  @result{}  16
(radix)                                              @result{}  2

(define (f n) (number->string n (radix)))

(f 10)                                               @result{}  "1010"
(parameterize ((radix 8)) (f 10))                    @result{}  "12"
(parameterize ((radix 8) (prompt (f 10))) (prompt))  @result{}  "1010"
@end example
@end deffn

@node Debugging
@chapter Debugging

@deffn Syntax trace procedure
Cause @var{procedure} to be "traced", that is debugging output will
be written to the standard error port every time @var{procedure}
is called, with the parameters and return value.

Note that Kawa will normally assume that a procedure defined with
the procedure-defining variant of @code{define} is constant,
and so it might be inlined:
@example
(define (ff x) (list x x))
(trace ff) ;; probably won't work
(ff 3)     ;; not traced
@end example
It works if you specify the @code{--no-inline} flag to Kawa.
Alternatively, you can use the variable-defining variant of @code{define}:
@example
#|kawa:1|# (define ff (lambda (x) name: 'ff (list x x)))
#|kawa:2|# (trace ff) ;; works
#|kawa:3|# (ff 3)
call to ff (3)
return from ff => (3 3)
(3 3)
@end example
Note the use of the @code{name:} procedure property to give the
anonymous @code{lambda} a name.
@end deffn

@deffn Syntax untrace procedure
Turn off tracing (debugging output) of @var{procedure}.
@end deffn

@deffn Procedure disassemble procedure
Returns a string representation of the disassembled bytecode
for @var{procedure}, when known.
@end deffn

@node Input-Output
@chapter Input, output, and file handling

Kawa has a number of useful tools for controlling input and output:

A programmable reader.

A powerful pretty-printer.

@menu
* Named output formats::
* Paths:: Paths - file name, URLs, and URIs
* Files:: File System Interface
* Reading and writing whole files::
* Ports::
* Format:: Formatted Output (Common-Lisp-style)
* Pretty-printing::
* Resources::
@end menu

@node Named output formats, Paths, , Input-Output
@section Named output formats

The @code{--output-format} (or @code{--format}) command-line switch
can be used to override the default format for how values are
printed on the standard output.  This format is used for values printed
by the read-eval-print interactive interface.  It is also used to
control how values are printed when Kawa evaluates a file named on the
command line (using the @code{-f} flag or just a script name).
(It also affects applications compiled with the @code{--main} flag.)
It currently affects how values are printed by a @code{load},
though that may change.

The default format depends on the current programming language.
For Scheme, the default is @code{scheme} for read-eval-print
interaction, and @code{ignore} for files that are loaded.

The formats currently supported include the following:
@table @code
@item scheme
Values are printed in a format matching the Scheme programming language,
as if using @code{display}.  "Groups" or "elements" are written as lists.
@item readable-scheme
Like @code{scheme}, as if using @code{write}:
Values are generally printed in a way that they can
be read back by a Scheme reader.  For example, strings have quotation marks,
and character values are written like @samp{#\A}.
@item elisp
Values are printed in a format matching the Emacs Lisp programming language.
Mostly the same as @code{scheme}.
@item readable-elisp
Like @code{elisp}, but values are generally printed in a way that they can
be read back by an Emacs Lisp reader.  For example, strings have quotation
marks, and character values are written like @samp{?A}.
@item clisp
@itemx commonlisp
Values are printed in a format matching the Common Lisp programming language,
as if written by @code{princ}.
Mostly the same as @code{scheme}.
@item readable-clisp
@itemx readable-commonlisp
Like @code{clisp}, but as if written by @code{prin1}: values are generally
printed in a way that they can be read back by a Common Lisp reader.
For example, strings have quotation marks, and character values are
written like @samp{#\A}.
@item xml
@itemx xhtml
@itemx html
Values are printed in XML, XHTML, or HTML format.
This is discussed in more detail in @ref{Formatting XML}.
@item cgi
The output should follow the CGI standards.  I.e. assume that this
script is invoked by a web server as a CGI script/program, and that the
output should start with some response header,
followed by the actual response data.
To generate the response headers, use the @code{response-header} function.
If the @code{Content-type} response header has not been specified, and
it is required by the CGI standard, Kawa will attempt
to infer an appropriate @code{Content-type} depending on the following value.
@item ignore
Top-level values are ignored, instead of printed.
@end table

@node Paths
@section Paths - file name, URLs, and URIs

A @dfn{Path} is the name of a file or some other @dfn{resource}.
The path mechanism provides a layer of abstraction, so you can
use the same functions on either a filename or a URL/URI.
Functions that in standard Scheme take a filename
have been generalized to take a path or a path string,
as if using the @code{path} function below.  For example:
@example
(open-input-file "http://www.gnu.org/index.html")
(open-input-file (URI "ftp://ftp.gnu.org/README"))
@end example

@deffn Type path
A general path, which can be a @code{filename} or a @code{URI}.
It can be either a @code{filename} or a @code{URI}.
Represented using the abstract Java class @code{gnu.kawa.io.Path}.

Coercing a value to a @code{Path} is equivalent to
calling the @code{path} constructor documented below.
@end deffn

@deffn Constructor path arg
Coerces the @var{arg} to a @code{path}.
If @var{arg} is already a @code{path}, it is returned unchanged.
If @var{arg} is a @code{java.net.URI}, or a @code{java.net.URL}
then a @code{URI} value is returned.
If @var{arg} is a @code{java.io.File}, a @code{filepath} value is returned.
Otherwise, @var{arg} can be a string.
A @code{URI} value is returned if the string starts with a URI scheme
(such as @code{"http:"}),
and a @code{filepath} value is returned otherwise.
@end deffn

@deffn Predicate path? arg
True if @var{arg} is a @code{path} - i.e. an instance of a @code{gnu.kawa.io.Path}.
@end deffn

@deffn Procedure current-path [new-value]
With no arguments, returns the default directory of the current thread
as a @code{path}.
This is used as the base directory for relative pathnames.
The initial value is that of the @code{user.dir} property
as returned by @code{(java.lang.System:getProperty "user.dir")}.

If a @var{new-value} argument is given, sets the default directory:
@example
(current-path "/opt/myApp/")
@end example
A string value is automatically converted to a @code{path},
normally a @code{filepath}. 

Alternatively, you can change the default using a setter:
@example
(set! (current-path) "/opt/myApp/")
@end example

Since @code{current-path} is a @ref{Parameter objects,parameter object}, you can
locally change the value using @ref{parameterize-syntax,@code{parameterize}}.
@end deffn

@deffn Type filepath
The name of a local file.
Represented using the Java class @code{gnu.kawa.io.FilePath},
which is a wrapper around @code{java.io.File}.
@end deffn

@deffn Predicate filepath? arg
True if @var{arg} is a @code{filepath} - i.e. an instance of
a @code{gnu.kawa.io.FilePath}.
@end deffn

@anchor{URI-type}
@deffn Type URI
A Uniform Resource Indicator, which is a generalization of
the more familiar URL.  The general format is specified by
@uref{http://www.ietf.org/rfc/rfc2396.txt,
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax}.
Represented using the Java class @code{gnu.kawa.io.URIPath},
which is a wrapper around @code{java.net.URI}.
A URI can be a URL, or it be a relative URI.
@end deffn

@deffn Predicate URI? arg
True if @var{arg} is a @code{URI} - i.e. an instance of
a @code{gnu.kawa.io.URIPath}.
@end deffn

@deffn Type URL
A Uniform Resource Locator - a subtype of @code{URI}.
Represented using the Java class @code{gnu.kawa.io.URLPath},
which is a wrapper around a @code{java.net.URL}, in
addition to extending @code{gnu.kawa.io.URIPath}.
@end deffn

@subsection Extracting Path components

@deffn Procedure path-scheme arg
Returns the ``URI scheme'' of @var{arg} (coerced to a @code{path}) if it is
defined, or @code{#f} otherwise.  The URI scheme of a @code{filepath}
is @code{"file"} if the @code{filepath} is absolute, and @code{#f} otherwise.
@example
(path-scheme "http://gnu.org/") @result{} "http"
@end example
@end deffn

@deffn Procedure path-authority arg
Returns the authority part of @var{arg} (coerced to a @code{path}) if it is
defined, or @code{#f} otherwise.
The ``authority'' is usually the hostname, but may also include user-info
or a port-number.

@example
(path-authority "http://me@@localhost:8000/home") @result{} "me@@localhost:8000"
@end example
@end deffn

@deffn Procedure path-host arg
Returns the name name part of @var{arg} (coerced to a @code{path}) if it is
defined, or @code{#f} otherwise.

@example
(path-host "http://me@@localhost:8000/home") @result{} "localhost"
@end example
@end deffn

@deffn Procedure path-user-info arg
Returns the ``user info'' of @var{arg} (coerced to a @code{path}) if it is
specified, or @code{#f} otherwise.

@example
(path-host "http://me@@localhost:8000/home") @result{} "me"
@end example
@end deffn

@deffn Procedure path-port arg
Returns the port number of @var{arg} (coerced to a @code{path}) if it is
specified, or @code{-1} otherwise.  Even if there is a default port
associated with a URI scheme (such as 80 for @code{http}), the value
-1 is returned unless the port number is @emph{explictly} specified.

@example
(path-host "http://me@@localhost:8000/home") @result{} 8000
(path-host "http://me@@localhost/home") @result{} -1
@end example
@end deffn

@deffn Procedure path-file arg
Returns the ``path component'' of the @var{arg}
(coerced to a @code{path}).
(The name @code{path-path} might be more logical,
but it is obviously a bit awkward.)
The path component of a file name is the file name itself.
For a URI, it is the main hierarchical part of the URI,
without schema, authority, query, or fragment.
@example
(path-file "http://gnu.org/home/me.html?add-bug#body") @result{} "/home/me.html"
@end example
@end deffn

@deffn Procedure path-directory arg
If @var{arg} (coerced to a @code{path}) is directory,
return @var{arg}; otherwise return the ``parent'' path, without the
final component.
@example
(path-directory "http://gnu.org/home/me/index.html#body")
  @result{} (path "http://gnu.org/home/me/")
(path-directory "http://gnu.org/home/me/")
  @result{} (path "http://gnu.org/home/me/")
@end example
@code{(path-directory "./dir")} @code{@result{}} @code{(path "./dir")} if @code{dir} is a directory, and @code{(path ".")} otherwise.
@end deffn

@deffn Procedure path-parent arg
Returns the ``parent directory'' of @var{arg} (coerced to a @code{path}).
If @var{arg} is not a directory, same as @code{path-directory @var{arg}}.
@example
(path-parent "a/b/c") @result{} (path "a/b")
(path-parent "file:/a/b/c") @result{} (path "file:/a/b/c")
(path-parent "file:/a/b/c/") @result{} (path "file:/a/b/")
@end example
@end deffn

@deffn Procedure path-last arg
The last component of path component
of @var{arg} (coerced to a @code{path}).
Returns a substring of @code{(path-file @var{arg})}.
If that string ends with @samp{/} or the path separator,
that last character is ignored.
Returns the tail of the path-string, following
the last (non-final) @samp{/} or path separator.
@example
(path-last "http:/a/b/c") @result{} "c"
(path-last "http:/a/b/c/") @result{} "c"
(path-last "a/b/c") @result{} "c"
@end example
@end deffn

@deffn Procedure path-extension arg
Returns the ``extension'' of the @var{arg}
(coerced to a @code{path}).
@example
(path-extension "http://gnu.org/home/me.html?add-bug#body") @result{} "html"
(path-extension "/home/.init") @result{} #f
@end example
@end deffn

@deffn Procedure path-query arg
Returns the query part of @var{arg} (coerced to a @code{path}) if it is
defined, or @code{#f} otherwise.  The query part of a URI is the
part after @samp{?}.
@example
(path-query "http://gnu.org/home?add-bug") @result{} "add-bug"
@end example
@end deffn

@deffn Procedure path-fragment arg
Returns the fragment part of @var{arg} (coerced to a @code{path}) if it is
defined, or @code{#f} otherwise.  The fragment of a URI is the
part of after @samp{#}.
@example
(path-query "http://gnu.org/home#top") @result{} "top"
@end example
@end deffn

@deffn Procedure resolve-uri uri base
Returns a @var{uri} unchanged if it is an absolute URI.
Otherwise resolves it against a base URI @var{base},
which is normally (though not always) absolute.

This uses the algorithm specifyed by RFC-3986 (assuming @var{base}
is absolute), unlike the obsolete RFC-2396 algorithm used
by @code{java.net.URI.resolve}.
@end deffn

@node Files
@section File System Interface

@deffn Procedure file-exists? filename
Returns true iff the file named @var{filename} actually exists.
This function is defined on arbitrary @code{path} values:
for URI values we open a @code{URLConnection}
and invoke @code{getLastModified()}.
@end deffn

@deffn Procedure file-directory? filename
Returns true iff the file named @var{filename} actually exists
and is a directory.
This function is defined on arbitrary @code{path} values;
the default implementation for non-file objects is to
return @code{#t} iff the path string ends with the character @samp{/}.
@end deffn

@deffn Procedure file-readable? filename
Returns true iff the file named @var{filename} actually exists
and can be read from.
@end deffn

@deffn Procedure file-writable? filename
Returns true iff the file named @var{filename} actually exists
and can be writen to.
(Undefined if the @var{filename} does not exist,
but the file can be created in the directory.)
@end deffn

@deffn Procedure delete-file filename
Delete the file named @var{filename}.
On failure, throws an exception.
@end deffn

@deffn Procedure rename-file oldname newname
Renames the file named @var{oldname} to @var{newname}.
@end deffn

@deffn Procedure copy-file oldname newname-from path-to
Copy the file named @var{oldname} to @var{newname}.
The return value is unspecified.
@end deffn

@deffn Procedure create-directory dirname
Create a new directory named @var{dirname}.
Unspecified what happens on error (such as exiting file with the same name).
(Currently returns @code{#f} on error, but may change to be more compatible
with scsh.)
@end deffn

@deffn Procedure system-tmpdir
Return the name of the default directory for temporary files.
@end deffn

@deffn Procedure make-temporary-file [format]
Return a file with a name that does not match any existing file.
Use @var{format} (which defaults to @code{"kawa~d.tmp"}) to generate
a unique filename in @code{(system-tmpdir)}.
The current implementation is @emph{not} safe from race conditions;
this will be fixed in a future release (using Java2 features).
@end deffn

@node Reading and writing whole files
@section Reading and writing whole files

The following procedures and syntax allow you to read and write
the entire contents of a file, without iterating using a port.

@subsection Reading a file

For reading the contents of a file in a single operation,
you can use the following syntax:

@display
@stxlit{&<@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}}
@end display

This is equivalent to using the @code{path-data} function (defined below):
@display
@stxlit{(path-data} @stxlit{&@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{})}
@end display

For example:
@example
(define dir "/home/me/")
(define help-message &<@lbracechar{}&[dir]HELP@rbracechar{})
@end example
This binds @code{help-message} to the contents of the file
named @code{HELP} in the @code{dir} directory.

@anchor{Blobs}
@subsection Blobs

The content of a file is, in general, a sequence of uninterpreted bytes.
Often these bytes represent text in a locale-dependent encoding,
but we don't always know this. Sometimes they're images, or videos,
or word-processor documents.  A filename extension or a ``magic number''
in the file can give you hints, but not certainty as to the type of the data.

A @dfn{@uref{http://en.wikipedia.org/wiki/Binary_large_object,blob}}
is a raw uninterpreted sequence of bytes. It is a @code{bytevector}
that can be automatically converted to other types as needed,
specifically to a string or a bytevector.

The @code{&<@lbracechar{}..@rbracechar{}} returns a blob.  For example,
assume the file @code{README} contains (bytes representing)
the text @code{"Check doc directory.\n"}.  Then:
@example
#|kawa:1|# (define readme &<@lbracechar{}README@rbracechar{}))
|kawa:2|# readme:class
class gnu.lists.Blob
#|kawa:3|# (write (->string readme))
"Check doc directory.\n"
#|kawa:4|# (write (->bytevector readme))
#u8(67 104 101 99 107 32 100 111 99 32 100 105 114 101 99 116 111 114 121 46 10)
#|kawa:5|# (->bytevector readme):class
class gnu.lists.U8Vector
@end example

@subsection Writing to a file

The @code{&<@lbracechar{}..@rbracechar{}} syntax can be used with @code{set!}
to replace the contents of a file:
@example
(set! &<@lbracechar{}README@rbracechar{} "Check example.com\n")
@end example

The new contents must be blob-compatible - i.e. a bytevector or a string.

If you dislike using @code{<} as an output operator, you can instead using the @code{&>@lbracechar{}..@rbracechar{}} operation, which evaluates to a function whose single argument is the new value:
@example
(&>@lbracechar{}README@rbracechar{} "Check example.com\n")
@end example
In general:
@example
@stxlit{&>@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}}
@end example
is equivalent to:
@example
(lambda (new-contents)
  (set! @stxlit{&<@lbracechar{}}@stxref{named-literal-part}+@stxlit{@rbracechar{}} new-contents))
@end example

You can use @code{&>>} to append more data to a file:

@example
(&>>@lbracechar{}README@rbracechar{} "or check example2.com\n")
@end example

@subsection Functions

@deffn Procedure path-data path
Reads the contents of the file specified by @var{path},
where @var{path} can be a @ref{Paths,path} object, or anything that can
be converted to a @code{Path}, including a filename string or a URL. 
returning the result as a blob.
The result is a @emph{blob}, which is a kind of bytevector than can be
auto-converted to a string or bytevecor as required.

The function @code{path-data} has a setter, which replaces the contents
with new contents:
@example
(set! &<@lbracechar{}file-name@rbracechar{} new-contents)
@end example
@end deffn

@deffn Procedure path-bytes path
Reads the contents of the file specified by @var{path}, as
with the @code{path-data} function, but the result is a plain bytevector,
rather than a blob.  This functtion also has a setter, which you
can use to replace the file-contents by new bytevector-valued data.
@end deffn

@node Ports
@section Ports

Ports represent input and output devices.
An input port is a Scheme object that can deliver data upon
command, while an output port is a Scheme object that can
accept data.

Different @dfn{port types} operate on different data:
@itemize @bullet
@item
A @dfn{textual port} supports reading or writing of individual
characters from or to a backing store containing characters
using @code{read-char} and @code{write-char} below, and it supports
operations defined in terms of characters, such as @code{read} and
@code{write}.
@item
A @dfn{binary port} supports reading or writing of individual
bytes from or to a backing store containing bytes using
@code{read-u8} and @code{write-u8} below, as well as operations defined
in terms of bytes (integers in the range 0 to 255).

All Kawa binary ports created by procedures documented here
are also textual ports.  Thus you can either read/write
bytes as described above, or read/write
characters whose scalar value is in the range 0 to 255
(i.e. the Latin-1 character set), using @code{read-char} and @code{write-char}.

A native binary port is a @code{java.io.InputStream}
or @code{java.io.OutputStream} instance.  These are not textual ports.
You can use methods @code{read-u8} and @code{write-u8},
@c not true?
but not @code{read-char} and @code{write-char} on native binary ports.
(The functions @code{input-port?}, @code{output-port?}, @code{binary-port?},
and @code{port?} all currently return false on native binary ports,
but that may change.)
@end itemize

@deffn Procedure call-with-port port proc
The @code{call-with-port} procedure calls @var{proc} with port as an
argument. If @var{proc} returns, then the port is closed automatically
and the values yielded by the proc are returned.

If @var{proc} does not return, then the port must not be closed
automatically unless it is possible to prove that the port
will never again be used for a read or write operation.

As a Kawa extension, @var{port} may be any object
that implements @code{java.io.Closeable}.
It is an error if @var{proc} does not accept one argument.

@c @emph{Rationale}: Because Scheme’s escape procedures have unlimited
@c extent, it is possible to escape from the current continuation
@c but later to resume it. If implementations were permitted to
@c close the port on any escape from the current continuation,
@c then it would be impossible to write portable code using both
@c call-with-current-continuation and call-with-port.
@end deffn

@deffn Procedure call-with-input-file path proc
@deffnx Procedure call-with-output-file path proc
These procedures obtain a textual port obtained by
opening the named file for input or output as if by
@code{open-input-file} or @code{open-output-file}. The port and
@var{proc} are then passed to a procedure equivalent to
@code{call-with-port}.

It is an error if @var{proc} does not accept one argument.
@end deffn

@deffn Procedure input-port? obj
@deffnx Procedure output-port? obj
@deffnx Procedure textual-port? obj
@deffnx Procedure binary-port? obj
@deffnx Procedure port? obj
These procedures return @code{#t} if obj is an input port, output port,
textual port, binary port, or any kind of port,
respectively. Otherwise they return @code{#f}.

These procedures currently return @code{#f} on a native Java streams
(@code{java.io.InputStream} or @code{java.io.OutputStream}),
a native reader (a @code{java.io.Reader} that is not an
@code{gnu.mapping.Inport}), or a native writer (a @code{java.io.Writer}
that is not an @code{gnu.mapping.Outport}).  This may change if
conversions between native ports and Scheme ports becomes more seamless.

@end deffn

@deffn Procedure input-port-open? port
@deffnx Procedure output-port-open? port
Returns @code{#t} if @var{port} is still open and capable of performing
input or output, respectively, and @code{#f} otherwise.
(Not supported for native binary ports - i.e. @code{java.io.InputStteam}
or @code{java.io.OutputStream}.)
@end deffn

@deffn Procedure current-input-port
@deffnx Procedure current-output-port
@deffnx Procedure current-error-port
Returns the current default input port, output port, or
error port (an output port), respectively.
(The error port is the port to which errors and warnings should be sent
- the @dfn{standard error} in Unix and C terminology.)
These procedures are @ref{Parameter objects,parameter objects},
which can be overridden with @ref{parameterize-syntax,@code{parameterize}}.

The initial bindings for @code{(current-output-port)} and
@code{(current-error-port)} are hybrid textual/binary
ports that wrap the values of the corresponding @code{java.lang.System} fields
@code{out}, and @code{err}.  The latter, in turn are bound
to the standard output and error streams of the JVM process.
This means you can write binary data to standard output
using @code{write-bytevector} and @code{write-u8}.

The initial value @code{(current-input-port)} similarly is a textual port
that wraps the @code{java.lang.System} field @code{in}, which is bound
to the standard input stream of the JVM process.
It is a @emph{hybrid} textual/binary port only if there
is no console (as determined by @code{(java.lang.System:console)}
returning @code{#!null}) - i.e. if standard input is not a tty.

Here is an example that copies standard input to standard output:
@example
(let* ((in (current-input-port))
       (out (current-output-port))
       (blen ::int 2048)
       (buf (make-bytevector blen)))
  (let loop ()
    (define n (read-bytevector! buf in))
    (cond ((not (eof-object? n))
           (write-bytevector buf out 0 n)
           (loop)))))
@end example

@end deffn

@deffn Procedure with-input-from-file path thunk
@deffnx Procedure with-output-to-file path thunk
The file is opened for input or output as if by
@code{open-input-file} or @code{open-output-file}, and the new port
is made to be the value returned by @code{current-input-port}
or @code{current-output-port} (as used by @code{(read)},
@code{(write @var{obj})}, and so forth). The thunk is then called with no
arguments. When the @var{thunk} returns, the port is closed
and the previous default is restored. It is an error if @var{thunk}
does not accept zero arguments. Both procedures return
the values yielded by @var{thunk}. If an escape procedure is used
to escape from the continuation of these procedures, they
behave exactly as if the current input or output port had
been bound dynamically with @code{parameterize}.
@end deffn

@deffn Procedure open-input-file path
@deffnx Procedure open-binary-input-file path
Takes a @var{path} naming an existing file and returns a textual
input port or binary input port that is capable of delivering
data from the file.
@c If the file does not exist or cannot be
@c opened, an error that satisfies file-error? is signaled.

The procedure @code{open-input-file} checks the fluid variable
@ref{port-char-encoding,@code{port-char-encoding}} to determine how bytes are decoded
into characters.  The procedure @code{open-binary-input-file}
is equivalent to calling @code{open-input-file} with
@code{port-char-encoding} set to @code{#f}.
@end deffn

@deffn Procedure open-output-file path
@deffnx Procedure open-binary-output-file path
Takes a @var{path} naming an output file to be created and returns
respectively a textual output port or binary output port that is
capable of writing data to a new file by that name. If a
file with the given name already exists, the effect is unspecified.
@c If the file cannot be opened, an error that satisfies
@c file-error? is signaled.

The procedure @code{open-output-file} checks the fluid variable
@ref{port-char-encoding,@code{port-char-encoding}} to determine how characters are
encoded as bytes.  The procedure @code{open-binary-output-file}
is equivalent to calling @code{open-output-file} with
@code{port-char-encoding} set to @code{#f}.
@end deffn

@deffn Procedure close-port port
@deffnx Procedure close-input-port port
@deffnx Procedure close-output-port port
Closes the resource associated with @var{port}, rendering the port
incapable of delivering or accepting data. It is an error to
apply the last two procedures to a port which is not an
input or output port, respectively.
(Specifically, @code{close-input-port} requires a @code{java.io.Reader},
while @code{close-output-port} requires a @code{java.io.Writer}.
In contrast @code{close-port} accepts any object whose class
implements @code{java.io.Closeable}.)
@c Scheme implementations may provide ports which are simultaneously input
@c and output ports, such as sockets; the close-input-port
@c and close-output-port procedures can then be used to
@c close the input and output sides of the port independently.

These routines have no effect if the port has already been
closed.
@end deffn

@subsection String and bytevector ports

@deffn Procedure open-input-string string
Takes a string and returns a text input port that delivers characters
from the string. The port can be closed by @code{close-input-port},
though its storage will be reclaimed by the
garbage collector if it becomes inaccessible. 

@example
(define p
  (open-input-string "(a . (b c . ())) 34"))

(input-port? p)                 @result{}  #t
(read p)                        @result{}  (a b c)
(read p)                        @result{}  34
(eof-object? (peek-char p))     @result{}  #t
@end example
@end deffn

@deffn Procedure open-output-string
Returns an textual output port that will accumulate characters
for retrieval by @code{get-output-string}.
The port can be closed by the procedure @code{close-output-port},
though its storage will be reclaimed by the garbage collector
if it becomes inaccessible. 
@example
(let ((q (open-output-string))
  (x '(a b c)))
    (write (car x) q)
    (write (cdr x) q)
    (get-output-string q))        @result{}  "a(b c)"
@end example
@end deffn

@deffn Procedure get-output-string output-port
Given an output port created by @code{open-output-string},
returns a string consisting of the characters that have been
output to the port so far in the order they were output.
If the result string is modified, the effect is unspecified.

@example
(parameterize
    ((current-output-port (open-output-string)))
    (display "piece")
    (display " by piece ")
    (display "by piece.")
    (newline)
    (get-output-string (current-output-port)))
        @result{} "piece by piece by piece.\n"
@end example
@end deffn

@deffn Procedure call-with-input-string string proc
Create an input port that gets its data from @var{string},
call @var{proc} with that port as its one argument, and return
the result from the call of @var{proc}
@end deffn

@deffn Procedure call-with-output-string proc
Create an output port that writes its data to a @var{string},
and call @var{proc} with that port as its one argument.
Return a string consisting of the data written to the port.
@end deffn

@deffn Procedure open-input-bytevector bytevector
Takes a bytevector and returns a binary input port that
delivers bytes from the bytevector.
@end deffn

@deffn Procedure open-output-bytevector
Returns a binary output port that will accumulate bytes
for retrieval by @code{get-output-bytevector}.
@end deffn

@deffn Procedure get-output-bytevector port
Returns a bytevector consisting of the bytes that have been
output to the port so far in the order they were output.
It is an error if @var{port} was not created with @code{open-output-bytevector}.
@end deffn

@subsection Input

If @var{port} is omitted from any input procedure, it defaults
to the value returned by @code{(current-input-port)}. It is an
error to attempt an input operation on a closed port.

@deffn Procedure read [port]
The @code{read} procedure converts external representations of
Scheme objects into the objects themselves. That is, it is
a parser for the non-terminal @stxref{datum}.
It returns the next object parsable from the
given textual input port, updating port to point to the
first character past the end of the external representation
of the object.

If an end of file is encountered in the input before any
characters are found that can begin an object, then an
end-of-file object is returned. The port remains open, and
further attempts to read will also return an end-of-file object.
If an end of file is encountered after the beginning of
an object’s external representation, but the external representation
is incomplete and therefore not parsable, an error
that satisfies @code{read-error?} is signaled.
@end deffn

@deffn Procedure read-char [port]
Returns the next character available from the textual input
@var{port}, updating the port to point to the following character.
If no more characters are available, an end-of-file value is
returned.

The result type is @code{character-or-eof}.
@end deffn

@deffn Procedure peek-char [port]
Returns the next character available from the textual input @var{port},
but @emph{without} updating the port to point to the
following character. If no more characters are available, an
end-of-file value is returned.

The result type is @code{character-or-eof}.

@emph{Note:} The value returned by a call to @code{peek-char} is the same as
the value that would have been returned by a call to @code{read-char}
with the same @var{port}. The only difference is that the very next call
to @code{read-char} or @code{peek-char} on that @var{port} will return the
value returned by the preceding call to @code{peek-char}. In particular, a
call to @code{peek-char} on an interactive port will hang waiting for
input whenever a call to @code{read-char} would have hung.
@end deffn

@deffn Procedure read-line [port [handle-newline]]
Reads a line of input from the textual input @var{port}.
The @var{handle-newline} parameter determines what is done with
terminating end-of-line delimiter.
The default, @code{'trim}, ignores the delimiter;
@code{'peek} leaves the delimiter in the input stream;
@code{'concat} appends the delimiter to the returned value;
and @code{'split} returns the delimiter as a second value.
You can use the last three options to tell if the string was
terminated by end-or-line or by end-of-file.
If an end of file is encountered before any end of
line is read, but some characters have been read, a string
containing those characters is returned.
(In this case, @code{'trim}, @code{'peek}, and @code{'concat}
have the same result and effect.  The @code{'split} case returns two
values: The characters read, and the delimiter is an empty string.)
If an end of file is encountered before any characters are read,
an end-of-file object is returned.
For the purpose of this procedure, an
end of line consists of either a linefeed character, a carriage
return character, or a sequence of a carriage return character
followed by a linefeed character.
@end deffn

@deffn Procedure eof-object? obj
Returns @code{#t} if @var{obj} is an end-of-file object,
otherwise returns @code{#f}.

@code{Performance note}: If @var{obj} has type @code{character-or-eof},
this is compiled as an @code{int} comparison with -1.
@end deffn

@deffn Procedure eof-object
Returns an end-of-file object.
@end deffn

@deffn Procedure char-ready? [port]
Returns @code{#t} if a character is ready on the textual input
@var{port} and returns @code{#f} otherwise. If char-ready returns @code{#t}
then the next @code{read-char} operation on the given @var{port} is
guaranteed not to hang. If the port is at end of file then
@code{char-ready?} returns @code{#t}.

@emph{Rationale:} The @code{char-ready?} procedure exists to make it
possible for a program to accept characters from interactive ports
without getting stuck waiting for input. Any input editors as-
sociated with such ports must ensure that characters whose
existence has been asserted by @code{char-ready?} cannot be removed
from the input. If @code{char-ready?} were to return @code{#f} at end of
file, a port at end-of-file would be indistinguishable from an
interactive port that has no ready characters.
@end deffn

@deffn Procedure read-string k [port]
Reads the next @var{k} characters, or as many as are available
before the end of file, from the textual input @var{port} into a
newly allocated string in left-to-right order and returns the
string. If no characters are available before the end of file,
an end-of-file object is returned.
@end deffn

@deffn Procedure read-u8 [port]
Returns the next byte available from the binary input @var{port},
updating the @var{port} to point to the following byte. If no more
bytes are available, an end-of-file object is returned.
@end deffn

@deffn Procedure peek-u8 [port]
Returns the next byte available from the binary input @var{port},
but @emph{without} updating the @var{port} to point to the following byte.
If no more bytes are available, an end-of-file object is returned.
@end deffn

@deffn Procedure u8-ready? [port]
Returns @code{#t} if a byte is ready on the binary input @var{port} and
returns @code{#f} otherwise. If @code{u8-ready?} returns @code{#t} then the
next @code{read-u8} operation on the given port is guaranteed
not to hang. If the port is at end of file then @code{u8-ready?}
returns @code{#t}.
@end deffn

@deffn Procedure read-bytevector k [port]
Reads the next @var{k} bytes, or as many as are available before
the end of file, from the binary input @var{port} into a newly
allocated bytevector in left-to-right order and returns the
bytevector. If no bytes are available before the end of file,
an end-of-file object is returned.
@end deffn

@deffn Procedure read-bytevector! bytevector [port [start [end]]]
Reads the next @var{end} − @var{start} bytes, or as many as are
available before the end of file, from the binary input @var{port}
into @var{bytevector} in left-to-right order beginning at the @var{start}
position. If @var{end} is not supplied, reads until the end of
@var{bytevector} has been reached. If @var{start} is not supplied, reads
beginning at position 0. Returns the number of bytes read.
If no bytes are available, an end-of-file object is returned.
@end deffn

@subsection Output

If @var{port} is omitted from any output procedure, it defaults
to the value returned by @code{(current-output-port)}. It is an
error to attempt an output operation on a closed port.

The return type of these methods is @code{void}.

@deffn Procedure write obj [port]
Writes a representation of @var{obj} to the given textual output
@var{port}. Strings that appear in the written representation
are enclosed in quotation marks, and within those strings
backslash and quotation mark characters are escaped by
backslashes.
Symbols that contain non-ASCII characters
are escaped with vertical lines.
Character objects are written using the @code{#\} notation.

If @var{obj} contains cycles which would cause an infinite loop
using the normal written representation, then at least the
objects that form part of the cycle must be represented
using @ref{datum labels}. Datum
labels must not be used if there are no cycles.
@end deffn

@deffn Procedure write-shared obj [port]
The @code{write-shared} procedure is the same as @code{write}, except
that shared structure must be represented using datum
labels for all pairs and vectors that appear more than once
in the output.
@end deffn

@deffn Procedure write-simple obj [port]
The @code{write-simple} procedure is the same as @code{write}, except
that shared structure is never represented using datum labels.
This can cause write-simple not to terminate if @var{obj}
contains circular structure.
@end deffn

@deffn Procedure display obj [port]
Writes a representation of @var{obj} to the given textual output
port. Strings that appear in the written representation
are output as if by @code{write-string} instead of by @code{write}.
Symbols are not escaped. Character objects appear in the
representation as if written by @code{write-char} instead of by
@code{write}.
The @code{display} representation of other objects is unspecified.
@c However, display must always terminate. Thus if the normal write
@c representation is used, datum labels are needed
@c to represent cycles as in write.
@end deffn

@deffn Procedure newline [port]
Writes an end of line to textual output @var{port}.
This is done using the @code{println} method
of the Java class @code{java.io.PrintWriter}.
@end deffn

@deffn Procedure write-char char [port]
Writes the character @var{char} (not an external representation
of the character) to the given textual output @var{port}.
@end deffn

@deffn Procedure write-string string [port [start [end]]]
Writes the characters of @var{string} from @var{start} to @var{end}
in left-to-right order to the textual output @var{port}.
@end deffn

@deffn Procedure write-u8 byte [port]
Writes the @var{byte} to the given binary output port.
@end deffn

@deffn Procedure write-bytevector bytevector [port [start [end]]]
Writes the bytes of @var{bytevector} from @var{start} to @var{end}
in left-to-right order to the binary output @var{port}.
@end deffn

@deffn Procedure flush-output-port [port]
@deffnx Procedure force-output [port]
Forces any pending output on @var{port} to be delivered to the output file or
device and returns an unspecified value.  If the @var{port} argument is
omitted it defaults to the value returned by @code{(current-output-port)}.
(The name @code{force-output} is older,
while R6RS added @code{flush-output-port}. They have the same effect.)
@end deffn

@anchor{Prompts}
@cindex prompts
@subsection Prompts for interactive consoles (REPLs)

When an interactive input port is used for a read-eval-print-loop (REPL
or console) it is traditional for the REPL to print a short
@dfn{prompt} string to signal that the user is expected to type
an expression.  These prompt strings can be customized.

@anchor{input-prompt1}
@defvar input-prompt1
@defvarx input-prompt2
These are fluid variable whose values are string templates
with placeholders similar to @code{printf}-style format.
The placeholders are expanded (depending on the current state),
and the resulting string printed in front of the input line.

The @code{input-prompt1} is used normally.  For multi-line input commands
(for example if the first line is incomplete), @code{input-prompt1}
is used for the first line of each command, while @code{input-prompt2} is
used for subsequent ``continuation'' lines.

The following placeholders are handled:
@table @asis
@item @stxlit{%%}
A literal @samp{%}.
@item @stxlit{%N}
The current line number.  This is @code{(+ 1 (port-line @var{port}))}.
@item @stxlit{%}@var{n}@stxlit{P}@var{c}
Insert padding at this possion, repeating the following
  character @code{@var{c}} as needed to bring the total number of columns
of the prompt to that specified by the digits @code{@var{n}}.
@item @stxlit{%P}@var{c}
Same as @code{%@var{n}P@var{c}}, but @code{@var{n}} defaults to the number
of columns in the initial prompt from the expansion of @code{input-prompt1}.
This is only meaningful when expanding @code{input-prompt2} for
continuation lines.
@item @stxlit{%}@stxlitlbrace{}@var{hidden}@stxlit{%@}}
Same as @var{hidden}, but the characters of @var{hidden}
are assumed to have zero visible width.  Can be used for
@uref{https://en.wikipedia.org/wiki/ANSI_escape_code,ANSI escape sequences}
to change color or style:
@example
(set! input-prompt1 "%@{\e[48;5;51m%@}@{Kawa:%N@} %@{\e[0m%@}")
@end example
The above changes both the text and the background color
(to a pale blue).
@item @stxlit{%M}
Insert a ``message'' string.
Not normally used by Kawa, but supported by JLine.
@end table

These variables can be initialized by the command-line
arguments @code{console:prompt1=@var{prompt1}} and
@code{console:prompt2=@var{prompt2}}, respectively.  If these are
not specified, languages-specific defaults are used.
For example for Scheme the default value of @code{input-prompt1}
is @code{"#|kawa:%N|# "} and @code{input-prompt2} is @code{"#|$P.%N| "}.
These have the form of Scheme comments, to make it easier to cut-and-paste.

If @code{input-prompt1} (respectively @code{input-prompt2}) does not contain
an escape sequence (either @code{"%@{} or the escape character @code{"\e"})
then ANSI escape sequences are added to to highlight the prompt.
(Under DomTerm this sets the @code{prompt} style, which can be customised
with CSS but defaults to a light green background;
if using JLine the background is set to light green.)
@end defvar

For greater flexibility, you can also set a prompter procedure.

@deffn Procedure set-input-port-prompter! port prompter
Set the prompt procedure associated with @var{port} to @var{prompter},
which must be a one-argument procedure taking an input port,
and returning a string.
The procedure is called before reading the first line of a command;
its return value is used as the first-line prompt.

The prompt procedure can have side effects.
In Bash shell terms: It combines the features of @code{PROMPT_COMMAND}
and @code{PS1}.

The initial @var{prompter} is @code{default-prompter},
which returns the expansion of @code{input-prompt1}.
@end deffn

@deffn Procedure input-port-prompter port
Get the prompt procedure associated with @var{port}.
@end deffn

@deffn Procedure default-prompter port
The default prompt procedure.
Normally (i.e. when @code{input-port-read-state} is a space)
returns @code{input-prompt1} after expanding the @code{%}-placeholders.
Can also expand @code{input-prompt2} when @code{input-port-read-state}
is not whitespace.
@end deffn

@subsection Line numbers and other input port properties

@deffn Function port-column input-port
@deffnx Function port-line input-port
Return the current column number or line number of @var{input-port},
using the current input port if none is specified.
If the number is unknown, the result is @code{#f}.  Otherwise,
the result is a 0-origin integer - i.e. the first character
of the first line is line 0, column 0.  (However, when you
display a file position, for example in an error message,
we recommend you add 1 to get 1-origin integers.  This is
because lines and column numbers traditionally start with
1, and that is what non-programmers will find most natural.)
@end deffn

@deffn Procedure set-port-line! port line
Set (0-origin) line number of the current line of @var{port} to @var{num}.
@end deffn

@deffn Procedure input-port-line-number port
Get the line number of the current line of @var{port},
which must be a (non-binary) input port.
The initial line is line 1.
Deprecated; replaced by @code{(+ 1 (port-line @var{port}))}.
@end deffn

@deffn Procedure set-input-port-line-number! port num
Set line number of the current line of @var{port} to @var{num}.
Deprecated;  replaced by @code{(set-port-line! @var{port} (- @var{num} 1))}.
@end deffn

@deffn Procedure input-port-column-number port 
Get the column number of the current line of @var{port}, 
which must be a (non-binary) input port.
The initial column is column 1.
Deprecated; replaced by @code{(+ 1 (port-column @var{port}))}.
@end deffn

@deffn Procedure input-port-read-state port
Returns a character indicating the current @code{read} state of the @var{port}.
Returns @code{#\Return} if not current doing a @var{read},
@code{#\"} if reading a string;  @code{#\|} if reading a comment;  @code{#\(}
if inside a list; and @code{#\Space} when otherwise in a @code{read}.
The result is intended for use by prompt prcedures, and is not necessarily
correct except when reading a new-line.
@end deffn

@defvar symbol-read-case
A symbol that controls how @code{read} handles letters when reading a symbol.
If the first letter is @samp{U}, then letters in symbols are upper-cased.
If the first letter is @samp{D} or @samp{L}, then letters
in symbols are down-cased.
If the first letter is @samp{I}, then the case of letters in symbols
is inverted.
Otherwise (the default), the letter is not changed.
(Letters following a @samp{\} are always unchanged.)
The value of @code{symbol-read-case} only checked
when a reader is created, not each time a symbol is read.
@end defvar

@subsection Miscellaneous

@anchor{port-char-encoding}
@defvar port-char-encoding
Controls how bytes in external files are converted to/from internal
Unicode characters.  Can be either a symbol or a boolean.
If @code{port-char-encoding} is @code{#f}, the file is assumed
to be a binary file and no conversion is done.
Otherwise, the file is a text file.  The default is @code{#t}, which
uses a locale-dependent conversion.  If @code{port-char-encoding}
is a symbol, it must be the name of a character encoding known to Java.
For all text files (that is if @code{port-char-encoding} is not @code{#f}),
on input a @code{#\Return} character or
a @code{#\Return} followed by @code{#\Newline}
are converted into plain @code{#\Newline}.

This variable is checked when the file is opened;  not when actually
reading or writing.  Here is an example of how you can safely
change the encoding temporarily:
@example
(define (open-binary-input-file name)
  (fluid-let ((port-char-encoding #f)) (open-input-file name)))
@end example
@end defvar

@defvar *print-base*
The number base (radix) to use by default when printing rational numbers.
Must be an integer between 2 and 36, and the default is of course 10.
For example setting @code{*print-base*} to 16 produces hexadecimal output.
@end defvar

@defvar *print-radix*
If true, prints an indicator of the radix used when printing rational numbers.
If @code{*print-base*} is respectively 2, 8, or 16, then
@code{#b}, @code{#o} or @code{#x} is written before the number;
otherwise @code{#@var{N}r} is written, where @code{@var{N}} is the base.
An exception is when  @code{*print-base*} is 10, in which case a period
is written @emph{after} the number, to match Common Lisp; this may
be inappropriate for Scheme, so is likely to change.
@end defvar

@defvar *print-right-margin*
The right margin (or line width) to use when pretty-printing.
@end defvar

@defvar *print-miser-width*
If this an integer, and the available width is less or equal to this value,
then the pretty printer switch to the more @dfn{miser} compact style.
@end defvar

@defvar *print-xml-indent*
When writing to XML, controls pretty-printing and indentation.
If the value is @code{'always} or  @code{'yes} force each element to
start on a new suitably-indented line.
If the value is @code{'pretty} only force new lines for elements that
won't fit completely on a line.
The the value is @code{'no} or unset, don't add extra whitespace.
@end defvar

@node Format, , Ports, Input-Output
@section Formatted Output (Common-Lisp-style)

@deffn Procedure format destination fmt . arguments
An almost complete implementation of Common LISP format description
according to the CL reference book @cite{Common LISP} from Guy L.
Steele, Digital Press.  Backward compatible to most of the available
Scheme format implementations.

Returns @code{#t}, @code{#f} or a string; has side effect of printing
according to @var{fmt}.  If @var{destination} is @code{#t},
the output is to the current output port and @code{#!void} is returned.  If
@var{destination} is @code{#f}, a formatted string is returned as the
result of the call.  If @var{destination} is a string,
@var{destination} is regarded as the format string; @var{fmt} is
then the first argument and the output is returned as a string. If
@var{destination} is a number, the output is to the current error port
if available by the implementation. Otherwise @var{destination} must be
an output port and @code{#!void} is returned.@refill

@var{fmt} must be a string or an instance of @code{gnu.text.MessageFormat}
or @code{java.text.MessageFormat}.  If @var{fmt} is a string,
it is parsed as if by @code{parse-format}.
@end deffn

@deffn Procedure parse-format format-string
Parses @code{format-string}, which is a string of the form of a Common LISP
format description.  Returns an instance of @code{gnu.text.ReportFormat},
which can be passed to the @code{format} function.
@end deffn

A format string passed to @code{format} or @code{parse-format}
consists of format directives (that start with @samp{~}),
and regular characters (that are written directly to the destination).
Most of the Common Lisp (and Slib) format directives are implemented.
Neither justification, nor pretty-printing are supported yet.

Plus of course, we need documentation for @code{format}!

@subsection Implemented CL Format Control Directives

Documentation syntax: Uppercase characters represent the corresponding
control directive characters. Lowercase characters represent control
directive parameter descriptions.

@table @asis
@cindex ~a
@item @code{~A}
Any (print as @code{display} does).
@table @asis
@item @code{~@@A}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}A}
full padding.
@end table
@cindex ~s
@item @code{~S}
S-expression (print as @code{write} does).
@table @asis
@item @code{~@@S}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}S}
full padding.
@end table

@cindex ~c
@item @code{~C}
Character.
@table @asis
@item @code{~@@C}
prints a character as the reader can understand it (i.e. @code{#\} prefixing).
@item @code{~:C}
prints a character as emacs does (eg. @code{^C} for ASCII 03).
@end table
@end table

@subsection Formatting Integers

@table @asis
@cindex ~d
@item @code{~D}
Decimal.
@table @asis
@item @code{~@@D}
print number sign always.
@item @code{~:D}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}D}
padding.
@end table
@cindex ~x
@item @code{~X}
Hexadecimal.
@table @asis
@item @code{~@@X}
print number sign always.
@item @code{~:X}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}X}
padding.
@end table
@cindex ~o
@item @code{~O}
Octal.
@table @asis
@item @code{~@@O}
print number sign always.
@item @code{~:O}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}O}
padding.
@end table
@cindex ~b
@item @code{~B}
Binary.
@table @asis
@item @code{~@@B}
print number sign always.
@item @code{~:B}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}B}
padding.
@end table
@cindex ~r
@item @code{~@var{n}R}
Radix @var{n}.
@table @asis
@item @code{~@var{n},@var{mincol},@var{padchar},@var{commachar},@var{commawidth}R}
padding.
@end table
@item @code{~@@R}
print a number as a Roman numeral.
@item @code{~:@@R}
print a number as an ``old fashioned'' Roman numeral.
@item @code{~:R}
print a number as an ordinal English number.
@item @code{~R}
print a number as a cardinal English number.
@cindex ~p
@item @code{~P}
Plural.
@table @asis
@item @code{~@@P}
prints @code{y} and @code{ies}.
@item @code{~:P}
as @code{~P but jumps 1 argument backward.}
@item @code{~:@@P}
as @code{~@@P but jumps 1 argument backward.}
@end table
@end table

@var{commawidth} is the number of characters between two comma characters.


@subsection Formatting real numbers

@table @asis
@cindex ~f
@item @code{~F}
Fixed-format floating-point (prints a flonum like @var{mmm.nnn}).
@table @asis
@item @code{~@var{width},@var{digits},@var{scale},@var{overflowchar},@var{padchar}F}
@item @code{~@@F}
If the number is positive a plus sign is printed.
@end table
@end table

@table @asis
@cindex ~e
@item @code{~E}
Exponential floating-point (prints a flonum like @var{mmm.nnn}@code{E}@var{ee})
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}E}
@item @code{~@@E}
If the number is positive a plus sign is printed.
@end table
@end table

@table @asis
@cindex ~g
@item @code{~G}
General floating-point (prints a flonum either fixed or exponential).
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}G}
@item @code{~@@G}
If the number is positive a plus sign is printed.
@end table
A slight difference from Common Lisp:  If the number is printed
in fixed form and the fraction is zero,
then a zero digit is printed for the fraction, if allowed by the @var{width}
and @var{digits} is unspecified.
@end table

@table @asis
@cindex ~$
@item @code{~$}
Dollars floating-point (prints a flonum in fixed with signs separated).
@table @asis
@item @code{~@var{digits},@var{scale},@var{width},@var{padchar}$}
@item @code{~@@$}
If the number is positive a plus sign is printed.
@item @code{~:@@$}
A sign is always printed and appears before the padding.
@item @code{~:$}
The sign appears before the padding.
@end table
@end table

@subsection Miscellaneous formatting operators

@table @asis
@cindex ~%
@item @code{~%}
Newline.
@table @asis
@item @code{~@var{n}%}
print @var{n} newlines.
@end table
@cindex ~&
@item @code{~&}
print newline if not at the beginning of the output line.
@table @asis
@item @code{~@var{n}&}
prints @code{~&} and then @var{n-1} newlines.
@end table
@cindex ~|
@item @code{~|}
Page Separator.
@table @asis
@item @code{~@var{n}|}
print @var{n} page separators.
@end table
@cindex ~~
@item @code{~~}
Tilde.
@table @asis
@item @code{~@var{n}~}
print @var{n} tildes.
@end table
@cindex ~@i{newline}
@item @code{~}<newline>
Continuation Line.
@table @asis
@item @code{~:}<newline>
newline is ignored, white space left.
@item @code{~@@}<newline>
newline is left, white space ignored.
@end table
@cindex ~t
@item @code{~T}
Tabulation.
@table @asis
@item @code{~@@T}
relative tabulation.
@item @code{~@var{colnum},@var{colinc}T}
full tabulation.
@end table
@cindex ~?
@item @code{~?}
Indirection (expects indirect arguments as a list).
@table @asis
@item @code{~@@?}
extracts indirect arguments from format arguments.
@end table
@cindex ~(
@item @code{~(@var{str}~)}
Case conversion (converts by @code{string-downcase}).
@table @asis
@item @code{~:(@var{str}~)}
converts by @code{string-capitalize}.
@item @code{~@@(@var{str}~)}
converts by @code{string-capitalize-first}.
@item @code{~:@@(@var{str}~)}
converts by @code{string-upcase}.
@end table
@cindex ~*
@item @code{~*}
Argument Jumping (jumps 1 argument forward).
@table @asis
@item @code{~@var{n}*}
jumps @var{n} arguments forward.
@item @code{~:*}
jumps 1 argument backward.
@item @code{~@var{n}:*}
jumps @var{n} arguments backward.
@item @code{~@@*}
jumps to the 0th argument.
@item @code{~@var{n}@@*}
jumps to the @var{n}th argument (beginning from 0)
@end table
@item @code{~[@var{str0}~;@var{str1}~;...~;@var{strn}~]}
Conditional Expression (numerical clause conditional).
@table @asis
@cindex ~[
@item @code{~@var{n}[}
take argument from @var{n}.
@item @code{~@@[}
true test conditional.
@item @code{~:[}
if-else-then conditional.
@cindex ~;
@item @code{~;}
clause separator.
@item @code{~:;}
default clause follows.
@end table
@item @code{~@{@var{str}~@}}
Iteration (args come from the next argument (a list)).
@table @asis
@item @code{~@var{n}@{}
at most @var{n} iterations.
@cindex ~@{
@item @code{~:@{}
args from next arg (a list of lists).
@item @code{~@@@{}
args from the rest of arguments.
@item @code{~:@@@{}
args from the rest args (lists).
@end table
@cindex ~^
@item @code{~^}
Up and out.
@table @asis
@item @code{~@var{n}^}
aborts if @var{n} = 0
@item @code{~@var{n},@var{m}^}
aborts if @var{n} = @var{m}
@item @code{~@var{n},@var{m},@var{k}^}
aborts if @var{n} <= @var{m} <= @var{k}
@end table
@end table

@subsection Unimplemented CL Format Control Directives

@table @asis
@item @code{~:A}
print @code{#f} as an empty list (see below).
@item @code{~:S}
print @code{#f} as an empty list (see below).
@item @code{~<~>}
Justification.
@item @code{~:^}
@end table

@subsection Extended, Replaced and Additional Control Directives

These are not necesasrily implemented in Kawa!

@table @asis
@item @code{~I}
print a R4RS complex number as @code{~F~@@Fi} with passed parameters for
@code{~F}.
@item @code{~Y}
Pretty print formatting of an argument for scheme code lists.
@item @code{~K}
Same as @code{~?.}
@item @code{~!}
Flushes the output if format @var{destination} is a port.
@item @code{~_}
Print a @code{#\space} character
@table @asis
@item @code{~@var{n}_}
print @var{n} @code{#\space} characters.
@end table

@item @code{~@var{n}C}
Takes @var{n} as an integer representation for a character. No arguments
are consumed. @var{n} is converted to a character by
@code{integer->char}.  @var{n} must be a positive decimal number.@refill
@item @code{~:S}
Print out readproof.  Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@refill
@item @code{~:A}
Print out readproof.  Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@refill
@item @code{~F, ~E, ~G, ~$}
may also print number strings, i.e. passing a number as a string and
format it accordingly.
@end table

@node Pretty-printing
@section Pretty-printing

Pretty-printing is displaying a data structure as text,
by adding line-breaks and indenttaion so that the visual
structure of the output corresponds to the logical structure of
data structure.  This makes it easier to read and understand.
Pretty-printing takes into account the column width of the output
so as to avoid using more lines than needed.

Pretty-printing of standard sequences types such as lists and
vectors is done by default.  For example:
@example
#|kawa:11|# @kbd{(set! *print-right-margin* 50)}
#|kawa:12|# @kbd{'(ABCDEF (aa bb cc dd) (x123456789}
#|.....13|# @kbd{y123456789 z123456789) ABCDEFG HIJKL)}
(ABCDEF (aa bb cc dd)
 (x123456789 y123456789 z123456789) ABCDEFG HIJK)
@end example
Setting @code{*print-right-margin*} to 50
causes output to be limited to 50 columns.
Notice the top-level list has to be split,
but sub-lists @code{(aa bb cc dd)}
and @code{(x123456789 y123456789 z123456789)}
don't need to be split.

When outputting to a DomTerm REPL,
then @code{*print-right-margin*} is ignored,
and the line-breaking is actually handled by DomTerm.
If you change the window width, DomTerm will dynamically
re-calculate the line-breaks of previous pretten output.
This works even in the case of a session saved to an HTML
file, as long as JavaScript is enabled.

The concepts and terminology are
based on those of @uref{https://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node253.html,Common Lisp}.

@subsection Pretty-printing Scheme forms

Scheme and Lisp code is traditionally pretty-printed
slightly differently than plain lists.
The @code{pprint} procedure assumes the argument
is a Scheme form, and prints its accordingly.
For example the special form @code{(let ...)} is printed
differently from a regular function call @code{(list ...)}.

@deffn Procedure pprint obj [out]
Assume @var{obj} is a Scheme form, and pretty-print it
in traditional Scheme format.  For example:
@example
#|kawa:1|# @kbd{(import (kawa pprint))}
#|kawa:2|# @kbd{(define fib-form}
#|.....3|# @kbd{  '(define (fibonacci n)}
#|.....4|# @kbd{     (let loop ((i0 0) (i1 1) (n n))}
#|.....5|# @kbd{       (if (<= n 0) i0}
#|.....6|# @kbd{           (loop i1 (+ i0 i1) (- n 1))))))}
#|kawa:7|# @kbd{(set! *print-right-margin* 80)}
#|kawa:8|# @kbd{(pprint fib-form)}
(define (fibonacci n)
  (let loop ((i0 0) (i1 1) (n n)) (if (<= n 0) i0 (loop i1 (+ i0 i1) (- n 1)))))
#|kawa:9|# @kbd{(set! *print-right-margin* 40)}
#|kawa:10|# @kbd{(pprint fib-form)}
(define (fibonacci n)
  (let loop ((i0 0) (i1 1) (n n))
    (if (<= n 0)
        i0
        (loop i1 (+ i0 i1) (- n 1)))))
@end example

The @code{pprint} special-cases forms that start with
@code{define}, @code{if}, @code{lambda}, @code{let},
and a few more, and formats them with ``traditional'' indentation.
However, it is not as complete or polished as it should be.
(It should also use a programmable dispatch table,
rather than having these special cases hard-wired.
That is an improvemet for another day.)
@end deffn

@subsection Generic pretty-printing functions

The following procedures are used to indicate logical blocks,
and optional newlines.

To access them do:
@example
(import (kawa pprint))
@end example

In the following, @var{out} is the output port, which
defaults to @code{(current-output-port)}.

@deffn Syntax pprint-logical-block @var{options} @arbno{@stxref{statement}}

Evaluate the @var{statement}s within the context of a new ``logical block''.


The @var{options} are one or more of the following:
@table @asis
@item @stxlit{prefix:} @var{prefix}
@itemx @stxlit{per-line:} @var{per-line-prefix}
Emit @var{prefix} or @var{per-line-prefix} (only one of them can be specified) before the start of the logical block.
If @var{per-line-prefix} is provided, it is also print for each
line within the logical block, indented the same.
These are strings and default to @code{""}.
@item @stxlit{suffix:} @var{suffix}
Emit @var{suffix} after the end of the logical block.
@item @stxlit{out:} @var{out}
The output file.
@end table

For example to print a list you might do:
@example
(pprint-logical-block prefix: "(" suffix: ")"
   @i{print contents of list})
@end example

This macro is equivalent to:
@example
(pprint-start-logical-block @var{prefix} @var{is-per-line} @var{suffix} @var{out})
(try-finally
  (begin @arbno{@var{statement}})
  (pprint-end-logical-block @var{suffix} @var{out}))
@end example
@end deffn

@deffn Procedure pprint-start-logical-block prefix is-per-line suffix out
Start a logical block.
The @var{is-per-line} argument is a boolean to specifiy
of @var{prefix} is a per-line-prefix or a plain prefix.
@end deffn
@deffn Procedure pprint-end-logical-block suffix out
End a logical block.
@end deffn

@deffn Procedure pprint-newline kind [out]
Print a conditional newline, where @var{kind} is one of the
symbols @code{'fill}, @code{'linear}, @code{'mandatory},
or @code{'miser}.
Usually follows printing of a space, as nothing is printed
if the line is not broken here.
@end deffn

@deffn Procedure pprint-ident mode amount [out]
Change how much following lines are indented
(with the current logical block).
The @var{amount} is the size of the indentation, in characters.
The @var{mode} is either @code{'current} (if the
@var{amount} is relative to the current position),
or @code{'block} (if the @var{amount} is relative to the
start (after any @var{prefix}) of the current logical block).
@end deffn

@node Resources
@section Resources

A resource is a file or other fixed data that an application may access.
Resources are part of the application and are shipped with it, but are
stored in external files.  Examples are images, sounds,
and translation (localization) of messages.
In the Java world a resource is commonly bundled in the same jar file
as the application itself.

@deffn Syntax resource-url resource-name
Returns a @code{URLPath} you can use as a @code{URL}, or
you can pass to it @code{open-input-file} to read the resource data.
The @var{resource-name} is a string which is passed to the
@code{ClassLoader} of the containing module.
If the module class is in a jar file, things will magically
work if the resource is in the same jar file, and @var{resource-name}
is a filename relative to the module class in the jar.
If the module is immediately evaluated, the @var{resource-name} is resolved
against the location of the module source file.
@end deffn

@deffn Syntax module-uri
Evaluates to a special URI that can be used to access resources
relative to the class of the containing module.
The URI has the form @code{"class-resource://@var{CurrentClass}/"}
in compiled code, to allow moving the classes/jars.
The current @code{ClassLoader} is associated with the URI, so accessing
resources using the URI will use that @code{ClassLoader}.
Therefore you should not create a @code{"class-resource:"} URI
except by using this function or @code{resolve-uri},
since that might try to use the wrong @code{ClassLoader}.

The macro @code{resource-url} works by using @code{module-uri}
and resolving that to a normal @code{URL}.
@end deffn

@deffn Syntax module-class
Evaluates to the containing module class, as a @code{java.lang.Class} instance.
@end deffn

@node Types, Objects Classes and Modules, Input-Output, Top
@chapter Types

A @dfn{type} is a set of values, plus an associated set of operations
valid on those values.
Types are useful for catching errors ("type-checking"), documenting
the programmer's intent, and to help the compiler generate better code.
Types in some languages (such as C) appear in programs,
but do not exist at run-time.  In such languages, all type-checking
is done at compile-time.  Other languages (such as standard Scheme)
do not have types as such, but they have @dfn{predicates}, which
allow you to check if a value is a member of certain sets;  also,
the primitive functions will check at run-time if the arguments
are members of the allowed sets.  Other languages, including Java
and Common Lisp, provide a combination:  Types may be used as specifiers
to guide the compiler, but also exist as actual run-time values.
In Java, for each class, there is a corresponding @code{java.lang.Class}
run-time object, as well as an associated type (the set of values
of that class, plus its sub-classes, plus @code{null}).

Kawa, like Java, has first-class types, that is types exist as
objects you can pass around at run-time.  For each Java type,
there is a corresponding Kawa type (but not necessarily vice
versa).  It would be nice if we could represent run-time
type values using @code{java.lang.Class} objects, but unfortunately
that does not work very well.  One reason is that we need
to be able to refer to types and classes that do not exist yet,
because we are in the processing of compiling them.  Another
reason is that we want to be able to distinguish between different
types that are implemented using the same Java class.

Various Kawa constructs require or allow a type to be specified.
Those specifications consist of @dfn{type expressions}, and a type expression
is evaluated to yield a type value.  The current Kawa compiler
is rather simple-minded, and in many places only allows simple
types that the compiler can evaluate at compile-time.
More specifically, it only allows simple @dfn{type names}
that map to primitive Java types or Java classes.

@display
@stxdef{type} @stxref{expression}
@stxdef{opt-type-specifier} [@stxlit{::} @stxref{type}]
@end display

@menu
* Standard Types::
* Parameterized Types::
* Type tests and conversions::
@end menu

@node Standard Types
@section Standard Types

These types are predefined with the following names.

Instead of plain @code{@var{typename}} you can also use
the syntax @code{<@var{typename}>} with angle brackets,
but that syntax is no longer recommended, because it doesn't
``fit'' as well with some ways type names are used.

To find which Java classes these types map into, look in
@code{kawa/standard/Scheme.java}.

Note that the value of these variables are instances
of @code{gnu.bytecode.Type},
not (as you might at first expect) @code{java.lang.Class}.

The numeric types (@code{number}, @code{quantity},
@code{complex}, @code{real}, @code{rational}, @code{integer},
@code{long}, @code{int}, @code{short}, @code{byte}
@code{ulong}, @code{uint}, @code{ushort}, @code{ubyte},
@code{double}, @code{float})
are discussed in @ref{Numerical types}.

The types @code{character} and @code{char}
are discussed in @ref{Characters}.

@defvar Object
An arbitrary Scheme value - and hence an arbitrary Java object.
@end defvar

@defvar symbol
The type of Scheme symbols.
(Implemented using the Java class @code{gnu.mapping.Symbol}.)
(@CompatibilityNote{} Previous versions of Kawa implemented
a simple Scheme symbol using an interned @code{java.lang.String}.)
@end defvar

@defvar keyword
The type of keyword values.  @xref{Keywords}.
@end defvar

@defvar list
The type of Scheme lists (pure and impure, including the empty list).
@end defvar

@defvar pair
The type of Scheme pairs.  This is a sub-type of @code{list}.
@end defvar

@defvar string
The type of Scheme strings.
(Implemented using @code{java.lang.String} for immutable strings,
and @code{gnu.lists.FString} for mutable strings.
Both of these implement the interface @code{java.lang.CharSequence}.
In the future, we may change the representation for strings
containing ``surrogate characters'', for efficient indexing.)
(@CompatibilityNote{} Previous versions of Kawa
always used @code{gnu.lists.FString}.)
@end defvar

@defvar character
The type of Scheme character values.  This is a sub-type of
@code{Object}, in contrast to type @code{char}, which is the
primitive Java @code{char} type.
@end defvar

@defvar vector
The type of Scheme vectors.
@end defvar

@defvar procedure
The type of Scheme procedures.
@end defvar

@defvar input-port
The type of Scheme input ports.
@end defvar

@defvar output-port
The type of Scheme output ports.
@end defvar

@defvar String
This type name is a special case.  It specifies the class
@code{java.lang.String}.
However, coercing a value to @code{String} is done by
invoking the @code{toString} method on the value to be coerced.
Thus it "works" for all objects.
It also works for @code{#!null}.

When Scheme code invokes a Java method, any parameter
whose type is @code{java.lang.String} is converted
as if it was declared as a @code{String}.
@end defvar

@defvar parameter
A parameter object, as created by @code{make-parameter}.
This type can take a type parameter (sic):
@example
(define-constant client ::parameter[Client] (make-parameter #!null))
@end example
This lets Kawa know that reading the parameter (as in @code{(client)})
returns a value of the specified type (in this case @code{Client}).
@end defvar

More will be added later.

A type specifier can also be one of the primitive Java types.
The numeric types @code{long}, @code{int}, @code{short},
@code{byte}, @code{float}, and @code{double} are converted from the
corresponding Scheme number classes.  Similarly, @code{char}
can be converted to and from Scheme characters.  The type
@code{boolean} matches any object, and the result is @code{false}
if and only if the actual argument is @code{#f}.
(The value @code{#f} is identical to @code{Boolean.FALSE},
and @code{#t} is identical to @code{Boolean.TRUE}.)
The return type @code{void} indicates that no value is returned.

A type specifier can also be a fully-qualified Java class name
(for example @code{java.lang.StringBuffer}).  In that case,
the actual argument is cast at run time to the named class.
Also, @code{java.lang.StringBuffer[]} represents
an array of references to @code{java.lang.StringBuffer} objects.

@anchor{dynamic-type}
@defvar dynamic
Used to specify that the type is unknown, and is likely to change
at run-time.
Warnings about unknown member names are supressed
(a run-time name lookup is formed).
An expression of type @code{dynamic} is (statically) compatible with
any type.
@end defvar

@node Parameterized Types
@section Parameterized Types
Kawa has some basic support for parameterized (generic) types.
The syntax:
@example
Type[Arg1 Arg2 ... ArgN]
@end example
is more-or-less equivalent to Java's:
@example
Type<Arg1, Arg2, ..., ArgN>
@end example

This is a work-in-progress.  You can use this syntax with
fully-qualified class names, and also type aliases:
@example
(define v1 ::gnu.lists.FVector[gnu.math.IntNum] [4 5 6])
(define-alias fv gnu.lists.FVector)
(define v2 ::fv[integer] [5 6 7])
(define-alias fvi fv[integer])
(define v3 ::fvi [6 7 8])
@end example

@node Type tests and conversions
@section Type tests and conversions

Scheme defines a number of standard type testing predicates.
For example @code{(vector? x)} is @code{#t} if and only if
@code{x} is a vector.

Kawa generalizes this to arbitrary type names:
If @var{T} is a type-name (that is in scope at compile-time),
then @code{@var{T}?} is a one-argument function that returns
@code{#t} if the argument is an instance of the type @code{@var{T}},
and @code{#f} otherwise:
@example
(gnu.lists.FVector? #(123)) @result{} #t
(let ((iarr (int[] 10))) (int[]? iarr)) @result{} #t 
@end example

To convert (coerce) the result of an expression @var{value} to a
type @var{T} use the syntax: @code{(->@var{T} @var{value})}.
@example
(->float 12) @result{} 12.0f0
@end example

In general:
@example
(@var{T}? @var{x}) @result{} (instance? @var{x} @var{T})
(->@var{T} @var{x}) @result{} (as @var{T} @var{x})
@end example

@deffn Procedure instance? value type
Returns @code{#t} iff @var{value} is an instance of type @var{type}.
(Undefined if @var{type} is a primitive type, such as @code{int}.)
@end deffn

@deffn Procedure as type value
Converts or coerces @var{value} to a value of type @var{type}.
Throws an exception if that cannot be done.
Not supported for @var{type} to be a primitive type such as @code{int}.
@end deffn

@node Objects Classes and Modules, XML tools, Types, Top
@chapter Object, Classes and Modules

Kawa provides various ways to define, create, and access Java objects.
Here are the currently supported features.

The Kawa module system is based on the features of the Java class system.

@menu
* Defining new classes::
* Anonymous classes::
* Enumerations::          Enumeration types
* Annotations::
* Module classes::        Modules and how they are compiled to classes
* Importing::             Importing from a library
* Record types::          Defining Record Types
* Dynamic records::       Creating New Record Types On-the-fly
* Method operations::     Calling Java methods from Scheme
* Allocating objects::
* Field operations::      Accessing fields of Java objects
* Mangling::              Mapping Scheme names to Java names
* Scheme types in Java::
* Array operations::      Using Java arrays
* Loading Java functions into Scheme::
* Evaluating Scheme expressions from Java::
@end menu

@deffn Syntax this
Returns the "this object" - the current instance of the current class.
The current implementation is incomplete, not robust, and not
well defined.  However, it will have to do for now.
Note:  "@code{this}" is a macro, not a variable, so you have to write
it using parentheses: @samp{(this)}.  A planned extension will
allow an optional class specifier (needed for nested clases).
@end deffn

@node Defining new classes
@section Defining new classes

Kawa provides various mechanisms for defining new classes.
The @code{define-class} and @code{define-simple-class} forms
will usually be the preferred mechanisms.  They have basically
the same syntax, but have a couple of differences.
@code{define-class} allows multiple inheritance as well as true nested
(first-class) class objects.  However, the implementation
is more complex: code using it is slightly slower, and the mapping to
Java classes is a little less obvious.   (Each Scheme class is implemented
as a pair of an interface and an implementation class.)
A class defined by @code{define-simple-class} is slightly more
efficient, and it is easier to access it from Java code.

The syntax of @code{define-class} are mostly compatible with that
in the Guile and Stk dialects of Scheme.

@deffn Syntax define-class @stxref{class-name} @stxlit{(}supers ...@stxlit{)} @arbno{(@stxref{annotation}|@stxref{option-pair})} @stxref{field-or-method-decl} ...
@deffnx Syntax define-simple-class @stxref{class-name} @stxlit{(}supers ...@stxlit{)} @arbno{(@stxref{annotation}|@stxref{option-pair})}  @stxref{field-or-method-decl} ...

Defines a new class named @var{class-name}.  If @code{define-simple-class} is
used, creates a normal Java class named @var{class-name} in the current package.
(If @var{class-name} has the form @code{<xyz>} the Java implementation
type is named @code{xyz}.)  For @code{define-class} the implementation is
unspecified.  In most cases, the compiler creates a class pair,
consisting of a Java interface and a Java implementation class.
@end deffn
@display
@stxdef{class-name} @stxref{identifier}
@stxdef{option-pair} @var{option-keyword} @var{option-value}
@stxdef{field-or-method-decl} @stxref{field-decl} | @stxref{method-decl}
@end display

@subsection General class properties

The class inherits from the classes and interfaces listed in @var{supers}.
This is a list of names of classes that are in scope (perhaps imported
using @code{require}), or names for existing classes or interfaces
optionally surrounded by @code{<>}, such as @code{<gnu.lists.Sequence>}.
If @code{define-simple-class} is used, at most one of these may be
the name of a normal Java class or classes defined using
@code{define-simple-class}; the rest must be interfaces or classes
defined using @code{define-class}.
If @code{define-class} is used, @emph{all} of the classes listed
in @var{supers} should be interfaces or classes defined using
@code{define-class}.

@table @asis
@item @stxlit{interface:} @var{make-interface}
Specifies whether Kawa generates a Java class, interface, or both.
If @var{make-interface} is @code{#t}, then a Java interface is generated.
In that case all the supertypes must be interfaces, and
all the declared methods must be abstract.
If @var{make-interface} is @code{#f}, then a Java class is generated.
If @code{interface:}  is unspecified, the default is @code{#f}
for @code{define-simple-class}.  For @code{define-class} the default
is to generate an interface, and in addition (if needed) a helper
class that implements the interface.  (In that case any non-abstract methods
are compiled to static methods.  The methods that implement the interface
are just wrapper methods that call the real static methods.  This
allows Kawa to implement true multiple inheritance.)

@item @stxlit{access:} @var{kind}
Specifies the Java access permission on the class.
Can be one of @code{'public} (which is the default in Kawa),
@code{'package} (which the default "unnamed" permission in Java code),
@code{'protected}, @code{'private},
@code{'volatile}, or @code{'transient}.
Can also be used to specify @code{final}, @code{abstract}, or @code{enum}, as in Java.
(You don't need to explicitly specify the class is @code{abstract}
if any @var{method-body} is @code{#!abstract},
or you specify @code{interface: #t}.)
The @var{kind} can also be a list, as for example:
@example
access: '(protected volatile)
@end example

@item @stxlit{class-name:} @code{"}@var{cname}@code{"}
Specifies the Java name of the created class.
The @var{name} specified after @code{define-class}
or @code{define-simple-class} is the @emph{Scheme name},
i.e. the name of a Scheme variable that is bound to the class.
The Java name is by default derived from the Scheme name,
but you can override the default with a @code{class-name:} specifier.
If the @var{cname} has no periods, then it is a name in
the package of the main (module) class.
If the @var{cname} starts with a period,
then you get a class nested within the module class.
In this case the actual class name is @var{moduleClass}@code{$}@var{rname},
where @var{rname} is @var{cname} without the initial period.
To force a class in the top-level (unnamed) package (something
not recommended) write a period at the end of the @var{cname}.
@end table

@subsection Declaring fields

@display
@stxdef{field-decl} @stxlit{(}@stxref{field-name} (@stxref{annotation} | @stxref{opt-type-specifier} | @stxref{field-option})*@stxlit{)}
@stxdef{field-name} @stxref{identifier}
@stxdef{field-option} @stxref{keyword} @stxref{expression}
@end display

As a matter of style the following order is suggested, though this not enforced:
@display
@stxlit{(}@stxref{field-name} @stxref{annotation}* @stxref{opt-type-specifier} @stxref{field-option}*@stxlit{)}
@end display

Each @var{field-decl} declares a instance "slot" (field)
with the given @var{field-name}. 
By default it is publicly visible, but you can specify
a different visiblity with the @code{access:} specifier.
The following @var{field-option} @var{keyword}s are implemented:
@table @asis
@item @stxlit{type:} @stxref{type}
Specifies that @var{type} is the type of (the values of) the field.
Equivalent to @samp{:: @var{type}}.
@item @stxlit{allocation:} @var{kind}
If @var{kind} is @code{'class} or @code{'static} a single slot is shared
between all instances of the class (and its sub-classes).
Not yet implemented for @code{define-class},
only for @code{define-simple-class}.
In Java terms this is a @code{static} field.

If @var{kind} is @code{'instance} then
each instance has a separate value "slot", and they
are not shared. In Java terms, this is a non-@code{static} field.
This is the default.

@c You can use a keyword like @code{class:} or a string like @code{"class"}
@c if you prefer instead of a quoted symbol like @code{'class};
@c the latter is recommended.
@item @stxlit{access:} @var{kind}
Specifies the Java access permission on the field.
Can be one of @code{'private}, @code{'protected},
@code{'public} (which is the default in Kawa),
or @code{'package} (which the default "unnamed" permission
in Java code).
Can also be used to specify @code{volatile}, @code{transient},
@code{enum}, or @code{final}, as in Java,
or a quoted list with these symbols.
@item @stxlit{init:} @var{expr}
An expression used to initialize the slot.
The expression is evaluated in a scope that includes the field and
method names of the current class.
@item @stxlit{init-form:} @var{expr}
An expression used to initialize the slot.
The lexical environment of the @var{expr} is that of the @code{define-class};
it does @emph{not} include the field and method names of the current class.
or @code{define-simple-class}.
@item @stxlit{init-value:} @var{value}
A value expression used to initialize the slot.
For now this is synonymous with @var{init-form:}, but that may change
(depending on what other implementation do), so to be safe only use
@code{init-value:} with a literal.
@item @stxlit{init-keyword:} @code{@var{name}:}
A keyword that that can be used to initialize instance in @code{make} calls.
For now, this is ignored, and @var{name} should be the same as the
field's @var{field-name}.
@end table

The @var{field-name} can be left out.  That indicates a "dummy slot",
which is useful for initialization not tied to a specific field.
In Java terms this is an instance or static initializer, i.e., a
block of code executed when a new instance is created or the class is loaded.

In this example, @code{x} is the only actual field.  It is first
initialized to 10, but if @code{(some-condition)} is true
then its value is doubled.
@example
(define-simple-class <my-class> ()
  (allocation: 'class
   init: (perform-actions-when-the-class-is-initizalized))
  (x init: 10)
  (init: (if (some-condition) (set! x (* x 2)))))
@end example

@subsection Declaring methods

@display
@stxdef{method-decl} @stxlit{((}@stxref{method-name} @stxref{formal-arguments}@stxlit{)}
    @arbno{@stxref{method-option}} [@stxref{deprecated-return-specifier}] @stxref{method-body}@stxlit{)}
@stxdef{method-name} @stxref{identifier}
@stxdef{method-option} @stxref{annotation} | @stxref{opt-return-type} | @stxref{option-pair}
@stxdef{method-body} @stxref{body} | @stxlit{#!abstract} | @stxlit{#!native}
@stxdef{deprecated-return-specifier} @stxref{identifier}
@end display

Each @var{method-decl} declares a method,
which is by default public and non-static, and whose name is @var{method-name}.
(If @var{method-name} is not a valid
Java method name, it is mapped to something reasonable.
For example @code{foo-bar?} is mapped to @code{isFooBar}.)
The types of the method arguments can be specified in the
@var{formal-arguments}.  The return type can be specified by
a @var{opt-return-type}, @var{deprecated-return-specifier},
or is otherwise the type of the @var{body}.
Currently, the @var{formal-arguments} cannot contain optional, rest,
or keyword parameters.  (The plan is to allow optional parameters,
implemented using multiple overloaded methods.)

A @var{method-decl} in a @code{define-simple-class}
can have the following @var{option-keyword}s:
@table @asis
@item @stxlit{access:} @var{kind}
Specifies the Java access permission on the method.
Can be one of @code{'private}, @code{'protected},
@code{'public}, or @code{'package}.
Can also be @code{'synchronized}, @code{'final}, @code{'strictfp},
or a quoted list.
@item @stxlit{allocation:} @var{kind}
If @var{kind} is @code{'class} or @code{'static} creates a static method.
@item @stxlit{throws:} ( @var{exception-class-name} ... )
Specifies a list of checked exception that the method may throw.
Equivalent to a @code{throws} specification in Java code.
For example:
@example
(define-simple-class T
  (prefix)
  ((lookup name) throws: (java.io.FileNotFoundException)
   (make java.io.FileReader (string-append prefix name))))
@end example
@end table

The scope of the @var{body} of a method includes the @var{field-decl}s
and @var{method-decl}s of the class, including those inherited from
superclasses and implemented interfaces.

If the @var{method-body} is the special form @code{#!abstract},
then the method is abstract.  This means the method must
be overridden in a subclass, and you're not allowed to
create an instance of the enclosing class.

@example
(define-simple-class Searchable () interface: #t
  ((search value) :: boolean #!abstract))
@end example

If the @var{method-body} is the special form @code{#!native},
then the method is native, implemented using @uref{http://en.wikipedia.org/wiki/Java_Native_Interface,JNI}.

The special @var{method-name} @samp{*init*} can be used to name
a non-default constructor (only if @var{make-interface} discussed above
is @code{#f}).
It can be used to initialize a freshly-allocated instance
using passed-in parameters.
You can call a superclass or a sibling constructor using
the @code{invoke-special} special function.
(This is general but admittedly a bit verbose; a more compact
form may be added in the future.)
See the example below.

@subsection Example

In the following example we define a simple class @code{2d-vector}
and a class @code{3d-vector} that extends it.  (This is for illustration
only - defining 3-dimensional points as an extension
of 2-dimensional points does not really make sense.)

@example
(define-simple-class 2d-vector ()
  (x ::double init-keyword: x:)
  ;; Alternative type-specification syntax.
  (y type: double init-keyword: y:)
  (zero-2d :: 2d-vector allocation: 'static
   init-value: (2d-vector 0))
  ;; An object initializer (constructor) method.
  ((*init* (x0 ::double) (y0 ::double))
   (set! x x0)
   (set! y y0))
  ((*init* (xy0 ::double))
   ;; Call above 2-argument constructor.
   (invoke-special 2d-vector (this) '*init* xy0 xy0))
  ;; Need a default constructor as well.
  ((*init*) #!void)
  ((add (other ::2d-vector)) ::2d-vector
   ;; Kawa compiles this using primitive Java types!
   (2d-vector
     x: (+ x other:x)
     y: (+ y other:y)))
  ((scale (factor ::double)) ::2d-vector
   (2d-vector x: (* factor x) y: (* factor y))))

(define-simple-class 3d-vector (2d-vector)
  (z type: double init-value: 0.0 init-keyword: z:)
  ;; A constructor which calls the superclass constructor.
  ((*init* (x0 ::double) (y0 ::double) (z0 ::double))
   (invoke-special 2d-vector (this) '*init* x0 y0)
   (set! z z0))
  ;; Need a default constructor.
  ((*init*) #!void)
  ((scale (factor ::double)) ::2d-vector
   ;; Note we cannot override the return type to 3d-vector
   ;; because Kawa doesn't yet support covariant return types.
   (3d-vector
     x: (* factor x)
     y: (* factor (this):y) ;; Alternative syntax.
     z: (* factor z))))
@end example

Note we define both explicit non-default constructor methods,
and we associate fields with keywords, so they can be named
when allocating an object.  Using keywords requires a default constructor,
and since having non-default constructors suppresses
the implicit default constructor we have to explicitly define it.
Using both styles of constructors is rather redundant, though.

@node Anonymous classes
@section Anonymous classes

@deffn Syntax object @stxlit{(}supers ...@stxlit{)} field-or-method-decl ...
Returns a new instance of an anonymous (inner) class.
The syntax is similar to @code{define-class}.
@display
@stxdef{object-field-or-method-decl} @stxref{object-field-decl} | @stxref{method-decl}
@stxdef{object-field-decl} @stxlit{(}@stxref{field-name} (@stxref{annotation} | @stxref{opt-type-specifier} | @stxref{field-option})*  [@stxref{object-init}] @stxlit{)}
@stxdef{object-init} @stxref{expression}
@end display

Returns a new instance of a unique (anonymous) class.
The class inherits from the list of @var{supers}, where at most one of the
elements should be the base class being extended from, and the rest
are interfaces.

This is roughly equivalent to:
@example
(begin
  (define-simple-class @var{hname} (@var{supers} ...) @var{field-or-method-decl} ...)
  (make @var{hname}))
@end example

A @var{field-decl} is as for @code{define-class}, except
that we also allow an abbreviated syntax.
Each @var{field-decl} declares a public instance field.
If @var{object-finit} is given, it is an expression whose value
becomes the initial value of the field.
The @var{object-init} is evaluated at the same time as the @code{object}
expression is evaluated,
in a scope where all the @var{field-name}s are visible.

A @var{method-decl} is as for @code{define-class}.
@end deffn

@anchor{SAM-conversion}
@subsection Lambda as shorthand for anonymous class
An anonymous class is commonly used in the Java platform where a
function language would use a lambda expression.
Examples are call-back handlers, events handlers, and @code{run} methods.
In these cases Kawa lets you use a lambda expression as a short-hand
for an anonymous class.  For example:
@example
(button:addActionListener
  (lambda (e) (do-something)))
@end example
is equivalent to:
@example
(button:addActionListener
  (object (java.awt.event.ActionListener)
    ((actionPerformed (e ::java.awt.event.ActionEvent))::void
     (do-something))))
@end example
This is possible when the required type is an interface or
abstract class with a Single (exactly one) Abstract Methods.
Such a class is sometypes called a @dfn{SAM-type}, and the
conversion from a lambda expression to an anonymous class
is sometimes called @dfn{SAM-conversion}.

Note that Kawa can also infer the parameter and return types
of a method that overrides a method in a super-class.

@node Enumerations
@section Enumeration types

An enumeration type is a set of named atomic enumeration values
that are distinct from other values.  You define the type
using @code{define-enum}, and you reference enumeration values
using colon notation:
@example
(define-enum colors (red blue green))
(define favorite-color colors:green)
@end example
Displaying an enum just prints the enum name,
but readable output using @code{write} (or the @code{~s} @code{format}
specifier) prepends the type name:
@example
(format "~a" favorite-color) @result{} "green"
(format "~s" favorite-color) @result{} "colors:green"
@end example
The static @code{values} method returns a Java array of the enumeration
values, in declaration order, while @code{ordinal} yields the index
of an enumeration value:
@example
(colors:values) @result{} [red blue green]
((colors:values) 1) @result{} blue
(favorite-color:ordinal) @result{} 2
@end example
If you invoke the enumeration type as a function,
it will map the name (as a string) to the corresponding value.
(This uses the @code{valueOf} method.)
@example
(colors "red") @result{} red
(colors "RED") @result{} throws IllegalArgumentException
(eq? favorite-color (colors:valueOf "green")) @result{} #t
@end example

Kawa enumerations are based on Java enumerations.
Thus the above is similar to a Java5 @code{enum} declaration,
and the type @code{colors} above extends @code{java.lang.Enum}.

@deffn Syntax define-enum enum-type-name @var{option-pair}... @stxlit{(}enum-value-name ...@stxlit{)} @var{field-or-method-decl}...
This declares a new enumeration type @var{enum-type-name},
whose enumerations values are the @var{enum-value-name} list.
You can specify extra options and members using
@var{option-pair} and @var{field-or-method-decl},
which are as in @code{define-simple-class}.
(The @var{define-enum} syntax is similar to a
@code{define-simple-class} that extends @code{java.lang.Enum}.)
@end deffn

(Note that R6RS has a separate Enumerations library @code{(rnrs enum)}.
Unfortunately, this is not compatible with standard Java enums.
R6RS enums are simple symbols, which means you cannot distinguish
two enum values from different enumeration types if they have the
same value, nor from a vanilla symbol.  That makes them less useful.)

@node Annotations
@section Annotations of declarations

The Java platform lets you associate with each declaration zero or more
@uref{http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html, annotations}.
They provide an extensible mechanism to associate properties
with declarations.
Kawa support for annotations is not complete (the most important
functionality missing is being able to declare annotation types),
but is fairly functional.
Here is a simple example illustrating use of
@uref{http://jcp.org/en/jsr/detail?id=222,JAXB annotations}:
an @code{XmlRootElement} annotation on a class,
and an @code{XmlElement} annotation on a field:
@example
(import (class javax.xml.bind.annotation XmlRootElement XmlElement))
(define-simple-class Bib ( ) (@@XmlRootElement name: "bib")
  (books (@@XmlElement name: "book" type: Book) ::java.util.ArrayList))
(define-simple-class Book () ...)
@end example

@uref{http://per.bothner.com/blog/2011/Using-JAXB-annotations, This tutorial}
explains the JAXB example in depth.

Here is the syntax:
@display
@stxdef{annotation} @stxlit{(@@}@stxref{annotation-typename} @stxref{annotations-element-values}@stxlit{)}
@stxdef{annotations-element-values} @stxref{annotation-element-value}
  | @stxref{annotation-element-pair} ...
@stxdef{annotation-element-pair} @stxref{keyword} @stxref{annotation-element-value}
@stxdef{annotation-element-value} @stxref{expression}
@stxdef{annotation-typename} @stxref{expression}
@end display

An @var{annotations-element-values} consisting of just
a single @var{annotation-element-value} is equivalent to an
@var{annotation-element-pair} with a @code{value:} keyword.

Each @var{keyword} must correspond to the name of
an element (a zero-argument method) in the annotation type.
The corresponding @var{annotation-element-value} must be compatible with the
element type (return type of the method) of the annotation type.

Allowed element types are of the following kinds:
@itemize @bullet
@item
Primitive types, where the @var{annotation-element-value} must
be number or boolean coercible to the element type.
@item
Strings, where the @var{annotation-element-value} is normally a string literal.
@item
Classes, where the @var{annotation-element-value} is normally
a classname.
@item
Enumeration types. The value usually has the form @code{@var{ClassName}:@var{enumFieldname}}.
@item
Nested annotation types, where the  @var{annotation-element-value} must
be a compatible @var{annotation} value.
@item
An array of one of the allowable types.
An array constructor expression works, but using the
square bracket syntax is recommended.
@end itemize

Annotations are usually used in declarations,
where they are required to be ``constant-folded'' to compile-time
constant annotation values.
This is so they can be written to class files.
However, in other contexts an annotation can be used as an expression
with general sub-expressions evaluated at run-time:
@example
(define bk-name "book")
(define be (@@XmlElement name: bk-name type: Book))
(be:name) @result{} "book"
@end example
(This may have limited usefulness:  There are some bugs, including
lack of support for default values for annotation elements.
These bugs can be fixed if someone reports a need for
runtime construction of annotation values.)

@node Module classes
@section Modules and how they are compiled to classes

Modules provide a way to organize Scheme into
reusable parts with explicitly defined interfaces to the rest
of the program.
A @dfn{module} is a set of definitions that the module @dfn{exports},
as well as some @dfn{actions} (expressions evaluated for their side effect).
The top-level forms in a Scheme source file compile a module;
the source file is the @dfn{module source}.
When Kawa compiles the module source, the result is the
@dfn{module class}.  Each exported definition is translated to
a public field in the module class.

@subsection Name visibility

The definitions that a module exports are accessible to other modules.
These are the "public" definitions, to use Java terminology.
By default, all the identifiers declared at the top-level of a module
are exported, except those defined using @code{define-private}.
(If compiling with the @code{--main} flag,
then by default no identifiers are exported.)
However, a major purpose of using modules is to control the set of
names exported.  One reason is to reduce the chance of accidental
name conflicts between separately developed modules.  An even more
important reason is to enforce an interface:  Client modules should
only use the names that are part of a documented interface, and should
not use internal implementation procedures (since those may change).

If there is a @code{module-export} (or @code{export})
declaration in the module, then only those names listed are exported.
There can be more than one @code{module-export}, and they can be
anywhere in the Scheme file.  The recommended style has
a single @code{module-export} near the beginning of the file.

@anchor{meta-export-declaration}
@deffn Syntax module-export @arbno{@stxref{export-spec}}
@deffnx Syntax export @arbno{@stxref{export-spec}}
The forms @code{export} and @code{module-export} are equivalent.
(The older Kawa name is @code{module-export};
@code{export} comes from R7RS.)
Either form specifies a list of identifiers which
can be made visible to other libraries or programs.
@display
@stxdef{export-spec} @var{identifier}
  | @stxlit{(rename} @stxref{identifier}@sub{1} @stxref{identifier}@sub{2}@stxlit{)}
@end display
In the former variant, an @var{identifier} names a single binding
defined within or imported into the library, where the
external name for the export is the same as the name of
the binding within the library.
A @code{rename} spec exports the
binding defined within or imported into the library and
named by @var{identifier}@sub{1},
using @var{identifier}@sub{2} as the external name.

Note that it is an error if there is no definition for @var{identifier}
(or @var{identifier}@sub{1})
in the current module, or if it is defined using @code{define-private}.

As a matter of style, @code{export} or @code{module-export} should
appear after @code{module-name} but @emph{before} other commands
(including @code{import} or @code{require}).
(This is a requirement if there are any cycles.)

@end deffn

In this module, @code{fact} is public and @code{worker} is private:
@example
(module-export fact)
(define (worker x) ...)
(define (fact x) ...)
@end example

Alternatively, you can write:
@example
(define-private (worker x) ...)
(define (fact x) ...)
@end example

@subsection R7RS explicit library modules

A R7RS @code{define-library} form is another way to create a module.
The R7RS term @dfn{library} is roughly the same as a Kawa module.
In Kawa, each source file is a @ref{implicit library,@dfn{implicit module}},
which may contain zero or more explicit sub-modules (in
the form of @code{define-library}) optionally followed by
the definitions and expressions of the implicit (file-level) module.

@anchor{meta-library-definition}
@findex @i{library-definition}
@deffn Syntax define-library @stxref{library-name} @arbno{@stxref{library-declaration}}
@end deffn
@display
@stxdef{library-name} @stxlit{(} @stxref{library-name-parts} @stxlit{)}
@stxdef{library-name-parts} @atleastone{@var{identifier}}
@end display

A @meta{library-name} is a list whose members are identifiers and
exact non-negative integers. It is used to identify the library
uniquely when importing from other programs or
libraries. Libraries whose first identifier is @code{scheme} are
reserved for use by the R7RS report and future versions of that
report. Libraries whose first identifier is @code{srfi} are reserved
for libraries implementing @uref{http://srfi.schemer.org/,Scheme Requests for Implementation}.
It is inadvisable, but not an error, for identifiers
in library names to contain any of the characters @code{|} @code{\} @code{?}
@code{*} @code{<} @code{"} @code{:} @code{>} @code{+} @code{[} @code{]}
@code{/} @code {.} or control characters after escapes are
expanded.

See @ref{module-name} for how a @meta{library-name} is
mapped to a class name.

@display
@stxdef{library-declaration}
  @stxref{export-declaration}
  | @stxref{import-declaration}
  | @stxlit{(begin} @arbno{@stxref{statement}} @stxlit{)}
  | @stxlit{(include} @atleastone{@meta{filename}}@stxlit{)}
  | @stxlit{(include-ci} @atleastone{@meta{filename}}@stxlit{)}
  | @stxlit{(include-library-declarations} @atleastone{@meta{filename}}@stxlit{)}
  | @stxlit{(cond-expand} @arbno{@stxref{cond-expand-clause}} [@stxlit{(else} command-or-definition*@stxlit{)}]@stxlit{)}
  | @stxref{statement}
@end display

The @code{begin}, @code{include}, and @code{include-ci} declarations are
used to specify the body of the library. They have the
same syntax and semantics as the corresponding expression types.
This form of @code{begin} is analogous to, but not the
same as regular @code{begin}.
A plain @meta{statement} (which is allowed as a Kawa extension)
is also part of the body of the library,
as if it were wrapped in a @code{begin}).

The @code{include-library-declarations} declaration is similar
to @code{include} except that the contents of the file are
spliced directly into the current library definition. This
can be used, for example, to share the same @code{export} declaration
among multiple libraries as a simple form of library interface.

The @code{cond-expand} declaration has the same syntax and semantics
as the @code{cond-expand} expression type, except that
it expands to spliced-in library declarations rather than
expressions enclosed in @code{begin}.

When a library is loaded, its expressions are executed in
textual order. If a library’s definitions are referenced in
the expanded form of a program or library body, then that
library must be loaded before the expanded program or
library body is evaluated. This rule applies transitively. If
a library is imported by more than one program or library,
it may possibly be loaded additional times.

Similarly, during the expansion of a library @code{(foo)}, if any
syntax keywords imported from another library @code{(bar)} are
needed to expand the library, then the library @code{(bar)} must
be expanded and its syntax definitions evaluated before the
expansion of @code{(foo)}.

Regardless of the number of times that a library is loaded,
each program or library that imports bindings from a library must
do so from a single loading of that library, regardless
of the number of import declarations in which it
appears. That is, @code{(import (only (foo) a})) followed by
@code{(import (only (foo) b))} has the same effect as
@code{(import (only (foo) a b))}.

@subsection How a module becomes a class

If you want to just use a Scheme module as a module (i.e. @code{load}
or @code{require} it), you don't care how it gets translated
into a module class.  However, Kawa gives you some control over how this
is done, and you can use a Scheme module to define a class which
you can use with other Java classes.  This style of class definition
is an alternative to @code{define-class},
which lets you define classes and instances fairly conveniently.

The default name of the module class is the main part of the
filename of the Scheme source file (with directories and extensions
stripped off).  That can be overridden by the @code{-T} Kawa
command-line flag.  The package-prefix specified by the @code{-P}
flag is prepended to give the fully-qualified class name.

@anchor{module-name}
@deffn Syntax module-name name
@deffnx Syntax module-name <name>
@deffnx Syntax module-name @stxref{library-name}
Sets the name of the generated class, overriding the default.
If there is no @samp{.} in the @var{name}, the package-prefix
(specified by the @code{-P} Kawa command-line flag) is prepended.

If the form @meta{library-name} is used,
then the class name is the result of taking
each @meta{identifier} in the @meta{library-name-parts},
@ref{Mangling,mangling} if needed, and concatenating them
separated by periods.
For example @code{(org example doc-utils)} becomes
@code{org.example.doc-utils}.  (You can't reference the class name
@code{doc-utils} directly in Java, but the JVM has no problems with it.
In Java you can use reflection to access classes with such names.)

As a matter of style, @code{module-name} should be the first
command in a file (after possible comments).  It must appear
before a @code{require} or @code{import}, in case of cycles.
@end deffn

By default, the base class of the generated module class is unspecified;
you cannot count on it being more specific than @code{Object}.
However, you can override it with @code{module-extends}.

@deffn Syntax module-extends class
Specifies that the class generated from the immediately surrounding
module should extend (be a sub-class of) the class @code{@var{class}}.
@end deffn

@deffn Syntax module-implements interface ...
Specifies that the class generated from the immediately surrounding
module should implement the interfaces listed.
@end deffn

Note that the compiler does @emph{not} currently check that all the
abstract methods requires by the base class or implemented interfaces
are actually provided, and have the correct signatures.  This will
hopefully be fixed, but for now, if you are forgot a method, you will
probably get a verifier error

For each top-level exported definition the compiler creates a
corresponding public field with a similar (mangled) name.
By default, there is some indirection:  The value of the Scheme variable
is not that of the field itself.  Instead, the field is a
@code{gnu.mapping.Location} object, and the value Scheme variable is
defined to be the value stored in the @code{Location}.
Howewer, if you specify an explicit type, then the field will
have the specified type, instead of being a @code{Location}.
The indirection using @code{Location} is also avoided if you use
@code{define-constant}.

If the Scheme definition defines a procedure (which is not re-assigned
in the module), then the compiler assumes the variable as bound as a
constant procedure.  The compiler generates one or more methods
corresponding to the body of the Scheme procedure. It also generates
a public field with the same name; the value of the field is an
instance of a subclass of @code{<gnu.mapping.Procedure>} which when
applied will execute the correct method (depending on the actual arguments).
The field is used when the procedure used as a value (such as being passed
as an argument to @code{map}), but when the compiler is able to do so,
it will generate code to call the correct method directly.

You can control the signature of the generated method by declaring
the parameter types and the return type of the method.  See the
applet (@pxref{Applet compilation}) example for how this can be done.
If the procedures has optional parameters, then the compiler will
generate multiple methods, one for each argument list length.
(In rare cases the default expression may be such that this is
not possible, in which case an "variable argument list" method
is generated instead.  This only happens when there is a nested
scope @emph{inside} the default expression, which is very contrived.)
If there are @code{#!keyword} or @code{#!rest} arguments, the compiler
generate a "variable argument list" method.  This is a method whose
last parameter is either an array or a @code{<list>}, and whose
name has @code{$V} appended to indicate the last parameter is a list.

Top-leval macros (defined using either @code{define-syntax}
or @code{defmacro}) create a field whose type is currently a sub-class of
@code{kawa.lang.Syntax};  this allows importing modules to detect
that the field is a macro and apply the macro at compile time.

Unfortunately, the Java class verifier does not allow fields to have
arbitrary names.  Therefore, the name of a field that represents a
Scheme variable is "mangled" (@pxref{Mangling}) into an acceptable Java name.
The implementation can recover the original name of a field @code{X}
as @code{((gnu.mapping.Named) X).getName()} because all the standard
compiler-generated field types implement the @code{Named} interface.

@anchor{dual-purpose-class}
@subsection Same class for module and defined class

You can declare a class using @code{define-simple-class}
with the same name as the module class, for example the
following in a file named @code{foo.scm}:
@example
(define-simple-class foo ...)
@end example
In this case the defined class will serve dual-purpose as the module class.

To avoid confusion, in this case you must not specify
@code{module-extends}, @code{module-implements}, or @code{(module-static #t)}.
Also, the defined class should not have public static members.
In that case it works out pretty well: public static members
represent bindings exported by the module; other non-private members
``belong'' to the defined class.

In this case @code{(module-static 'init-run)} is implied.

@anchor{static-or-non-modules}
@subsection Static vs non-static modules

There are two kinds of module class:
A @dfn{static module} is a class (or gets compiled to a class)
all of whose public fields are static, and that does not have a
public constructor.  A JVM can only have a single global instance of
a static module.
An @dfn{instance module} has a public default constructor,
and usually has at least one non-static public field.
There can be multiple instances
of an instance module; each instance is called a @dfn{module instance}.
However, only a single instance of a module can be @dfn{registered}
in an environment, so in most cases there is only a single
instance of instance modules.  Registering an instance in an environment
means creating a binding mapping a magic name (derived from the class name)
to the instance.

In fact, any Java class class that has the properties of either
an instance module or a static module, is a module, and can be
loaded or imported as such;  the class need not have written
using Scheme.

You can control whether a module is compiled to a static or
a non-static class using either a command-line flag to the compiler,
or using the @code{module-static} special form.

@table @code
@item --module-static
Generate a static module
(as if @code{(module-static #t)} were specified).
This is (now) the default.
@item --module-nonstatic
@itemx --no-module-static
Generate a non-static module
(as if @code{(module-static #f)} were specified).
This used to be the default.
@item --module-static-run
Generate a static module
(as if @code{(module-static 'init-run)} were specified).
@end table

@deffn Syntax module-static name ...
@deffnx Syntax module-static @code{#t}
@deffnx Syntax module-static @code{#f}
@deffnx Syntax module-static @code{'init-run}
Control whether the generated fields and methods are static.
If @code{#t}  or @code{'init-run} is specified, then the module will be a
static module, @emph{all} definitions will be static.
If @code{'init-run} is specified, in addition the module body
is evaluated in the class's static initializer.
(Otherwise, it is run the first time it is @code{require}'d.)
Otherwise, the module is an instance module.  If there is a non-empty
list of @var{name}s then the module is an instance module, but the @var{name}s
that are explicitly listed will be compiled to static fields and methods.
If @code{#f} is specified, then all exported names will
be compiled to non-static (instance) fields and methods.

By default, if no @code{module-static} is specified:
@enumerate
@item
If there is a @code{module-extends} or @code{module-implements}
declaration, or one of the @code{--applet} or @code{--servlet}
command-line flags was specified, then @code{(module-static #f)} is implied.
@item
If one of the command-line flags
@code{--no-module-static}, @code{--module-nonstatic},
@code{--module-static}, or @code{--module-static-run} was specified,
then the default is @code{#f}, @code{#f}, @code{#t}, or @code{'init-run},
respectively.
@item
If the module class is @ref{dual-purpose-class,dual-purpose}
then @code{(module-static 'init-run)} is implied.
@item
Otherwise the default is @code{(module-static #t)}.
(It used to be @code{(module-static #f)} in older Kawa versions.)
@end enumerate

The default is @code{(module-static #t)}.  It usually produces more efficient
code, and is recommended if a module contains only procedure or macro
definitions. However, a static module means that all environments in a JVM
share the same bindings, which you may not want if you use
multiple top-level environments.
@end deffn

The top-level actions of a module will get compiled to a @code{run}
method.  If there is an explicit @code{method-extends}, then the
module class will also automatically implement @code{java.lang.Runnable}.
(Otherwise, the class does not implement @code{Runnable}, since in that
case the @code{run} method return an @code{Object} rather than @code{void}.
This will likely change.)

@subsection Module options

Certain compilation options can be be specified @emph{either}
on the command-line when compiling, or in the module itself.

@deffn Syntax module-compile-options [key@stxlit{:} value] ...
This sets the value of the @code{key} option to @code{value}
for the current module (source file).  It takes effect as
soon it is seen during the first macro-expansion pass,
and is active thereafter (unless overridden by @code{with-compile-options}).

The @var{key:} is one of the supported option names 
(The ending colon makes it a Kawa keyword). Valid
option keys are:

@itemize @bullet
@item
@stxlit{main:} - Generate an application, with a main method.
@end itemize

@itemize @bullet
@item
@stxlit{full-tailcalls:} - Use a calling convention that supports proper tail recursion.
@end itemize

@itemize @bullet
@item
@stxlit{warn-undefined-variable:} - Warn if no compiler-visible binding for a variable.

@item
@stxlit{warn-unknown-member:} - Warn if referencing an unknown method or field.

@item
@stxlit{warn-invoke-unknown-method:} - Warn if invoke calls an unknown method (subsumed by warn-unknown-member).

@item
@stxlit{warn-unused:} - Warn if a variable is usused or code never executed.

@item
@stxlit{warn-unreachable:} - Warn if this code can never be executed.
@item
@stxlit{warn-void-used:} - Warn if an expression depends on the value of a void sub-expression (one that never returns a value).
@item
@stxlit{warn-as-error:} - Treat a compilation warning as if it were an error.
@end itemize

The @var{value} must be a literal value: either a boolean
(@code{#t} or @code{#f}), a number, or a string,
depending on the @var{key}.
(All the options so far are boolean options.)

@example
(module-compile-options warn-undefined-variable: #t)
;; This causes a warning message that y is unknown.
(define (func x) (list x y))
@end example
@end deffn

@deffn Syntax with-compile-options [key: value] ... body
Similar to @code{module-compile-options}, but the option
is only active within @var{body}.

The module option key @code{main:} has no effect when applied 
to a particular body via the @code{with-compile-options} syntax.

@example
(define (func x)
  (with-compile-options warn-invoke-unknown-method: #f
    (invoke x 'size)))
@end example
@end deffn

@node Importing
@section Importing from a library

@anchor{require}
You can import a module into the current namespace with @code{import} or @code{require}.  This adds the exported bindings (or a subset of them) to the
current lexical scope.  It follows that these bindings (which are said
to be imported) are determined at compile-time.

@anchor{meta-import-declaration}
@deffn Syntax import @arbno{@stxref{import-set}}
An @code{import} declaration provides a way to import identifiers
exported by a library (module). Each @meta{import-set} names a set of
bindings from a library and possibly specifies local names
for the imported bindings.
@display
@stxdef{import-set}
    @meta{classname}
  | @stxref{library-reference}
  | @stxlit{(library} @stxref{library-reference} @stxlit{)}
  | @stxlit{(class} @var{class-prefix} @arbno{@var{import-only-name}}@stxlit{)}
  | @stxlit{(only} @stxref{import-set} @arbno{@var{import-only-name}}@stxlit{)}
  | @stxlit{(except} @stxref{import-set} @arbno{@var{identifier}}@stxlit{)}
  | @stxlit{(prefix} @stxref{import-set} @var{identifier} @stxlit{)}
  | @stxlit{(rename} @stxref{import-set} @arbno{@stxref{rename-pair}}@stxlit{)}
@stxdef{library-reference} @stxlit{(} @stxref{library-name-parts} [@stxref{explicit-source-name}]@stxlit{)}
@stxdef{import-only-name} @var{identifier}|@stxref{rename-pair}
@stxdef{explicit-source-name} @stxref{string}
@stxdef{rename-pair} @stxlit{(} @var{identifier}@sub{1} @var{identifier}@sub{2}@stxlit{)}
@end display

A @var{library-reference} is mapped to a class name by concatenating
all the identifiers, separated by dots.
For example:
@example
(import (gnu kawa slib srfi37))
@end example
is equivalent to:
@example
(import gnu.kawa.slib.srfi37)
@end example
as well as to:
@example
(require gnu.kawa.slib.srfi37)
@end example

By default, all of an imported library's exported bindings are made
visible within an importing library using the names given to the
bindings by the imported library.  The precise set of bindings to be
imported and the names of those bindings can be adjusted with the
@code{only}, @code{except}, @code{prefix}, and @code{ rename} forms as
described below.

@itemize
@item 
An @code{only} form produces a subset of the bindings from another
@meta{import-set}, including only the listed @meta{identifier}s.  The
included @meta{identifier}s must be in the original @meta{import-set}.
If a @var{rename-pair} is used, then the @code{@var{identifier}@sub{1}}
must be in the original @meta{import-set},
and is renamed to @code{@var{identifier}@sub{2}}.  For example:
@example
(import (only (kawa example) A (B1 B2) C (D1 D2)))
@end example
is equivalent to:
@example
(import (rename (only (kawa example) A B1 C D1)
                (B1 B2) (D1 D2)))
@end example
The names @code{A}, @code{B1}, @code{C}, and @code{D1} must
exist in the library @code{(kawa example)}.  The bindings are
accessible using the names @code{A}, @code{B2}, @code{C}, and @code{D2}.

@item 
An @code{except} form produces a subset of the bindings from another
@meta{import-set}, including all but the listed @meta{identifier}s.  All
of the excluded @meta{identifier}s must be in the original @meta{import-set}.

@item 
A @code{prefix} form adds the @meta{identifier} prefix to each name from
another @meta{import-set}.

@item 
A @code{rename} form:
@example
(rename (@var{identifier}@sub{1} @var{identifier}@sub{2}) @dots{})
@end example
@noindent
removes the bindings for @code{@var{identifier}@sub{1} @dots{}} to form an
intermediate @meta{import-set}, then adds the bindings back for the
corresponding @code{@var{identifier}@sub{2} @dots{}} to form the final
@meta{import-set}.  Each @code{@var{identifier}@sub{1}} must be in the original
@meta{import-set}, each @var{identifier}@sub{2} must not be in the
intermediate @meta{import-set}, and the @var{identifier}@sub{2}s must be
distinct.
@end itemize

A @code{class} form is a convenient way to define abbreviations
for class names; it may be more convenient than @code{define-alias}.
The @var{class-prefix} is concatenated with each @meta{identifier}
(with a period in between) to produce a classname.
Each @meta{identifier} becomes an alias for the class.
For example:
@example
(import (class java.util Map (HashMap HMap)))
@end example
This defines @code{Map} as an alias for @code{java.util.Map},
and @code{HMap} as an alias for @code{java.util.HashMap}.
(You can think of the @code{class} form as similar to a @code{only} form,
where the @var{class-prefix} names a special kind of
library represented of a Java package, and whose exported
bindings are the classes in the package.)

You can combine the @code{class} form with
@code{only}, @code{except}, @code{rename}, and @code{prefix},
though only @code{prefix} is likely to be useful.  For example:
@example
(import (prefix (class java.lang Long Short) jl-))
@end example
is equivalent to
@example
(import (class java.lang (Long jl-Long) (Short jl-Short)))
@end example
which is equivalent to:
@example
(define-private-alias jl-Short java.lang.Short)
(define-private-alias jl-Long java.lang.Long)
@end example
@end deffn

@deffn Syntax require @stxlit{'}featureName
@deffnx Syntax require classname [@stxref{explicit-source-name}]
@deffnx Syntax require @stxref{explicit-source-name}]
Search for a matching module (class), and add the names
exported by that module to the current set of visible names.
Normally, the module is specified using @var{classname}.

The form @code{require} has similar functionality as @code{import},
but with a different syntax, and without options like @code{rename}.

If a @code{@stxlit{"}@var{sourcepath}@stxlit{"}} is specified then
that is used to locate the source file for the module, and if necessary,
compile it.

If a @code{'@var{featurename}} is specified then the
@var{featurename} is looked up (at compile time) in the "feature table"
which yields the implementing @var{classname}.
@end deffn

@deffn Syntax provide @stxlit{'}featurename
Declare that @code{'@var{featurename}} is available.
A following @code{cond-expand} in this scope will match @var{featurename}.
@end deffn

Using @code{require} and @code{provide} with @var{featurename}s is
similar to the same-named macros in SLib, Emacs, and Common Lisp.
However, in Kawa these are not functions, but instead they
are syntax forms that are processed at compile time.  That is
why only quoted @var{featurename}s are supported.
This is consistent with Kawa emphasis on compilation and
static binding.

For some examples, you may want to look in the @code{gnu/kawa/slib}
directory.

@subsection Searching for modules

When Kawa sees a @code{import} or @code{require} it searches for
either a matching source file or a previously-compiled class with a
matching name.

For @code{import} we generate a classname by converting it in the same
way @code{module-name} does:  taking each identifier in the
@meta{library-name-parts}, mangling if needed, and concatenating the parts
separated by periods.

If there is a matching module in any @meta{program-unit} that is
in the process of being compiled, we use that.  This may be
a file requested to be compiled with the @code{-C} command-line switch,
or an extra @meta{library-definition} in a file already parsed.
Kawa will attempt to finish compiling the module and load the class,
but if there are circular dependencies it will use the uncompiled definitions.

Next Kawa looks for a matching class in the context classpath.
(There is special handling if the library-name starts with @code{srfi},
and certain builtin classes will have @code{kawa.lib.} prepended.)

Kawa also searches for a matching source file, described below.
It uses the implicit source name (formed by concatenating the
library-name parts, separated by @code{"/"}), as well as
any @meta{explicit-source-name}.  The source file is parsed as
a @stxref{program-unit}.  It is an error if the @meta{program-unit}
does not declare a library (explicit or implicit) with the
matching name.

If Kawa finds both a matching source file and a class, it will pick one
based on which is newer.

@subsection Searching for source files

The Java property @code{kawa.import.path} controls how @code{import}
and @code{require} search for a suitable source file.  Example usage:
@example
$ kawa -Dkawa.import.path=".:<foo fo>/opt/fo-libs/*.scm:/usr/local/kawa"
@end example

The value of the @code{kawa.import.path} property is a list of
path elements, separated by @code{":"}.
Each path element is combined with either the explicit source name
or the implicit source name to produce a filename.
If a matching file exists, then we have found a source file.

If a path element contains a @code{"*"} then the @code{"*"}
is replaced by the implicit source name (without an extension).
(Any explicit source name is ignored in this case.)
For example, for @code{(import (foo bar))} or @code{(require foo.bar)}
the implicit source name is @code{"foo/bar"}.  If the path element is
@code{"/opt/kawa/*.sc"} then the resulting filename is @code{"/opt/kawa/foo/bar.sc"}.

If there is no @code{"*"} in the path element, and there is an
explicit source, then it is appended to the path element
(or replaces the path element if the explicit source is absolute).
Otherwise we use the implicit source, followed by the default file extension.
(The default file extension is that of the current source if that is a
named file; otherwise the default for the current language, which
is @code{".scm"}  for Scheme.)

A path element that starts with a selector of the
form @code{"<@stxref{library-name-parts}>"} is only applicable if a prefix
of the requested module name matches the @meta{library-name-parts}.  If there
is @code{"*"} in the path element, that is replaced by the corresponding rest
of the implicit source name. For example if importing @code{(fee fo foo fum})
and the path element is @code{"<fee fo>/opt/fo-libs/*.scm"} then the
resulting filename is @code{"/opt/fo-libs/foo/fum.scm"}.
If there is a selector but no @code{"*"}, then the rest of the path element
following the selector is combined with the explicit or implicit source
as if there were no selector (assuming of course that the selector matches).

If the resulting filename is relative, then it is resolved
relative to the @dfn{current root}.  For example the source to
a library with the name @code{(x y)} that compiles to
a class @code{x.y} might be a  file named @code{/a/b/x/y.scm}.
Then the current root would be @code{/a/b/}
- that is the directory that results from removing the library name
suffix from the file name.

More generally: assume the current module has @math{N} name components.
For example the name @code{(x y)}
(with the class name @code{x.y}) has 2 components.
The current root is what you get when you take the current file name
(say @code{"/a/b/c/d.scm"}), and remove everything after
the @math{N}'th slash (@code{"/"}) from the end (say @code{"c/d.scm"};
what remains (e.g. @code{"/a/b/"} is the current root.
(If the current input source is not a named file,
use the value of @code{(current-path)} with a @code{"/"} appended.)

The default search path is @code{"."} - i.e. just search relative
to the current root.

@subsection Builtin libraries

The following libraries are bundled with Kawa:

@table @code
@item (scheme base)
@itemx (scheme case-lambda)
@itemx (scheme char)
@itemx (scheme complex)
@itemx (scheme cxr)
@itemx (scheme cxr)
@itemx (scheme eval)
@itemx (scheme inexact)
@itemx (scheme lazy)
@itemx (scheme load)
@itemx (scheme process-context)
@itemx (scheme read)
@itemx (scheme repl)
@itemx (scheme time)
@itemx (scheme write)
@itemx (scheme r5rs)
The above are standard libraries as defined by R7RS.
@item (rnrs arithmetic bitwise)
@itemx (rnrs hashtables)
@itemx (rnrs lists)
@itemx (rnrs programs)
@itemx (rnrs sorting)
@itemx (rnrs unicode)
The above are standard libraries as defined by R6RS.
@item (kawa reflect)
Defines procedures and syntax for acessing Java objects and members:
  @code{as}
  @code{field}
  @code{instance?}
  @code{invoke}
  @code{invoke-static}
  @code{invoke-special}
  @code{make}
  @code{primitive-throw}
  @code{set-field!}
  @code{set-static-field!}
  @code{static-field}
@item (kawa expressions)
@itemx (kawa hashtable)
@itemx (kawa quaternions)
@itemx (kawa rotations)
@itemx (kawa regex)
@itemx (kawa string-cursors)
Various Kawa libraries @i{add details}.
@item (kawa base)
All the bindings by default available to the kawa top-level.
@end table

@subsection Importing a SRFI library

Importing a supported SRFI numbered @var{N} is conventionally
doing using a @code{(import (srfi @var{N}))}
or the older R6RS syntax @code{(import (srfi :@var{N}))} (with a colon, for historical reasons).  You can also give it
a name, as specified by @uref{http://srfi.schemers.org/srfi-95/srfi-95.html,SRFI 95}. For example, any of these work:
@example
(import (srfi 95))
(import (srfi 95 sorting-and-merging))
(import (srfi :95))
(import (srfi :95 sorting-and-merging))
@end example
You can also use @code{(require 'srfi-@var{N})}:
@example
(require 'srfi-95)
@end example

@subsection Importing from a plain class

Note you can import from many classes, even if they weren't
compiled from a library-definition.  The set of @code{public} fields
in a class are considered as the set of exported definitions,
with the names demangled as needed.

The module can be static module (all public fields must be static),
or an instance module (it has a public default constructor).

If an imported definition is a non-static field and if no module
instance for that class
has been registered in the current environment, then a new instance
is created and registered (using a "magic" identifier).
If the module class either inherits from @code{gnu.expr.ModuleBody}
or implements @code{java.lang.Runnable} then the corresponding @code{run}
method is executed.  (This is done @emph{after} the instance is
registered so that cycles can be handled.)  These actions (creating,
registering, and running the module instance) are done both at compile
time and at run time, if necessary.

All the imported fields of the module class are then incorporated
in the current set of local visible names in the current module.
(This is for both instance and static modules.)
This is done at compile time - no new bindings are created at run-time
(except for the magic binding used to register the module instance),
and the imported bindings are private to the current module.
References to the imported bindings will be compiled as field
references, using the module instance (except for static fields).

@node Record types
@section Record types

The @code{define-record-type} form can be used for creating new data
types, called record types. A predicate, constructor, and field
accessors and modifiers are defined for each record type.
The @code{define-record-type} feature is specified
by @uref{http://srfi.schemers.org/srfi-9/srfi-9.html,SRFI-9},
which is implemented by many modern Scheme implementations.

@deffn Syntax define-record-type @var{type-name} (@var{constructor-name} @var{field-tag} ...) @var{predicate-name} (@var{field-tag} @var{accessor-name} [@var{modifier-name}]) ...

The form @code{define-record-type} is generative: each use creates a new
record type that is distinct from all existing types, including other
record types and Scheme's predefined types. Record-type definitions may
only occur at top-level (there are two possible semantics for `internal'
record-type definitions, generative and nongenerative, and no consensus
as to which is better).

An instance of @code{define-record-type} is equivalent to the following definitions:
@itemize
@item
The @var{type-name} is bound to a representation of the record type
itself.
@item
The @var{constructor-name} is bound to a procedure that takes
as many arguments as there are @var{field-tag}s in the
@code{(@var{constructor-name} ...)} subform and returns
a new @var{type-name} record. Fields whose tags are listed with
@var{constructor-name} have the corresponding argument as their initial
value. The initial values of all other fields are unspecified.
@item
The @var{predicate-name} is a predicate that returns @code{#t}
when given a value returned by @var{constructor-name}
and @code{#f} for everything else.
@item
Each @var{accessor-name} is a procedure that takes a record of
type @var{type-name} and returns the current value of the corresponding field.
It is an error to pass an accessor a value which is not a record of the
appropriate type.
@item
Each @var{modifier-name} is a procedure that takes a record of
type @var{type-name} and a value which becomes the new value of
the corresponding field.
The result (in Kawa) is the empty value @code{#!void}.
It is an error to pass a
modifier a first argument which is not a record of the appropriate type.
@end itemize

Set!ing the value of any of these identifiers has no effect on the
behavior of any of their original values.
@end deffn

Here is an example of how you can define a record type named @code{pare}
with two fields @code{x} and @code{y}:
@example
(define-record-type pare
  (kons x y)
  pare?
  (x kar set-kar!)
  (y kdr))
@end example

The above defines @code{kons} to be a constructor,
@code{kar} and @code{kdr} to be accessors,
@code{set-kar!} to be a modifier,
and @code{pare?} to be a predicate for @code{pare}s.
@example
(pare? (kons 1 2))        @result{} #t
(pare? (cons 1 2))        @result{} #f
(kar (kons 1 2))          @result{} 1
(kdr (kons 1 2))          @result{} 2
(let ((k (kons 1 2)))
  (set-kar! k 3)
  (kar k))                @result{} 3
@end example

Kawa compiles the record type into a nested class.
If the @code{define-record-type} appears at module level,
the result is a class that is a member of the module class.
For example if the above @code{pare} class is define in a
module @code{parelib}, then the result is a class
named @code{pare} with the internal JVM name @code{parelib$pare}.
The @code{define-record-type} can appear inside a procedure,
in which case the result is an inner class.

The nested class has a name derived from
the @var{type-name}.  If the @var{type-name} is valid Java class name,
that becomes the name of the Java class.  If the @var{type-name} has
the form @code{<@var{name}>} (for example @code{<pare>}), then @var{name}
is used, if possible, for the Java class name.  Otherwise, the name
of the Java class is derived by "mangling" the @var{type-name}.
In any case, the package is the same as that of the surrounding module.

Kawa generates efficient code for the resulting functions,
without needing to use run-time reflection.

@node Dynamic records, Method operations, Record types, Objects Classes and Modules
@section Creating New Record Types On-the-fly

Calling the @code{make-record-type} procedure creates a new record data
type at run-time, without any compile-time support.
It is primarily provided for compatibility; in most cases it is better
to use the @code{define-record-type} form (@pxref{Record types}).

@deffn Procedure make-record-type type-name field-names
Returns a @dfn{record-type descriptor}, a value representing a new data
type disjoint from all others.  The @var{type-name} argument must be a
string, but is only used for debugging purposes (such as the printed
representation of a record of the new type).  The @var{field-names}
argument is a list of symbols naming the @dfn{fields} of a record of the
new type.  It is an error if the list contains any duplicates.
@end deffn

@c @deffn Procedure make-record-sub-type type-name field-names rtd
@c Returns a @dfn{record-type descriptor}, a value representing a new data
@c type, disjoint from all others.  The @var{type-name} argument must be a
@c string.  The @var{field-names} argument is a list of symbols naming the
@c additional @dfn{fields} to be appended to @var{field-names} of
@c @var{rtd}.  It is an error if the combinded list contains any
@c duplicates.@refill
@c
@c Record-modifiers and record-accessors for @var{rtd} work for the new
@c record-sub-type as well.  But record-modifiers and record-accessors for
@c the new record-sub-type will not neccessarily work for @var{rtd}.@refill
@c @end deffn

@deffn Procedure record-constructor rtd [field-names]
Returns a procedure for constructing new members of the type represented
by @var{rtd}.  The returned procedure accepts exactly as many arguments
as there are symbols in the given list, @var{field-names}; these are
used, in order, as the initial values of those fields in a new record,
which is returned by the constructor procedure.  The values of any
fields not named in that list are unspecified.  The @var{field-names}
argument defaults to the list of field names in the call to
@code{make-record-type} that created the type represented by @var{rtd};
if the @var{field-names} argument is provided, it is an error if it
contains any duplicates or any symbols not in the default list.

@c In Kawa, @var{rtd} may be any @code{Class} that has a public default
@c constructor, as long as the @var{field-names} are public instance
@c fields.  (The fields should have type @code{Object} -- unless you
@c know what you are doing!)
@end deffn

@deffn Procedure record-predicate rtd
Returns a procedure for testing membership in the type represented by
@var{rtd}.  The returned procedure accepts exactly one argument and
returns a true value if the argument is a member of the indicated record
type; it returns a false value otherwise.

@c In Kawa, the returned procedure checks if the argument is an instance
@c of @var{rtd} or one of its sub-classes.
@end deffn

@c @deffn Procedure record-sub-predicate rtd
@c Returns a procedure for testing membership in the type represented by
@c @var{rtd} or its parents.  The returned procedure accepts exactly one
@c argument and returns a true value if the argument is a member of the
@c indicated record type or its parents; it returns a false value
@c otherwise.@refill
@c @end deffn

@deffn Procedure record-accessor rtd field-name
Returns a procedure for reading the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly one argument which must be a record of the appropriate
type; it returns the current value of the field named by the symbol
@var{field-name} in that record.  The symbol @var{field-name} must be a
member of the list of field-names in the call to @code{make-record-type}
that created the type represented by @var{rtd}.
@end deffn

@deffn Procedure record-modifier rtd field-name
Returns a procedure for writing the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly two arguments: first, a record of the appropriate type,
and second, an arbitrary Scheme value; it modifies the field named by
the symbol @var{field-name} in that record to contain the given value.
The returned value of the modifier procedure is unspecified.  The symbol
@var{field-name} must be a member of the list of field-names in the call
to @code{make-record-type} that created the type represented by @var{rtd}.
@end deffn

@deffn Procedure record? obj
Returns a true value if @var{obj} is a record of any type and a false
value otherwise.
@end deffn

@deffn Procedure record-type-descriptor record
Returns a record-type descriptor representing the type of the given
record.  That is, for example, if the returned descriptor were passed to
@code{record-predicate}, the resulting predicate would return a true
value when passed the given record.
@end deffn

@deffn Procedure record-type-name rtd
Returns the type-name associated with the type represented by rtd.  The
returned value is @code{eqv?} to the @var{type-name} argument given in
the call to @code{make-record-type} that created the type represented by
@var{rtd}.@refill
@end deffn

@deffn Procedure record-type-field-names rtd
Returns a list of the symbols naming the fields in members of the type
represented by @var{rtd}.  The returned value is @code{equal?} to the
field-names argument given in the call to @code{make-record-type} that
created the type represented by @var{rtd}.@refill
@end deffn

Records are extensions of the class @code{Record}.
These procedures use the Java 1.1 reflection facility.

@node Method operations, Allocating objects, Dynamic records, Objects Classes and Modules
@section Calling Java methods from Scheme

You can call a Java method as if it were a Scheme procedure
using various mechanisms.

@subsection Calling static methods using colon notation

The easiest way to invoke a static method is to use
@ref{Colon notation, colon notation}, specifically:
@display
@stxlit{(}@var{class-expression}@stxlit{:}@var{method-name} @var{argument} ...@stxlit{)}
@end display

The @var{class-expression} can be a class in the current lexical
scope, such as a class defined using @code{define-simple-class}:
@example
(define-simple-class MyClass ()
  ((add2 x y) allocation: 'static (+ x y)))
(MyClass:add2 3 4) @result{} 7
@end example

Often @var{class-expression} is a fully-qualified class name:
@example
(java.lang.Math:sqrt 9.0) @result{} 3.0
@end example

This is only allowed when the name is of a class that exists
and is accessible both at compile-time and run-time,
and the name is not otherwise lexically bound.

You can also use a defined alias:
@example
(define-alias jlMath java.lang.Math)
(jlMath:sqrt 16.0) @result{} 4.0
@end example

You can even evaluate @var{class-expression} at run-time
(in which case Kawa may have to use slower reflection):
@example
(let ((math java.lang.Math)) math:sqrt 9.0) @result{} 3.0
@end example

Here @code{java.lang.Math} evaluates to a @code{java.lang.Class}
instance for the named class (like Java's @code{java.lang.Class.class},
again assuming the class exists and is accessible both at compile-time and
run-time, and the name is not otherwise lexically bound.

@subsection Calling instance methods using colon notation

The syntax is:
@display
@stxlit{(}@var{instance}@stxlit{:}@var{method-name} @var{argument} ...@stxlit{)}
@end display
This invokes the method named @var{method-name}
with the evaluated  @var{instance} as the target object
and the evaluated @var{argument}s as the method arguments.

For example:
@example
((list 9 8 7):toString) @result{} "(9 8 7)"
([5 6 7]:get 2) @result{} 7
@end example

This older syntax is also available:
@display
@stxlit{(*:}@var{method-name} @var{instance} @var{argument} ...@stxlit{)}
@end display

For example:
@example
(*:toString (list 9 8 7))
@end example

You can also name the class explicitly:
@display
@stxlit{(}@var{class-expression}@stxlit{:}@var{method-name} @var{instance} @var{argument} ...@stxlit{)}
@end display
For example:
@example
(java.util.List:get [5 6 7] 2) @result{} 7
@end example
Using an explicit class is like coercing the @var{instance}:
@display
@stxlit{(*:}@var{method-name} @stxlit{(as }@var{class-expression} @var{instance} @stxlit{)}@var{argument} ...@stxlit{)}
@end display

Note that for some special values,
including @code{java.lang.Class} instances, you can't
use the compact form of @ref{Colon notation, colon notation}
where the @var{instance} is before the comma:
@example
(java.lang.Integer:getDeclaredField "MAX_VALUE") @result{} @i{error}
@end example
This is because in this case we look for a static member
of @code{java.lang.Integer}
(at least as currently defined and implemented),
while we want an instance member of @code{java.lang.Class}.
In those cases you can use one of
these alternative forms, which all return the same
@code{java.lang.reflect.Field} result:
@example
(*:getDeclaredField java.lang.Integer "MAX_VALUE")
(java.lang.Class:getDeclaredField java.lang.Integer "MAX_VALUE")
(invoke java.lang.Integer 'getDeclaredField "MAX_VALUE")
@end example

@subsection Method names

The method to invoke is selected using the specified
method name and argments.  If specified name is not a Java name,
it is "mangled" (@pxref{Mangling}) into a valid Java name.
All accessible methods whose names match are considered.
Methods that match after appending @code{$V} or @code{$X} or @code{$V$X}
are also considered.  A @code{$V} suffix matches a variable
number of arguments:  any excess arguments are collect into an
@code{gnu.lists.LList} or a Java array (depending on the final parameter type).
A @code{$X} specifies that the method expects an extra implicit
@code{CallContext} parameter.  In that case the method's result is written
to the @code{CallContext}, so the method result type must be @code{void}.

(Kawa may compile a procedure with a @code{#!rest} or keyword args
whose name is @code{@var{fn}} to a method named @code{@var{fn}$V}.
It adds an implicit parameter for the extra arguments.
By default this extra extra parameter is a Scheme list.
You can specify a Java array type instead, in which case the method is
named @code{@var{fn}} without the @code{$V},
and instead it is marked as a Java-5 varargs method.
The array element type must be compatible with all the extra arguments.)

@subsection Invoking a method with the @code{invoke} function

If you prefer, you can instead use the following functions.
(There is also an older deprecated lower-level interface
(@pxref{Low-level Method invocation}.)

@deffn Procedure invoke-static class name args ...
The @var{class} can be a @code{java.lang.Class}, a
@code{gnu.bytecode.ClassType}, or a @code{symbol} or @code{string}
that names a Java class.  The @var{name} can be @code{symbol} or
@code{string} that names one or more methods in the Java class.

Any accessible methods (static or instance) in the specified @var{class}
(or its super-classes) that match "@var{name}" or "@var{name}$V" collectively
form a generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the first actual argument is used as the @code{this} argument.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, @code{WrongType} is thrown.

An example:
@example
(invoke-static java.lang.Thread 'sleep 100)
@end example

The behavior of interpreted code and compiled code is not
identical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the @code{invoke-static} call
if it can pick a single "best" matching method.
@end deffn

@deffn Procedure invoke object name args ...
The @var{name} can be @code{<symbol>} or
@code{<string>} that names one or more methods in the Java class.

Any accessible methods (static or instance) in the specified @var{class}
(or its super-classes) that match "@var{name}" or "@var{name}$V" collectively
form a generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the @var{object} is used as the @code{this} argument;
otherwise @var{object} is prepended to the @var{args} list.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, @code{WrongType} is thrown.

The behavior of interpreted code and compiled code is not
indentical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the @code{invoke-static} call
if it can pick a single "best" matching method.

If the compiler cannot determine the method to call (assuming
the method name is constant), the compiler has to generate code
at run-time to find the correct method.  This is much slower,
so the compiler will print a warning.  To avoid a waning, you can
use a type declaration, or insert a cast:
@example
(invoke (as java.util.Date my-date) 'setDate cur-date)
@end example
or
@example
(let ((my-date ::java.util.Date (calculate-date))
      (cur-date ::int (get-cur-date)))
  (invoke my-date 'setDate cur-date))
@end example
@end deffn

@deffn Procedure invoke-special class receiver-object name arg ...
The @var{class} can be a @code{java.lang.Class}, a
@code{gnu.bytecode.ClassType}, or a @code{symbol} or @code{string}
that names a Java class.  
The @var{name} can be @code{symbol} or
@code{string} that names one or more methods in the Java class.

This procedure is very similar to @code{invoke} and @code{invoke-static}
and invokes the specified method, ignoring any methods in subclasses
that might overide it.  One interesting use is to invoke a method in
your super-class like the Java language @code{super} keyword.

Any methods in the specified @var{class} that match "@var{name}" or
"@var{name}$V" collectively form a generic procedure.  That generic
procedure is then applied as in @code{invoke} using the
@code{receiver-object} and the arguments (if any).

The compiler must be able to inline this procedure (because you cannot
force a specific method to be called using reflection).  Therefore the
@var{class} and @var{name} must resolve at compile-time to a specific
method.

@example
(define-simple-class <MyClass> (<java.util.Date>)
  ((get-year) :: <int>
   (+ (invoke-special <java.util.Date> (this) 'get-year)) 1900)
  ((set-year (year :: <int>)) :: <void>
   (invoke-special <java.util.Date> (this) 'set-year (- year 1900))))
@end example
@end deffn

@deffn Procedure class-methods class name
Return a generic function containing those methods of @var{class}
that match the name @var{name}, in the sense of @code{invoke-static}.
Same as:
@example
(lambda args (apply invoke-static (cons class (cons name args))))
@end example
@end deffn

Some examples using these functions are @samp{vectors.scm}
and @samp{characters.scm} the directory @samp{kawa/lib} in
the Kawa sources.

@subsection Using a namespace prefix

@emph{This way of invoking a method is deprecated.}

You can use @code{define-namespace} to define an alias for a Java class:
@example
(define-namespace Int32 "class:java.lang.Integer")
@end example
In this example the name @code{Int32} is a @dfn{namespace alias}
for the namespace whose full name is @code{"class:java.lang.Integer"}.
The full name should be the 6 characters @code{"class:"} followed
by the fully-qualified name of a Java class.

Instead of a @var{vamespace-uri} you can use a variable that names
a class, usually of the form @code{<@var{classname}>}.
The following is equivalent to the above:
@example
(define-namespace Int32 <java.lang.Integer>)
@end example
However, there is one important difference: The @code{<@var{classname}>}
is first searched in the lexical scope.
It may resolve to a class defined in the current compilation unit
(perhaps defined using @code{define-simple-class}),
or imported from another module,
or an alias (such as from @code{define-alias}).
Only if @code{<@var{classname}>} is @emph{not} found in the current
scope is it tried as the class name @var{classname}.

You can name a method using a @dfn{qualified name} containing a colon.
The part of the name before the colon is a namespace alias (in
this case @code{Int32}), and the part of the name after the colon is the
method name.  For example:
@example
(Int32:toHexString 255) @result{} "ff"
@end example
This invokes the static method @code{toHexString} in the
Java class @code{java.lang.Integer}, passing it the argument @code{255},
and returning the String @code{"ff"}.

The general syntax is
@example
(@var{prefix}:@var{method-name} @var{arg} ...)
@end example
This invokes the method named @var{method-name} in the class corresponding
to @var{prefix}, and the @var{arg}s are the method arguments.

You can use the method name @code{new} to construct new objects:
@example
(Int32:new '|255|)
@end example
This is equivalent to the Java expression @code{new Integer("255")}.
You can also write:
@example
(Int32:new "255")
@end example

You can also call instance methods using a namespace prefix:
@example
(Int32:doubleValue (Int32:new "00255"))
@end example
This returns the @code{double} value @code{255.0}.

As a shorthand, you can use the name of a Java class instead of a
namespace alias:
@example
(java.lang.Integer:toHexString 255)
(java.lang.Object:toString some-value)
@end example
If Kawa sees a qualified name with a prefix that is not defined @emph{and}
that matches the name of a known class, then Kawa will automatically
treat the prefix
as a nickname for namespace uri like @code{class:java.lang.Integer}.
Both conditions should be true at both compile-time and run-time.
However, using an explicit @code{define-namespace} is recommended.

As a final shorthand you can use an identifier in handle brackets,
such as an existing type alias like @code{<list>}.
The following are all equivalent:
@example
(<list>:list3 'a 'b 'c)
@end example
This is equivalent to:
@example
(define-namespace @var{prefix} <list>
(@var{prefix}:list3 'a 'b 'c)
@end example
for some otherwise-unused @var{prefix}.

@node Allocating objects, Field operations, Method operations, Objects Classes and Modules
@section  Allocating objects

The recommended way to create an instance of a type @var{T}
is to ``call'' @var{T} as if it were a function, with the
arguments used to initialize the object.
If @code{T} is a class and @code{T} has a matching constructor,
then the arguments will used for constructor arguments:
@example
(java.util.StringTokenizer "this/is/a/test" "/")
@end example
(You can think of the type @var{T} as being
coerced to an instance-constructor function.)

If @code{T} is a container or collection type,
then typically the arguments will be used to specify
the child or component values.
Many standard Scheme procedures fit this convention.
For example in Kawa @code{list} and @code{vector} evaluate to
types, rather than procedures as in standard Scheme,
but because types can be used as constructor functions it just works:
@example
(list 'a (+ 3 4) 'c) @result{} (a 7 c)
(vector 'a 'b 'c) @result{} #(a b c)
@end example
Any class @code{T} that has a default constructor
and an @code{add} method can be initialized this way.
Examples are @code{java.util} collection classes,
and @code{jawa.awt} and @code{javax.swing} containers.
@example
(java.util.ArrayList 11 22 33) @result{} [11, 22, 333]
@end example
The above expression is equivalent to:
@example
(let ((tmp (java.util.ArrayList)))
  (tmp:add 11)
  (tmp:add 22)
  (tmp:add 33)
  tmp)
@end example

Allocating Java arrays (@pxref{Creating-new-Java-arrays}) uses a
similar pattern:
@example
(int[] 2 3 5 7 11)
@end example

Sometimes you want to set some named property to an initial value.
You can do that using a keyword argument.  For example:
@example
(javax.swing.JButton text: "Do it!" tool-tip-text: "do it")
@end example

This is equivalent to using @dfn{setter methods}:
@example
(let ((tmp (javax.swing.JButton)))
  (tmp:setText "Do it!")
  (tmp:setToolTipText "do it")
  tmp)
@end example

A keyword argument @code{@var{key-name}}@stxlit{:} can
can translated to either a @code{@stxlit{set}@var{KeyName}@stxlit{:}}
or a  @code{@stxlit{add}@var{KeyName}@stxlit{:}} method.
The latter makes it convenient to add listeners:

@example
(javax.swing.JButton
  text: "Do it!"
  action-listener:
   (object (java.awt.event.ActionListener)
     ((actionPerformed e) (do-the-action))))
@end example
This is equivalent to: 
@example
(let ((tmp (javax.swing.JButton)))
  (tmp:setText "Do it!")
  (tmp:addActionListener
    (object (java.awt.event.ActionListener)
      ((actionPerformed e) (do-the-action))))
  tmp)
@end example

Making use of so-called ``SAM-conversion'' (@pxref{SAM-conversion})
 makes it even more convenient:
@example
(javax.swing.JButton
  text: "Do it!"
  action-listener:
   (lambda (e) (do-the-action)))
@end example

The general case allows for a mix of
constructor arguments, property keywords, and child values:
@display
@var{class-type} @stxref{constructor-value}... @stxref{property-initializer}... @stxref{child-value}...
@stxdef{constructor-value} @stxref{expression}
@stxdef{property-initializer} @stxref{keyword} @stxref{expression}
@stxdef{child-value} @stxref{expression}
@end display

First an object is constructed with the @var{constructor-value} arguments
(if any) passed to the object constructor; 
then named properties (if any) are used to initialize named properties;
and then remaining arguments are used to add child values.

There is an ambiguity if there is no @var{property-initializer} -
we can't distinguish between a @var{constructor-value}
and a @var{child-value}.
In that case, if there is a matching constructor method, then all of the
arguments are constructor arguments;
otherwise, there must a default constructor, and all
of the arguments are @var{child-value} arguments.

There is a trick you can you if you need both
@var{constructor-value} and @var{child-value} arguments:
separate them with an ``empty keyword'' @code{||:}.
This matches a method named @code{add}, which means that
the next argument effectively a @var{child-value} - as do
all the remaining arguments. Example:
@example
(let ((vec #(1 2 3)))
  (java.util.ArrayList vec ||: 4 5 6))
  @result{} [1, 2, 3, 4, 5, 6]
@end example

The compiler rewrites these allocations expression
to generated efficient bytecode, assuming that the ``function''
being applied is a type known by the compiler.
Most of the above expressions also work if the type is applied
at run-time, in which case Kawa has to use slower reflection:
@example
(define iarr int[])
(apply iarr (list 3 4 5)) @result{} [3 4 5]
@end example
However @code{add@var{Xxx}} methods and SAM-conversion
are currently only recognized in the case of a class known at compile-time,
not at run-time.

Here is a working Swing demo illustrating many of these techniques:

@example
(import (class javax.swing
               JButton Box JFrame))
(define-simple-class HBox (Box)
  ((*init*) (invoke-special Box (this) '*init* 0)))

(define value 0)

(define txt
  (javax.swing.JLabel
   text: "0"))

(define (set-value i)
  (set! value i)
  (set! txt:text (number->string i)))

(define fr
  (JFrame
     title: "Hello!"
     (Box 1#|VERTICAL|# ||:
      (javax.swing.Box:createGlue)
      txt
      (javax.swing.Box:createGlue)
      (HBox
       (JButton ;; uses 1-argument constructor
	"Decrement" ;; constructor argument
	tool-tip-text: "decrement"
	action-listener: (lambda (e) (set-value (- value 1))))
       (javax.swing.Box:createGlue)
       (JButton ;; uses 0-argument constructor
	text: "Increment"
	tool-tip-text: "increment"
	action-listener: (lambda (e) (set-value (+ value 1))))))))
(fr:setSize 200 100)
(set! fr:visible #t)
@end example

If you prefer, you can use the older @code{make} special function:

@deffn Procedure make type args ...
Constructs a new object instance of the specified @var{type},
which must be either a @code{java.lang.Class} or a
@code{<gnu.bytecode.ClassType>}.
Equivalent to:
@example
@var{type} @var{args} ...
@end example
@end deffn

Another (semi-deprecated) function is to use the colon notation
with the @code{new} pseudo-function.
The following three are all equivalent:
@example
(java.awt.Point:new x: 4 y: 3)
(make java.awt.Point: x: 4 y: 3)
(java.awt.Point x: 4 y: 3)
@end example 

@node Field operations, Mangling, Allocating objects, Objects Classes and Modules
@section Accessing object fields

@subsection Accessing static fields and properties

The recommmended way to access fields 
uses the @ref{Colon notation, colon notation}.
For static fields and properties the following is recommended:
@display
@var{class-expression}@stxlit{:}@var{field-name}
@end display
For example:
@example
java.lang.Integer:MAX_VALUE
@end example

A property with a @code{get} method is equivalent to a field.
The following are all equivalent:
@example
java.util.Currency:available-currencies
java.util.Currency:availableCurrencies
(java.util.Currency:getAvailableCurrencies)
@end example

Just like for a method call, the @var{class-expression}
can be a class in the current lexical scope,
a fully-qualified class name, or more generally an
expression that evaluates to a class.

@subsection Accessing instance fields and properties

The syntax is:
@display
@var{instance}@stxlit{:}@var{field-name}
@end display

The @var{field-name} can of course be the name of an actual
object field, but it can also be the name of a property with
a zero-argument @code{get} method.
For example, if @code{cal} is a @code{java.util-Calendar} instance,
then the following are all equivalent:
@example
cal:time-zone
cal:timeZone
(cal:getTimeZone)
(cal:get-time-zone)
@end example

You can use colon notation to assign to a field:
@example
(set! cal:time-zone TimeZone:default)
@end example
which is equivalent to:
@example
(cal:setTimeZone (TimeZone:getDefault))
@end example

A Java array only has the @code{length} field, plus the @code{class} property:
@example
(int[] 4 5 6):length @result{} 3
(int[] 4 5 6):class:name @result{} "int[]"
@end example

@subsection Using field and static-field methods

The following methods are useful in cases where colon notation
is ambiguous, for example where there are both fields and methods
with the same name.
You might also prefer as a matter of style, to
emphasise that a field is being accessed.

@deffn Procedure field object fieldname
Get the instance field with the given @var{fieldname} from the given
@var{Object}.  Returns the value of the field, which must be accessible.
This procedure has a @code{setter}, and so can be used as the first
operand to @code{set!}.

The field name is "mangled" (@pxref{Mangling}) into a valid Java name.
If there is no accessible field whose name is @code{"@var{fieldname}"},
we look for a no-argument method whose name is
@code{"get@var{Fieldname}"} (or @code{"is@var{Fieldname}"} for a
boolean property).

If @var{object} is a primitive Java array, then @var{fieldname} can only
be @code{'length}, and the result is the number of elements of the array.
@end deffn

@deffn Procedure static-field class fieldname
Get the static field with the given @var{fieldname} from the given
@var{class}.  Returns the value of the field, which must be accessible.
This procedure has a @code{setter}, and so can be used as the first
operand to @code{set!}.

If the @var{fieldname} is the special name @code{class},
then it returns the @code{java.lang.Class} object corresponding to
@var{class} (which is usually a @code{gnu.bytecode.ClassType} object).
@end deffn

Examples:
@example
(static-field java.lang.System 'err)
;; Copy the car field of b into a.
(set! (field a 'car) (field b 'car))
@end example

@deffn Procedure slot-ref object fieldname
A synonym for @code{(field @var{object} @var{fieldname})}.
@end deffn

@deffn Procedure slot-set! object fieldname value
A synonym for @code{(set! (field @var{object} @var{fieldname}) @var{value})}.
@end deffn

@subsection Older colon-dot notation

There is older syntax where following the colon
there is field name a following the colon @emph{and} a period.

To access an static field named @var{field-name} use this syntax
@example
(@var{prefix}:.@var{field-name} @var{instance})
@end example
The @var{prefix} can be as discussed in @xref{Method operations}.
Here are 5 equivalent ways:
@example
(java.lang.Integer:.MAX_VALUE)
(<java.lang.Integer>:.MAX_VALUE)
(define-namespace Int32 <java.lang.Integer>)
(Int32:.MAX_VALUE)
(define-namespace Integer "class:java.lang.Integer")
(Integer:.MAX_VALUE)
(define-alias j.l.Integer java.lang.Integer)
(j.l.Integer:.MAX_VALUE)
@end example
You can set a static field using this syntax:
@example
(set! (@var{prefix}:.@var{field-name}) @var{new-value})
@end example

The special field name @code{class} can be used to extract the
@code{java.lang.Class} object for a class-type.  For example:
@example
(java.util.Vector:.class) @result{} class java.util.Vector
@end example

To access a instance field named @var{field-name} use the following syntax.
Note the period before the @var{field-name}.
@example
(*:.@var{field-name} @var{instance})
@end example
This syntax works with @code{set!} - to set the field use this syntax:
@example
(set! (*:.@var{field-name} @var{instance}) @var{new-value})
@end example
Here is an example:
@example
(define p (list 3 4 5))
(*:.cdr p) @result{} (4 5)
(set! (*:.cdr p) (list 6 7))
p @result{} (3 6 7)
@end example

You can specify an explicit class:
@example
(@var{prefix}:.@var{field-name} @var{instance})
@end example
If @var{prefix} is bound to @code{<@var{class}>}, then the above
is equivalent to:
@example
(*:.@var{field-name} (as <@var{class}> @var{instance}))
@end example

@node Mangling, Scheme types in Java, Field operations, Objects Classes and Modules
@section Mapping Scheme names to Java names

Programs use "names" to refer to various values and procedures.
The definition of what is a "name" is different in different
programming languages.  A name in Scheme (and other Lisp-like
languages) can in principle contain any character (if using a
suitable quoting convention), but typically names consist of
"words" (one or more letters) separated by hyphens, such
as @samp{make-temporary-file}.  Digits
and some special symbols are also used.  Traditionally, Scheme is
case-insensitive;  this means that the names @samp{loop},
@samp{Loop}, and @samp{LOOP} are all the same name.  Kawa
is by default case-sensitive, but we recommend that you
avoid using upper-case letters as a general rule.

The Java language and the Java virtual machine uses names for
classes, variables, fields and methods.
Names in the Java language can contain upper- and lower-case letters,
digits, and the special symbols @samp{_} and @samp{$}.
The Java virtual machine (JVM) allows most characters, but still
has some limitations.

Kawa translates class names, package names, field names, and local variable
names using the
@uref{https://blogs.oracle.com/jrose/entry/symbolic_freedom_in_the_vm,''symbolic'' convention}, so most characters are unchanged.
For example the Scheme function @samp{file-exists?}
becomes the field @samp{file-exists?}, but @code{dotted.name}
becomes @samp{dotted\,name}.
Such names may not be valid Java name, so to access them from a
Java program you might have to use reflection.

When translating procedure names to method names,
Kawa uses a different translation, in order to achieve
more ``Java-like'' names. This means translating a
Scheme-style name like @samp{make-temporary-file} to
"mixed-case" words, such as @samp{makeTemporaryFile}.
The basic rule is simple:  Hyphens are dropped, and
a letter that follows a hyphen is translated to its
upper-case (actually "title-case") equivalent.  Otherwise,
letters are translated as is.

Some special characters are handled specially.  A final @samp{?}
is replaced by an @emph{initial} @samp{is}, with the following
letter converted to titlecase.  Thus @samp{number?} is
converted to @samp{isNumber} (which fits with Java conventions),
and @samp{file-exists?} is converted to @samp{isFileExists}
(which doesn't really).
The pair @samp{->} is translated to @samp{$To$}.
For example @samp{list->string} is translated to @samp{list$To$string}.

Some symbols are mapped to a mnemonic sequence, starting with a dollar-sign,
followed by a two-character abbreviation.  For example, the less-than
symbol @samp{<} is mangled as @samp{$Ls}.
See the source code to the @code{mangleName} method in the
@code{gnu.expr.Mangling} class for the full list.
Characters that do not have a mnemonic abbreviation are
mangled as @samp{$} followed by a four-hex-digit unicode value.
For example @samp{Tamil vowel sign ai} is mangled as @samp{$0bc8}.

Note that this mapping may map different Scheme names to the
same Java name.  For example @samp{string?}, @samp{String?},
@samp{is-string}, @samp{is-String},
and @samp{isString} are all mapped to the same Java identifier
@samp{isString}.  Code that uses such "Java-clashing" names
is @emph{not} supported.  There is very partial support for
renaming names in the case of a clash, and there may be better
support in the future.  However, some of the nice features of
Kawa depend on being able to map Scheme name to Java names
naturally, so we urge you to @emph{not} write code that
"mixes" naming conventions by using (say) the names @samp{open-file}
and @samp{openFile} to name two different objects.

@node Scheme types in Java, Array operations, Mangling, Objects Classes and Modules
@section Scheme types in Java

All Scheme values are implemented by sub-classes of @samp{java.lang.Object}.

Scheme symbols are implemented using @code{java.lang.String}.
(Don't be confused by the fact the Scheme sybols are represented
using Java Strings, while Scheme strings are represented by
@code{gnu.lists.FString}.  It is just that the semantics of Java strings
match Scheme symbols, but do not match mutable Scheme strings.)
Interned symbols are presented as interned Strings.
(Note that with JDK 1.1 string literals are automatically interned.)

Scheme integers are implemented by @code{gnu.math.IntNum}.
Use the make static function to create a new IntNum from an int or a long.
Use the intValue or longValue methods to get the int or long value of
an IntNum.

A Scheme "flonum" is implemented by @code{gnu.math.DFloNum}.

A Scheme pair is implemented by @code{gnu.lists.Pair}.

A Scheme vector is implemented by @code{gnu.lists.FVectror}.

Scheme characters are implemented using @code{gnu.text.Char}.

Scheme strings are implemented using @code{gnu.lists.FString}.

Scheme procedures are all sub-classes of @code{gnu.mapping.Procedure}.
The "action" of a @samp{Procedure} is invoked by using one of
the @samp{apply*} methods:  @samp{apply0}, @samp{apply1},
@samp{apply2}, @samp{apply3}, @samp{apply4}, or @samp{applyN}.
Various sub-class of @samp{Procedure} provide defaults
for the various @samp{apply*} methods.  For example,
a @samp{Procedure2} is used by 2-argument procedures.
The @samp{Procedure2} class provides implementations of all
the @samp{apply*} methods @emph{except} @samp{apply2},
which must be provided by any class that extends @code{Procedure2}.

@node Array operations, Loading Java functions into Scheme, Scheme types in Java, Objects Classes and Modules
@section Using Java Arrays

@anchor{Creating-new-Java-arrays}
@subsection Creating new Java arrays
To allocate a Java array you can use the array type specifier
as a constructor function.  For example, to allocate an array with room for 10 elements
each of each is a primitive @code{int}:
@example
(int[] length: 10)
@end example

You can specify the initial elements instead of the length:
@example
(object[] 31 32 33 34)
@end example
This creates a 4-length array, initialized to the given values.

Note this is a variation of the generation object-allocation
(@pxref{Allocating objects}) pattern.  You can explicitly
use the @code{make} function, if you prefer:
@example
(make object[] 31 32 33 34)
@end example

If you specify a length, you can also specify initial values for selected
elements.
If you specify an index, in the form of a literal integer-valued keyword,
then following elements are placed starting at that position.
@example
(int[] length: 100 10 12 80: 15 16 50: 13 14)
@end example
This creates an array with 100 elements.  Most of them are initialized
to the default value of zero,
but elements with indexes 0, 1, 50, 51, 80, 81 are initialized
to the values 10, 12, 13, 14, 15, 16, respectively.

@subsection Accessing Java array elements

You can access the elements of a Java array by treating it as
a one-argument function, where the argument is the index:
@example
(define primes (integer[] 2 3 5 7 11 13))
(primes 0) @result{} 2
(primes 5) @result{} 13
@end example

You can set an element by treating the array as a function
with a @code{setter}:
@example
(set! (primes 0) -2)
(set! (primes 3) -7)
primes @result{} [-2 3 5 -7 11 13]
@end example

To get the number of elements of an array, you can treat
it as having a @code{length} field:
@example
primes:length @result{} 6
@end example

Here is a longer example.  This is the actual definition of the
standard @code{gcd} function.  Note the @code{args} variable
receives all the arguments on the form of an @code{integer} array.
(This uses the Java5 varargs feature.)
@example
(define (gcd #!rest (args ::integer[])) ::integer
  (let ((n ::int args:length))
    (if (= n 0)
	0
	(let ((result ::integer (args 0)))
	  (do ((i ::int 1 (+ i 1)))
	      ((>= i n) result)
	    (set! result (gnu.math.IntNum:gcd result (args i))))))))
@end example

The above example generates good code,
thanks to judicious use of casts and type specifications.
In general, if Kawa knows that
a ``function'' is an array then it will generate efficient
bytecode instructions for array operations.

@subsection Old low-level array macros

The deprecated @ref{Low-level array macros} are also supported.

@node Loading Java functions into Scheme, Evaluating Scheme expressions from Java, Array operations, Objects Classes and Modules
@section Loading Java functions into Scheme

When @code{kawa -C} compiles (@pxref{Files compilation}) a Scheme module
it creates a class that implements the @code{java.lang.Runnable} interface.
(Usually it is a class that extends the @code{gnu.expr.ModuleBody}.)
It is actually fairly easy to write similar "modules" by hand in Java,
which is useful when you want to extend Kawa with  new "primitive functions"
written in Java.  For each function you need to create an object that
extends @code{gnu.mapping.Procedure}, and then bind it in the global
environment.  We will look at these two operations.

There are multiple ways you can create a @code{Procedure} object.  Below
is a simple example, using the @code{Procedure1} class, which is class
extending @code{Procedure} that can be useful for one-argument
procedure.  You can use other classes to write procedures.  For example
a @code{ProcedureN} takes a variable number of arguments, and you must
define @code{applyN(Object[] args)} method instead of @code{apply1}.
(You may notice that some builtin classes extend @code{CpsProcedure}.
Doing so allows has certain advantages, including support for
full tail-recursion, but it has some costs, and is a bit trickier.)

@example
import gnu.mapping.*;
import gnu.math.*;
public class MyFunc extends Procedure1
@{
  // An "argument" that is part of each procedure instance.
  private Object arg0;

  public MyFunc(String name, Object arg0)
  @{
    super(name);
    this.arg0 = arg0;
  @}

  public Object apply1 (Object arg1)
  @{
    // Here you can so whatever you want. In this example,
    // we return a pair of the argument and arg0.
    return gnu.lists.Pair.make(arg0, arg1);
  @}
@}
@end example

You can create a @code{MyFunc} instance and call it from Java:
@example
  Procedure myfunc1 = new MyFunc("my-func-1", Boolean.FALSE);
  Object aresult = myfunc1.apply1(some_object);
@end example
The name @code{my-func-1} is used when @code{myfunc1} is printed
or when @code{myfunc1.toString()} is called.  However,
the Scheme variable @code{my-func-1} is still not bound.
To define the function to Scheme, we can create
a "module", which is a class intended to be loaded
into the top-level environment.  The provides the definitions to be
loaded, as well as any actions to be performed on loading 

@example
public class MyModule
@{
  // Define a function instance.
  public static final MyFunc myfunc1
    = new MyFunc("my-func-1", IntNum.make(1));
@}
@end example

If you use Scheme you can use @code{require}:
@example
#|kawa:1|# (require <MyModule>)
#|kawa:2|# (my-func-1 0)
(1 0)
@end example

Note that @code{require} magically defines @code{my-func-1} without
you telling it to.  For each public final
field, the name and value of the field are entered in the
top-level environment when the class is loaded.  (If there are
non-static fields, or the class implements @code{Runnable}, then
an instance of the object is created, if one isn't available.)
If the field value is a @code{Procedure} (or implements @code{Named}),
then the name bound to the procedure is used instead of the field name.
That is why the variable that gets bound in the Scheme environment is
@code{my-func-1}, not @code{myfunc1}.

Instead of @code{(require <MyModule>)}, you can do @code{(load "MyModule")}
or @code{(load "MyModule.class")}.
If you're not using Scheme, you can use Kawa's @code{-f} option:
@example
$ kawa -f MyModule --xquery --
#|kawa:1|# my-func-1(3+4)
<list>1 7</list>
@end example

If you need to do some more complex calculations when a module is loaded,
you can put them in a @code{run} method, and have the module
implement @code{Runnable}:

@example
public class MyModule implements Runnable
@{
  public void run ()
  @{
    Interpreter interp = Interpreter.getInterpreter();
    Object arg = Boolean.TRUE;
    interp.defineFunction (new MyFunc ("my-func-t", arg));
    System.err.println("MyModule loaded");
  @}
@}
@end example

Loading @code{MyModule} causes @code{"MyModule loaded"} to be printed,
and @code{my-func-t} to be defined.  Using @code{Interpreter}'s
@code{defineFunction} method is recommended because it does the righ
things even for languages like Common Lisp that use separate
"namespaces" for variables and functions.

A final trick is that you can have a @code{Procedure} be its own module:

@example
import gnu.mapping.*;
import gnu.math.*;
public class MyFunc2 extends Procedure2
@{
  public MyFunc(String name)
  @{
    super(name);
  @}

  public Object apply2 (Object arg1, arg2)
  @{
    return gnu.lists.Pair.make(arg1, arg2);
  @}

  public static final MyFunc myfunc1 = new MyFunc("my-func-2);
@}
@end example

@node Evaluating Scheme expressions from Java, , Loading Java functions into Scheme, Objects Classes and Modules
@section Evaluating Scheme expressions from Java

The following methods are recommended if you need to evaluate a
Scheme expression from a Java method.
(Some details (such as the @samp{throws} lists) may change.)

@deftypefn {Static method} void Scheme.registerEnvironment ()
Initializes the Scheme environment.  Maybe needed if you
try to load a module compiled from a Scheme source file.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (InPort @var{port}, Environment @var{env})
Read expressions from @var{port}, and evaluate them in the
@var{env} environment, until end-of-file is reached.
Return the value of the last expression,
or @code{Interpreter.voidObject} if there is no expression.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (String @var{string}, Environment @var{env})
Read expressions from @var{string}, and evaluate them in the
@var{env} environment, until the end of the string is reached.
Return the value of the last expression,
or @code{Interpreter.voidObject} if there is no expression.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (Object @var{sexpr}, Environment @var{env})
The @var{sexpr} is an S-expression (as may be returned by @code{read}).
Evaluate it in the @var{env} environment, and return the result.
@end deftypefn

For the @code{Environment} in most cases you could use
@samp{Environment.current()}.  Before you start, you
need to initialize the global environment,
which you can do with
@example
Environment.setCurrent(new Scheme().getEnvironment());
@end example

Alternatively, rather than setting the global environment,
you can use this style:
@example
Scheme scm = new Scheme();
Object x = scm.eval("(+ 3 2)");
System.out.println(x);
@end example

@subsection Using @code{javax.script} portable Java scripting

Kawa also supports the standard
@uref{http://docs.oracle.com/javase/8/docs/api/javax/script/package-summary.html,@code{javax.script}} API.
The main advantage of this API is if you want your users to be able to choose
between multiple scripting languages.  That way you can support Kawa
without Kawa-specific programming.

For example the standard JDK tool @uref{http://docs.oracle.com/javase/8/docs/technotes/tools/unix/jrunscript.html,jrunscript} provides a
read-eval-print-loop for any language that implements the  @code{javax.script}
API.  It knows nothing about Kawa but can still use it:
@example
$ jrunscript -cp kawa.jar -l scheme
scheme> (cadr '(3 4 5))
4
@end example

(Of course the @code{jrunscript} REPL isn't as  nice as the one that
Kawa provides.  For example the latter can handle multi-line inputs.)

@node XML tools
@chapter Working with XML and HTML

Kawa has a number of features for working with XML, HTML,
and generated web pages.

In Kawa you don't write XML or HTML directly.
Instead you write expressions that evaluate to ``node objects''
corresponding to elements, attributes, and text.
You then write these node objects using either an XML or HTML format.

Many web-page-generating tools require you to work directly
with raw HTML, as for example:
@example
(display "<p>Don't use the <code>&lt;blink&gt;</code> tag.</p>")
@end example

In Kawa you would instead do:
@example
(display (html:p "Don't use the " (html:code "<blink>") " tag."))
@end example

The conversion from node objects to XML or HTML is handled by
the formatter (or serializer).
Some advantages of doing it this way are:
@itemize
@item
You don't have to worry about quoting special characters.
Missing or incorrect quoting is a common source of bugs
and security problems on systems that work directly with text, such as PHP.
@item
Some errors, such as mismatched element tags, are automatically avoided.
@item
The generated XML can be validated as it is generated,
or even using compile-time type-checking.  (Kawa doesn't yet do either.)
@item
In an application that also reads XML,
you can treat XML that is read in and XML that is generated using
the same functions.
@end itemize

@menu
* Formatting XML::
* Creating HTML nodes::
* Creating XML nodes::
* XML literals::
* Server-side scripts::  Writing web-server-side Kawa scripts
* Self-configuring page scripts::
* Servlets::             Installing Kawa programs as Servlets
* CGI scripts::          Installing Kawa programs as CGI scripts
* HTTP requests::        Functions for accessing HTTP requests
* HTTP response::        Functions for generating HTTP response
* XML beyond Scheme::    Using non-Scheme languages for XML/HTML
@end menu

@node Formatting XML, Creating HTML nodes, , XML tools
@section Formatting XML

The easiest way to generate HTML or XML output is to run Kawa
with the appropriate @ref{Named output formats, , @code{--output-format} option}.

The intentation is that these output modes should be compatible with
@uref{http://www.w3.org/TR/2006/PR-xslt-xquery-serialization-20061121/,
XSLT 2.0 and XQuery 1.0 Serialization}.
(However, that specifies many options, most
of which have not yet been implemented.

@table @code
@item xml
Values are printed in XML format.
"Groups" or "elements" are written as using xml element syntax.
Plain characters (such as @samp{<}) are escaped (such as @samp{&lt;}).
@item xhtml
Same as @code{xml}, but follows the xhtml compatibility guidelines.
@item html
Values are printed in HTML format.
Mostly same as @code{xml} format, but certain elements without body,
are written without a closing tag.   For example @code{<img>} is written
without @code{</img>}, which would be illegal for html, but required for xml.
Plain characters (such as @samp{<}) are not escaped inside @code{<script>}
or @code{<style>} elements.
@end table

To illustrate:
@example
$ kawa --output-format html
#|kawa:1|# (html:img src:"img.jpg")
<img src="img.jpg">
@end example
@example
$ kawa --output-format xhtml
#|kawa:1|# (html:img src:"img.jpg")
<img xmlns="http://www.w3.org/1999/xhtml" src="img.jpg" />
@end example
@example
$ kawa --output-format xml
#|kawa:1|# (html:img src:"img.jpg")
<img xmlns="http://www.w3.org/1999/xhtml" src="img.jpg"></img>
@end example
And here is the default @code{scheme} formatting:
@example
$ kawa
#|kawa:1|# (html:img src:"img.jpg")
(@{http://www.w3.org/1999/xhtml@}img src: img.jpg )
@end example

@deffn Procedure as-xml value
Return a value (or multiple values) that when printed will
print @var{value} in XML syntax.
@example
(require 'xml)
(as-xml (make-element 'p "Some " (make-element 'em "text") "."))
@end example
prints @code{<p>Some <em>text</em>.</p>}.
@end deffn

@deffn Procedure unescaped-data data
Creates a special value which causes @code{data} to be printed,
as is, without normal escaping.  For example, when the output format
is XML, then printing @code{"<?xml?>"} prints as @samp{&lt;?xml?&gt;},
but @code{(unescaped-data "<?xml?>")} prints as  @samp{<?xml?>}.
@end deffn

@node Creating HTML nodes, Creating XML nodes, Formatting XML, XML tools
@section Creating HTML nodes

The @code{html} prefix names a special namespace
(@pxref{Namespaces}) of functions to create HTML element nodes.
For example, @code{html:em} is a constructor that
when called creates a element node whose tag is @code{em}.
If this element node is formatted as HTML, the
result has an @code{<em>} tag.

@deffn Syntax html:@var{tag} attributes ... content ...
Creates an element node whose tag is @var{tag}.
The parameters are first zero or more attributes, followed
by zero of more child values.
An attribute is either an attribute value (possibly
created using @code{make-attribute}), or a pair of arguments:
A keyword followed by the attribute value.
Child values are usually either strings (text content),
or nested element nodes, but can also be comment or processing-instruction
nodes.
@example
(html:a href: "http://gnu.org/" "the "(html:i "GNU")" homepage")
@end example
@end deffn

The compound identifier @code{html:@var{tag}} is actually
a type: When you call it as a function you're using Kawa's
standard coercion of a type to its constructor function.
This means you can do type tests:
@example
(define some-node ...)
(if (instance? some-node html:blink)
  (error "blinking not allowed!"))
@end example

Object identity is currently not fully specified.  Specifically,
it is undefined if a nested (child) element node is copied
``by value'' or ``by reference''.  This is related to whether
nodes have a parent reference.  In the XPath/XQuery data model
nodes do have a parent reference, and child nodes are conceptually
copied.  (In the actual implemention copying is commonly avoided.)
Kawa/Scheme currently followed the XQuery copying semantics,
which may not be the most appropriate for Scheme.

@node Creating XML nodes, XML literals, Creating HTML nodes, XML tools
@section Creating XML nodes

The XML data model is similar to HTML, with one important addition:
XML tags may be @dfn{qualified names}, which are similar
to @ref{Namespaces, , compound symbols}.

You must do this to use the following types and functions:
@example
(require 'xml)
@end example

The following types and functions assume:
@example
(require 'xml)
@end example

@deffn Procedure make-element tag [attribute ...] child ...
Create a representation of a XML element, corresponding to
@example
<@var{tag} @var{attribute}...>@var{child}...</@var{tag}>
@end example
The result is a @code{TreeList}, though if the result context is a consumer
the result is instead "written" to the consumer.
Thus nested calls to @code{make-element} only result in a
single @code{TreeList}.
More generally, whether an @var{attribute} or @var{child} is includded
by copying or by reference is (for now) undefined.
The @var{tag} should currently be a symbol, though in the future it should
be a qualified name.
An @var{attribute} is typically a call to @code{make-attribute},
but it can be any attribute-valued expression.
@example
(make-element 'p
	      "The time is now: "
	      (make-element 'code (make <java.util.Date>)))
@end example
@end deffn

@deffn Procedure element-name element
Returns the name (tag) of the element node, as a symbol (QName).
@end deffn

@deffn Procedure make-attribute name value...
Create an "attribute", which is a name-value pair.
For now, @var{name} should be a symbol.
@end deffn

@deffn Procedure attribute-name element
Returns the name of the attribute node, as a symbol (QName).
@end deffn

@deffn Type comment
Instances of this type represent comment values,
specifically including comments in XML files.
Comment nodes are currently ignored when printing using Scheme formatting,
though that may change.
@end deffn
@deffn Constructor comment comment-text
Create a comment object with the specified @var{comment-text}.
@end deffn

@deffn Type processing-instruction
Instances of this type represent ``processing instructions'',
such as may appear in XML files.
Processing-instruction nodes are currently ignored when printing using
Scheme formatting, though that may change.
@end deffn
@deffn Constructor processing-instruction target contents
Crreate a processing-instruction object with the specified @var{target}
(a simple symbol) and @var{contents} (a string).
@end deffn

@node XML literals, Server-side scripts, Creating XML nodes, XML tools
@section XML literals

You can write XML literals directly in Scheme code,
following a @code{#}.
Notice that the outermost element needs to be prefixed
by @code{#}, but nested elements do not (and must not).
@example
#<p>The result is <b>final</b>!</p>
@end example

Actually, these are not really literals since they can contain
enclosed expressions:
@example
#<em>The result is &@{result@}.</em>
@end example
The value of @var{result} is substituted into the output,
in a similar way to quasi-quotation.
(If you try to quote one of these ``XML literals'',
what you get is unspecified and is subject to change.)

An @var{xml-literal} is usually an element constructor,
but there some rarely used forms (processing-instructions,
comments, and CDATA section) we'll cover later.

@display
@stxdef{xml-literal} @stxlit{#}@stxref{xml-constructor}
@stxdef{xml-constructor} @stxref{xml-element-constructor}
  | @stxref{xml-PI-constructor}
  | @stxref{xml-comment-constructor}
  | @stxref{xml-CDATA-constructor}
@end display

@subsection Element constructors

@display
@stxdef{xml-element-constructor}
    @stxlit{<}@stxref{QName} @stxref{xml-attribute}*@stxlit{>}@stxref{xml-element-datum}...@stxlit{</}@stxref{QName} @stxlit{>}
  | @stxlit{<}@stxref{xml-name-form} @stxref{xml-attribute}*@stxlit{>}@stxref{xml-element-datum}...@stxlit{</>}
  | @stxlit{<}@var{xml-name-form} @stxref{xml-attribute}*@stxlit{/>}
@stxdef{xml-name-form} @stxref{QName}
  | @stxref{xml-enclosed-expression}
@stxdef{xml-enclosed-expression}
    @stxlit{@lbracechar{}}@stxref{expression}@stxlit{@rbracechar{}}
  | @stxlit{(}@stxref{expression}...@stxlit{)}
@end display

The first @var{xml-element-constructor} variant uses a literal @var{QName},
and looks like standard non-empty XML element, where the starting @var{QName}
and the ending @var{QName} must match exactly:

@example
#<a href="next.html">Next</a>
@end example

As a convenience, you can leave out the ending tag(s):
@example
This is a paragraph in <emphasis>DocBook</> syntax.</>
@end example

You can use an expression to compute the element tag at runtime -
in that case you @emph{must} leave out the ending tag:
@example
#<p>This is <(if be-bold 'strong 'em)>important</>!</p>
@end example

You can use arbitrary @var{expression} inside curly braces,
as long as it evaluates to a symbol.
You can leave out the curly braces
if the @var{expression} is a simple parenthesised compound expression.
The previous example is equivalent to:
@example
#<p>This is <@{(if be-bold 'strong 'em)@}>important</>!</p>
@end example

The third @var{xml-element-constructor} variant above is an XML
``empty element''; it is equivalent to the second variant
when there are no @var{xml-element-datum} items.

(Note that every well-formed XML element, as defined in the XML specifications,
is a valid @var{xml-element-constructor}, but not vice versa.)

@subsection Elements contents (children)

The ``contents'' (children) of an element
are a sequence of character (text) data, and nested nodes.
The characters @code{&}, @code{<}, and @code{>} are special,
and need to be escaped.

@display
@stxdef{xml-element-datum}
    any character except @code{&}, or @code{<}.
  | @stxref{xml-constructor}
  | @stxref{xml-escaped}
@stxdef{xml-escaped}
    @stxlit{&}@stxref{xml-enclosed-expression}
  | @stxlit{&}@stxref{xml-entity-name}@stxlit{;}
  | @stxref{xml-character-reference}
@stxdef{xml-character-reference}
    @stxlit{&#}@stxref{digit}+@stxlit{;}
  | @stxlit{&#x}@stxref{hex-digit}+@stxlit{;}
@end display

Here is an example shows both hex and decimal character references:
@example
#<p>A&#66;C&#x44;E</p>  @result{}  <p>ABCDE</p>
@end example

@display
@stxdef{xml-entity-name} @stxref{identifier}
@end display
Currently, the only supported values for @var{xml-entity-name}
are the builtin XML names @code{lt}, @code{gt}, @code{amp},
@code{quot}, and @code{apos}, which stand for the characters
@code{<}, @code{>}, @code{&}, @code{"}, and @code{'}, respectively.
The following two expressions are equivalent:
@example
#<p>&lt; &gt; &amp; &quot; &apos;</p>
#<p>&@{"< > & \" '"@}</p>
@end example

@subsection Attributes

@display
@stxdef{xml-attribute}
    @stxref{xml-name-form}@stxlit{=}@stxref{xml-attribute-value}
@stxdef{xml-attribute-value}
    @stxlit{"}@stxref{quot-attribute-datum}*@stxlit{"}
  | @stxlit{'}@stxref{apos-attribute-datum}*@stxlit{'}
@stxdef{quot-attribute-datum}
    any character except @code{"}, @code{&}, or @code{<}.
  | @stxref{xml-escaped}
@stxdef{apos-attribute-datum}
    any character except @code{'}, @code{&}, or @code{<}.
  | @stxref{xml-escaped}
@end display

If the @var{xml-name-form} is either @code{xmlns} or
a compound named with the prefix @code{xmlns}, then
technically we have a namespace declaration, rather than
an attribute.

@subsection QNames and namespaces

The names of elements and attributes are @dfn{qualified names}
(QNames), which are represented using compound symbols (@pxref{Namespaces}).
The lexical syntax for a QName is either a simple identifier,
or a (prefix,local-name) pair:

@display
@stxdef{QName} @stxref{xml-local-part}
   | @stxref{xml-prefix}@stxlit{:}@stxref{xml-local-part}
@stxdef{xml-local-part} @stxref{identifier}
@stxdef{xml-prefix} @stxref{identifier}
@end display

An @var{xml-prefix} is an alias for a namespace-uri,
and the mapping between them is defined by a namespace-declaration.
You can either use a @code{define-namespace} form, or you
can use a @dfn{namespace declaration attribute}:

@display
@stxdef{xml-namespace-declaration-attribute}
    @stxlit{xmlns:}@stxref{xml-prefix}@stxlit{=}@stxref{xml-attribute-value}
  | @stxlit{xmlns=}@stxref{xml-attribute-value}
@end display

The former declares @var{xml-prefix} as a namespace alias for
the namespace-uri specified by @var{xml-attribute-value}
(which must be a compile-time constant).
The second declares that @var{xml-attribute-value} is the default
namespace for simple (unprefixed) element tags.
(A default namespace declaration is ignored for attribute names.)

@example
(let ((qn (element-name #<gnu:b xmlns:gnu="http://gnu.org/"/>)))
  (list (symbol-local-name qn)
        (symbol-prefix qn)
        (symbol-namespace-uri qn)))
@result{} ("b" "gnu" "http://gnu.org/")

@end example

@subsection Other XML types

@subsubsection Processing instructions

An @var{xml-PI-constructor} can be used to create an XML
@dfn{processing instruction}, which can be used to pass
instructions or annotations to an XML processor (or tool).
(Alternatively, you can use the @code{processing-instruction}
type constructor.)

@display
@stxdef{xml-PI-constructor} @stxlit{<?}@stxref{xml-PI-target} @stxref{xml-PI-content}@stxlit{?>}
@stxdef{xml-PI-target} @var{NCname} (i.e. a simple (non-compound) identifier)
@stxdef{xml-PI-content} any characters, not containing @code{?>}.
@end display

For example, the DocBook XSLT stylesheets can use the @code{dbhtml}
instructions to specify that a specific chapter should be
written to a named HTML file:
@example
#<chapter><?dbhtml filename="intro.html" ?>
<title>Introduction</title>
...
</chapter>
@end example

@subsubsection XML comments

You can cause XML comments to be emitted in the XML output document.
Such comments can be useful for humans reading the XML document,
but are usually ignored by programs.
(Alternatively, you can use the @code{comment} type constructor.)

@display
@stxdef{xml-comment-constructor} @stxlit{<!--}@stxref{xml-comment-content}@stxlit{-->}
@stxdef{xml-comment-content} any characters, not containing @code{--}.
@end display

@subsubsection CDATA sections

A @code{CDATA} section can be used to avoid excessive use of
@var{xml-entity-ref} such as @code{&amp;} in element content.

@display
@stxdef{xml-CDATA-constructor} @stxlit{<![CDATA[}@stxref{xml-CDATA-content}@stxlit{]]>}
@stxdef{xml-CDATA-content} any characters, not containing @code{]]>}.
@end display

The following are equivalent:
@example
#<p>Specal characters <![CDATA[< > & ' "]]> here.</p>
#<p>Specal characters &lt; &gt; &amp; &quot; &apos; here.</p>
@end example

Kawa remembers that you used a @code{CDATA} section in
the @var{xml-element-constructor} and will write it out
using a @code{CDATA} constructor.

@node Server-side scripts, Self-configuring page scripts, XML literals, XML tools
@section Web page scripts

A Kawa @dfn{web page script} is a Kawa program that is invoked
by a web server because the server received an HTTP request.
The result of evaluating the top-level expressions becomes
the HTTP response that the servlet sends back to the client, usually a browser.

A web page script may be as simple as:
@example
(format "The time is <~s>." (java.util.Date))
@end example
This returns a response of consisting of a formatted string
giving the current time.
The string would interpreted as @code{text/plain} content:
The angle brackets are regular characters, and not
HTML tag markers.

The script can alternatively evaluate to XML/HTML node
values, for example those created by @ref{XML literals}:
@example
#<p>Hello, <b>&(request-remote-host)</b>!</p>
@end example
In this case the response would be @code{text/html} or similar content:
The angle brackets should be interpreted by the browser as HTML tag markers.
The function @code{request-remote-host} is available (automatically)
to web page scripts; it returns the host that made the HTTP request,
which is then interpolated into the response.

Following sections will go into more details about how
to write web page scripts.  You can do so in any supported
Kawa language, including Scheme, BRL, KRL, or XQuery.

A web server will use a URL mapping to map a request URL
to a specific web page script.  This can be done in a
number of different ways:
@itemize
@item
The easiest to manage is to use Kawa's mechanism for
@ref{Self-configuring page scripts}.  Ths is especially
easy if you the web server built in to JDK 6, since no
configuration files are needed.
You can also use a ``servlet engine'' like Tomcat or Glassfish.

@item
You can explicitly compile the web page script to a servlet,
in the same way Java servlets are compiled.
This can then be installed ("deployed") in a servlet-supporting
web server, such a Tomcat or Glassfish.  @xref{Servlets}.
@item
You can run the servlet as a @ref{CGI scripts,CGI script}.
@end itemize

For details on how to extract information from the request
see @ref{HTTP requests}.
For details on how the response is created see @ref{HTTP response,Generating HTTP responses}.
If the response is HTML or XML, you may want to
read @ref{Creating HTML nodes}, or @ref{Creating XML nodes},
or @ref{XML literals}.

Here are some examples, starting with a simple @code{hello.scm}:
@example
(response-content-type 'text/html) ; Optional
(html:p
  "The request URL was: " (request-url))
(make-element 'p
  (let ((query (request-query-string)))
    (if query
      (values-append "The query string was: " query)
      "There was no query string.")))
@end example
This returns two @code{<p>} (paragraph) elements: One using
@code{make-element} and one using the @code{html:p} constructor.
Or you may prefer to use @ref{XML literals}.

The same program using KRL:
@example
<p>The request URL was: [(request-url)]</p>,
<p>[(let ((query (request-query-string)))
    (if query
      (begin ]The query string was: [query)

      ]There was no query string.[))]</p>
@end example

You can also use XQuery:
@example
<p>The request URL was: @{request-url()@}</p>
<p>@{let $query := request-query-string() return
    if ($query)
    then ("The query string was: ",$query)
    else "There was no query string."@}</p>
@end example

The @code{+default+} script in the @code{doc} directory is
useful for reading the Kawa documentation using a browser.
The script uses the @code{jar:} URL scheme to automatically extract
and uncompress the pages from @code{doc/kawa-manual.epub},
which is in EPUB3 format.  Read the script for usage instructions.

@node Self-configuring page scripts, Servlets, Server-side scripts, XML tools
@section Self-configuring web page scripts

Kawa makes it easy to set up a web site without configuration
files.  Instead, the mapping from request URL to web page script
matches the layout of files in the application directory.

Many web servers make it easy to execute a script using a script
processor which is selected depending on the extension of the
requested URL. That is why you see lots of URLs that end in
@code{.cgi}, @code{.php}, or @code{.jsp}. This is bad, because it
exposes the server-side implementation to the user: Not only are such
URLs ugly, but they make it difficult to change the server without
breaking people's bookmarks and search engines. A server will usually
provide a mechanism to use prettier URLs, but doing so requires extra
effort, so many web-masters don't.

If you want a script to be executed in response to a URL
@code{http://host/app/foo/bar} you give the script the name
@code{app/foo/bar}, in the appropriate server ``application''
directory (as explained below). You get to pick the name @code{bar}.
Or you can use the name @code{bar.html}, even though the file named
@code{bar.html} isn't actually
an html file - rather it produces html when evaluated. Or better: just use
a name without an extension at all.
Kawa figures
out what kind of script it is based on the content of the file,
rather than the file name.  Once Kawa has
found a script, it looks at the first line to see if it can recognize
the kind (language) of the script. Normally this would be a comment
that contains the name of a programming language that Kawa
knows about.  For example:
@example
;; Hello world page script written in -*- scheme -*- 
#<p>Hello, <b>&(request-remote-host)</b>!</p>
@end example
(Using the funny-looking string @code{-*- scheme -*-} has the
bonus is that it recognized by the Emacs text editor.)

A script named @code{+default+} is run if there isn't a matching script.
For example assume the following is a file named @code{+default}.
@example
;; This is -*- scheme -*-
(make-element 'p "servlet-path: " (request-servlet-path))
@end example
This becomes the default script for HTTP requests that aren't handled
by a more specific script. 
The @code{request-servlet-path} function
returns the "servlet path", which is the part of the requested URL
that is relative to the current web application. Thus a request for
@code{http://host:port/app/this/is/a/test} will return:
@example
servlet-path: /this/is/a/test
@end example

@subsection Using the OpenJDK built-in web server

The easiest way to run a Kawa web server is to
use the web server built in to JDK 6 or later.

@example
kawa --http-auto-handler @var{context-path} @var{appdir} --http-start @var{port}
@end example

This starts a web server that listens on the given @var{port},
using the files in directory @var{appdir} to handle
requests that start with the given @var{context-path}.
The @var{context-path} must start with a @code{"/"} (one is added if
needed), and it is recommended that it also end with a @code{"/"}
(otherwise you might get some surprising behavior).

You can specify multiple @code{--http-auto-handler} options.

For example use the files in the current directory to handle
all requests on the standard port 80 do:
@example
kawa --http-auto-handler / . --http-start 80
@end example

There are some examples in the @code{testsuite/webtest} directory
the Kawa source distribution.  You can start the server thus:
@example
bin/kawa --http-auto-handler / testsuite/webtest/ --http-start 8888
@end example
and then for example browse to @code{http://localhost:8888/adder.scm}.

For lots of information about the HTTP request, browse to
@code{http://localhost:8888/info/@var{anything}}.

@subsection Using a servlet container

You can also can use a ``servlet container''
such as Tomcat or Glassfish with self-configuring script.
See @ref{Servlets} for information on how to install
these servers, and the concept of web applications.
Once you have these server installed, you create a
web application with the following in the
@code{@var{appdir}/WEB-INF/web.xml} configuration file:
@example
<web-app>
  <display-name>Kawa auto-servlet</display-name>
  <servlet>
    <servlet-name>KawaPageServlet</servlet-name>
    <servlet-class>gnu.kawa.servlet.KawaPageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>KawaPageServlet</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>
@end example
This creates a web application where all URLs
are handled by the @code{gnu.kawa.servlet.KawaPageServlet} servlet class,
which is included in the Kawa jar file.
The @code{KawaPageServlet} class handles the searching
and compiling described in this page.

@subsection Finding a matching script

When Kawa receives a request for:
@example
http://host:port/appname/a/b/anything
@end example
it will look for a file:
@example
@var{appdir}/a/b/anything
@end example

If such a file exists, the script will be executed, as described
below. If not, it will look for a file name @code{+default+} in the same
directory. If that desn't exist either, it will look for @code{+default+}
in the parent
directory, then the grand-parent directory, and so on until it gets to
the appname web application root directory. So the default script is
this: @code{@var{appdir}/+default}.

If that doesn't exist then Kawa returns a 404 "page not found" error. 

@subsection Determining script language

Once Kawa has found a script file corresponding to a request URL,
it needs to determine if this is a data file or a web page script,
and in the latter case, what language it is written in.

Kawa recognizes the following "magic strings" in the first line of a script:

@table @code
@item kawa:scheme
The Scheme language.

@item kawa:xquery
The XQuery language.

@item kawa:@var{language}
Some other language known to Kawa.
@end table

Kawa also recognizes Emacs-style "mode specifiers":

@table @code
@item -*- scheme -*-
The Scheme language.
@item -*- xquery -*-
The XQuery language (though Emacs doesn't know about XQuery).
@item -*- emacs-lisp -*-
@itemx -*- elisp -*-
The Emacs Lisp extension language.
@item -*- common-lisp -*-
@itemx -*- lisp -*-
    The Common Lisp language.
@end table

Also, it also recognizes comments in the first two columns of the line:
@table @code
@item ;;
A Scheme or Lisp comment - assumed to be in the Scheme language.
@item (:
Start of an XQuery comment, so assumed to be in the XQuery language.
@end table

If Kawa doesn't recognize the language of a script (and it
isn't named +default+) then it assumes the file is a data file. It
asks the servlet engine to figure out the content type (using the
getMimeType method of ServletContext), and just copies the file into
the response.

@subsection Compilation and caching

Kawa automatically compiles a script into a class. The
class is internal to the server, and is not written out to
disk. (There is an unsupported option to write the compiled file to a
class file, but there is no support to use previously-compiled
classes.) The server then creates a module instance to handle the
actual request, and runs the body (the @code{run} method)
of the script class. On subsequence
requests for the same script, the same class and instance are reused;
only the @code{run} is re-executed.

If the script is changed, then it is re-compiled and a new module
instance created. This makes it very easy to develop and modify a
script. (Kawa for performance reasons doesn't check more
than once a second whether a script has been modified.)

@node Servlets, CGI scripts, Self-configuring page scripts, XML tools
@section Installing web page scripts as Servlets

You can compile a Kawa program to a @uref{http://en.wikipedia.org/wiki/Java_Servlet,Servlet}, and run it
in a servlet engine (a Servlet-aware web server).
One or more servlets are installed together as a web application.
This section includes specific information for
the Tomcat and Glassfish web servers.

@subsection Creating a web application

A @dfn{web application} is a group of data, servlets, and
configuration files to handle a related set of URLs.
The @uref{http://jcp.org/aboutJava/communityprocess/final/jsr315/index.html,
servlet specification}
specifies the directory structure of a web application.

Assume the web application is called @code{myapp}, and lives in a
directory with the same name.  The application normally handles
requests for URLs that start with @code{http://example.com/myapp}.
Most files in the application directory are used to handle
requests with corresponding URL.  For example,
a file @code{myapp/list/help.html} would be the response
to the request @code{http://example.com/myapp/list/help.html}.

The directory @code{WEB-INF} is special.  It contains configuration
files, library code, and other server data.

So to create the @code{myapp} application, start with:
@example
mkdir myapp
cd myapp
mkdir WEB-INF WEB-INF/lib WEB-INF/classes
@end example

Copy the Kawa jar from the @code{lib} direcory.
(You can also use a ``hard'' link, but symbolic links may not
work, for security systems.)
@example
cp @var{kawa-home}/kawa-@value{VERSION}.jar WEB-INF/lib/kawa.jar
@end example

If you build Kawa from source, you must specify the
@code{--with-servlet} @ref{configure options,configure option}.

You should also create the file @code{WEB-INF/web.xml}.
For now, this is is just a place-holder:
@example
<web-app>
  <display-name>My Application</display-name>
</web-app>
@end example

@subsection Compiling a web page script to a servlet

Assume for simplicity that the source files
are in the @code{WEB-INF/classes} directory, and make that the
current directory:
@example
cd .../myapp/WEB-INF/classes
@end example

Depending on the source language, you compile your script
sing the @code{--servlet} switch:
@example
kawa --servlet -C hello.scm
@end example
or:
@example
kawa --servlet --krl -C hello.krl
@end example
or:
@example
kawa --servlet --xquery -C hello.xql
@end example

This lets the web-application find the compiled servlets.
Finally, you just need to add the new servlet to
the @code{WEB-INF/web.xml} file:
@example
<web-app>
  <display-name>My Application</display-name>

  <servlet>
    <servlet-name>MyHello</servlet-name>
    <servlet-class>hello</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyHello</servlet-name>
    <url-pattern>/hello</url-pattern>
  </servlet-mapping>
</web-app>
@end example

The @code{<servlet>} clause says that the servlet named
@code{MyHello} is implemented by the Java class @code{hello}.
The @code{<servlet-mapping>} clause says that a request
URL @code{/hello} should be handled by the servlet named @code{MyHello}.
The URL is relative to the application context path,
so the actual URL would be @code{http://example.com/myapp/hello}.

@subsection Installing a servlet under Tomcat
@cindex Tomcat

Apache's @uref{http://tomcat.apache.org/,Tomcat} is an open-source
implementation of the servlet specifications.
After you @uref{http://tomcat.apache.org/download-60.cgi, download it},
uncompress it in some convenient location,
which is commonly referred to as @code{$CATALINA_HOME}.

To install your web application, copy/move its directory
to be in the @code{$CATALINA_HOME/webapps} directory.
Thus for the example above you would have
a @code{$CATALINA_HOME/webapps/myapp} directory.

To start or stop Tomcat use the scripts in @code{$CATALINA_HOME/bin}.
For example to start Tomcat on a GNU/Linux system run
@code{$CATALINA_HOME/bin/startup.sh}.  This will start a web server
that listens on the default port of 8080,
so you can browse the above example at @code{http://localhost:8080/myapp/hello}.

If you're running Fedora GNU/Linux, you can use the @code{tomcat6} package:
@example
# yum install tomcat6
# export CATALINA_HOME=/usr/share/tomcat6
@end example
You can the manage Tomcat like other system services.
You can install webapps under @code{$CATALINA_HOME/webapps}.

@subsection Installing a servlet under Glassfish
@cindex Glassfish

@uref{https://glassfish.dev.java.net/,Glassfish} from Oracle/Sun
is a open-source ``application server'' that implements
Java EE 6, including the 3.0 servlet specification.
After you @uref{https://glassfish.dev.java.net/downloads/3.0.1-final.html, download it}, uncompress it in some convenient location.
This location is called @var{as-install-parent} in the
@uref{http://docs.sun.com/app/docs/doc/820-7689/aboaa?a=view,Quick Start Guide}.
The commands you will use is most in @code{@var{as-install}/bin},
where @var{as-install} is @code{@var{as-install}/glassfish}.

To start the server, do:
@example
@var{as-install}/bin/startserv
@end example
or under under Windows:
@example
@var{as-install}\bin\startserv.bat
@end example
The default post to listen to is @code{8080};
you can the port (and lots of other properties)
using the adminstration console at port @code{4848}.

A web application does not need to be any particular
location, instead you just install it with this command:
@example
@var{as-install}/bin/adadmin deploy @var{appdir}
@end example
where @var{appdir} is the application directory - @code{myapp} in the example.
(Use @code{asadmin.bat} under Windows.)

@subsection Servlet-specific script functions

The following functions only work within a servlet container.
To use these functions, first do:
@example
(require 'servlets)
@end example

You can conditionalize your code to check at compile-time for servlets,
like this:

@example
(cond-expand
 (in-servlet
   (require 'servlets)
   (format "[servlet-context: ~s]" (current-servlet-context)))
 (else
   "[Not in a servlet]"))
@end example

For a run-time check you can test if @code{(current-servlet)} is
non-@code{#!null}.

@deffn Procedure current-servlet
When called from a Kawa servlet handler, returns the
actual @code{javax.servlet.http.HttpServlet} instance.
Returns @code{#!null} if the current context is not that of
@code{KawaServlet}.
(Hence this function also returns @code{#!null} if you compile a servlet
``by hand'' rather that using the @code{--servet} option.)
@end deffn

@deffn Procedure current-servlet-context
Returns the context of the currently executing servlet,
as an instance of @code{javax.servlet.ServletContext}.
@end deffn

@deffn Procedure current-servlet-config
Returns the @code{ServletConfig} of the currently executing servlet.
@end deffn

@deffn Procedure get-request
Return the current servlet request, as an instance of
@code{javax.servlet.http.HttpServletRequest}.
@end deffn

@deffn Procedure get-response
Return the current servlet response, as an instance of
@code{javax.servlet.http.HttpServletResponse}.
@end deffn

@deffn Procedure request-servlet-path
Get the servlet path of the current request.
Similar to @code{request-script-path}, but not always the same,
depending on configuration, and does @emph{not} end with a @code{"/"}.
@end deffn

@deffn Procedure request-path-info
Get the path info of the current request.
Corresponds to the CGI variable @code{PATH_INFO}.
@end deffn

@deffn Procedure servlet-context-realpath [path]
Returns the file path of the current servlet's "Web application".
@end deffn

@node CGI scripts, HTTP requests, Servlets, XML tools
@section Installing Kawa programs as CGI scripts

The recommended way to have a web-server run a Kawa program
as a CGI script is to compile the Kawa program to a servlet
(as explained in @ref{Server-side scripts}, and then use
Kawa's supplied CGI-to-servlet bridge.

First, compile your program to one or more class files
as explained in @ref{Server-side scripts}.  For example:
@example
kawa --servlet --xquery -C hello.xql
@end example

Then copy the resulting @code{.class} files to your server's
CGI directory.  On Red Hat GNU/Linux, you can do the following (as root):
@example
cp hello*.class /var/www/cgi-bin/
@end example

Next find the @code{cgi-servlet} program that Kawa builds and installs.
If you installed Kawa in the default place, it will be in
@code{/usr/local/bin/cgi-servlet}.
(You'll have this if you installed Kawa from source, but not
if you're just using Kawa @code{.jar} file.)
Copy this program into the same CGI directory:
@example
cp /usr/local/bin/cgi-servlet /var/www/cgi-bin/
@end example

You can link instead of copying:
@example
ln -s /usr/local/bin/cgi-servlet /var/www/cgi-bin/
@end example
However, because of security issues this may not work, so it is
safer to copy the file.  However, if you already have a copy
of @code{cgi-servlet} in the CGI-directory, it is safe to make
a hard link instead of making an extra copy.

Make sure the files have the correct permissions:
@example
chmod a+r /var/www/cgi-bin/hello*.class /var/www/cgi-bin/hello
chmod a+x /var/www/cgi-bin/hello
@end example

Now you should be able to run the Kawa program,
using the URL @url{http://localhost/cgi-bin/hello}.
It may take a few seconds to get the reply, mainly because of the
start-up time of the Java VM.  That is why servlets are
preferred.  Using the CGI interface can still be useful
for testing or when you can't run servlets.

@node HTTP requests, HTTP response, CGI scripts, XML tools
@section Functions for accessing HTTP requests

The following functions are useful for accessing
properties of a HTTP request, in a Kawa program that is
run either as a servlet or a CGI script.  These functions
can be used from plain Scheme, from KRL (whether
in BRL-compatible mode or not), and from XQuery.

The examples below assume the request @code{http://example.com:8080/myapp/foo/bar?val1=xyz&val2=abc}, where @code{myapp} is the application context.
We also assume that this is handled by a script @code{foo/+default+}.

The file @code{testsuite/webtest/info/+default+} in the Kawa source distribution
calls most of these functions.
You can try it as described in @ref{Self-configuring page scripts}.

@subsection Request URL components

@deffn Procedure request-URI
Returns the URI of the request, as a value of type @code{URI}.
This excludes the server specification,
but includes the query string.
(It is the combination of CGI variables @code{SCRIPT_NAME},
@code{PATH_INFO}, and @code{QUERY_STRING}.
Using servlets terminology, it is the combination of
Context Path, Servlet Path, PathInfo, and Query String.)
@example
(request-URI) @result{} "/myapp/foo/bar?val1=xyz&val2=abc"
@end example
@end deffn

@deffn Procedure request-path
Returns the URI of the request, as a value of type @code{URI}.
This excludes the server specification and the query string.
Equivalent to @code{(path-file (request-URI))}.
(It is the combination of CGI variables @code{SCRIPT_NAME}, and
@code{PATH_INFO}.
Same as the concatenation of @code{(request-context-path)},
@code{(request-script-path)}, and @code{(request-local-path)}.
Using servlets terminology, it is the combination of
Context Path, Servlet Path, and PathInfo.)
@example
(request-path) @result{} "/myapp/foo/bar"
@end example
@end deffn

@deffn Procedure request-uri
This function is deprecated, because of possible confusion
with @code{request-URI}.  Use @code{request-path} instead.
@end deffn

@deffn Procedure request-url
Returns the complete URL of the request, except the query string.
The result is a @code{java.lang.StringBuffer}.
@example
(request-url) @result{} "http://example.com:8080/myapp/foo/bar"
@end example
@end deffn

@deffn Procedure request-context-path
Returns the context path, relative to the server root.
This is an initial substring of the @code{(request-path)}.
Similar to the Context Path of a servlet request,
except that it ends with a @code{"/"}.
@example
(request-context-path) @result{} "/myapp/"
@end example
@end deffn

@deffn Procedure request-script-path
Returns the path of the script, relative to the context.
This is either an empty string, or a string that ends with @code{"/"},
but does not start with one. (The reason for this is to produce URIs
that work better with operations like @code{resolve-uri}.)
This is conceptually similar to @code{request-servlet-path},
though not always the same, and the @code{"/"} conventions differ.
@example
(request-script-path) @result{} "foo/"
@end example
@end deffn

@deffn Procedure request-local-path
Returns the remainder of the @code{request-path},
relative to the @code{request-script-path}.
@example
(request-local-path) @result{} "bar"
@end example
@end deffn

@deffn Procedure request-query-string
Returns the query string from an HTTP request.  The query string is
the part of the request URL after a question mark.
Returns false if there was no query string.
Corresponds to the CGI variable @code{QUERY_STRING}.
@example
(request-query-string) @result{} "val1=xyz&val2=abc"
@end example
@end deffn

@subsection Request parameters

Request parameters are used for data returned from forms,
and for other uses.
They may be encoded in the query string or in the request body.

@deffn Procedure request-parameter name [default]
If there is a parameter with the given name (a string),
return the (first) corresponding value, as a string.
Otherwise, return the @var{default} value,
or @code{#!null} if there is no @var{default}.
@example
(request-parameter "val1") @result{} "xyz"
(request-parameter "val9" "(missing)") @result{} "(missing)"
@end example
@end deffn

@deffn Procedure request-parameters name
If there is are one or more parameter with the given name (a string),
return them all (as multiple values).
Otherwise, return no values (i.e. @code{(values)}).
@example
(request-parameters "val1") @result{} "xyz"
(request-parameters "val9") @result{} #!void
@end example
@end deffn

@deffn Procedure request-parameter-map
Request a map of all the parameters.
This is a map from strings to a sequence of strings.
(Specifically, a @code{java.util.Map<String,java.util.List<String>>}.)
@end deffn

@subsection Request headers

The request headers are a set of (keyword, string)-pairs
transmitted as part of the HTTP request, before the request body.

@deffn Procedure request-header name
If there is a header with the given @var{name} (a string),
return the corresponding value string.
Otherwise, return @code{#!null}.
@example
(request-header "accept-language") @result{} "en-us,en;q=0.5"
@end example
@end deffn

@deffn Procedure request-header-map
Request a map of all the headers.
This is a map from strings to a sequence of strings.
(Specifically, a @code{java.util.Map<String,java.util.List<String>>}.)
@end deffn

@subsection Request body

@deffn Procedure request-input-port
Return a textual input port for reading the request body,
as a sequence of characters.
@end deffn

@deffn Procedure request-input-stream
Return a binary input stream for reading the request body,
as a sequence of bytes.
@end deffn

@deffn Procedure request-body-string
Return the entire request body as a string
@end deffn

@subsection Request IP addresses and ports

Information about the interface and port on which the request was received.

@deffn Procedure request-local-socket-address
The local address on which the request was received.
This is the combination of @code{(request-local-host)}
and @code{(request-local-port)}, as an instance of
@code{java.net.InetSocketAddress}.
@end deffn
@deffn Procedure request-local-host
Get the IP address of the interface on which request was received,
as an @code{java.net.InetAddress}.
@end deffn
@deffn Procedure request-local-IP-address
Get the IP address of the interface on which request was received,
a string in numeric form:
@example
(request-local-host) @result{} "127.0.0.1"
@end example
@end deffn
@deffn Procedure request-local-port
Get the port this request was received on.
@example
(request-local-port) @result{} 8080
@end example
@end deffn

Information about the interface and port of the remote client that invoked the request.

@deffn Procedure request-remote-socket-address
The address of the remote client (usually a web browser)
which invoked the request.
This is the combination of @code{(request-remove-host)}
and @code{(request-remote-port)}, as an instance of
@code{java.net.InetSocketAddress}.
@end deffn
@deffn Procedure request-remote-host
Get the IP address of the remote client which invoked the request,
as an @code{java.net.InetAddress}.
@end deffn
@deffn Procedure request-remote-IP-address
Get the IP address of the remote client which invoked the request,
as a string in numeric form.
@example
(request-remote-host) @result{} "123.45.6.7"
@end example
@end deffn
@deffn Procedure request-remote-port
The port used by the remote client.
@end deffn

@subsection Miscellaneous request properties

@deffn Procedure request-path-translated
Map the request-path to a file name (a string)
in the server application directory.
Corresponds to the CGI variable @code{PATH_TRANSLATED}.
@end deffn

@deffn Procedure request-method
Returns the method of the HTTP request, usually @code{"GET"}
or @code{"POST"}.  Corresponds to the CGI variable @code{REQUEST_METHOD}.
@end deffn

@deffn Procedure request-scheme
Returns the scheme (protocol) of the request.
Usually @code{"http"}, or @code{"https"}.
@end deffn

@node HTTP response, XML beyond Scheme, HTTP requests, XML tools
@section Generating HTTP responses

The result of evaluating the top-level expressions of a web page script
becomes the HTTP response that the servlet sends back to the browser.
The result is typically an HTML/XML element code object
Kawa will automatically format the result as appropriate for the type.
Before the main part of the response there may be
special "response header values",
as created by the @code{response-header} function.
Kawa will use the response header values to set various
required and optional fields of the HTTP response.
Note that @code{response-header} does not actually do anything
until it is "printed" to the standard output.
Note also that a @code{"Content-Type"} response value is
special since it controls the formatting of the following
non-response-header values.

@deffn Procedure response-header key value
Create the response header @samp{@var{key}: @var{value}} in the HTTP
response.  The result is a "response header value" (of some unspecified
type).  It does not directly set or print a response header, but only
does so when you actually "print" its value to the response output stream.
@end deffn

@deffn Procedure response-content-type type
Species the content-type of the result - for example @code{"text/plain"}.
Convenience function for @code{(response-header "Content-Type" @var{type})}.
@end deffn

@deffn Procedure error-response code [message]
Creates a response-header with an error code of @var{code} and a
response message of @var{message}.
(For now this is the same as @code{response-status}.)

Note this also returns a response-header value, which does not actually
do anything unless it is returned as the result of executing a servlet body.
@end deffn

@deffn Procedure response-status code [message]
Creates a response-header with an status code of @var{code} and a
response message of @var{message}.
(For now this is the same as @code{error-response}.)
@end deffn

@node XML beyond Scheme, , HTTP response, XML tools
@section Using non-Scheme languages for XML/HTML 

@subsection XQuery language

Bundled with Kawa is a fairly complete implementation of W3C's
new @uref{http://www.w3c.org/XML/Query,XML Query language}.
If you start Kawa with the @code{--xquery} it selects the "XQuery"
source language; this also prints output using XML syntax.
See the @uref{http://www.gnu.org/software/qexo/,Qexo (Kawa-XQuery) home page}
for examples and more information.

@subsection XSL transformations

There is an experimental implementation of the XSLT (XML Stylesheet
Language Transformations) language.  Selecting @code{--xslt} at the
Kawa command line will parse a source file according to the syntax
on an XSLT stylesheet.
See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
for more information.

@menu
* KRL::              KRL - The Kawa Report Language for generating XML/HTML
@end menu

@node KRL, , ,  XML beyond Scheme
@subsection KRL - The Kawa Report Language for generating XML/HTML

KRL (the "Kawa Report Language") is powerful Kawa dialect for embedding
Scheme code in text files such as HTML or XML templates.  You select
the KRL language by specifying @code{--krl} on the Kawa command line.

KRL is based on on @uref{http://brl.sourceforge.net/,BRL},
Bruce Lewis's "Beautiful Report Language", and
uses some of BRL's code, but there are some experimental differences,
and the implementation core is different.  You can run KRL in
BRL-compatility-mode by specifying @code{--brl} instead of @code{--krl}.

@subsection Differences between KRL and BRL

This section summarizes the known differences between KRL and BRL.
Unless otherwise specified, KRL in BRL-compatibility mode will
act as BRL.

@itemize
@item
In BRL a normal Scheme string @code{"mystring"} is the same
as the inverted quote string @code{]mystring[}, and both are instances
of the type @code{<string>}.
In KRL @code{"mystring"} is a normal Scheme string of type @code{<string>},
but @code{]mystring[} is special type that suppresses output escaping.
(It is equivalent to @code{(unescaped-data "mystring")}.)
@item
When BRL writes out a string, it does not do any processing
to escape special characters like @code{<}.  However, KRL in its default
mode does normally escape characters and strings.  Thus @code{"<a>"}
is written as @code{&lt;a&gr;}.
You can stop it from doing this by overriding the output format, for example
by specifying @code{--output-format scheme} on the Kawa command line,
or by using the @code{unescaped-data} function.
@item
Various Scheme syntax forms, including @code{lambda},
take a @stxref{body}, which is a list of one or more declarations and
expressions.  In normal Scheme and in BRL the value of a @var{body}
is the value of the last expression.  In KRL the value of a @var{body}
is the concatenation of all the values of the expressions,
as if using @code{values-append}.
@item
In BRL a word starting with a colon is a keyword.
In KRL a word starting with a colon is an identifier, which by
default is bound to the @code{make-element} function specialized
to take the rest of the word as the tag name (first argument).
@item
BRL has an extensive utility library.  Most of this has not yet been ported
to KRL, even in BRL-compatibility mode.
@end itemize

@node Miscellaneous
@chapter Miscellaneous topics

@deffn Procedure scheme-implementation-version
Returns the Kawa version number as a string.
@c (Compatible with slib.)
@end deffn

@deffn Procedure scheme-window [shared]
Create a read-eval-print-loop in a new top-level window.
If @var{shared} is true, it uses the same environment as the
current @code{(interaction-environment)};  if not (the default),
a new top-level environment is created.

You can create multiple top-level window that can co-exist.
They run in separate threads.
@end deffn

@menu
* Composable pictures::
* Building JavaFX applications::
* Building for Android::  Building for Android devices
* Android view construction::
* System inquiry::
* Processes::
* Time-related functions::
* Low-level functions:: Deprecated low-level functions
@end menu

@node Composable pictures
@section Composable pictures

The @code{(kawa pictures)} library lets you create geometric shapes
and images, and combine them in interesting ways.
The @ref{Tutorial - Pictures,tutorial} gives an introduction.

The easiest way to use and learn the @code{pictures} library
is with a suitable REPL.  You can use the old Swing-based console
or any @ref{Using DomTerm,DomTerm}-based terminal emulator.
You can create a suitable window either by starting @code{kawa}
with the @code{-w} flag, or by running the @code{kawa} command
inside an existing DomTerm-based terminal emulator.
The screenshot below is of the latter,
using the @code{qtdomterm} terminal emulator.

@image{images/domterm-pictures-1}

After @code{(import (kawa swing))} you can use @code{show-picture}
to display a picture in a Swing window.

A @dfn{picture} is an object that can be displayed on a screen,
web-page, or printed page, and combined with other pictures.

A picture has a method printing itself in a graphical context.
It also has various properties.

An important property of a picture is its @dfn{bounding box}.
This is a rectangle (with edges parallel to the axes) that
surrounds the contents of the picture.
Usually the entire visible part of the picture is inside the
bounding box, but in some cases part of the picture may stick
outside the bounding box.
For example when a circle is drawn (stroked) with a ``pen'',
the bounding box is that of the infinitely-thin mathematical circle, so
``ink'' from the pen that is outside the circle may be outside the bounding box.

A picture has an origin point corresponding to the (0 0) cordinates.
The origin is commonly but not always inside the bounding box.
Certain operations (for example @code{hbox}) combine pictures by putting
them ``next to'' each other, where ``next to'' is defined in
terms of the bounding box and origin point.

@c The Racket language has a @uref{https://docs.racket-lang.org/pict/,Pict}
@c library, with a lot more functionality;
@c it is used by the @uref{https://docs.racket-lang.org/quick/,Racket tutorial}.
@c Racket also has a @uref{https://docs.racket-lang.org/teachpack/2htdpimage-guide.html,@code{2htdp/image} library} which should also be studied.

@subsection Coordinates - points and dimensions

The library works with a two-dimensional grid,
where each position has an x cordinate and y coordinate.
Normally, x values increase as you move right on the screen/page,
while y values increase as you move @emph{down}.
This convention matches that used by Java 2D, SVG, and many other
graphics library.  However, note that this is different from the traditional
mathematical convention of y values increasing as you go up.

By default, one unit is one ``pixel''.  (More precisely,
it is the @code{px} unit in the CSS specification.)

@deffn Type Point
A point is a pair consisting of an x and a y coordinate.
@end deffn

@deftypefn Literal {} &P@stxlit{[} @var{x} @var{y} @stxlit{]}
Construct a point value with the specified @var{x} and @var{y} values.
Both @var{x} and @var{y} are expressions that evaluate to real numbers:
@example
&P[(+ old-right 10) baseline]
@end example
@end deftypefn

@deffn Type Dimension
A dimension value is a pair of a width and a height.
It is used for the size of pictures in the two dimensions.

In a context that expects a point, a dimension is treated
as an offset relative to some other point.
@end deffn

@deftypefn Literal {} &D@stxlit{[} @var{width} @var{height} @stxlit{]}
Construct a dimension value with the specified @var{width}
and @var{height} values, which are both expressions that
evaluate to real numbers.
@end deftypefn

@subsection Shapes

A shape is a collection of lines and curves.
Examples include lines, circles, and polygons.
A shape can be @dfn{stroked}, which you can think of as
being drawn by a very fancy calligraphic pen that
follows the lines and curves of the shape.

A @dfn{closed shape} is a shape that is continuous and ends up where it
started.  This includes circles and polygons.
A closed shape can be filled, which means the entire ``interior''
is painted with some color or texture.

A shape is represented by the Java @code{java.awt.Shape} interface.
The @code{picture} library only provides relatively simple shapes,
but you can use any methods that create a @code{java.awt.Shape} object.

@dfn{Shape} is effectively a sub-type of @dfn{picture},
though they're represented using using disjoint classes:
If you use a shape where a picture is required,
the shape is automatically converted to a picture,
as if using the @code{draw} procedure.

@deffn Procedure line p1 [p2 ...]
In the simple case two points are specified, and the result
is a line that goes from point @var{p1} to @var{p2}.
If @var{n} points are specied, the result is a @dfn{polyline}:
a path consisting of @var{n-1} line segments, connecting adjacent arguments.
(If only a single point is specified, the result is degenerate
single-point shape.)

All of the points except the first can optionally be specified
using a dimension, which is treated an an offset from the previous point:
@example
(line &P[30 40] &D[10 5] &D[10 -10])
@end example
is the same as:
@example
(line &P[30 40] &P[40 45] &P[50 35])
@end example
@end deffn

@deffn Procedure polygon p1 [p2 ...]
Constructs a closed shape from line segments.
This is the same as calling @code{line} with the same arguments,
with the addition of a final line segment from the last point
back to the first point.
@end deffn

@deffn Procedure rectangle p1 [p2]
A rectangle is closed polygon of 4 line segments that are
alternatively parallel to the x-axis and the y-axis.
I.e. if you rotate a rectangle it is no longer a rectangle by
this definition, though of course it still has a rectangular shape.
If @var{p2} is not specified, constructs a rectangle whose upper-left corner
is @code{&P[0 0]} and whose lower-right corner is @var{p1}.
If @var{p2} is specified, constructs a rectangle whose upper-left corner
is @var{p1} and whose lower-right corner is @var{p2}.
If @var{p2} is a dimension it is considered a relative offset from @var{p1},
just like for @code{polygon}.
@end deffn

@deffn Procedure circle radius [center]
Creates a circle with the specified @var{radius}.
If the @var{center} is not specified, it defaults to @code{&P[0 0]}.
@end deffn

@subsection Colors and paints

A @dfn{paint} is a color pattern used to fill part of the canvas.
A paint can be a color, a texture (a replicated pattern), or a gradient
(a color that gradually fades to some other color).

A @dfn{color} is defined by red, green, and blue values.
It may also have an alpha component, which specifies transparency.

@deffn Procedure ->paint value
Converts @var{value} to a color - or more general a paint.
Specificlly, the return type is @code{java.awt.Paint}.
The @var{value} can be any one of:
@itemize
@item
A @code{java.awt.Paint}, commonly a @code{java.awt.Color}.
@item
A 24-bit integer value is converted to a color.
Assume the integer is equal
to a hexadecimal literal of the form @code{#xRRGGBB}.
Then @code{RR} (bits 16-23) is the intensity of the red component;
@code{GG} (bits 8-15) is the intensity of the green component; and
@code{RR} (bits 0-7) is the intensity of the red component.
@item
One of the standard HTML/CSS/SVG color names, as a string or symbol.
See the table in @code{gnu/kawa/models/StandardColor.java} source file.
Case is ignored, and you can optionally use hyphens to separate words.
For example @code{'hot-pink}, @code{'hotpink}, and @code{'hotPink}
are all the same sRGB color @code{#xFF69B4}.
@end itemize
@end deffn

@deffn Procedure with-paint paint picture
Create a new picture that is the ``same'' as @var{picture}
but use @var{paint} as the default paint.
For @var{paint} you can use any valid argument to @code{->paint}.
The default paint (which is the color black if none is specified)
is used for both @code{fill} (paint interior) and @code{draw} (stroke outline).

@example
#|kawa:1|# @kbd{(! circ1 (circle 20 &P[20 20]))}
#|kawa:2|# @kbd{(hbox (fill circ1) (draw circ1))}
@image{images/paint-circ-1}
#|kawa:3|# @kbd{(with-paint 'hot-pink (hbox (fill circ1) (draw circ1)))}
@image{images/paint-circ-2}
@end example
Above we use @code{with-paint} to create a cloned picture, which is
the same as the original @code{hbox}, except for the default paint,
in this case the color @code{hot-pink}.
@example
#|kawa:4|# @kbd{(! circ2 (hbox (fill circ1) (with-paint 'hot-pink (fill circ1))))}
#|kawa:5|# @kbd{circ2}
@image{images/paint-circ-3}
#|kawa:6|# @kbd{(with-paint 'lime-green circ2)}
@image{images/paint-circ-4}
@end example
Here @code{circ2} is an @code{hbox} of two filled circles,
one that has unspecified paint, and one that is @code{hot-pink}.
Printing @code{circ2} directly uses black for the
circle with unspecified color,
but if we wrap @code{circ2} in another @code{with-paint}
that provides a default that is used for the first circle.
@end deffn

@subsection Filling a shape with a color

@deffn Procedure fill shape
@deffnx Procedure fill paint shape

Fill the ``inside'' of @var{shape}.
If no @var{paint} is specified, uses the current default paint.
Otherwise, @code{(fill @var{paint} @var{shape})}
is the same @code{(with-paint @var{paint} (file @var{shape}))}.
@end deffn

@subsection Stroking (outlining) a shape

@deffn Procedure draw @arbno{option} @atleastone{shape}

Returns a picture that draws the outline of the @var{shape}.
This is called @dfn{stroking}.
An @var{option} may be one of:
@itemize
@item
A @code{Paint} or @code{Color} object, which is used to draw the shape.
@item
A standard color name, such as @code{'red} or @code{'medium-slate-blue}.
This is mapped to a @code{Color}.
@item
A join-specifier, which is a symbol specifying how each curve of the shape is
connected to the next one.
The options are @code{'miter-join}, @code{'round-join}, and @code{'bevel-join}.
The default if none is specified is @code{'miter-join}.
@item
A end-cap-specifier, which is a symbol specifying how each end of the
shape is terminated.
The options are @code{'square-cap}, @code{'round-cap}, or @code{'butt-cap}.
The default is @code{'butt-cap}.
(This follows SVG and HTML Canvas.
The default in plain Java AWT is a square cap.)
@item
A real number specifies the thickness of the stroke.
@item
A @code{java.awt.Stroke} object.
This combines join-specifier, end-cap-specifier, thickness, and more
in a single object.  The @code{BasicStroke} class can specify dashes,
though that is not yet supported for SVG output; only AWT or image output.
@end itemize

Let us illustrate with a sample line @code{lin}
and a helper macro @code{show-draw}, which adds a border around a shape,
then draws the given shape with some options, and finally
re-draws the shape in plain form.
@example
#|kawa:10|# @kbd{(define lin (line &P[0 0] &P[300 40] &P[200 100] &P[50 70]))}
#|kawa:11|# @kbd{(define-syntax show-draw}
#|....:12|# @kbd{  (syntax-rules ()}
#|....:13|# @kbd{    ((_ options ... shape)}
#|....:14|# @kbd{     (border 12 'bisque (zbox (draw options ... shape) shape)))))}
#|....:15|# @kbd{(show-draw 8 'lime lin)}
@image{images/show-draw-1}
#|....:16|# @kbd{(show-draw 8 'lime 'round-cap 'round-join lin)}
@image{images/show-draw-2}
#|....:17|# @kbd{(show-draw 8 'lime 'square-cap 'bevel-join lin)}
@image{images/show-draw-3}
@end example
@end deffn
Notice how the different cap and join styles change the drawing.
Also note how the stroke (color lime) extends beyond its bounding box,
into the surrounding border (color bisque).
@subsection Affine transforms

A 2D affine transform is a linear mapping from coordinates to
coordinates.  It generalizes translation, scaling, flipping, shearing,
and their composition.  An affine transform maps straight parallel lines
into other straight parallel lines, so it is only a subset of possible
mappings - but a very useful subset.

@deffn Procedure affine-transform xx xy yx yy x0 y0
@deffnx Procedure affine-transform px py p0
Creates a new affine transform.
The result of applying @code{(affine-transform @var{x@sub{x}} @var{x@sub{y}} @var{y@sub{x}} @var{y@sub{y}} @var{x@sub{0}} @var{y@sub{0}})}
to the point @code{&P[@var{x} @var{y}]}
is the transformed point
@example
&P[(+ (* @var{x} @var{x@sub{x}}) (* @var{y} @var{y@sub{x}}) @var{x@sub{0}})
   (+ (* @var{x} @var{x@sub{y}}) (* @var{y} @var{y@sub{y}}) @var{y@sub{0}})]
@end example

If using point arguments,
@code{(affine-transform &P[@var{x@sub{x}} @var{x@sub{y}}] &P[@var{y@sub{x}} @var{y@sub{y}}] &P[@var{x@sub{0}} @var{y@sub{0}}])}
is equivalent to:
@code{(affine-transform @var{x@sub{x}} @var{x@sub{y}} @var{y@sub{x}} @var{y@sub{y}} @var{x@sub{0}} @var{y@sub{0}})}.
@end deffn

@deffn Procedure with-transform transform picture
@deffnx Procedure with-transform transform shape
Creates a transformed picture.

If the argument is a @var{shape}, then the result is also a shape.
@end deffn

@deffn Procedure with-transform transform point
Apply a transform to a single point, yielding a new point.
@end deffn

@deffn Procedure with-transform transform1 transform2
Combine two transforms, yielding the composed transform.
@end deffn

@deffn Procedure rotate angle
@deffnx Procedure rotate angle picture
The one-argument variant creates a new affine transform that rotates
a picture about the origin by the specified @var{angle}.
A positive @var{angle} yields a clockwise rotation.
The @var{angle} can be either a quantity (with a unit of
either @code{rad} radians, @code{deg} (degrees), or @code{grad} (gradians)),
or it can be a unit-less real number (which is treated as degrees).

The two-argument variant applies the resulting transform to
the specified picture.  It is equivalent to:
@example
(with-transform (rotate @var{angle}) @var{picture})
@end example
@end deffn

@deffn Procedure scale factor
@deffnx Procedure scale factor picture
Scales the @var{picture} by the given @var{factor}.
The @var{factor} can be a real number.
The @var{factor} can also be a point or a dimension, in which case
the two cordinates are scaled by a different amount.

The two-argument variant applies the resulting transform to
the specified picture.  It is equivalent to:
@example
(with-transform (scale @var{factor}) @var{picture})
@end example
@end deffn

@deffn Procedure translate offset
@deffnx Procedure translate offset picture

The single-argument variant creates a transform
that adds the @var{offset} to each point.
The @var{offset} can be either a point or a dimension (which
are treated quivalently).

The two-argument variant applies the resulting transform to
the specified picture.  It is equivalent to:
@example
(with-transform (translate @var{offset}) @var{picture})
@end example
@end deffn

@subsection Combining pictures

@deffn Procedure hbox [spacing] picture ...
@deffnx Procedure vbox [spacing] picture ...
@deffnx Procedure zbox picture ...
Make a combined picture from multiple sub-pictures drawn
either ``next to'' or ``on top of'' each other.

The case of @code{zbox} is simplest: The sub-pictures are drawn
in argument order at the same position (origin).  The ``@code{z}'' refers to
the idea that the pictures are stacked on top of each other along
the ``Z-axis'' (the one perpendicular to the screen).

The @code{hbox} and @code{vbox} instead place the sub-pictures
next to each other, in a row or column.
If @var{spacing} is specified, if must be a real number.
That much extra spacing is added between each sub-picture.

More precisely: @code{hbox} shifts each sub-picture except the first
so its left-origin control-point
(see discussion at @code{re-center}) has the same position
as the right-origin control point of the previous picture
@var{plus} the amount of @var{spacing}.
Similarly, @code{vbox} shifts each sub-picture except the first
so its top-origin control point has the same position
as the bottom-origin point of the previous picture, plus @var{spacing}.

The bounding box of the result is the smallest rectangle that
includes the bounding boxes of the (shifted) sub-pictures.
The origin of the result is that of the first picture.
@end deffn

@deffn Procedure border [size [paint]] picture
Return a picture that combines @var{picture}
with a rectangular border (frame) around @var{picture}'s bounding box.
The @var{size} specifies the thickness of the border:
it can be real number, in which it is the thickness on all four sides;
it can be a Dimension, in which case the width is the left and right
thickness, while the height is the top and bottom thickness;
or it can be a Rectangle, in which case it is the new bounding box.
If @var{paint} is specified it is used for the border;
otherwise the default paint is used.
The border is painted before (below) the @var{picture} painted.
The bounding box of the result is that of the border, while
the origin point is that of the original @var{picture}.
@example
#|kawa:2|# @kbd{(with-paint 'blue (border &D[8 5] (fill 'pink (circle 30))))}
@image{images/border-1}
@end example
@end deffn

@deffn Procedure padding width [background] picture
This is similar to @code{border},
but it just adds extra space around @var{picture},
without painting it.  The @var{size} is specified the same way.
If @var{background} is specified,
it becomes the background paint for the entire padded
rectangle (both @var{picture} and the extra padding).
@example
#|kawa:3|# @kbd{(define circ1 (fill 'teal (circle 25)))}
#|kawa:4|# @kbd{(zbox (line &P[-30 20] &P[150 20])}
#|kawa:5|# @kbd{  (hbox circ1 (padding 6 'yellow circ1) (padding 6 circ1)))}
@image{images/padding-1}
@end example
This shows a circle drawn three ways:
as-is; with padding and a background color;
with padding and a transparent background.
A line is drawn before (below) the circles to contrast
the yellow vs transparent backgrounds.
@end deffn

@deffn Procedure re-center [xpos] [ypos] picture
Translate the @var{picture} such that the point specified by @var{xpos}
and @var{ypos} is the new origin point, adjusting the bounding box to match.
If the @var{picture} is a shape, so is the result.

The @var{xpos} can have four possible values, all of which are symbols:
@code{'left} (move the origin to the left edge of the bounding box);
@code{'right} (move the origin to the left edge of the bounding box);
@code{'center} (or @code{'centre}) (move the origin to halfway between the left and right edges);
or @code{'origin} (don't change the location along the x-axis).
The @var{ypos} can likewise have four possible values:
@code{'top} (move the origin to the top edge of the bounding box);
@code{'bottom} (move the origin to the bottom edge of the bounding box);
@code{'center} (or @code{'centre}) (move the origin to halfway between the
top and bottom edges);
or @code{'origin} (don't change the location along the y-axis).

A single @code{'center} argument
is the same as specifying @code{'center} for both axis; this is the default.
A single @code{'origin} argument
is the same as specifying @code{'origin} for both axis;
this is the same as just @var{picture}.

The 16 control points are shown below, relative to a picture's
bounding box and the X- and Y-axes.
The abbreviations have the obvious values, for example
@code{LC} means @code{'left 'center}.
@example
LT    OT  CT      RT
  ┌────┬──────────┐
  │    │          │
  │    │          │
LC│   OC  C       │RC
LO├────O──CO──────┤RO
  │    │          │
  └────┴──────────┘
LB    OB  CB       RB   
@end example
The result of (for example) @code{(re-center 'left 'center @var{P})}
is @var{P} translated so the origin is at control point @code{LC}.

@example
#|kawa:1|# @kbd{(define D (fill 'light-steel-blue (polygon &P[-20 0] &P[0 -20] &P[60 0] &P[0 40])))}
#|kawa:2|# @kbd{(zbox D (draw 'red (circle 5)))}
@image{images/re-center-1}
@end example
Above we defined @code{D} as a vaguely diamond-shaped quadrilateral.
A small red circle is added to show the origin point.
Below we display 5 versions of @code{D} in a line (an @code{hbox}),
starting with the original @code{D} and 4 calls to @code{re-center}.
@example
#|kawa:3|# @kbd{(zbox (hbox D (re-center 'top D) (re-center 'bottom D)}
#|....:4|# @kbd{              (re-center 'center D) (re-center 'origin D))}
#|....:5|# @kbd{  (line &P[0 0] &P[300 0]))}
@image{images/re-center-2}
@end example
The line at @var{y=0} shows the effects of @code{re-center}.
@end deffn

@subsection Images

An image is a picture represented as a rectangular grid of color values.
An image file is some encoding (usually compressed) of an image,
and mostly commonly has the extensions @code{png}, @code{gif},
or @code{jpg}/@code{jpeg}.

A ``native image'' is an instance of @code{java.awt.image.BufferedImage},
while a ``picture image'' is an instance of @code{gnu.kawa.models.DrawImage}.
(Both classes implement the @code{java.awt.image.RenderedImage} interface.)
A @code{BufferedImage} is automatically converted to a @code{DrawImage}
when needed.

@deffn Procedure image bimage
@deffnx Procedure image picture
@deffnx Procedure image src: path

Creates a picture image, using either an existing native image @var{bimage},
or an image file specified by @var{path}.

Writing @code{(image src: @var{path})} is roughly the same
as @code{(image (read-image @var{path}))} except that the former
has the @var{path} associated with the resulting picture image.
This can make a difference when the image is used or displayed.

If the argument is a @var{picture}, it is converted to an image
as if by @code{->image}.
@end deffn

@deffn Procedure image-read path
Read an image file from the specified @var{path},
and returns a native image object (a @code{BufferedImage}).
@example
#|kawa:10|# @kbd{(define img1 (image-read "http://pics.bothner.com/2013/Cats/06t.jpg"))}
#|kawa:11|# @kbd{img1}
@image{images/image-cat-1a}
#|kawa:12|# @kbd{(scale 0.6 (rotate 30 img1))}
@image{images/image-cat-1b}
@end example
@end deffn

Note that while @code{img1} above is a (native) image,
the scaled rotated image is not an image object.
It is a picture - a more complex value that @emph{contains} an image.

@deffn Procedure image-write picture path
The @var{picture} is converted to an image
(as if by using @code{->image}) and then it is written
to the specified @var{path}.
The format used depends on (the lower-cased string value of) the path:
A JPG file if the name ends with @code{".jpg"} or @code{".jpeg"};
a GIF file if the name ends with @code{".gif"};
a PNG file if the name ends with @code{".png"}.
(Otherwise, the defalt is PNG, but that might change.)
@end deffn

@deffn Procedure image-width image
@deffnx Procedure image-height image
Return the width or height of the given @var{image}, in pixels.
@end deffn

@deffn Procedure ->image picture
Convert @var{picture} to an image (a @code{RenderedImage}).
If the @var{picture} is an image, return as-is.
Otherwise, create an empty image (a @code{BufferedImage} whose size is the
@var{picture}'s bounding box), and ``paint'' the @var{picture} into it.
@example
#|kawa:1|# @kbd{(define c (fill (circle 10)))}
#|kawa:2|# @kbd{(scale 3 (hbox c (->image c)))}
@image{images/image-scaled-1}
@end example
Here we take a circle @code{c}, and convert it to an image.
Note how when the image is scaled, the pixel artifacts are very noticable.
Also note how the origin of the image is the top-level corner,
while the origin of the original circle is its center.
@end deffn

@subsection Compositing - Controlling how pictures are combined

@deffn Procedure with-composite [[compose-op] picture] ...
Limited support - SVG and DomTerm output has not been implemented.
@end deffn

@subsection Displaying and exporting pictures 

@subsubsection Export to SVG

@deffn Procedure picture-write-svg picture path [headers]
Writes the @var{picture} to the file specified @var{path},
in SVG (Structered Vector Graphics) format.
If @var{headers} is true (which is the default)
first write out the XML and DOCTYPE declarations
that should be in a well-formed standaline SVG file.
Otherwise, just write of the @code{<svg>} element.
(Modern browers should be able to display a file
consisting of just the @code{<svg>} element,
as long as it has extension @code{.svg}, @code{.xml}, or @code{.html};
the latter may add some extra padding.)
@end deffn

@deffn Procedure picture->svg-node picture
Returns a SVG representation of @code{picture},
in the form of an @code{<svg>} element,
similar to those discussed in @ref{Creating XML nodes}.
If you convert the @code{<svg>} element to a string,
you get formatted XML;
if you @code{write} the @code{<svg>} element
you get an @ref{XML literals,XML literal} of form @code{"#<svg>...</svg>"}.
If you @code{display} the @code{<svg>} element
in a DomTerm terminal you get the picture (as a picture).
This works because when you display an element in DomTerm
it gets inserted into the display.
@end deffn

@subsubsection Display in Swing

These procedures require @code{(import (kawa swing))} in addition to
@code{(import (kawa pictures))}.

The convenience function @code{show-picture} is useful
for displaying a picture in a new (Swing) window.

@deffn Procedure show-picture picture
If this is the first call to @code{show-pictures},
displays @var{picture} in a new top-level window (using the Swing toolkit).
Sequenent calls to  @code{show-picture} will reuse the window.
@example
#|kawa:1|# @kbd{(import (kawa swing) (kawa pictures))}
#|kawa:2|# @kbd{(show-picture @var{some-picture})}
#|kawa:3|# @kbd{(set-frame-size! &D[200 200])} ; Adjust window size
#|kawa:4|# @kbd{(show-picture @var{some-other-picture})}
@end example
@end deffn

@deffn Procedure picture->jpanel picture
Return a @code{JPanel} that displays @var{picture}.
You can change the displayed picture by:
@example
(set! @var{panel}:picture @var{some-other-picture})
@end example
@end deffn

@deffn Procedure set-frame-size! size [frame]
If @var{frame} is specified, set its size.
Otherwise, remember the size for future @code{show-picture} calls;
if there is already a @code{show-picture} window, adjust its size.
@end deffn

@subsubsection Convert to image

You can convert a picture to an image using the @code{->image} procedure,
or write it to a file using the @code{image-write} procedure.

@node Building JavaFX applications
@section Building JavaFX applications

@cindex JavaFX
Kawa makes it easy to build ``rich client'' (i.e. GUI) applications using
@uref{http://www.oracle.com/technetwork/java/javafx/overview/index.html,JavaFX}.
For example the following program will print up a window with a button;
clicking on the button will print a message on the console output about the
event.
@example
(require 'javafx-defs)
(javafx-application)

(javafx-scene
 title: "Hello Button"
 width: 600 height: 450
 (Button
  text: "Click Me"
  layout-x: 25
  layout-y: 40
  on-action: (lambda (e) (format #t "Event: ~s~%~!" e))))
@end example

JavaFX support is builtin to the pre-built @code{kawa-@value{VERSION}.jar}.
It is easiest to use JDK 8; see below if you're using JDK 7.
If you build Kawa from source, specify @code{--with-javafx} on the
@code{configure} command line (assuming you're using JDK 8).

Assume the above file is @code{HelloButton1.scm}, you can
run it like this:
@example
$ kawa HelloButton1.scm
@end example

For more information and examples read this (slightly older)
@uref{http://per.bothner.com/blog/2011/JavaFX-using-Kawa-intro/,introduction},
and
@uref{http://localhost/per/blog/2011/JavaFX-using-Kawa-animation/,this on animation}.

The @code{browse-kawa-manual} script in the @code{doc} directory (source only)
uses JavaFX WebView to create a window for browsing the Kawa documentation.

@subsection Using JavaFX with JDK 7
JDK 8 ships with JavaFX, and it is in the default @code{CLASSPATH}.
JDK 7 update 9 or later does have JavaFX included, but it is a separate
@code{jfxrt.jar} which not in the default @code{CLASSPATH}.
Thus you have to explicitly add @code{jfxrt.jar}.
To run the previous @code{HelloButton1.scm} you can do:
@example
java -cp $JAVA_HOME/lib/jfxrt.jar:$KAWA_HOME/kawa.jar HelloButton1.scm
@end example

If you build Kawa from source, do:
@example
$ ./configure --with-javafx=$JAVA_HOME --enable-kawa-frontend ...other-args...
@end example
The resulting Kawa binary sets up the path to @code{jfxrt.jar} so you just need to do:
@example
$ kawa HelloButton1.scm
@end example

@node Building for Android
@section Building for Android

Google's phone/tablet operating system
@uref{https://developers.google.com/android/,Android}
is based on a custom virtual machine on top of a Linux kernel.
Even though Android isn't strictly (or legally) speaking Java,
you can build Android applications using Kawa.

Below is "Hello world" written in Kawa Scheme.  A slightly
more interesting example is in @ref{Android view construction,next section}.

@example
(require 'android-defs)
(activity hello
  (on-create-view
   (android.widget.TextView (this)
    text: "Hello, Android from Kawa Scheme!")))
@end example

The following instructions have been tested on GNU/Linux,
specifically Fedora 17.
@uref{http://asieno.com/blog/index.php/post/2012/08/16/Setting-up-the-environment-Android-Kawa,This link} may be helpful if you're building on Windows.

@subsection Downloading and setting up the Android SDK

First @uref{http://code.google.com/android/download.html,download the Android SDK}. Unzip in a suitable location, which we'll refer to as @code{ANDROID_HOME}.

@example
export ANDROID_HOME=/path/to/android-sdk-linux
PATH=$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools:$PATH
@end example

Next you have to get the appropriate platform SDK:

@example
$ android update sdk
@end example
You need to select an Android ``platform''.
Platform (API) 16 corresponds to Android 4.1.2 (Jelly Bean).
Select that or whatever you prefer, and click @code{Install}.
(You can install multiple platforms, but each project
is built for a specific platform.)

@example
ANDROID_PLATFORM=android-16
@end example

@subsection Building Kawa for Android

Set @code{JAVA_HOME} to where your JDK tree is.
You should use JDK 6; JDK 7 does not work at time of writing.

@example
$ export JAVA_HOME=/opt/jdk1.6
@end example

First @ref{Getting Kawa,get the Kawa source code}.

If using Ant (as is recommended on Windows):

@example
$ ant -Denable-android=true
@end example
Alternatively, you can use @code{configure} and @code{make}:

@example
$ KAWA_DIR=path_to_Kawa_sources
$ cd $KAWA_DIR
$ ./configure --with-android=$ANDROID_HOME/platforms/$ANDROID_PLATFORM/android.jar --disable-xquery --disable-jemacs
$ make
@end example

@subsection Creating the application

Next, we need to create a project or ``activity''.
This tutorial assumes you want to create the project
in the target directory @code{KawaHello},
with the main activity being a class named @code{hello} in a
package @code{kawa.android}:
@example
PROJECT_DIR=KawaHello
PROJECT_CLASS=hello
PROJECT_PACKAGE=kawa.android
PROJECT_PACKAGE_PATH=kawa/android
@end example

To create the project use the following command:
@example
$ android create project --target $ANDROID_PLATFORM --name $PROJECT_DIR --activity $PROJECT_CLASS --path ./$PROJECT_DIR --package $PROJECT_PACKAGE
@end example

Replace the skeleton @code{hello.java} by the Scheme code at the
top of this note, placing in a file named @code{hello.scm}:
@example
$ cd $PROJECT_DIR
$ HELLO_APP_DIR=`pwd`
$ cd $HELLO_APP_DIR/src/$PROJECT_PACKAGE_PATH
$ rm $PROJECT_CLASS.java
$ @i{create} $PROJECT_CLASS.scm
@end example

We need to copy/link the Kawa jar file so the Android SDK can find it:
@example
$ cd $HELLO_APP_DIR
$ ln -s $KAWA_DIR/kawa-@value{VERSION}.jar libs/kawa.jar
@end example

Optionally, you can use kawart-@value{VERSION}.jar, which is slightly smaller,
but does not support eval, and does not get built by the Ant build:
@example
$ ln -s $KAWA_DIR/kawart-@value{VERSION}.jar libs/kawa.jar
@end example

Copy or link @code{custom_rules.xml} from the Kawa sources:
@example
ln -s $KAWA_DIR/gnu/kawa/android/custom_rules.xml .
@end example

Finally to build the application just do:
@example
$ ant debug
@end example

@subsection Running the application on the Android emulator

First you need to create an @uref{http://developer.android.com/tools/devices,Android Virtual Device (avd)}. Start:
@example
android
@end example
Then from menu @code{Tools} select @code{Manage AVDs...}.
In the new window click @code{New....}
Pick a @code{Name} (we use @code{avd16} in the following),
a @code{Target} (to match @code{$ANDROID_PLATFORM}),
and optionally change the other properties, before clicking @code{Create AVD}.

Now you can start up the Android emulator:

@example
$ emulator -avd avd16 &
@end example
Wait until Android has finished booting (you will see the Android home screen),
click the menu and home buttons. Now install our new application:

@example
adb install bin/KawaHello-debug.apk
@end example

@subsection Running the application on your device

If the emulator is running, kill it:
@example
$ kill %emulator
@end example

On your phone or other Android devude, enable USB debugging.
(This is settable from the @code{Settings} application,
under @code{Applications / Development}.)

Connect the phone to your computer with the USB cable.
Verify that the phone is accessible to @code{adb}:
@example
$ adb devices
List of devices attached 
0A3A560F0C015024	device
@end example

If you don't see a device listed, it may be permission problem. You can figure out which device corresponds to the phone by doing:

@example
$ ls -l /dev/bus/usb/*
/dev/bus/usb/001:
total 0
...
crw-rw-rw- 1 root wheel 189, 5 2010-10-18 16:52 006
...
@end example

The timestamp corresponds to when you connected the phone.
Make the USB connection readable:
@example
$ sudo chmod a+w /dev/bus/usb/001/006
@end example

Obviously if you spend time developing for an Androd phone you'll want to automate this process;
@uref{https://sites.google.com/site/siteofhx/Home/android/drivers/udc,this link}
or @uref{https://groups.google.com/forum/?fromgroups=#!topic/android-developers/nTfhhPktGfM,this link} may be helpful.

Anyway, once @code{adb} can talk to the phone, you install in the same way as before:
@example
adb install bin/KawaHello-debug.apk
@end example

@subsection Some debugging notes

You will find a copy of the SDK documentation in @code{$ANDROID_HOME/docs/index.html}.

If the emulator complains that your application has stopped unexpectedly, do:
@example
$ adb logcat
@end example

This shows log messages, stack traces, output from the @code{Log.i} logging method, and other useful information.
(You can alternatively start @code{ddms} (Dalvik Debug Monitor Service), click on the @code{kawa.android line} in the top-left sub-window to select it, then from the @code{Device} menu select @code{Run logcat....}).

To uninstall your application, do:
@example
$ adb uninstall kawa.android
@end example

@subsection Other resources

(A more interesting @uref{http://androidscheme.blogspot.com/2010/10/text-to-speech-app.html,text-to-speech} example app is on Santosh Rajan's @uref{http://androidscheme.blogspot.com/,Android-Scheme blog}.)

@uref{https://github.com/ecraven/SchemeAndroidOGL}

@node Android view construction
@section Android view construction

An Android user interface is constructed from @code{View} objects.
The following is an example that illustrates some features of
Kawa to help write views hierarchies,
The example is self-contained, and can be built and run
as described in @ref{Building for Android}.

@example
(require 'android-defs)
(activity hello
  (on-create-view 
   (define counter ::integer 0)
   (define counter-view
     (TextView text: "Not clicked yet."))
   (LinearLayout orientation: LinearLayout:VERTICAL
    (TextView text: "Hello, Android from Kawa Scheme!")
    (Button
     text: "Click here!"
     on-click-listener: (lambda (e)
                          (set! counter (+ counter 1))
                          (counter-view:setText
                           (format "Clicked ~d times." counter))))
    counter-view)))
@end example

The first @code{import} form imports various useful definitions
from the Kawa Android library.  Using these is not required for
writing a Kawa application, but makes it more convenient.

The names @code{LinearLayout}, @code{TextView}, and @code{Button}
are just aliases for standard Android @code{View} sub-classes.
A few are prefined by @code{(require 'android-defs)}, or you
can define them yourself using @code{define-alias}.

An Android application consists of one or more @dfn{activities},
each of which is an instance of the @code{android.app.Activity} class.
You can use the @code{activity} macro to define your @code{Activity} class.
The first macro argument (in this case @code{hello}) is the class name,
and the others are members of the class, in the syntax of
a @stxref{field-or-method-decl}.  The sub-form @code{on-create-view}
is an abbreviation for declaring an @code{onCreate} method
(which is called when the @code{Activity} starts up
@c LOOK THIS UP - also when re-started?
followed by a @code{setContentView}:
The body of the @code{on-create-view} is evaluated.
The result should be a @code{View} expression,
which is passed to @code{setContentView}.

@deffn Procedure current-activity [new-value]
With no arguments, returns the current @code{Activity}.
If a @var{new-value} argument is given, sets the current activity.
It is set automatically by the @code{on-create} and @code{on-create-view}
methods of the @code{activity} macro.

Since @code{current-activity} is a @ref{Parameter objects,parameter object},
you can
locally change the value using @ref{parameterize-syntax,@code{parameterize}}.
@end deffn

@subsection View object allocation

To create an instance of a @code{View} class you ``call'' the
class as if it were a function,
as described in @ref{Allocating objects}.
For example:
@example
(TextView (this) text: "Hello, Android from Kawa Scheme!")
@end example

If you @code{(require 'android-defs)} that defines
some special handling for @code{View} classes.
You can leave out the @code{(this)} argument,
which refers to the enclosing @code{Activity}:
@example
(TextView text: "Hello, Android from Kawa Scheme!")
@end example

@subsection Event handlers

You can register event listeners on Android @code{View} objects
using methods typically named @code{setOn@var{EVENT}Listener}.
For example @code{setOnClickListener}.  When allocating
an object you can leave out the @code{set}, and you can optionally
use Scheme-style names: @code{on-click-listener}.  The argument
is an object of a special nested listener class,
for example @code{View$OnClickListener}.  These are
single-method classes, so you can use a lambda expression
and @ref{SAM-conversion} will automatically create the needed
listener class.

@node System inquiry
@section System inquiry

@defvar home-directory
A string containing the home directory of the user.
@end defvar

@deffn Procedure command-line
Returns a nonempty list of immutable strings. The first element is
an implementation-specific name for the running top-level
program.
The remaining elements are the command-line arguments,
as passed to the @code{main} method (except for those
flags processed by Kawa itself).

The first element will depend on how the Kawa module was invoked.
Kawa uses the following rules to determine the command name:

@enumerate
@item
If the property @code{kawa.command.name} is set, that is used.
This variable can be set on the @code{kawa} command line,
for example from a script:
@example
kawa -Dkawa.command.name="$0" foo "$@@"
@end example
This variable is also set implicitly by the meta-arg option.  FIXME.
@item
If we're reading a source file that starts with the Unix command-file prefix
@samp{#!/} then we use the name of the source file.
The assumption is that such a file is an executable script.
@item
If the Java property @code{kawa.command.line} is set,
then we use that (after stripping off text that duplicates
the remaining arguments).
The @code{kawa} program sets this property to the
command line used to invoke it
(specifically the contents of the entire @code{argv} array),
before invoking the @code{java} program.
@item
If the Java property @code{sun.java.command} is set,
then we use that (after stripping off text that duplicates
the remaining arguments), and then prepending the string @code{"java "}.
The OpenJDK @code{java} program sets this property.
@item
If all else fails, the command name is @code{"kawa"}.
@end enumerate
@end deffn

@defvar command-line-arguments
Any command-line arguments (following flags processed by Kawa itself)
are assigned to the global variable @samp{command-line-arguments},
which is a vector of strings.
@end defvar

@deffn Procedure process-command-line-assignments
Process any initial command-line options that set variables.
These have the form @code{@var{name}=@var{value}}.
Any such command-line options (at the start of the command-line)
are processed and removed from the command-line.
@example
$ java kawa.repl -- abc=123 def
#|kawa:1|# (write (command-line))
("java kawa.repl --" "abc=123" "def")
#|kawa:2|# (process-command-line-assignments)
#|kawa:3|# (write (command-line))
("java kawa.repl -- abc=123" "def")
#|kawa:4|# abc
123
@end example
This function is mostly useful for Kawa applications
compiled with the @code{--main} option.
(It is used to set XQuery @code{external} variables.)
@end deffn

@deffn Procedure get-environment-variable name
Many operating systems provide each running process with
an environment conisting of environment variables.
(This environment is not to be confused with the
Scheme environments that can be passed to @code{eval}.)
Both the name and value of an environment variable are
strings. The procedure @code{get-environment-variable}
returns the value of the environment variable @var{name},
or @code{#f} if the environment variable is not found.
@c It may use locale information to encode the name and
@c decode the value of the environment variable.
(This uses the @code{java.lang.System:getenv} method.)
It is an error to mutate the resulting string.
@example
(get-environment-variable "PATH")
    @result{} "/usr/local/bin:/usr/bin:/bin"
@end example
@end deffn

@deffn Procedure get-environment-variables
Returns the names and values of all the environment variables as an alist,
where the car of each entry is the name of an environment variable,
and the cdr is its value, both as strings.
It is an error to mutate any of the strings or the alist itself.
@example
(get-environment-variables)
  @result{} (("USER" . "root") ("HOME" . "/"))
@end example
@end deffn

@node Processes
@section Processes

A @dfn{process} is a native (operating-system-level) application or
program that runs separately from the current virtual machine.

Many programming languages have facilities to allow access to system
processes (commands).  (For example Java has @code{java.lang.Process}
and @code{java.lang.ProcessBuilder}.)
These facilities let you send data to the standard input, extract the
resulting output, look at the return code, and sometimes even pipe
commands together.   However, this is rarely as easy as it is using
the old Bourne shell; for example command substitution is awkward.
Kawa's solution is based on these two ideas:
@itemize
@item
A ``process expression'' (typically a function call) evaluates to a
@code{LProcess} value, which provides access to a Unix-style
(or Windows) process.
@item
In a context requiring a string (or a bytevector), an @code{LProcess} is
automatically converted to a string (or bytevector)
comprising the standard output from the process.
@end itemize

@subsection Creating a process

The most flexible way to start a process is with either the
@code{run-process} procedure or
the @code{&`@lbracechar{}@meta{command}@rbracechar{}} syntax
for @ref{process literals}.

@deffn Procedure run-process @arbno{@stxref{process-keyword-argument}} @meta{command}
Creates a process object, specifically a @code{gnu.kawa.functions.LProcess}
object.
A @var{process-keyword-argument} can be used to set various options,
as discussed below.

The @var{command} is the process command-line (name and arguments).
It can be an array of strings, in which case those are used as the
command arguments directly:
@example
(run-process ["ls" "-l"])
@end example
The @var{command} can also be a single string, which is split (tokenized)
into command arguments separated by whitespace.
Quotation groups words together just like traditional shells:
@example
(run-process "cmd a\"b 'c\"d k'l m\"n'o")
   @result{} (run-process ["cmd"   "ab 'cd"   "k'l m\"no"])
@end example

The syntax shorthand @code{&`@lbracechar{}@meta{command}@rbracechar{}}
or @code{&sh@lbracechar{}@meta{command}@rbracechar{}} (discussed below)
is usually more convenient.
@end deffn

@display
@stxdef{process-keyword-argument}
    @stxref{process-redirect-argument}
  | @stxref{process-environment-argument}
  | @stxref{process-misc-argument}
@end display

We discuss @stxref{process-redirect-argument} and
@stxref{process-environment-argument} later.
@anchor{meta-process-misc-argument}
The @var{process-misc-argument} options are just the following:
@table @asis
@item @stxlit{shell:} @var{shell}
Currently, @var{shell} must be one of @code{#f} (which is ignored)
or @code{#t}.  The latter means to use an external shell to tokenize
the @var{command}.
I.e. the following are equivalent:
@example
(run-process shell: #t "@var{command}")
(run-process ["/bin/sh" "-c" "@var{command}"])
@end example
@item @stxlit{directory:} @var{dir}
Change the working directory of the new process to @var{dir}.
@end table

@anchor{process literals}
@subsection Process literals

A simple @dfn{process literal} is a kind of
@ref{Named quasi-literals,named literal} that uses the backtick character
(@code{`}) as the @stxref{cname}.
For example:
@example
&`@lbracechar{}date --utc@rbracechar{}
@end example
This is equivalent to:
@example
(run-process "date --utc")
@end example

In general the following are
roughly equivalent (using @ref{string quasi-literals}):
@example
&`[@var{args}...]@lbracechar{}@var{command}@rbracechar{}
(run-process @var{args}... &@lbracechar{}@var{command}@rbracechar{})
@end example
The reason for the ``roughly'' is if @var{command} contains
escaped sub-expressions; in that case @code{&`} may process
the resulting values differently from plain string-substitution,
as discussed below.

If you use @code{&sh} instead of @code{&`} then a shell is used:
@example
&sh@lbracechar{}rm *.class@rbracechar{}
@end example
which is equivalent to:
@example
&`@lbracechar{}/bin/sh -c "rm *.class"@rbracechar{}
@end example

In general, the following are equivalent:
@example
&sh[@var{args}...]@lbracechar{}@var{command}@rbracechar{}
&`[shell: #t @var{args}...]@lbracechar{}@var{command}@rbracechar{}
@end example

@subsection Process values and process output

The value returned from a call to @code{run-process} or a process literal
is an instance of @code{gnu.kawa.functions.LProcess}.
This class extends @code{java.lang.Process}, so you can treat it as
any other @code{Process} object.
@example
#|kawa:1|# (define p1 &`@lbracechar{}date --utc@rbracechar{})
#|kawa:2|# (p1:toString)
gnu.kawa.functions.LProcess@@377dca04
#|kawa:3|# (write p1)
gnu.kawa.functions.LProcess@@377dca04
@end example

What makes an @code{LProcess} interesting is that it is also
a @ref{Blobs,blob}, which is automatically
converted to a string (or bytevector) in a context that requires it.
The contents of the blob comes from the standard output of the process.
The blob is evaluated @ref{Lazy evaluation,lazily},
so data it is only collected when requested.

@example
#|kawa:4|# (define s1 ::string p1)
#|kawa:5|# (write s1)
"Wed Jan  1 01:18:21 UTC 2014\n"
#|kawa:6|# (define b1 ::bytevector p1)
(write b1)
#u8(87 101 100 32 74 97 110 ... 52 10)
@end example

The @code{display} procedure prints it in ``human'' form, as a string:
@example
#|kawa:7|# (display p1)
Wed Jan  1 01:18:21 UTC 2014
@end example
This is also the default REPL formatting:
@example
#|kawa:8|# &`@lbracechar{}date --utc@rbracechar{}
Wed Jan  1 01:18:22 UTC 2014
@end example

When you type a command to a shell, its output goes to the console,
Similarly, in a REPL the output from the process
is copied to the console output - which can sometimes by optimized
by letting the process inherit its standard output from the Kawa process.

@subsection Substitution and tokenization

To substitute the variable or the result of an expression
in the command line use the usual syntax for quasi literals:
@example
(define filename (make-temporary-file))
&sh@lbracechar{}run-experiment >&[filename]@rbracechar{}
@end example

Since a process is convertible a string, we need no special
syntax for command substitution:
@example
`@lbracechar{}echo The directory is: &[&`@lbracechar{}pwd@rbracechar{}]@rbracechar{}
@end example
or equivalently:
@example
`@lbracechar{}echo The directory is: &`@lbracechar{}pwd@rbracechar{}@rbracechar{}
@end example

@anchor{substitution-tokenization}
Things get more interesting when considering the interaction between
substitution and tokenization. This is not simple string
interpolation. For example, if an interpolated value contains a quote
character, we want to treat it as a literal quote, rather than a token
delimiter. This matches the behavior of traditional shells. There are
multiple cases, depending on whether the interpolation result is a
string or a vector/list, and depending on whether the interpolation is
inside quotes.

@itemize
@item
If the value is a string, and we're not inside quotes, then all
non-whitespace characters (including quotes) are literal, but
whitespace still separates tokens:
@example
(define v1 "a b'c ")
&`@lbracechar{}cmd x y&[v1]z@rbracechar{}   @result{}  (run-process ["cmd" "x" "ya" "b'c" "z"])
@end example
@item
If the value is a string, and we are inside single quotes,
all characters (including whitespace) are literal.
@example
&`@lbracechar{}cmd 'x y&[v1]z'@rbracechar{}   @result{}  (run-process ["cmd" "x ya b'c z"])
@end example
Double quotes work the same except that newline is an argument
separator. This is useful when you have one filename per line, and the
filenames may contain spaces, as in the output from @code{find}:
@example
&`@lbracechar{}ls -l "&`@lbracechar{}find . -name '*.pdf'@rbracechar{}"@rbracechar{}
@end example
This solves a problem that is quite painful with traditional shells.
@item
If the value is a vector or list (of strings), and we're not inside
quotes, then each element of the array becomes its own argument, as-is:
@example
(define v2 ["a b" "c\"d"])
&`@lbracechar{}cmd &[v2]@rbracechar{}  @result{}  (run-process ["cmd" "a b" "c\"d"])
@end example
However, if the enclosed expression is adjacent to non-space non-quote
characters, those are prepended to the first element, or appended to
the last element, respectively.
@example
&`@lbracechar{}cmd x&[v2]y@rbracechar{}   @result{}  (run-process ["cmd" "xa b" "c\"dy"])
&`@lbracechar{}cmd x&[[]]y@rbracechar{}   @result{}  (run-process ["cmd" "xy"])
@end example
This behavior is similar to how shells handle @code{"$@@"}
(or @code{"$@lbracechar{}name[@@]@rbracechar{}"} for general arrays), though in Kawa you would
leave off the quotes.

Note the equivalence:
@example
&`@lbracechar{}&[array]@rbracechar{}   @result{}  (run-process array)
@end example
@item
If the value is a vector or list (of strings), and we @emph{are}
inside quotes, it is equivalent to interpolating a single string
resulting from concatenating the elements separated by a space:
@example
&`@lbracechar{}cmd "&[v2]"@rbracechar{}
 @result{}  (run-process ["cmd" "a b c\"d"])
@end example
This behavior is similar to how shells handle @code{"$*"} (or
@code{"$@lbracechar{}name[*]@rbracechar{}"} for general arrays).
@item
If the value is the result of a call to @code{unescaped-data} then it
is parsed as if it were literal. For example a quote in the unescaped
data may match a quote in the literal:
@example
(define vu (unescaped-data "b ' c d '"))
&`@lbracechar{}cmd 'a &[vu]z'@rbracechar{}   @result{}  (run-process ["cmd" "a b " "c" "d" "z"])
@end example
@item
If we're using a shell to tokenize the command, then we add quotes or
backslashes as needed so that the shell will tokenize as described
above:
@example
(define authors ["O'Conner" "de Beauvoir"])
&sh@lbracechar{}list-books &[authors]@rbracechar{}
@end example
The command passed to the shell is:
@example
list-books 'O'\''Conner' 'de Beauvoir
@end example
Having quoting be handled by the @code{$construct$:sh}
implementation automatically eliminates common code injection problems.
@end itemize

Smart tokenization only happens when using the quasi-literal forms such
as @code{&`@lbracechar{}command@rbracechar{}}.
You can of course use string templates with @code{run-process}:
@example
(run-process &@lbracechar{}echo The directory is: &`@lbracechar{}pwd@rbracechar{}@rbracechar{})
@end example
However, in that case there is no smart tokenization: The template is
evaluated to a string, and then the resulting string is tokenized,
with no knowledge of where expressions were substituted.

@subsection Input/output redirection

You can use various keyword arguments to specify standard input, output,
and error streams. For example to lower-case the text in @code{in.txt},
writing the result to @code{out.txt}, you can do:
@example
&`[in-from: "in.txt" out-to: "out.txt"]@lbracechar{}tr A-Z a-z@rbracechar{}
@end example
or:
@example
(run-process in-from: "in.txt" out-to: "out.txt" "tr A-Z a-z")
@end example

@anchor{meta-process-redirect-argument}
A @var{process-redirect-argument} can be one of the following:

@table @asis
@item @stxlit{in:} @var{value}
The @var{value} is evaluated, converted to a string (as if
using @code{display}), and copied to the input file of the process.
The following are equivalent:
@example
&`[in: "text\n"]@lbracechar{}command@rbracechar{}
&`[in: &`@lbracechar{}echo "text"@rbracechar{}]@lbracechar{}command@rbracechar{}
@end example
You can pipe the output from @code{command1} to the input
of @code{command2} as follows:
@example
&`[in: &`@lbracechar{}command1@rbracechar{}]@lbracechar{}command2@rbracechar{}
@end example
@item @stxlit{in-from:} @var{path}
The process reads its input from the specified @var{path}, which
can be any value coercible to a @code{filepath}.
@item @stxlit{out-to:} @var{path}
    The process writes its output to the specified @var{path}. 
@item @stxlit{err-to:} @var{path}
    Similarly for the error stream. 
@item @stxlit{out-append-to:} @var{path}
@item @stxlit{err-append-to:} @var{path}
    Similar to @code{out-to} and @code{err-to}, but append to the file
    specified by @var{path}, instead of replacing it.
@item @stxlit{in-from: 'pipe}
@item @stxlit{out-to: 'pipe}
@item @stxlit{err-to: 'pipe}
Does not set up redirection. Instead, the specified stream is available
using the methods @code{getOutputStream}, @code{getInputStream},
or @code{getErrorStream}, respectively, on the resulting @code{Process} object,
just like Java's @code{ProcessBuilder.Redirect.PIPE}.
@item @stxlit{in-from: 'inherit}
@item @stxlit{out-to: 'inherit}
@item @stxlit{err-to: 'inherit}
Inherits the standard input, output, or error stream from the
current JVM process. 
@item @stxlit{out-to:} @var{port}
@item @stxlit{err-to:} @var{port}
Redirects the standard output or error of the process to
the specified @var{port}.
@item @stxlit{out-to: 'current}
@item @stxlit{err-to: 'current}
Same as @code{out-to: (current-output-port)},
or @code{err-to: (current-error-port)}, respectively. 
@item @stxlit{in-from:} @var{port}
@item @stxlit{in-from: 'current}
Re-directs standard input to read from the @var{port}
(or @code{(current-input-port)}). It is unspecified how much is read from
the @var{port}. (The implementation is to use a thread that reads from the
port, and sends it to the process, so it might read to the end of the port,
even if the process doesn't read it all.) 
@item @stxlit{err-to: 'out}
Redirect the standard error of the process to be merged with the
standard output. 
@end table

The default for the error stream (if neither @code{err-to} or
@code{err-append-to} is specified) is equivalent to @code{err-to: 'current}.

@emph{Note:} Writing to a port is implemented by copying the output or error
stream of the process. This is done in a thread, which means we don't have
any guarantees when the copying is finished. (In the future we might
change @code{process-exit-wait} (discussed later) wait for not only the
process to finish, but also for these helper threads to finish.)

A @uref{https://en.wikipedia.org/wiki/Here_document,here document} is
a form a literal string, typically multi-line, and commonly used in
shells for the standard input of a process.  You can use string literals or
@ref{string quasi-literals} for this.
For example, this passes the string @code{"line1\nline2\nline3\n"} to
the standard input of @code{command}:
@example
(run-process [in: &@lbracechar{}
    &|line1
    &|line2
    &|line3
    @rbracechar{}] "command")
@end example

Note the use of @code{&|} to mark the end of ignored indentation.

@subsection Pipe-lines

Piping the output of one process as the input of another
is in princple easy - just use the @code{in:}
process argument.  However, writing a multi-stage pipe-line quickly gets ugly:
@example
&`[in: &`[in: "My text\n"]@lbracechar{}tr a-z A-Z@rbracechar{}]@lbracechar{}wc@rbracechar{}
@end example
The convenience macro @code{pipe-process} makes this much nicer:
@example
(pipe-process
  "My text\n"
  &`@lbracechar{}tr a-z A-Z@rbracechar{}
  &`@lbracechar{}wc@rbracechar{})
@end example

@deffn Syntax pipe-process input @arbno{process}
All of the @var{process} expressions must be @code{run-process} forms,
or equivalent @code{&`@lbracechar{}command@rbracechar{}} forms.
The result of evaluating @var{input} becomes the input to the first
@var{process}; the output from the first @var{process} becomes
the input to the second @var{process}, and so on.  The result of
whole @code{pipe-process} expression is that of the last @var{process}.

Copying the output of one process to the input of the next is
optimized: it uses a copying loop in a separate thread. Thus you can
safely pipe long-running processes that produce huge output. This
isn't quite as efficient as using an operating system pipe, but is
portable and works pretty well.
@end deffn

@subsection Setting the process environment

@anchor{meta-process-environment-argument}
By default the new process inherits the system environment of the current
(JVM) process as returned by @code{System.getenv()}, but you can override it.
A @var{process-environment-argument} can be one of the following:

@table @asis
@item @stxlit{env-}@var{name}@stxlit{:} @var{value}
In the process environment, set the @code{"@var{name}"} to the
specified @var{value}. For example:
@example
&`[env-CLASSPATH: ".:classes"]@lbracechar{}java MyClass@rbracechar{}
@end example
@item @var{NAME}@stxlit{:} @var{value}
Same as using the @code{env-@var{NAME}} option above, but only if the
@code{@var{NAME}} is uppercase (i.e. if uppercasing @code{@var{NAME}} yields
the same string). For example the previous example could be written:
@example
&`[CLASSPATH: ".:classes"]@lbracechar{}java MyClass@rbracechar{}
@end example
@item @stxlit{environment:} @var{env}
The @var{env} is evaluated and must yield a @code{HashMap}.
This map is used as the system environment of the process. 
@end table

@subsection Waiting for process exit

When a process finishes, it returns an integer exit code.
The code is traditionally 0 on successful completion,
while a non-zero code indicates some kind of failure or error.

@deffn Procedure process-exit-wait process
The @var{process} expression must evaluate to a process
(any @code{java.lang.Process} object).
This procedure waits for the process to finish, and then returns the
exit code as an @code{int}.
@example
(process-exit-wait (run-process "echo foo")) @result{} 0
@end example
@end deffn

@deffn Procedure process-exit-ok? process
Calls @code{process-exit-wait}, and then returns @code{#false}
if the process exited it 0, and returns @code{#true} otherwise.

This is useful for emulating the way traditional shell do
logic control flow operations based on the exit code.
For example in @code{sh} you might write:
@example
if grep Version Makefile >/dev/null
then echo found Version
else echo no Version
fi
@end example

The equivalent in Kawa:

@example
(if (process-exit-ok? &`@lbracechar{}grep Version Makefile@rbracechar{})
  &`@lbracechar{}echo found@rbracechar{}
  &`@lbracechar{}echo not found@rbracechar{})
@end example

Strictly speaking these are not quite the same, since the Kawa
version silently throws away the output from @code{grep}
(because no-one has asked for it). To match the output from the @code{sh},
you can use @code{out-to: 'inherit}:
@example
(if (process-exit-ok? &`[out-to: 'inherit]@lbracechar{}grep Version Makefile@rbracechar{})
  &`@lbracechar{}echo found@rbracechar{}
  &`@lbracechar{}echo not found@rbracechar{})
@end example
@end deffn

@anchor{Exiting the current process}
@subsection Exiting the current process

@deffn Procedure exit [code]
Exits the Kawa interpreter, and ends the Java session.
Returns the value of @var{code} to the operating system:
The @var{code} must be integer, or the special
values @code{#f} (equivalent to -1), or
@code{#t} (equivalent to 0).
If @var{code} is not specified, zero is returned.
The @var{code} is a status code; by convention a non-zero
value indicates a non-standard (error) return.

Before exiting, finally-handlers (as in @code{try-finally},
or the @var{after} procedure of @code{dynamic-wind}) are
executed, but only in the current thread, and only if
the current thread was started normally. (Specifically
if we're inside an @code{ExitCalled} block with non-zero
nesting - see @code{gnu.kawa.util.ExitCalled}.)
Also, JVM shutdown hooks are executed - which includes
flushing buffers of output ports.  (Specifically
@code{Writer} objects registered with the @code{WriterManager}.)
@end deffn

@deffn Procedure emergency-exit [code]
Exits the Kawa interpreter, and ends the Java session.
Communicates an exit value in the same manner as @code{exit}.
Unlike @code{exit}, neither finally-handlers nor
shutdown hooks are executed.
@end deffn

@subsection Deprecated functions

@deffn Procedure make-process command envp
Creates a @code{<java.lang.Process>} object, using the specified
@var{command} and @var{envp}.
The @var{command} is converted to an array of Java strings
(that is an object that has type @code{<java.lang.String[]>}.
It can be a Scheme vector or list (whose elements should be
Java strings or Scheme strings);  a Java array of Java strings;
or a Scheme string.  In the latter case, the command is converted
using @code{command-parse}.
The @var{envp} is process environment;  it should be either
a Java array of Java strings, or the special @code{#!null} value.

Except for the representation of @var{envp}, this is similar to:
@example
(run-process environment: @var{envp} @var{command})
@end example
@end deffn

@deffn Procedure system command
Runs the specified @var{command}, and waits for it to finish.
Returns the return code from the command.  The return code is an integer,
where 0 conventionally means successful completion.
The @var{command} can be any of the types handled by @code{make-process}.

Equivalent to:
@example
(process-exit-wait (make-process @var{command} #!null))
@end example
@end deffn

@defvar command-parse
The value of this variable should be a one-argument procedure.
It is used to convert a command from a Scheme string to a Java
array of the constituent "words".
The default binding, on Unix-like systems, returns a new command to
invoke @code{"/bin/sh" "-c"} concatenated with the command string;
on non-Unix-systems, it is bound to @code{tokenize-string-to-string-array}.
@end defvar

@deffn Procedure tokenize-string-to-string-array command
Uses a @code{java.util.StringTokenizer} to parse the @var{command} string
into an array of words.  This splits the @var{command} using spaces
to delimit words; there is no special processing for quotes or other
special characters.
(This is the same as what @code{java.lang.Runtime.exec(String)} does.)
@end deffn

@node Time-related functions
@section Time-related functions

@deffn Procedure current-second
Returns an inexact number represent the current time on the
@uref{http://en.wikipedia.org/wiki/International_Atomic_Time,International Atomic Time (TAI)} scale.
The value 0.0 represents midnight on January 1, 1070 TAI (equivalent
to 10 seconds before midnight Universal Time), and
the value 1.0 represents on TAI second later.
Neither high acuracy nor high precision are required; in particular
returning Coordinated Universal Time plus a suitable
constant might be the best an implementation cat do.
The Kawa implementation just multiplies by 0.001 the result of calling
the method @code{currentTimeMillis} in class @code{java.lang.System}.
@end deffn

@deffn Procedure current-jiffy
Returns the number of @dfn{jiffies} as an exact integer that have
elapses since an arbitrary implementation-defined epoch (instant).
A jiffy is an implementation-defined fraction of a second which is
defined by the return value of the @code{jiffies-per-second} procedure.
The starting epoch (instant 0) is guaranteed to be constant during
a run of the program, but may vary between runs.
(At the time of writing, Kawa's jiffy is one nano-second.)

@emph{Rationale:} Jiffies are allowed to be implementation-dependent
so that @code{current-jiffy} can execute with minimal overhead.
It should be very likely that a compactly represented integer will
suffice as the return value.  Any particular jiffy size will be
inappropriate some some implementations: a microsecond is too long for
a very fast machine, while a much smaller unit would force many
implementations to return integers which have to allocated for most calls,
rendering @code{current-jiffy} less useful for accurate timing measurements.
@end deffn

@deffn Procedure jiffies-per-second
Returns an exact integer representing the number of jiffies
per SI second. This value is an implementation-specified
constant.
(At the time of writing, the value in Kawa is 1,000,000,000.)
@end deffn

@deffn Procedure sleep time
Suspends the current thread for the specified time.
The @var{time} can be either a pure number (in secords),
or a quantity whose unit is a time unit (such as @code{10s}).
@end deffn

@node Low-level functions
@section Deprecated low-level functions

These sections document older and less convenient ways
to call Java methods, access Java fields, and use Java arrays.

@anchor{Low-level Method invocation}
@subsection Low-level Method invocation
The following lower-level primitives require you to specify
the parameter and return types explicitly.
You should probably use the functions @code{invoke} and @code{invoke-static}
(@pxref{Method operations}) instead.

@deffn Syntax primitive-constructor class (argtype ...)
Returns a new anonymous procedure, which when called will create
a new object of the specified class, and will then call the
constructor matching the specified argument types.
@end deffn

@deffn Syntax primitive-virtual-method class method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the instance method whose name is the string @var{method}
in the class whose name is @var{class}.
@end deffn

@deffn Syntax primitive-static-method class method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the static method whose name is the string @var{method}
in the class whose name is @var{class}.
@end deffn

@deffn Syntax primitive-interface-method interface method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the matching method from the interface whose name is @var{interface}.
@end deffn

The macros return procedure values, just like @code{lambda}.
If the macros are used directly as the procedure of a procedure call,
then kawa can inline the correct bytecodes to call the specified methods.
(Note also that neither macro
checks that there really is a method that matches the specification.)
Otherwise, the Java reflection facility is used.

@subsection Low-level field operations

The following macros evaluate to procedures that can be used to
access or change the fields of objects or static fields.
The compiler can inline each to a single bytecode instruction
(not counting type conversion).

These macros are deprecated.
The @code{fields} and @code{static-field} functions
(@pxref{Field operations}) are easier to use, more powerful, and
just as efficient.  However, the high-level functions currently do
not provide access to non-public fields.

@deffn Syntax primitive-get-field class fname ftype
Use this to access a field named @var{fname} having type @var{type} in
class @var{class}.  Evaluates to a new one-argument procedure,
whose argument is a reference to an object of the specified @var{class}.
Calling that procedure returns the value of the specified field.
@end deffn

@deffn Syntax primitive-set-field class fname ftype
Use this to change a field named @var{fname} having type @var{type} in
class @var{class}.  Evaluates to a new two-argument procedure,
whose first argument is a reference to an object of the
specified @var{class}, and the second argument is the new value.
Calling that procedure sets the field to the specified value.
(This macro's name does not end in a @samp{!}, because it does not actually
set the field.  Rather, it returns a function for setting the field.)
@end deffn

@deffn Syntax primitive-get-static class fname ftype
Like @code{primitive-get-field}, but used to access static fields.
Returns a zero-argument function, which when called returns
the value of the static field.
@end deffn

@deffn Syntax primitive-set-static class fname ftype
Like @code{primitive-set-field}, but used to modify static fields.
Returns a one-argument function, which when called sets the
value of the static field to the argument.
@end deffn

@anchor{Low-level array macros}
@subsection Old low-level array macros

The following macros evaluate to procedures that can be used to
manipulate primitive Java array objects.
The compiler can inline each to a single bytecode instruction
(not counting type conversion).

@deffn Syntax primitive-array-new element-type
Evaluates to a one-argument procedure.  Applying the resulting procedure to
an integer count allocates a new Java array of the specified length,
and whose elements have type @var{element-type}.
@end deffn

@deffn Syntax primitive-array-set element-type
Evaluates to a three-argument procedure.  The first argument of
the resulting procedure must be an array whose elements have type
@var{element-type};  the second argument is an index;  and the third
argument is a value (coercible to @var{element-type}) which replaces
the value specified by the index in the given array.
@end deffn

@deffn Syntax primitive-array-get element-type
Evaluates to a two-argument procedure.  The first argument of
the resulting procedure must be an array whose elements have type
@var{element-type};  the second argument is an index.
Applying the procedure returns the element at the specified index.
@end deffn

@deffn Syntax primitive-array-length element-type
Evaluates to a one-argument procedure.  The argument of
the resulting procedure must be an array whose elements have type
@var{element-type}.
Applying the procedure returns the length of the array.
(Alternatively, you can use @code{(field @var{array} 'length)}.)
@end deffn

@node FAQs
@chapter Frequently Asked Questions

@ignore
@subsubheading What is the difference between load, require, import, and include?

Handling @code{include} is all done at compile time.  It's as if the text
of the included file is copied and replaces the include command.
If the include is inside a @code{let}, the included text can
use the name defined in the @code{let}.

In contrast @code{load} is a procedure, not syntax.
It reads and evaluates each line in the file, one at a time,
@end ignore

@anchor{importing-class-names}
@subsubheading What is the equivalent of Java import?

To provide a short name for a class instead of the complete fully-qualified
name use either @code{define-alias} (or @code{define-private-alias})
or the @code{import}-@code{class} combination.
For example, to be able to write @code{ArrayList} instead
of @code{java.util.ArrayList} do either:
@example
(import (class java.util ArrayList))
@end example
or
@example
(define-alias ArrayList java.util.ArrayList)
@end example
Using @code{import} is recommended:
It handles errors better,
and it allows you to define multiple aliases conveniently:
@example
(import (class java.util Map HashMap))
@end example

Both forms allow renaming.  For example if you want to refer
to @code{java.lang.StringBuilder} as @code{StrBuf} do:
@example
(import (class java.lang (StringBuilder StrBuf)))
@end example
or:
@example
(define-alias StrBuf java.lang.StringBuilder)
@end example

The name(s) defined by @code{import} are by default private.
A name defined using @code{define-alias} is by default exported;
to avoid that use @code{define-private-alias} instead.

You can also use @code{define-namespace} to introduce an abbreviation or
renaming of a class name, but as a matter of style @code{define-alias}
is preferred.

There is no direct equivalent to Java's @code{import PackageOrTypeName.*}
(type-import-on-demand) declaration, but you can alias a package:
@example
(define-alias jutil java.util)
(define mylist :: jutil:List (jutil:ArrayList))
@end example

To import a static member, giving it a shortened name
(like Java's static-import-on-demand declaration), you can use
@code{define-alias}.  For example:
@example
(define-alias console java.lang.System:console)
@end example

For static fields only (not methods or member classes) you can
use an @code{import} form, either:
@example
(import (only (java lang System) out))
@end example
or:
@example
(import (only java.lang.System out))
@end example
This works because Kawa can treat any class as a ``library'';
in which case it considers all public static fields as exported bindings.

@subsubheading How do I refer to a Java member (nested) class?

Consider the Java SE member class @code{javax.swing.text.AbstractDocument.Content}.
Using the Java syntax doesn't work in Kawa.
Inside you should use Kawa's colon operator:
@example
javax.swing.text.AbstractDocument:Content
@end example
Alternatively, you can use the internal JVM class name:
@example
javax.swing.text.AbstractDocument$Content
@end example

@subsubheading Why does Kawa's REPL use display rather than write?

The read-eval-print-loop of most Scheme implementations prints the
evaluation result using @code{write}, while Kawa uses @code{display} by default.

First note that it is easy to override the default with the
@code{--output-format} command-line option:
@example
$kawa --output-format readable-scheme
#|kawa:1|# "abc"
"abc"
@end example

The reason @code{display} is the default is because of a vision of the REPL
console as more than just printing out Scheme objects in
textual form for use by a programmer.
Some examples:
@itemize
@item
A math program can display equations and graphs as the
output of an expression.
@item
An expression can evaluate to a "picture" which would
be @uref{http://per.bothner.com/blog/2007/ReplPane/,displayed inline}.
@item
An HTML/XML obj can be insert into the output in visual
form if the console understands HTML.  (There is a prototype
for this that works by using the JavaFX WebView as the display.)
@item
The plan for "Kawa-shell" functionality is to have expressions
that evaluate to process objects, which would be lazy strings.
This string would be the data from standard output.  Thus the
effect of displaying a process object would be to print out
the standard output - just like a regular shell.  Users would
find it confusing/annoying if shell output used quotes.
@end itemize

This "repl-as-pad" model doesn't work as well if the repl
uses @code{write} rather than @code{display}. 

@node Framework
@chapter The Kawa language framework

Kawa is a framework written in Java for implementing
high-level and dynamic languages, compiling them into Java bytecodes.

The Kawa distributions includes of other programming languages
besides Scheme,
including @uref{../qexo/index.html, XQuery (Qexo)}
and @uref{http://JEmacs.sourceforge.net/,Emacs Lisp (JEmacs)}.

For a technical overview of Kawa, see these
@uref{http://www.gnu.org/software/kawa/internals/index.html}.
Javadoc generated @uref{http://www.gnu.org/software/kawa/api/,documentation of the Kawa classes} is also available.
The packages
@uref{http://www.gnu.org/software/kawa/api/gnu/bytecode/package-summary.html,@code{gnu.bytecode}},
@uref{http://www.gnu.org/software/kawa/api/gnu/math/package-summary.html,@code{gnu.math}},
@uref{http://www.gnu.org/software/kawa/api/gnu/lists/package-summary.html,@code{gnu.lists}},
@uref{http://www.gnu.org/software/kawa/api/gnu/xml/package-summary.html,@code{gnu.xml}},
@uref{http://www.gnu.org/software/kawa/api/gnu/expr/package-summary.html,@code{gnu.expr}},
@uref{http://www.gnu.org/software/kawa/api/gnu/mapping/package-summary.html,@code{gnu.mapping}},
and
@uref{http://www.gnu.org/software/kawa/api/gnu/text/package-summary.html,@code{gnu.text}},
are used by Kawa, and distributed with it, but may be independently useful.

This @uref{gnu.bytecode/compiling-regexps.html,article} explains how to
use @code{gnu.bytecode} to compile regular expressions to bytecode.

@node License
@chapter License

@menu
* Software-License::      License for the Kawa software
* Manual-License::        License for the Kawa manual
@end menu

@node Software-License, Manual-License, , License
@section License for the Kawa software

The license for the Kawa software
(except the optional JEmacs and BRL features - see below) is the
@uref{http://opensource.org/licenses/mit-license.php, X11/MIT license}
which is quoted below.

@example
The software (with related files and documentation) in these packages
are copyright (C) 1996-2009  Per Bothner.

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.
@end example

In the past the Kawa license was a ``modified GNU GPL (General
Public License)".
If you find any files that contain the old license or otherwise seem
to contradict the new license, please report that as a bug.

Some of the JEmacs files are based on Emacs and have a GPL license,
which is incompatible with non-Free (proprietary) products.  For that
reason, the @code{gnu.jemacs.*} packages are not included any more in
the standard @code{.jar}, or by default when building from source, to
avoid surprises.
To build JEmacs you have to specify the @code{configure}
flag @code{--enable-jemacs} or the @code{ant} flag
@code{-Denable-jemacs=true}.

Some code in @code{gnu/brl} and @code{gnu/kawa/brl} is copyright
Bruce R. Lewis and Eaton Vance Management,
with a modified-GPL license: no restrictions if used
unmodified, but otherwise the GPL applies.
These packages are no longer included by default in Kawa builds,
but have to be selected with the @code{configure}
flag @code{--enable-brl} or the @code{ant} flag @code{-Denable-brl=true}.

Kawa uses some math routines from fdlib's libf77,
which have a AT&T Bell Laboratories and Bellcore copyright.
See the source file @code{gnu/math/DComplex.java}.

The sorting routine in @code{gnu.xquery.util.OrderedTuples}
is a re-implementatiomn in Java of code copyrighted by
Simon Tatham.

Some of the Scheme code in @code{kawa/lib} and @code{gnu/kawa/slib}
are copyright other parties, and may have slightly different
license wording, but I believe none of then contradicts the
main Kawa license or impose extra restrictions.
Search for the word @code{copyright} in these directories.

Some code has been converted from other languages, with permission.
This includes the @code{rationalize} method
in @code{gnu/math/RatNum.java}, based on an algorithm of Alan Bawden,
as expressed by Marc Feeley in C-Gambit.
The concepts and algorithm of @code{gnu/text/PrettyWriter.java}
are converted from SBCL, which is in the public domain.

@node Manual-License, , Software-License, License
@section License for the Kawa manual

Here is the copyright license for this manual:

Copyright @copyright{} 1996, 1997, 1998, 1999, 2005 Per Bothner

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.

Permission is granted to copy and distribute modified versions of this
manual under the conditions for verbatim copying, provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

Permission is granted to copy and distribute translations of this manual
into another language, under the above conditions for modified versions,
except that this permission notice may be stated in a translation approved
by the author.

Parts of this manual are copied from the @uref{http://www.r6rs.org/,R6RS}
or @uref{http://www.r7rs.org/,R7RS}, which both state:
@quotation
We intend this report to belong to the entire Scheme community, and so
we grant permission to copy it in whole or in part without fee. In
particular, we encourage implementors of Scheme to use this report as
a starting point for manuals and other documentation, modifying it as
necessary.
@end quotation

Parts of this manual were derived from the SLIB manual,
copyright @copyright{} 1993-1998 Todd R. Eigenschink and Aubrey Jaffer.

Parts of this manual were derived from ISO/EIC 10179:1996(E)
(Document Style and Specifical Language) - unknown copyright.

This manual has quoted from SRFI-6 (Basic String Ports),
which is Copyright (C) William D Clinger (1999). All Rights Reserved.

This manual has quoted from SRFI-8 (receive: Binding to multiple values),
which is Copyright (C) John David Stone (1999). All Rights Reserved.

This manual has quoted from SRFI-9 (Defining Record Types)
which is Copyright (C) Richard Kelsey (1999).  All Rights Reserved.

This manual has quoted from SRFI-11 (Syntax for receiving multiple values),
which is Copyright (C) Lars T. Hansen (1999). All Rights Reserved.

This manual has quoted from SRFI-25 (Multi-dimensional Array Primitives),
which is Copyright (C) Jussi Piitulainen (2001). All Rights Reserved.

This manual has quoted from SRFI-26 (Notation for Specializing
Parameters without Currying),
which is Copyright (C) Sebastian Egner (2002). All Rights Reserved.

This manual has quoted from SRFI-39 (Parameter objects),
which is Copyright (C) Marc Feeley (2002). All Rights Reserved.

The following notice applies to SRFI-6, SRFI-8, SRFI-9, SRFI-11, SRFI-25,
SRFI-26, and SRFI-39,
which are quoted in this manual, but it does not apply to the manual as a whole:

@quotation
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it or
assist in its implementation may be prepared, copied, published and
distributed, in whole or in part, without restriction of any kind,
provided that the above copyright notice and this paragraph are included
on all such copies and derivative works. However, this document itself
may not be modified in any way, such as by removing the copyright notice
or references to the Scheme Request For Implementation process or
editors, except as needed for the purpose of developing SRFIs in which
case the procedures for copyrights defined in the SRFI process must be
followed, or as required to translate it into languages other than
English.

The limited permissions granted above are perpetual and will not be
revoked by the authors or their successors or assigns.

This document and the information contained herein is provided on an
"AS IS" basis and THE AUTHOR AND THE SRFI EDITORS DISCLAIM ALL
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY
WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY
RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
PARTICULAR PURPOSE.
@end quotation

This manual has quoted from SRFI-69 (Basic hash tables),
which is Copyright (C) Panu Kalliokoski (2005). All Rights Reserved.

The following notice applies to SRFI-69,
which is quoted in this manual, but it does not apply to the manual as a whole:

@quotation
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.
@end quotation

This manual has made use of text and examples from Dorai Sitaram's
@code{pregexp} implementation.  But not where the latter talks about
@code{pregexp-xxx} functions; the manual also talks about
the @code{regex-xxx} functions (which are similar but use a
slightly different regular expression syntax).
The @code{pregexp} distribution has the following @code{COPYING} file:
@quotation
Copyright (c) 1999-2005, Dorai Sitaram.
All rights reserved.

Permission to copy, modify, distribute, and use this work or
a modified copy of this work, for any purpose, is hereby
granted, provided that the copy includes this copyright
notice, and in the case of a modified copy, also includes a
notice of modification.  This work is provided as is, with
no warranty of any kind.
@end quotation

@c I'd prefer to call this node plain "Index", but that causes a clash
@c with index.html when generating HTML on case-insenstive file systems.
@node Overall Index,  , License, Top
@appendix Index
@printindex cp

@bye