aemoncannon / las3r

A lisp compiler for the AVM2.

This URL has Read+Write access

las3r / src / lsr / las3r.core.lsr
100644 2459 lines (2010 sloc) 73.48 kb
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
;; Copyright (c) Rich Hickey. All rights reserved.
;; Copyright (c) Aemon Cannon. All rights reserved.
;; The use and distribution terms for this software are covered by the
;; Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
;; which can be found in the file CPL.TXT at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
 
 
(in-ns 'las3r.core)
 
(def *compiler* (. *runtime* compiler))
 
 
(def
 #^{:arglists '([& items])
    :doc "Creates a new list containing the items."}
 list (. com.las3r.runtime.List creator))
 
(def
 #^{:arglists '([x seq])
    :doc "Returns a new seq where x is the first element and seq is
    the rest."}
 
 cons (fn* cons [x seq] (. com.las3r.runtime.RT (cons x seq))))
 
;;during bootstrap we don't have destructuring let, loop or fn, will redefine later
(def
 #^{:macro true}
 let (fn* let [& decl] (cons 'let* decl)))
 
(def
 #^{:macro true}
 fn (fn* fn [& decl] (cons 'fn* decl)))
 
(def
 #^{:arglists '([coll])
    :doc "Returns the first item in the collection. Calls seq on its
    argument. If coll is nil, returns nil."}
 first (fn first [coll] (. com.las3r.runtime.RT (first coll))))
 
(def
 #^{:arglists '([coll])
    :doc "Returns a seq of the items after the first. Calls seq on its
  argument. If there are no more items, returns nil."}
 rest (fn rest [x] (. com.las3r.runtime.RT (rest x))))
 
(def
 #^{:doc "Same as (first (rest x))"
    :arglists '([x])}
 second (fn second [x] (first (rest x))))
 
(def
 #^{:doc "Same as (first (first x))"
    :arglists '([x])}
 ffirst (fn ffirst [x] (first (first x))))
 
(def
 #^{:doc "Same as (rest (first x))"
    :arglists '([x])}
 rfirst (fn rfirst [x] (rest (first x))))
 
(def
 #^{:doc "Same as (first (rest x))"
    :arglists '([x])}
 frest (fn frest [x] (first (rest x))))
 
(def
 #^{:doc "Same as (rest (rest x))"
    :arglists '([x])}
 rrest (fn rrest [x] (rest (rest x))))
 
 
(def
 #^{:arglists '([coll x] [coll x & xs])
    :doc "conj[oin]. Returns a new collection with the xs
    'added'. (conj nil item) returns (item). The 'addition' may
    happen at different 'places' depending on the concrete type."}
 conj (fn conj
        ([coll x] (. com.las3r.runtime.RT (conj coll x)))
        ([coll x & xs]
(if xs
(recur (conj coll x) (first xs) (rest xs))
(conj coll x)))))
 
 
(def
 #^{:arglists '([coll])
    :doc "Sequence. Returns a new ISeq on the collection. If the
    collection is empty, returns nil. (seq nil) returns nil. seq also
    works on Strings and native arrays."
    :tag com.las3r.runtime.ISeq}
 seq (fn seq [coll] (. com.las3r.runtime.RT (seq coll))))
 
(def
 #^{:arglists '([c x])
    :doc "Evaluates x and tests if it is an instance of the class
    c. Returns true or false"}
 instance? (fn instance? [c x] (. com.las3r.runtime.RT (isInstance c x))))
 
 
(def
 #^{:arglists '([x])
    :doc "Return true if x implements ISeq"}
 seq? (fn seq? [x] (instance? com.las3r.runtime.ISeq x)))
 
(def
 #^{:arglists '([x])
    :doc "Return true if x is a String"}
 string? (fn string? [x] (instance? String x)))
 
(def
 #^{:arglists '([x])
    :doc "Return true if x implements IMap"}
 map? (fn map? [x] (instance? com.las3r.runtime.IMap x)))
 
(def
 #^{:arglists '([x])
    :doc "Return true if x implements IVector "}
 vector? (fn vector? [x] (instance? com.las3r.runtime.IVector x)))
 
 
(def
 #^{:arglists '([map key val] [map key val & kvs])
    :doc "assoc[iate]. When applied to a map, returns a new map of the
    same (hashed/sorted) type, that contains the mapping of key(s) to
    val(s). When applied to a vector, returns a new vector that
    contains val at index. Note - index must be <= (count vector)."}
 assoc
 (fn assoc
   ([map key val] (. com.las3r.runtime.RT (assoc map key val)))
   ([map key val & kvs]
      (let [ret (assoc map key val)]
(if kvs
(recur ret (first kvs) (second kvs) (rrest kvs))
ret)))))
 
;;;;;;;;;;;;;;;; loop ;;;;;;;;;;;;;;;;;;;;;;;;;
 
(def
 #^{:macro true
    :doc "Loop macro that expands into a let expression with a body that
          applies a function to the bound locals."}
 loop* (fn* loop* [bindings & body]
(let [names-vals (. com.las3r.runtime.RT (unzip (seq bindings)))
names (. com.las3r.runtime.PersistentVector (createFromSeq (seq (first names-vals))))
vals (seq (second names-vals))]
(concat (list 'let bindings (concat (list (concat (list 'fn names) body)) names)))))
 )
 
;;;;;;;;;;;;;;;;; metadata ;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
(def
 #^{:arglists '([obj])
    :doc "Returns the metadata of obj, returns nil if there is no metadata."}
 meta (fn meta [x]
        (if (instance? com.las3r.runtime.IObj x)
          (. #^com.las3r.runtime.IObj x meta))))
 
(def
 #^{:arglists '([#^com.las3r.runtime.IObj obj m])
    :doc "Returns an object of the same type and value as obj, with
    map m as its metadata."}
 with-meta (fn with-meta [#^com.las3r.runtime.IObj x m]
             (. x (withMeta m))))
 
 
(def
 #^{:arglists '([coll])
    :doc "Return the last item in coll, in linear time"}
 last (fn last [s]
        (if (rest s)
          (recur (rest s))
          (first s))))
 
(def
 #^{:arglists '([coll])
    :doc "Return a sequence of all but the last item in coll, in linear time"}
 butlast (fn butlast [s]
           (loop* [ret [] s s]
(if (rest s)
(recur (conj ret (first s)) (rest s))
(seq ret)))))
 
 
 
(def
 #^{:private true}
 sigs
 (fn [fdecl]
   (if (seq? (first fdecl))
     (loop* [ret [] fdecl fdecl]
(if fdecl
(recur (conj ret (first (first fdecl))) (rest fdecl))
(seq ret)))
     (list (first fdecl)))))
 
(def
 
 #^{:doc "Same as (def name (fn [params* ] exprs*)) with any doc-string or attrs added
    to the var metadata"
    :arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
 defn (fn defn [name & fdecl]
        (let [
m (if (string? (first fdecl))
                  {:doc (first fdecl)}
                  {})
              fdecl (if (string? (first fdecl))
                      (rest fdecl)
                      fdecl)
              m (if (map? (first fdecl))
                  (conj m (first fdecl))
                  m)
              fdecl (if (map? (first fdecl))
                      (rest fdecl)
                      fdecl)
              fdecl (if (vector? (first fdecl))
                      (list fdecl)
                      fdecl)
              m (if (map? (last fdecl))
                  (conj m (last fdecl))
                  m)
              fdecl (if (map? (last fdecl))
                      (butlast fdecl)
                      fdecl)
              m (conj {:arglists (list 'quote (sigs fdecl))} m)
]
          `(def ~(with-meta name (conj (if (meta name) (meta name) {}) m)) (fn ~@fdecl)))))
 
 
(. (var defn) (setMacro))
 
(defn to-array
  "Returns an array of Objects containing the contents of coll, which
  can be any Collection."
  [coll] (. com.las3r.runtime.RT (toArray coll)))
(def ary to-array)
 
(defn cast
  "Throws an Error if x is not a c, else returns x."
  [c x] (. com.las3r.runtime.RT (cast c x)))
 
 
(defn vector
  "Creates a new vector containing the args."
  [& args]
  (. com.las3r.runtime.PersistentVector (createFromSeq args)))
 
 
(defn hash-map
  "keyval => key val
  Returns a new hash map with supplied mappings."
  [& keyvals]
  (. com.las3r.runtime.PersistentHashMap (createFromSeq keyvals)))
 
(defn array-map
  "keyval => key val
  Returns a new array map with supplied mappings."
  [& keyvals]
  (. com.las3r.runtime.PersistentArrayMap (createFromSeq keyvals)))
 
(defn hash-set
  "Returns a new hash set with supplied values."
  [& vals]
  (. com.las3r.runtime.PersistentHashSet (createFromSeq vals)))
 
 
(def
 
 #^{:doc "Like defn, but the resulting function name is declared as a
  macro and will be used as a macro by the compiler when it is
  called."
    :arglists '([name doc-string? attr-map? [params*] body]
[name doc-string? attr-map? ([params*] body)+ attr-map?])}
 defmacro (fn [name & args]
            (list 'do
                  (cons `defn (cons name args))
                  (list '. (list 'var name) '(setMacro)))))
 
(. (var defmacro) (setMacro))
 
(defmacro when
  "Evaluates test. If logical true, evaluates body in an implicit do."
  [test & body]
  (list 'if test (cons 'do body)))
 
(defmacro when-not
  "Evaluates test. If logical false, evaluates body in an implicit do."
  [test & body]
  (list 'if test nil (cons 'do body)))
 
(defn nil?
  "Returns true if x is nil, false otherwise."
  {:tag Boolean}
  [x] (identical? x nil))
 
(defn false?
  "Returns true if x is the value false, false otherwise."
  {:tag Boolean}
  [x] (identical? x false))
 
(defn true?
  "Returns true if x is the value true, false otherwise."
  {:tag Boolean}
  [x] (identical? x true))
 
(defn not
  "Returns true if x is logical false, false otherwise."
  {:tag Boolean}
  [x] (if x false true))
 
 
(defn str
  "With no args, returns the empty string. With one arg x, returns
  x.toString(). (str nil) returns the empty string. With more than
  one arg, returns the concatenation of the str values of the args."
  {:tag String}
  ([] "")
  ([x]
     (if (nil? x) "" (cast String x )))
  ([x & ys]
     (loop* [sb (str x)
more ys]
(if more
(recur (. sb (concat (str (first more)))) (rest more))
(str sb)))))
 
(defn char-code->str
  "Return the string corresponding to the numeric code."
  [code]
  (. String (fromCharCode code)))
 
(defn symbol
  "Returns a Symbol with the given namespace and name."
  ([name] (. com.las3r.runtime.Symbol (intern1 *runtime* name)))
  ([ns name] (. com.las3r.runtime.Symbol (intern2 *runtime* ns name))))
 
 
(defn keyword
  "Returns a Keyword with the given namespace and name. Do not use :
  in the keyword strings, it will be added automatically."
  ([name] (. com.las3r.runtime.Keyword (intern2 *runtime* nil name)))
  ([ns name] (. com.las3r.runtime.Keyword (intern2 *runtime* ns name))))
 
(defn gensym
  "Returns a new symbol with a unique name. If a prefix string is
  supplied, the name is prefix# where # is some unique number. If
  prefix is not supplied, the prefix is 'G'."
  ([] (gensym "G__"))
  ([prefix-string] (. com.las3r.runtime.Symbol (intern1 *runtime* (str prefix-string (str (. *runtime* (nextID))))))))
 
(defmacro cond
  "Takes a set of test/expr pairs. It evaluates each test one at a
  time. If a test returns logical true, cond evaluates and returns
  the value of the corresponding expr and doesn't evaluate any of the
  other tests or exprs. (cond) returns nil."
  [& clauses]
  (when clauses
    (list 'if (first clauses)
(second clauses)
(cons 'cond (rest (rest clauses))))))
 
(defn spread
  {:private true}
  [arglist]
  (cond
   (nil? arglist) nil
   (nil? (rest arglist)) (seq (first arglist))
   :else (cons (first arglist) (spread (rest arglist)))))
 
(defn apply
  "Applies fn f to the argument list formed by prepending args to argseq."
  {:arglists '([f args* argseq])}
  [f & args]
  (apply* f (spread args)))
 
(defn list*
  "Creates a new list containing the item prepended to more."
  [item & more]
  (spread (cons item more)))
 
 
(defmacro lazy-cons
  "Expands to code which produces a seq object whose first is
  first-expr and whose rest is rest-expr, neither of which is
  evaluated until first/rest is called. Each expr will be evaluated at most
  once per step in the sequence, e.g. calling first/rest repeatedly on the
  same node of the seq evaluates first/rest-expr once - the values they yield are
  cached."
  [first-expr & rest-expr]
  (list 'new 'com.las3r.runtime.LazyCons (list `fn (list [] first-expr) (list* [(gensym)] rest-expr))))
 
 
(defn concat
  "Returns a lazy seq representing the concatenation of the elements in the supplied colls."
  ([] nil)
  ([x] (seq x))
  ([x y]
     (if (seq x)
       (lazy-cons (first x) (concat (rest x) y))
       (seq y)))
  ([x y & zs]
     (let [cat (fn cat [xys zs]
(if (seq xys)
(lazy-cons (first xys) (cat (rest xys) zs))
(when zs
(recur (first zs) (rest zs)))))]
       (cat (concat x y) zs))))
 
 
(defn throw-rte
  "Throw a runtime error with the given message."
  [m] (throw (new com.las3r.errors.RuntimeError m)))
 
 
;;;;;;;;;;;;;;;;at this point all the support for syntax-quote exists;;;;;;;;;;;;;;;;;;;;;;
 
(defn =
  "Equality. Returns true if x equals y, false if not. Same as
  Java x.equals(y) except it also works for nil, and compares
  numbers in a type-independent manner. Clojure's immutable data
  structures define equals() (and thus =) as a value, not an identity,
  comparison."
  {:tag Boolean}
  ([x] true)
  ([x y] (. com.las3r.util.Util (equal x y)))
  ([x y & more]
     (if (= x y)
       (if (rest more)
(recur y (first more) (rest more))
(= y (first more)))
       false)))
 
(defn not=
  "Same as (not (= obj1 obj2))"
  {:tag Boolean}
  ([x] false)
  ([x y] (not (= x y)))
  ([x y & more]
     (not (apply = x y more))))
 
 
(defn compare
  "Comparator. Returns 0 if x equals y, -1 if x is logically 'less
  than' y, else 1. Same as Java x.compareTo(y) except it also works
  for nil, and compares numbers in a type-independent manner. x must
  implement Comparable"
  {:tag Number
   :inline (fn [x y] `(. com.las3r.util.Util compare ~x ~y))}
  [x y] (. com.las3r.util.Util (compare x y)))
 
(defmacro and
  "Evaluates exprs one at a time, from left to right. If a form
  returns logical false (nil or false), and returns that value and
  doesn't evaluate any of the other expressions, otherwise it returns
  the value of the last expr. (and) returns true."
  ([] true)
  ([x] x)
  ([x & rest]
     `(let [and# ~x]
(if and# (and ~@rest) and#))))
 
(defmacro or
  "Evaluates exprs one at a time, from left to right. If a form
  returns a logical true value, or returns that value and doesn't
  evaluate any of the other expressions, otherwise it returns the
  value of the last expression. (or) returns nil."
  ([] nil)
  ([x] x)
  ([x & rest]
     `(let [or# ~x]
(if or# or# (or ~@rest)))))
 
 
 
 
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
 
(defn reduce
  "f should be a function of 2 arguments. If val is not supplied,
  returns the result of applying f to the first 2 items in coll, then
  applying f to that result and the 3rd item, etc. If coll contains no
  items, f must accept no arguments as well, and reduce returns the
  result of calling f with no arguments. If coll has only 1 item, it
  is returned and f is not called. If val is supplied, returns the
  result of applying f to val and the first item in coll, then
  applying f to that result and the 2nd item, etc. If coll contains no
  items, returns val and f is not called."
  ([f coll]
     (let [s (seq coll)]
       (if s
(reduce f (first s) (rest s))
(f))))
  ([f val coll]
     (let [s (seq coll)]
       (if (instance? com.las3r.runtime.IReduce s)
         (. #^com.las3r.runtime.IReduce s (reduce f val))
         ((fn [f val s]
            (if s
              (recur f (f val (first s)) (rest s))
              val))
          f val s)))))
 
(defn reverse
  "Returns a seq of the items in coll in reverse order. Not lazy."
  [coll]
  (reduce conj nil coll))
 
 
;; Special functions
 
(defn complement
  "Takes a fn f and returns a fn that takes the same arguments as f,
  has the same effects, if any, and returns the opposite truth value."
  [f] (fn [& args]
        (not (apply f args))))
 
 
(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  [x] (fn [& args] x))
 
 
(defn identity
  "Returns its argument."
  [x] x)
 
 
(defn comp
  "Takes a set of functions and returns a fn that is the composition
  of those fns. The returned fn takes a variable number of args,
  applies the rightmost of fns to the args, the next
  fn (right-to-left) to the result, etc."
  [& fs]
  (let [fs (reverse fs)]
    (fn [& args]
      (loop* [ret (apply (first fs) args) fs (rest fs)]
(if fs
(recur ((first fs) ret) (rest fs))
ret)))))
 
 
(defn partial
  "Takes a function f and fewer than the normal arguments to f, and
  returns a fn that takes a variable number of additional args. When
  called, the returned function calls f with args + additional args."
  ([f arg1]
     (fn [& args] (apply f arg1 args)))
  ([f arg1 arg2]
     (fn [& args] (apply f arg1 arg2 args)))
  ([f arg1 arg2 arg3]
     (fn [& args] (apply f arg1 arg2 arg3 args)))
  ([f arg1 arg2 arg3 & more]
     (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))
 
 
 
 
;;map stuff
 
(defn contains?
  "Returns true if key is present, else false."
  [map key] (. com.las3r.runtime.RT (contains map key)))
 
(defn get
  "Returns the value mapped to key, not-found or nil if key not present."
  ([map key]
     (. com.las3r.runtime.RT (get map key)))
  ([map key not-found]
     (. com.las3r.runtime.RT (get map key not-found))))
 
(defn dissoc
  "dissoc[iate]. Returns a new map of the same (hashed/sorted) type,
  that does not contain a mapping for key(s)."
  ([map] map)
  ([map key]
     (. com.las3r.runtime.RT (dissoc map key)))
  ([map key & ks]
     (let [ret (dissoc map key)]
       (if ks
(recur ret (first ks) (rest ks))
ret))))
 
(defn disj
  "disj[oin]. Returns a new set of the same (hashed/sorted) type, that
  does not contain key(s)."
  ([set] set)
  ([#^com.las3r.runtime.ISet set key]
     (. set (remove key)))
  ([set key & ks]
     (let [ret (disj set key)]
       (if ks
(recur ret (first ks) (rest ks))
ret))))
 
(defn find
  "Returns the map entry for key, or nil if key not present."
  [map key] (. com.las3r.runtime.RT (find map key)))
 
(defn select-keys
  "Returns a map containing only those entries in map whose key is in keys"
  [map keyseq]
  (loop* [ret {} keys (seq keyseq)]
(if keys
(let [entry (. com.las3r.runtime.RT (find map (first keys)))]
(recur
(if entry
(conj ret entry)
ret)
(rest keys)))
ret)))
 
(defn keys
  "Returns a sequence of the map's keys."
  [map] (. com.las3r.runtime.RT (keys map)))
 
(defn vals
  "Returns a sequence of the map's values."
  [map] (. com.las3r.runtime.RT (vals map)))
 
(defn key
  "Returns the key of the map entry."
  [#^com.las3r.runtime.MapEntry e]
  (. e key))
 
(defn val
  "Returns the value in the map entry."
  [#^com.las3r.runtime.MapEntry e]
  (. e value))
 
 
(defn name
  "Returns the name String of a symbol or keyword."
  [x]
  (. x (getName)))
 
(defn namespace
  "Returns the namespace String of a symbol or keyword, or nil if not present."
  [x]
  (. x (getNamespace)))
 
 
;;math stuff
 
(defn +
  "Returns the sum of nums. (+) returns 0."
  ([] 0)
  ([x] (cast Number x))
  ([x y] (. com.las3r.runtime.Numbers (add x y)))
  ([x y & more]
     (reduce + (+ x y) more)))
 
(defn *
  "Returns the product of nums. (*) returns 1."
  ([] 1)
  ([x] (cast Number x))
  ([x y] (. com.las3r.runtime.Numbers (multiply x y)))
  ([x y & more]
     (reduce * (* x y) more)))
 
(defn /
  "If no denominators are supplied, returns 1/numerator,
  else returns numerator divided by all of the denominators."
  ([x] (/ 1 x))
  ([x y] (. com.las3r.runtime.Numbers (divide x y)))
  ([x y & more]
     (reduce / (/ x y) more)))
 
(defn -
  "If no ys are supplied, returns the negation of x, else subtracts
  the ys from x and returns the result."
  ([x] (. com.las3r.runtime.Numbers (minus x)))
  ([x y] (. com.las3r.runtime.Numbers (minus x y)))
  ([x y & more]
     (reduce - (- x y) more)))
 
(defn <
  "Returns non-nil if nums are in monotonically increasing order,
  otherwise false."
  ([x] true)
  ([x y] (. com.las3r.runtime.Numbers (lt x y)))
  ([x y & more]
     (if (< x y)
       (if (rest more)
(recur y (first more) (rest more))
(< y (first more)))
       false)))
 
(defn <=
  "Returns non-nil if nums are in monotonically non-decreasing order,
  otherwise false."
  ([x] true)
  ([x y] (. com.las3r.runtime.Numbers (lte x y)))
  ([x y & more]
     (if (<= x y)
       (if (rest more)
(recur y (first more) (rest more))
(<= y (first more)))
       false)))
 
(defn >
  "Returns non-nil if nums are in monotonically decreasing order,
  otherwise false."
  ([x] true)
  ([x y] (. com.las3r.runtime.Numbers (gt x y)))
  ([x y & more]
     (if (> x y)
       (if (rest more)
(recur y (first more) (rest more))
(> y (first more)))
       false)))
 
(defn >=
  "Returns non-nil if nums are in monotonically non-increasing order,
  otherwise false."
  ([x] true)
  ([x y] (. com.las3r.runtime.Numbers (gte x y)))
  ([x y & more]
     (if (>= x y)
       (if (rest more)
(recur y (first more) (rest more))
(>= y (first more)))
       false)))
 
(defn ==
  "Returns non-nil if nums all have the same value, otherwise false"
  ([x] true)
  ([x y] (. com.las3r.runtime.Numbers (equiv x y)))
  ([x y & more]
     (if (== x y)
       (if (rest more)
(recur y (first more) (rest more))
(== y (first more)))
       false)))
 
(defn max
  "Returns the greatest of the nums."
  ([x] x)
  ([x y] (if (> x y) x y))
  ([x y & more]
     (reduce max (max x y) more)))
 
(defn min
  "Returns the least of the nums."
  ([x] x)
  ([x y] (if (< x y) x y))
  ([x y & more]
     (reduce min (min x y) more)))
 
(defn inc
  "Returns a number one greater than num."
  [x] (. com.las3r.runtime.Numbers (inc x)))
 
(defn dec
  "Returns a number one less than num."
  [x] (. com.las3r.runtime.Numbers (dec x)))
 
(defn pos?
  "Returns true if num is greater than zero, else false"
  [x] (> x 0))
 
(defn neg?
  "Returns true if num is less than zero, else false"
  [x] (< x 0))
 
(defn zero?
  "Returns true if num is zero, else false"
  [x] (= x 0))
 
(defn rem
  "rem[ainder] of dividing numerator by denominator."
  [num div]
  (. com.las3r.runtime.Numbers (remainder num div)))
 
;;Bit ops
 
(defn bit-not
  "Bitwise complement"
  [x] (. com.las3r.runtime.Numbers (not x)))
 
 
(defn bit-and
  "Bitwise and"
  ([x] x)
  ([x y] (. com.las3r.runtime.Numbers (and x y)))
  ([x y & more]
     (reduce bit-and (bit-and x y) more)))
 
(defn bit-or
  "Bitwise or"
  ([x] x)
  ([x y] (. com.las3r.runtime.Numbers (or x y)))
  ([x y & more]
     (reduce bit-or (bit-or x y) more)))
 
(defn bit-xor
  "Bitwise exclusive or"
  ([x] x)
  ([x y] (. com.las3r.runtime.Numbers (xor x y)))
  ([x y & more]
     (reduce bit-and (bit-and x y) more)))
 
(defn bit-shl
  "Bitwise shift left"
  ([x n] (. com.las3r.runtime.Numbers (shl x n))))
 
(defn bit-shr
  "Bitwise shift right"
  ([x n] (. com.las3r.runtime.Numbers (shr x n))))
 
(defn bit-sar
  "Bitwise shift arithmetic right"
  ([x n] (. com.las3r.runtime.Numbers (sar x n))))
 
;; clojury aliases
(def bit-shift-left bit-shl)
(def bit-shift-right bit-sar)
 
 
(defn even?
  "Returns true if n is even, throws an exception if n is not an integer"
  [n] (zero? (bit-and n 1)))
 
(defn odd?
  "Returns true if n is odd, throws an exception if n is not an integer"
  [n] (not (even? n)))
 
 
;;;;;;;;; var stuff
 
 
(defmacro binding
  "binding => var-symbol init-expr
 
  Creates new bindings for the (already-existing) vars, with the
  supplied initial values, executes the exprs in an implicit do, then
  re-establishes the bindings that existed before."
  [bindings & body]
  (let [var-ize (fn [var-vals]
(loop* [ret [] vvs (seq var-vals)]
(if vvs
(recur (conj (conj ret `(var ~(first vvs))) (second vvs))
(rest (rest vvs)))
(seq ret))))]
    `(do
       (. com.las3r.runtime.Var (pushBindings *runtime* (hash-map ~@(var-ize bindings))))
       (try
~@body
(finally
(. com.las3r.runtime.Var (popBindings *runtime*)))))))
 
 
(defn find-var
  "Returns the global var named by the namespace-qualified symbol, or
  nil if no var with that name."
  [sym] (. com.las3r.runtime.Var (find *runtime* sym)))
 
 
 
;; Collection stuff
 
(defn count
  "Returns the number of items in the collection. (count nil) returns
  0. Also works on strings, arrays and maps"
  [coll] (. com.las3r.runtime.RT (count coll)))
 
 
;;list stuff
 
(defn nth
  "Returns the value at the index. get returns nil if index out of
  bounds, nth throws an exception unless not-found is supplied. nth
  also works for strings, Java arrays, regex Matchers and Lists, and,
  in O(n) time, for sequences."
  ([coll index] (. com.las3r.runtime.RT (nth coll index)))
  ([coll index not-found] (. com.las3r.runtime.RT (nth coll index not-found))))
 
 
;;;;;;;;;;;;;;;;; Tracing to console...
 
(defn pr
  "Trace out the object. By default, pr and prn print in a way that objects
  can be read by the reader"
  ([] nil)
  ([x]
     (. *runtime* (print x *out*))
     nil)
  ([x & more]
     (pr x)
     (. *out* (write \space))
     (apply pr more)))
 
 
(defn newline
  "Writes a newline to the output stream that is the current value of
  *out*"
  []
  (. *out* (write \newline))
  nil)
 
 
(defn prn
  "Same as pr followed by (newline)."
  [& more]
  (apply pr more)
  (newline))
 
 
(defn print
  "Trace out the object(s). print and println produce output for human consumption."
  [& more]
  (binding [*print-readably* nil]
    (apply pr more)))
 
 
(defn println
  "Same as print followed by (newline)"
  [& more]
  (binding [*print-readably* nil]
    (apply prn more)))
 
 
(defmacro assert
  "Evaluates expr and throws an exception if it does not evaluate to
 logical true."
  [x]
  `(when-not ~x
     (throw (new Error (str "Assert failed: " '~x)))))
 
 
 
;;;;;;;;;;;;;;;;;;; sequence fns ;;;;;;;;;;;;;;;;;;;;;;;
 
(defn not-empty
  "If coll is empty, returns nil, else coll"
  [coll] (when (seq coll) coll))
  
(defn every?
  "Returns true if (pred x) is logical true for every x in coll, else
  false."
  [pred coll]
  (if (seq coll)
    (and (pred (first coll))
(recur pred (rest coll)))
    true))
 
(def
 #^{:tag Boolean
    :doc "Returns false if (pred x) is logical true for every x in
  coll, else true."
    :arglists '([pred coll])}
 not-every? (comp not every?))
 
(defn some
  "Returns the first logical true value of (pred x) for any x in coll,
  else nil."
  [pred coll]
  (when (seq coll)
    (or (pred (first coll)) (recur pred (rest coll)))))
 
 
(def
 #^{:tag Boolean
    :doc "Returns false if (pred x) is logical true for any x in coll,
  else true."
    :arglists '([pred coll])}
 not-any? (comp not some))
 
 
(defn map
  "Returns a lazy seq consisting of the result of applying f to the
  set of first items of each coll, followed by applying f to the set
  of second items in each coll, until any one of the colls is
  exhausted. Any remaining items in other colls are ignored. Function
  f should accept number-of-colls arguments."
  ([f coll]
     (when (seq coll)
       (lazy-cons (f (first coll)) (map f (rest coll)))))
  ([f coll & colls]
     (when (and (seq coll) (every? seq colls))
       (lazy-cons (apply f (first coll) (map first colls))
(apply map f (rest coll) (map rest colls))))))
 
(defn mapcat
  "Returns the result of applying concat to the result of applying map
  to f and colls. Thus function f should return a collection."
  [f & colls]
  (apply concat (apply map f colls)))
 
(defn filter
  "Returns a lazy seq of the items in coll for which
  (pred item) returns true. pred must be free of side-effects."
  [pred coll]
  (when (seq coll)
    (if (pred (first coll))
      (lazy-cons (first coll) (filter pred (rest coll)))
      (recur pred (rest coll)))))
 
(defn take
  "Returns a lazy seq of the first n items in coll, or all items if
  there are fewer than n."
  [n coll]
  (when (and (pos? n) (seq coll))
    (lazy-cons (first coll) (take (dec n) (rest coll)))))
 
(defn take-while
  "Returns a lazy seq of successive items from coll while
  (pred item) returns true. pred must be free of side-effects."
  [pred coll]
  (when (and (seq coll) (pred (first coll)))
    (lazy-cons (first coll) (take-while pred (rest coll)))))
 
(defn drop
  "Returns a lazy seq of all but the first n items in coll."
  [n coll]
  (if (and (pos? n) (seq coll))
    (recur (dec n) (rest coll))
    (seq coll)))
 
(defn drop-last
  "Return a lazy seq of all but the last n (default 1) items in coll"
  ([s] (drop-last 1 s))
  ([n s] (map (fn [x _] x) (seq s) (drop n s))))
 
(defn drop-while
  "Returns a lazy seq of the items in coll starting from the first
  item for which (pred item) returns nil."
  [pred coll]
  (if (and (seq coll) (pred (first coll)))
    (recur pred (rest coll))
    (seq coll)))
 
(defn cycle
  "Returns a lazy (infinite!) seq of repetitions of the items in
  coll."
  [coll]
  (when (seq coll)
    (let [rep (fn thisfn [xs]
(if xs
(lazy-cons (first xs) (thisfn (rest xs)))
(recur (seq coll))))]
      (rep (seq coll)))))
 
(defn split-at
  "Returns a vector of [(take n coll) (drop n coll)]"
  [n coll]
  [(take n coll) (drop n coll)])
 
(defn split-with
  "Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
  [pred coll]
  [(take-while pred coll) (drop-while pred coll)])
 
(defn repeat
  "Returns a lazy (infinite!) seq of xs."
  [x] (lazy-cons x (repeat x)))
 
(defn replicate
  "Returns a lazy seq of n xs."
  [n x] (take n (repeat x)))
  
(defn iterate
  "Returns a lazy seq of x, (f x), (f (f x)) etc. f must be free of side-effects"
  [f x] (lazy-cons x (iterate f (f x))))
 
(defn range
  "Returns a lazy seq of nums from start (inclusive) to end
  (exclusive), by step, where start defaults to 0 and step to 1."
  ([end] (if (> end 0)
           (new com.las3r.runtime.Range 0 end)
           (take end (iterate inc 0))))
  ([start end] (if (< start end)
                 (new com.las3r.runtime.Range start end)
                 (take (- end start) (iterate inc start))))
  ([start end step]
     (take-while (partial (if (pos? step) > <) end) (iterate (partial + step) start))))
 
 
(defn merge
  "Returns a map that consists of the rest of the maps conj-ed onto
  the first. If a key occurs in more than one map, the mapping from
  the latter (left-to-right) will be the mapping in the result."
  [& maps] (reduce conj maps))
 
 
(defn merge-with
  "Returns a map that consists of the rest of the maps conj-ed onto
  the first. If a key occurs in more than one map, the mapping(s)
  from the latter (left-to-right) will be combined with the mapping in
  the result by calling (f val-in-result val-in-latter)."
  [f & maps]
  (let [merge-entry (fn [m e]
(let [k (key e) v (val e)]
(if (contains? m k)
(assoc m k (f (m k) v))
(assoc m k v))))
merge2 (fn [m1 m2]
(reduce merge-entry m1 (seq m2)))]
    (reduce merge2 maps)))
 
 
 
 
(defn zipmap
  "Returns a map with the keys mapped to the corresponding vals."
  [keys vals]
  (loop* [map {}
ks (seq keys)
vs (seq vals)]
(if (and ks vs)
(recur (assoc map (first ks) (first vs))
(rest ks)
(rest vs))
map)))
 
 
(defn line-seq
  "Returns the lines of text from rdr as a lazy sequence of strings.
  rdr must implement java.io.BufferedReader."
  [#^com.las3r.jdk.io.BufferedReader rdr]
  (let [line (. rdr (readLine))]
    (when line
      (lazy-cons line (line-seq rdr)))))
 
 
(defn eval
  "Evaluates the form data structure (provided as a string!) and calls back with the result
   if callback is provided."
  ([form] (. *runtime* (evalStr form)))
  ([form callback] (. *runtime* (evalStr form callback)))
  ([form callback err-callback] (. *runtime* (evalStr form callback nil err-callback)))
  ([form callback err-callback progress] (. *runtime* (evalStr form callback progress err-callback))))
 
(defmacro doseq
  "Repeatedly executes body (presumably for side-effects) with
  binding-form bound to successive items from coll. Does not retain
  the head of the sequence. Returns nil."
  [item list & body]
  `(loop* [list# (seq ~list)]
(when list#
(let [~item (first list#)]
~@body)
(recur (rest list#)))))
 
(defn dorun
  "When lazy sequences are produced via functions that have side
  effects, any effects other than those needed to produce the first
  element in the seq do not occur until the seq is consumed. dorun can
  be used to force any effects. Walks through the successive rests of
  the seq, does not retain the head and returns nil."
  ([coll]
     (when (and (seq coll) (or (first coll) true))
       (recur (rest coll))))
  ([n coll]
     (when (and (seq coll) (pos? n) (or (first coll) true))
       (recur (dec n) (rest coll)))))
 
(defn doall
  "When lazy sequences are produced via functions that have side
  effects, any effects other than those needed to produce the first
  element in the seq do not occur until the seq is consumed. doall can
  be used to force any effects. Walks through the successive rests of
  the seq, retains the head and returns it, thus causing the entire
  seq to reside in memory at one time."
  ([coll]
     (dorun coll)
     coll)
  ([n coll]
     (dorun n coll)
     coll))
 
(defmacro dotimes
  "Repeatedly executes body (presumably for side-effects) with name
  bound to integers from 0 through n-1."
  [i n & body]
  `(let [n# ~n]
     (loop* [~i 0]
(when (< ~i n#)
~@body
(recur (inc ~i))))))
 
 
(defn import
  "import-list => (package-symbol class-name-symbols*)
 
  For each name in class-name-symbols, adds a mapping from name to the
  class named by package.name to the current namespace. Use :import in the ns
  macro in preference to calling this directly."
  [& import-lists]
  (when import-lists
    (let [#^com.las3r.runtime.LispNamespace ns *ns*
pkg (ffirst import-lists)
classes (rfirst import-lists)]
      
      (doseq c classes
(. ns (importClass c (. com.las3r.runtime.RT (classForName (str pkg "." c)))))))
    (apply import (rest import-lists))))
 
 
(defn into
  "Returns a new coll consisting of to-coll with all of the items of
  from-coll conjoined."
  [to from]
  (let [ret to items (seq from)]
    (if items
      (recur (conj ret (first items)) (rest items))
      ret)))
 
(defn #^Class class
  "Returns the Class of x"
  [#^Object x] (if (nil? x) x (. com.las3r.runtime.RT (classForInstance x))))
 
 
;; (vec '(1 2 3))
(defn vec
  "Creates a new vector containing the contents of coll."
  [coll]
  (into [] (seq coll)))
 
 
 
;;;;;;;;;;;; regex ;;;;;;;;;;;;;;;;;
 
(defn re
  "Given a string and an optional string of flag characters,
   return an instance of RegExp, for use, e.g. in re-match."
  {:tag RegExp}
  ([s] (re s ""))
  ([s flags] (new RegExp s flags)))
  
 
(defn re-match
  "Apply r to str one time. If r is not found in str, return nil.
   Otherwise, return a vector of matched groups, where nth(0) is
   the entire match."
  [#^RegExp r #^String s]
  (let [m (. r (exec s))]
    (if (nil? m) nil
(vec m))))
;;(re-match (re "a(b)") "ababababababa")
 
 
(defn re-matches
  "Returns a lazy sequence of successive matches of pattern in string.
   Each match is processed with re-match. If no matches are found, result
   is nil."
  [#^RegExp r s]
  (when-not (. r global) (throw-rte "RegExp supplied to re-matches must have global flag set."))
  ((fn step []
     (let [m (. r (exec s))]
       (when m
(lazy-cons (vec m) (step)))))))
;;(take 8 (re-matches (re "a(b)" "g") "ababababababa"))
 
 
(defn macroexpand-1
  "If form represents a macro form, returns its expansion,
  else returns form."
  [form]
  (. (. *runtime* compiler) (macroexpand1 form)))
 
 
 
(defn macroexpand
  "Repeatedly calls macroexpand-1 on form until it no longer
  represents a macro form, then returns it. Note neither
  macroexpand-1 nor macroexpand expand macros in subforms."
  [form]
  (let [ex (macroexpand-1 form)]
    (if (identical? ex form)
      form
      (macroexpand ex))))
 
 
(defn create-struct
  "Returns a structure basis object."
  [& keys]
  (. com.las3r.runtime.PersistentStructMap (createSlotMap keys)))
 
(defmacro defstruct
  "Same as (def name (create-struct keys...))"
  [name & keys]
  `(def ~name (create-struct ~@keys)))
  
(defn struct-map
  "Returns a new structmap instance with the keys of the
  structure-basis. keyvals may contain all, some or none of the basis
  keys - where values are not supplied they will default to nil.
  keyvals can also contain keys not in the basis."
  [s & inits]
  (. com.las3r.runtime.PersistentStructMap (create s inits)))
 
(defn struct
  "Returns a new structmap instance with the keys of the
  structure-basis. vals must be supplied for basis keys in order -
  where values are not supplied they will default to nil."
  [s & vals]
  (. com.las3r.runtime.PersistentStructMap (construct s vals)))
 
(defn accessor
  "Returns a fn that, given an instance of a structmap with the basis,
  returns the value at the key. The key must be in the basis. The
  returned function should be (slightly) more efficient than using
  get, but such use of accessors should be limited to known
  performance-critical areas."
  [s key]
  (. com.las3r.runtime.PersistentStructMap (getAccessor s key)))
 
(defn subvec
  "Returns a persistent vector of the items in vector from
  start (inclusive) to end (exclusive). If end is not supplied,
  defaults to (count vector). This operation is O(1) and very fast, as
  the resulting vector shares structure with the original and no
  trimming is done."
  ([v start]
     (subvec v start (count v)))
  ([v start end]
     (. com.las3r.runtime.RT (subvec v start end))))
 
 
(defn #^{:private true}
  filter-key [keyfn pred amap]
  (loop* [ret {} es (seq amap)]
(if es
(if (pred (keyfn (first es)))
(recur (assoc ret (key (first es)) (val (first es))) (rest es))
(recur ret (rest es)))
ret)))
 
 
(defmacro time
  "Evaluates expr and prints the time it took. Returns the value of
   expr."
  [expr]
  `(let [start# (. com.las3r.runtime.RT (sysTime))
ret# ~expr]
     (prn (str "Elapsed time: " (- (. com.las3r.runtime.RT (sysTime)) start#) " msecs"))
     ret#))
 
(defn set
  "Returns a set of the distinct elements of coll."
  [coll] (apply hash-set coll))
 
(defn find-ns
  "Returns the namespace named by the symbol or nil if it doesn't exist."
  [sym] (. com.las3r.runtime.LispNamespace (find *runtime* sym)))
 
 
(defn create-ns
  "Create a new namespace named by the symbol if one doesn't already
  exist, returns it or the already-existing namespace of the same
  name."
  [sym] (. com.las3r.runtime.LispNamespace (findOrCreate *runtime* sym)))
 
 
(defn remove-ns
  "Removes the namespace named by the symbol. Use with caution.
  Cannot be used to remove the clojure namespace."
  [sym] (. com.las3r.runtime.LispNamespace (remove *runtime* sym)))
 
 
(defn all-ns
  "Returns a sequence of all namespaces."
  [] (. com.las3r.runtime.LispNamespace (all *runtime*)))
 
 
(defn ns-name
  "Returns the name of the namespace, a symbol."
  [#^com.las3r.runtime.LispNamespace ns]
  (. ns (getName)))
 
 
(defn ns-map
  "Returns a map of all the mappings for the namespace."
  [#^com.las3r.runtime.LispNamespace ns]
  (. ns (getMappings)))
 
 
(defn ns-unmap
  "Removes the mappings for the symbol from the namespace."
  [#^com.las3r.runtime.LispNamespace ns sym]
  (. ns (unmap sym)))
 
(defn ns-publics
  "Returns a map of the public intern mappings for the namespace."
  [#^com.las3r.runtime.LispNamespace ns]
  (filter-key val (fn [#^com.las3r.runtime.Var v] (and (instance? com.las3r.runtime.Var v)
(= ns (. v ns))
(. v (isPublic))))
(ns-map ns)))
 
(defn ns-imports
  "Returns a map of the import mappings for the namespace."
  [#^com.las3r.runtime.LispNamespace ns]
  (filter-key val (partial instance? Class) (ns-map ns)))
 
 
(defn refer
  "refers to all public vars of ns, subject to filters.
  filters can include at most one each of:
 
  :exclude list-of-symbols
  :only list-of-symbols
  :rename map-of-fromsymbol-tosymbol
 
  For each public interned var in the namespace named by the symbol,
  adds a mapping from the name of the var to the var to the current
  namespace. Throws an exception if name is already mapped to
  something else in the current namespace. Filters can be used to
  select a subset, via inclusion or exclusion, or to provide a mapping
  to a symbol different from the var's name, in order to prevent
  clashes. Use :use in the ns macro in preference to calling this directly."
  [ns-sym & filters]
  (let [ns (or (find-ns ns-sym) (throw (new Error (str "No namespace: " ns-sym))))
fs (apply hash-map filters)
nspublics (ns-publics ns)
rename (or (get fs :rename) {})
exclude (apply hash-set (get fs :exclude))
to-do (or (get fs :only) (keys nspublics))]
    (doseq sym to-do
      (when-not (contains? exclude sym)
(let [v (get nspublics sym)]
(when-not v
(throw (new Error (str sym " is not public"))))
(. *ns* (refer (or (get rename sym) sym) v)))))))
 
(defn ns-refers
  "Returns a map of the refer mappings for the namespace."
  [#^com.las3r.runtime.Namespace ns]
  (filter-key val (fn [#^com.las3r.runtime.Var v] (and (instance? com.las3r.runtime.Var v)
(not= ns (. v ns))))
(ns-map ns)))
 
(defn ns-interns
  "Returns a map of the intern mappings for the namespace."
  [#^com.las3r.runtime.Namespace ns]
  (filter-key val (fn [#^com.las3r.runtime.Var v] (and (instance? com.las3r.runtime.Var v)
(= ns (. v ns))))
(ns-map ns)))
 
 
(defn alias
  "Add an alias in the current namespace to another
  namespace. Arguments are two symbols: the alias to be used, and
  the symbolic name of the target namespace. Use :as in the ns macro in preference
  to calling this directly."
  [alias namespace-sym]
  (. *ns* (addAlias alias (find-ns namespace-sym))))
 
(defn ns-aliases
  "Returns a map of the aliases for the namespace."
  [#^com.las3r.runtime.LispNamespace ns] (. ns (getAliases)))
 
(defn ns-unalias
  "Removes the alias for the symbol from the namespace."
  [#^com.las3r.runtime.LispNamespace ns sym]
  (. ns (removeAlias sym)))
 
(defn take-nth
  "Returns a lazy seq of every nth item in coll."
  [n coll]
  (when (seq coll)
    (lazy-cons (first coll) (take-nth n (drop n coll)))))
 
(defn interleave
  "Returns a lazy seq of the first item in each coll, then the second
  etc."
  [& colls]
  (apply concat (apply map list colls)))
 
 
(defn nthrest
  "Returns the nth rest of coll, (seq coll) when n is 0."
  [coll n]
  (loop* [n n xs (seq coll)]
(if (and xs (pos? n))
(recur (dec n) (rest xs))
xs)))
 
(defn var-get
  "Gets the value in the var object"
  [#^com.las3r.runtime.Var x] (. x (get)))
 
(defn var-set
  "Sets the value in the var object to val. The var must be
 thread-locally bound."
  [#^com.las3r.runtime.Var x val] (. x (set val)))
 
(defmacro with-local-vars
  "varbinding=> symbol init-expr
 
  Executes the exprs in a context in which the symbols are bound to
  vars with per-thread bindings to the init-exprs. The symbols refer
  to the var objects themselves, and must be accessed with var-get and
  var-set"
  [name-vals-vec & body]
  `(let [~@(interleave (take-nth 2 name-vals-vec)
(repeat '(. com.las3r.runtime.Var (create *runtime*))))]
     (. com.las3r.runtime.Var (pushThreadBindings *runtime* (hash-map ~@name-vals-vec)))
     (try
      ~@body
      (finally (. com.las3r.runtime.Var (popThreadBindings *runtime*))))))
 
(defmacro doto
  "Evaluates x then calls all of the methods with the supplied
  arguments in succession on the resulting object, returning it.
 
  (doto (new java.util.HashMap) (put \"a\" 1) (put \"b\" 2))"
  [x & members]
  (let [gx (gensym)]
    `(let [~gx ~x]
       (do
~@(map (fn [m] (list '. gx m))
members))
       ~gx)))
 
(defmacro memfn
  "Expands into code that creates a fn that expects to be passed an
  object and any args and calls the named instance method on the
  object passing the args. Use when you want to treat a Java method as
  a first-class fn."
  [name & args]
  `(fn [target# ~@args]
     (. target# (~name ~@args))))
 
(defmacro ..
  "form => fieldName-symbol or (instanceMethodName-symbol args*)
 
  Expands into a member access (.) of the first member on the first
  argument, followed by the next member on the result, etc. For
  instance:
 
  (.. System (getProperties) (get \"os.name\"))
 
  expands to:
 
  (. (. System (getProperties)) (get \"os.name\"))
 
  but is easier to write, read, and understand."
  ([x form] `(. ~x ~form))
  ([x form & more] `(.. (. ~x ~form) ~@more)))
 
(defmacro ->
  "Macro. Threads the expr through the forms. Inserts x as the
  second item in the first form, making a list of it if it is not a
  list already. If there are more forms, inserts the first form as the
  second item in second form, etc."
  ([x form] (if (seq? form)
`(~(first form) ~x ~@(rest form))
(list form x)))
  ([x form & more] `(-> (-> ~x ~form) ~@more)))
 
(defn symbol?
  "Return true if x is a Symbol"
  [x] (instance? com.las3r.runtime.Symbol x))
 
 
(defn keyword?
  "Return true if x is a Keyword"
  [x] (instance? com.las3r.runtime.Keyword x))
 
 
(defn num
  "Coerce to Number"
  {:tag Number}
  [x] (. com.las3r.runtime.RT (numCast x)))
 
 
(defn int
  "Coerce to int"
  [x] (. com.las3r.runtime.RT (intCast x)))
 
 
(defn rand
  "Returns a random floating point number between 0 (inclusive) and
  1 (exclusive)."
  ([] (. Math (random)))
  ([n] (* n (rand))))
 
(defn rand-int
  "Returns a random integer between 0 (inclusive) and n (exclusive)."
  [n] (int (rand n)))
 
(defmacro defn-
  "same as defn, yielding non-public def"
  [name & decls]
  (list* `defn (with-meta name (assoc (or (meta name) {}) :private true)) decls))
 
 
 
 
(defn destructure [bindings]
  (let [bmap (apply array-map bindings)
pb (fn pb [bvec b v]
(let [pvec
(fn [bvec b val]
(let [gvec (gensym "vec__")]
(loop* [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthrest gvec n))
n
(rrest bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Error "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(inc n)
(rest bs)
seen-rest?))))
ret))))
pmap
(fn pmap [bvec b v]
(let [gmap (or (get b :as) (gensym "map__"))
defaults (get b :or)]
(loop* [ret (-> bvec (conj gmap) (conj v))
bes (reduce
(fn [bes entry]
(reduce (fn [a b] (assoc a b (get b (val entry))))
(dissoc bes (key entry))
(get bes (key entry))))
(dissoc b :as :or)
{:keys (fn [a] (keyword (str a))), :strs str, :syms (fn [a] (list `quote a))})]
(if (seq bes)
(let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (get defaults bb))
(list `get gmap bk)))
(rest bes)))
ret)
)))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Error (str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (key b) (val b)))]
    (if (every? symbol? (keys bmap))
      bindings
      (reduce process-entry [] bmap))))
;; (try (destructure '[{a :a} {:a 1}]) (catch Error e (. e (getStackTrace))))
;; {:a}
 
 
;; (let [[a b c] [1 2 3]] a)
;; (let [[a b c & d] [1 2 3 4 5 6 7]] d)
(defmacro let
  "Evaluates the exprs in a lexical context in which the symbols in
  the binding-forms are bound to their respective init-exprs or parts
  therein."
  [bindings & body]
  (when (odd? (count bindings))
    (throw (new Error "Odd number of elements in let bindings")))
  `(let* ~(destructure bindings) ~@body))
 
;; ((fn [[x y z] a b c & d] x) [1 2 3] 2 3 4 5 6 7)
(defmacro fn
  "(fn name? [params* ] exprs*)
  (fn name? ([params* ] exprs*)+)
 
  params => positional-params* , or positional-params* & rest-param
  positional-param => binding-form
  rest-param => binding-form
  name => symbol
 
  Defines a function"
  [& sigs]
  (let [name (if (symbol? (first sigs)) (first sigs) nil)
sigs (if name (rest sigs) sigs)
sigs (if (vector? (first sigs)) (list sigs) sigs)
psig (fn [sig]
(let [[params & body] sig]
(if (every? symbol? params)
sig
(loop* [params params
new-params []
lets []]
(if params
(if (symbol? (first params))
(recur (rest params) (conj new-params (first params)) lets)
(let [gparam (gensym "p__")]
(recur (rest params) (conj new-params gparam)
(-> lets (conj (first params)) (conj gparam)))))
`(~new-params
(let ~lets
~@body)))))))
new-sigs (map psig sigs)]
    (with-meta
     (if name
       (list* 'fn* name new-sigs)
       (cons 'fn* new-sigs))
     {} ;;*macro-meta*
     )))
 
 
(defmacro loop
  "Evaluates the exprs in a lexical context in which the symbols in
  the binding-forms are bound to their respective init-exprs or parts
  therein. Acts as a recur target."
  [bindings & body]
  (let [db (destructure bindings)]
    (if (= db bindings)
      `(loop* ~bindings ~@body)
      (let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
 
(defmacro when-first
  "bindings => x xs
 
  Same as (when (seq xs) (let [x (first xs)] body))"
  [bindings & body]
  (if (vector? bindings)
    (let [[x xs] bindings]
      `(when (seq ~xs)
(let [~x (first ~xs)]
~@body)))
    (throw (new Error
"when-first now requires a vector for its binding"))))
 
(defmacro lazy-cat
  "Expands to code which yields a lazy sequence of the concatenation
  of the supplied colls. Each coll expr is not evaluated until it is
  needed."
  ([coll] `(seq ~coll))
  ([coll & colls]
     `(let [iter# (fn iter# [coll#]
(if (seq coll#)
(lazy-cons (first coll#) (iter# (rest coll#)))
(lazy-cat ~@colls)))]
(iter# ~coll))))
 
 
(defmacro for
  "List comprehension. Takes a vector of one or more
 binding-form/collection-expr pairs, each followed by an optional filtering
 :when/:while expression (:when test or :while test), and yields a
 lazy sequence of evaluations of expr. Collections are iterated in a
 nested fashion, rightmost fastest, and nested coll-exprs can refer to
 bindings created in prior binding-forms.
 (take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
  ([seq-exprs expr]
     (let [pargs (fn [xs]
(loop [ret []
[b e & [w f & wr :as r] :as xs] (seq xs)]
(if xs
(cond
(= w :when) (recur (conj ret {:b b :e e :f f :w :when}) wr)
(= w :while) (recur (conj ret {:b b :e e :f f :w :while}) wr)
:else (recur (conj ret {:b b :e e :f true :w :while}) r))
(seq ret))))
 
emit (fn emit [[{b :b f :f w :w} & [{ys :e} :as rses]]]
(let [giter (gensym "iter__") gxs (gensym "s__")]
`(fn ~giter [~gxs]
(when-first [~b ~gxs]
(if ~f
~(if rses
`(let [iterys# ~(emit rses)
fs# (iterys# ~ys)]
(if fs#
(lazy-cat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
`(lazy-cons ~expr (~giter (rest ~gxs))))
~(if (= w :when)
`(recur (rest ~gxs))
nil))))))]
       `(let [iter# ~(emit (pargs seq-exprs))]
(iter# ~(second seq-exprs))))))
      
 
(defn special-symbol?
  "Returns true if s names a special form"
  [s]
  (. *runtime* (isSpecial s)))
 
(defn subs
  "Returns the substring of s beginning at start inclusive, and ending
  at end (defaults to length of string), exclusive."
  ([#^String s start] (. s (substring start)))
  ([#^String s start end] (. s (substring start end))))
 
(defn max-key
  "Returns the x for which (k x), a number, is greatest."
  ([k x] x)
  ([k x y] (if (> (k x) (k y)) x y))
  ([k x y & more]
     (reduce (fn [a b] (max-key k a b)) (max-key k x y) more)))
 
(defn min-key
  "Returns the x for which (k x), a number, is least."
  ([k x] x)
  ([k x y] (if (< (k x) (k y)) x y))
  ([k x y & more]
     (reduce (fn [a b] (min-key k a b)) (min-key k x y) more)))
 
 
(defn distinct
  "Returns a lazy sequence of the elements of coll with duplicates removed"
  [coll]
  (let [step (fn step [[f & r :as xs] seen]
(when xs
(if (contains? seen f) (recur r seen)
(lazy-cons f (step r (conj seen f))))))]
    (step (seq coll) #{})))
;;(distinct '(1 1 4 3 4 2 ))
 
(defmacro if-let
  "if test is true, evaluates then with binding-form bound to the value of test, if not, yields else"
  ([binding-form test then]
     `(if-let ~binding-form ~test ~then nil))
  ([binding-form test then else]
     `(let [temp# ~test]
(if temp#
(let [~binding-form temp#]
~then)
~else))))
 
(defmacro when-let
  "when test is true, evaluates body with binding-form bound to the value of test"
  [binding-form test & body]
  `(let [temp# ~test]
     (when temp#
       (let [~binding-form temp#]
~@body))))
 
 
(defmacro comment
  "Ignores body, yields nil"
  [& body])
 
 
;;;;;;;;;;;;;;;; for..each and for..in wrappers
 
(defn get-property-values
  "Return a list of all the values of an object's dynamic properties, wrapper for actionscript's for each(...) construct."
  [obj]
  (. *runtime* (propertyValuesList obj)))
 
(defn get-property-names
  "Return a list of all the names of an object's dynamic properties, wrapper for actionscript's for(.. in ..) construct."
  [obj]
  (. *runtime* (propertyNamesList obj)))
 
(defn get-property
  "Return an instance's property value using the array access [] operator."
  [instance property]
  (. *runtime* (getPropertyByName instance property)))
 
(defn set-property!
  "Set an instance's property to value using the array access [] operator."
  [instance property value]
  (. *runtime* (setPropertyByName instance property value)))
 
 
 
 
;;;;;;;;;;;;;;;; multimethods ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 
(defn alter-var-root
  "Atomically alters the root binding of var v by applying f to its
  current value plus any args"
  [#^com.las3r.runtime.Var v f & args] (. v (alterRoot f args)))
 
(defn class?
  "Returns true if x is an instance of Class"
  [x] (instance? Class x))
 
(defn make-hierarchy
  "Creates a hierarchy object for use with derive, isa? etc."
  [] {:parents {} :descendants {} :ancestors {}})
 
(def #^{:private true}
     global-hierarchy (make-hierarchy))
 
(defn bases
  "Returns the immediate superclass and direct interfaces of c, if any"
  [#^Class c]
  (let [i (. com.las3r.runtime.RT (getInterfaces c))
        s (. com.las3r.runtime.RT (getSuperClass c))]
    (set
     (if s (cons s i) i))))
 
(defn supers
  "Returns the immediate and indirect superclasses and interfaces of c, if any"
  [#^Class c]
  (let [i (. com.las3r.runtime.RT (getInterfaces c))
        s (. com.las3r.runtime.RT (getSuperClasses c))]
    (set (concat i s))))
 
(defn conforms?
  "Does child conform to the interface of parent?"
  [#^Class child #^Class parent]
  (or (= child parent)
      (contains? (supers child) parent)))
 
(defn isa?
  "Returns true if (= child parent), or child is directly or indirectly derived from
  parent, either via a Java type inheritance relationship or a
  relationship established via derive. h must be a hierarchy obtained
  from make-hierarchy, if not supplied defaults to the global
  hierarchy"
  ([child parent] (isa? global-hierarchy child parent))
  ([h child parent]
     (or (= child parent)
(and (class? parent) (class? child)
(conforms? child parent))
(contains? ((:ancestors h) child) parent)
(and (class? child) (some (fn [c] (contains? ((:ancestors h) c) parent)) (supers child)))
(and (vector? parent) (vector? child)
(= (count parent) (count child))
(loop [ret true i 0]
(if (or (not ret) (= i (count parent)))
ret
(recur (isa? h (child i) (parent i)) (inc i))))))))
 
(defn parents
  "Returns the immediate parents of tag, either via a Java type
  inheritance relationship or a relationship established via derive. h
  must be a hierarchy obtained from make-hierarchy, if not supplied
  defaults to the global hierarchy"
  ([tag] (parents global-hierarchy tag))
  ([h tag] (not-empty
            (let [tp (get (:parents h) tag)]
              (if (class? tag)
                (into (set (bases tag)) tp)
                tp)))))
 
(defn ancestors
  "Returns the immediate and indirect parents of tag, either via a Java type
  inheritance relationship or a relationship established via derive. h
  must be a hierarchy obtained from make-hierarchy, if not supplied
  defaults to the global hierarchy"
  ([tag] (ancestors global-hierarchy tag))
  ([h tag] (not-empty
            (let [ta (get (:ancestors h) tag)]
              (if (class? tag)
                (into (set (supers tag)) ta)
                ta)))))
 
(defn descendants
  "Returns the immediate and indirect children of tag, through a
  relationship established via derive. h must be a hierarchy obtained
  from make-hierarchy, if not supplied defaults to the global
  hierarchy. Note: does not work on Java type inheritance
  relationships."
  ([tag] (descendants global-hierarchy tag))
  ([h tag] (if (class? tag)
             (throw (new Error("UnsupportedOperationException: Can't get descendants of classes")))
             (not-empty (get (:descendants h) tag)))))
 
 
(defn derive
  "Establishes a parent/child relationship between parent and
  tag. Parent must be a namespace-qualified symbol or keyword and
  child can be either a namespace-qualified symbol or keyword or a
  class. h must be a hierarchy obtained from make-hierarchy, if not
  supplied defaults to, and modifies, the global hierarchy."
  ([tag parent]
     (assert (namespace parent))
     (assert (or (class? tag) (and (instance? com.las3r.runtime.Named tag) (namespace tag))))
 
     (alter-var-root #'global-hierarchy derive tag parent) nil)
  ([h tag parent]
     (assert (not= tag parent))
     (assert (or (class? tag) (instance? com.las3r.runtime.Named tag)))
     (assert (instance? com.las3r.runtime.Named parent))
     (let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce (fn [ret k]
(assoc ret k
(reduce conj (get targets k #{}) (cons target (targets target)))))
m (cons source (sources source))))]
       (or
(when-not (contains? (tp tag) parent)
(when (contains? (ta tag) parent)
(throw (new Error (str tag "already has" parent "as ancestor"))))
(when (contains? (ta parent) tag)
(throw (new Error (str "Cyclic derivation:" parent "has" tag "as ancestor"))))
{:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)})
h))))
 
(defn underive
  "Removes a parent/child relationship between parent and
  tag. h must be a hierarchy obtained from make-hierarchy, if not
  supplied defaults to, and modifies, the global hierarchy."
  ([tag parent] (alter-var-root #'global-hierarchy underive tag parent) nil)
  ([h tag parent]
     (let [tp (:parents h)
td (:descendants h)
ta (:ancestors h)
tf (fn [m source sources target targets]
(reduce
(fn [ret k]
(assoc ret k
(reduce disj (get targets k) (cons target (targets target)))))
m (cons source (sources source))))]
       (if (contains? (tp tag) parent)
{:parent (assoc (:parents h) tag (disj (get tp tag) parent))
:ancestors (tf (:ancestors h) tag td parent ta)
:descendants (tf (:descendants h) parent ta tag td)}
h))))
 
(defmacro defmulti
  "Creates a new multimethod with the associated dispatch function. If
  default-dispatch-val is supplied it becomes the default dispatch
  value of the multimethod, otherwise the default dispatch value
  is :default."
  ([name dispatch-fn] `(defmulti ~name ~dispatch-fn :default))
  ([name dispatch-fn default-val]
     `(def ~(with-meta name (assoc ^name :tag 'com.las3r.runtime.MultiFn))
(new com.las3r.runtime.MultiFn *runtime* ~dispatch-fn ~default-val))))
 
(defmacro defmethod
  "Creates and installs a new method of multimethod associated with dispatch-value. "
  [multifn dispatch-val & fn-tail]
  `(. ~multifn (addMethod ~dispatch-val (fn ~@fn-tail))))
 
(defn remove-method
  "Removes the method of multimethod associated with dispatch-value."
  [multifn dispatch-val]
  (. multifn (removeMethod dispatch-val)))
 
(defn prefer-method
  "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y when there is a conflict"
  [multifn dispatch-val-x dispatch-val-y]
  (. multifn (preferMethod dispatch-val-x dispatch-val-y)))
 
;;;;;;;;;;;;;;;; emacs integration ;;;;;;;;;;;;;;;;;;;;;;;
 
(import '(flash.net URLLoader URLRequest))
(import '(flash.events Event IOErrorEvent TimerEvent ProgressEvent))
(import '(flash.utils Timer))
(import '(flash.net Socket))
(import '(com.las3r.util StringBuffer))
 
 
(defn- read-bytes
  "Helper function for reading 0-terminated strings from eval_pipe."
  [socket buffer]
  (let [term 0]
    (loop [to-eval []]
      (if (> (. socket bytesAvailable) 0)
(let [byte (. socket (readUnsignedByte))]
(if (= byte term)
(let [src (str buffer)]
(. buffer (clear))
(recur (cons src to-eval)))
(let []
(. buffer (append (char-code->str byte)))
(recur to-eval)
)))
to-eval
))))
 
(defn- connect-to-eval-pipe
  "Connect to eval_pipe, reading and evaluating strings as they arrive."
  ([] (connect-to-eval-pipe 9877))
  ([port]
     (let [socket (new Socket)
buffer (new StringBuffer)]
       (. socket (addEventListener (. Event CONNECT) (fn [e] (println "Connected to eval_pipe."))))
       (. socket (addEventListener (. Event CLOSE) (fn [e] (println "Disconnected from eval_pipe."))))
       (. socket (addEventListener (. IOErrorEvent IO_ERROR) (fn [e] (println "Error on eval_pipe."))))
       (. socket (addEventListener
(. ProgressEvent SOCKET_DATA)
(fn [e]
(doseq src (read-bytes socket buffer)
(eval src
(fn [val] (prn val))
(fn [err] (binding [*out* *err*]
(prn err)))))
)))
       (println (str "Attempting connection to eval_pipe at localhost:" port "."))
       (. socket (connect "localhost" port))
       socket
       )))
 
(def *ctep-sockets* (ary []))
(defn ctep
  "Connect to the eval pipe. If we don't hold a reference to the socket, it'll get GC'd, so we
   push it onto a global, mutable array."
  []
  (let [s (connect-to-eval-pipe)]
    (. *ctep-sockets* (push s))
    s
    ))
 
 
(defn load-url
  "Load data from a URL using flash.net.URLLoader, setup on-complete and on-error as event listeners."
  [url on-complete on-error]
  (let [request (new flash.net.URLRequest url)
loader (new flash.net.URLLoader)]
    (. loader (addEventListener "complete" on-complete))
    (. loader (addEventListener "ioError" on-error))
    (. loader (addEventListener "securityError" on-error))
    (. loader (load request))))
 
(defn browse-file
  "Browse to a file. Apply callback to the loaded FileReference."
  [filters callback]
  (let [f (new flash.net.FileReference)
data-handler
(fn [e] (callback f))]
    (. f (addEventListener (. Event SELECT) (fn [e] (. f (load)))))
    (. f (addEventListener (. Event COMPLETE) data-handler))
    (. f (browse (to-array filters)))))
 
 
(defn browse-save-file
  "Browse to a file. Apply callback to the loaded FileReference."
  ([data name] (browse-save-file data name (fn [d] )))
  ([data name callback]
     (let [f (new flash.net.FileReference)
data-handler
(fn [e] (callback f))]
       (. f (addEventListener (. Event COMPLETE) data-handler))
       (. f (save data name)))))
 
(defn eval-url
  "Evaluate the code in the provided URL and call back with the result or error if callbacks are provided."
  ([url] (eval-url url (fn [e] nil) (fn [e] nil)))
  ([url callback] (eval-url url callback (fn [e] nil)))
  ([url callback err-callback]
     (load-url url
(fn [e]
(eval (.. e target data) callback err-callback))
err-callback)))
 
(defn compile-str
  "Evaluate all forms in src, returns a ByteArray containing compiled swf."
  [src module-id callback]
  (. *compiler* (beginAOTCompile module-id))
  (eval src
(fn [val]
(callback (. *compiler* (getAOTCompileBytes)))
(. *compiler* (endAOTCompile)))
(fn [err]
(binding [*out* *err*] (prn err))
(. *compiler* (endAOTCompile)))
(fn [a b] (print "."))
))
 
(defn compile-str-and-save
  "Evaluate all forms in src, create a ByteArray containing compiled forms,
   initiate saving of those bytes as a SWF file."
  [src module-id]
  (compile-str src module-id (fn [bytes]
(let [f (new flash.net.FileReference)]
(. f (save bytes (str module-id ".swf")))))))
 
(defn compile-file-and-save
  "1. Browse to a source file.
   2. Compile all forms in the source file.
   3. Browse a location to save the compiled swf module."
  [module-id]
  (let [filters [(new flash.net.FileFilter "lsr" "*.lsr")]]
    (browse-file filters
(fn [f]
(let [src (str (. f data))]
(compile-str-and-save src module-id))))))
 
(defn load-module
  "1. Browse to a swf module on the local file system.
   2. Load the compiled lisp forms contained inside."
  [module-id]
  (let [filters [(new flash.net.FileFilter "swf" "*.swf")]]
    (browse-file
     filters
     (fn [f]
       (. *runtime*
(loadModule
module-id (. f data)
(fn [val] (prn val))
(fn [err] (binding [*out* *err*]
(prn err)))))
       ))))
 
(defn load-file
  "1. Browse to a lsr source file on the local file system.
   2. Load the lisp forms contained inside."
  []
  (let [filters [(new flash.net.FileFilter "lsr" "*.lsr")]]
    (browse-file
     filters
     (fn [f]
       (let [src (str (. f data))]
(eval src
(fn [val] (prn val))
(fn [err] (binding [*out* *err*]
(prn err)))
(fn [a b] (print "."))
))
       ))))
 
 
;;;;;;;;;;;;;;;;;;;; Generating Documentation ;;;;;;;;;;;;;;;;;;;;
 
 
(defn print-doc [v]
  (println "-------------------------")
  (println (str (ns-name (get ^v :ns)) "/" (get ^v :name)))
  (prn (get ^v :arglists))
  (when (get ^v :macro)
    (println "Macro"))
  (println " " (get ^v :doc))
  )
 
 
(defn print-textile-doc [v]
  (println (str "**" (ns-name (get ^v :ns)) "/" (get ^v :name) "**") "<br>")
  (println "<notextile>" (get ^v :arglists) "</notextile>" "<br>")
  (when (get ^v :macro)
    (println "Macro"))
  (newline)
  (println "<notextile>" (get ^v :doc) "</notextile>")
  (println "<br>")
  (println "<br>")
  )
 
 
(defn print-special-doc
  [name type anchor]
  (println "-------------------------")
  (println name)
  (println type))
 
(defmacro doc
  "Prints documentation for a var or special form given its name"
  [name]
  (cond
   (special-symbol? `~name)
   `(print-special-doc '~name "Special Form")
   :else
   `(print-doc (var ~name))))
 
 
(defn doc-all-publics
  "Prints documentation for all public vars in the given namespace."
  [ns]
  (doseq ea (vals (ns-publics ns))
    (print-doc ea))
  )
 
(defn textile-doc-all-publics
  "Prints documentation for all public vars in the given namespace."
  [ns]
  (doseq ea (vals (ns-publics ns))
    (print-textile-doc ea))
  )
 
 
(defn generate-api-doc
  "Write all api documentation for the given namespace. Save that string to a file."
  [ns]
  (let [output (new com.las3r.io.NaiveStringWriter)]
    (binding [*out* output]
      (textile-doc-all-publics ns))
    (browse-save-file (str output) (str (. ns name) "_doc.txt"))))
 
 
 
;;;;;;;;;;;;;;;;;; Crude testing, until we're able to run real unit tests
 
 
(defmacro assert-true
  [form]
  `(try (if ~form
(print ".")
(prn (list "Failure: " '~form " Expecting truthy")))
(catch Error e# (prn (list "Error in: " '~form " " (. e# message))))))
 
 
(defmacro assert-false
  [form]
  `(try (if (not ~form)
(print ".")
(prn (list "Failure: " '~form " Expecting falsy")))
(catch Error e# (prn (list "Error in: " '~form " " (. e# message))))))
 
 
(defn run-tests []
  (assert-true (= (reduce + '(1 2 3)) 6))
  (assert-true (= (reduce + 0 '(1 2 3)) 6))
  (assert-true (= (reverse '(0 1 2 3)) '(3 2 1 0)))
 
  (assert-true (and true 1 2 :horse))
  (assert-false (and true nil))
 
  (assert-true (= :unicorn (cond nil :horse
nil :dog
:else :unicorn)))
 
  (assert-true (every? pos? '(1 2 3 4)))
  (assert-false (every? pos? '(1 -1 3 4)))
 
  (assert-true (not-every? pos? '(1 -1 3 4)))
  (assert-false (not-every? pos? '(1 2 3 4)))
 
  (assert-true (not-any? neg? '(1 1 3 4)))
 
  (assert-true (= (some neg? '(1 1 -2 4)) true))
 
  (assert-true (= (map (fn [ea] (+ ea 1)) '(0 1 2 3)) '(1 2 3 4)))
 
  (assert-true (= (take 2 '(1 2 2)) '(1 2)))
  (assert-true (= (drop 2 '(1 2 2)) '(2)))
 
  (assert-true (= (zipmap '(:a :b :c) '(1 2 3)) { :a 1 :b 2 :c 3}))
 
  (assert-true (= (merge {:a 1 :b 2} {:c 3}) { :a 1 :b 2 :c 3}))
 
  (assert-true (= #{:a :b :c} (set (keys {:a 1 :b 2 :c 3}))))
  (assert-true (= #{1 2 3} (set (vals {:a 1 :b 2 :c 3}))))
 
  ;; Test non-Obj equality
  (assert-false (= (new flash.display.Sprite) (new flash.display.Sprite)))
  (assert-true (let [s1 (new flash.display.Sprite)
s2 s1]
(= s1 s2)))
 
  ;; Check that overwriting keys works.
  (assert-true (= (get (assoc '{:a 2} :a 1) :a) 1))
 
  ;; This was failing verification because the 'do' was being emitted as a statement..
  (assert-true (= 1 (if true (do (doseq a (quote (1 2)) a) 1))))
 
  (assert-true (let [obj (new Object)]
(set! (. obj nums) [])
(set! (. obj funcs) [])
(doseq ea '[1 2 3 4 5]
(set! (. obj funcs) (conj
(. obj funcs)
(fn [] (set! (. obj nums) (conj (. obj nums) ea)))
)))
(doseq ea (. obj funcs) (ea))
(= [1 2 3 4 5] (. obj nums))
))
  
  ;;namespace stuff
  (let [sym (gensym)]
    (assert-false (find-ns sym))
    (create-ns sym)
    (assert-true (find-ns sym))
    (remove-ns sym)
    (assert-false (find-ns sym)))
  
  (assert-true (= [1 2] (-> [] (conj 1) (conj 2))))
 
  ;;Test destructuring binds
  (assert-true (= '(1 2 3) (let [[a b c] [1 2 3]] (list a b c))))
  
  (assert-true (= '(4 5) (let [[a b c & d] [1 2 3 4 5]] d)))
  
  (assert-true (= '[1 2 3 4 5] (let [[a b c & d :as e] [1 2 3 4 5]] e)))
  
  (assert-true (= '(1 2 3 4 5) (let [[a b c & d :as e] '(1 2 3 4 5)] e)))
  
  (assert-true (= '[1 2 3 4] (let [[[x1 y1][x2 y2]] [[1 2] [3 4]]] [x1 y1 x2 y2])))
  
  (assert-true (= '["a" "s" ("d" "j" "h" "h" "f" "d" "a" "s") "asdjhhfdas"]
(let [[a b & c :as str] "asdjhhfdas"] [a b c str])))
  
  ;; "Map binding forms"
  (assert-true (= [5 3 6 {:c 6, :a 5}] (let [{a :a, b :b, c :c, :as m :or {a 2 b 3}} {:a 5 :c 6}] [a b c m])))
 
  ;; "pull apart just about anything"
  (assert-true (= (let [{j :j, k :k, i :i, [r s & t :as v] :ivec, :or {i 12 j 13}}
{:j 15 :k 16 :ivec [22 23 24 25]}]
[i j k r s t v])
'[12 15 16 22 23 (24 25) [22 23 24 25]]))
 
  ;; Test ranges
  (assert-true (= '(0 1 2 3 4 5) (range 6)))
  (assert-true (= '(1 2 3 4 5) (range 1 6)))
 
  ;; line-seq with line-feed
  (let [s (line-seq (new com.las3r.jdk.io.BufferedReader (new com.las3r.jdk.io.StringReader "hello\ndude")))]
    (assert-true (= (first s) "hello"))
    (assert-true (= (second s) "dude")))
 
  ;; now with carriage return..
  (let [s (line-seq (new com.las3r.jdk.io.BufferedReader (new com.las3r.jdk.io.StringReader "hello\r\ndude")))]
    (assert-true (= (first s) "hello"))
    (assert-true (= (second s) "dude")))
 
  ;; For comprehension
  (assert-true (= (take 3 (for [x (range 100) :when (odd? x)] [x]))
'([1][3][5])))
 
  ;; Regexes
  (assert-true (= (re-match #"app(le)" "The bear ate the apple.")
'["apple" "le"]
))
 
  (assert-true (= (re-match #"pineapp(le)" "The bear ate the apple.") nil))
 
  (assert-true (= (re-matches (re "app(le)" "g") "The bear ate the apple.")
'(["apple" "le"])
))
 
  (assert-true (= (re-matches (re "app(le)" "g") "The bear ate my apple and your apple, too.")
'(["apple" "le"]["apple" "le"])
))
 
  (assert-true (= (re-matches (re "pineapp(le)" "g") "The bear ate my apple and your apple, too.") nil))
 
 
  ;; Test class handling necessary for multimethods
  (assert-true (contains? (bases flash.display.Sprite) flash.display.DisplayObjectContainer))
  (assert-true (contains? (bases flash.display.Sprite) flash.display.IBitmapDrawable))
  (assert-true (contains? (bases flash.display.Sprite) flash.events.IEventDispatcher))
  (assert-true (not (contains? (bases flash.display.Sprite) flash.display.DisplayObject)))
  (assert-true (not (contains? (bases flash.display.Sprite) flash.display.DisplayObject)))
  (assert-true (contains? (supers flash.display.Sprite) flash.display.DisplayObject))
  (assert-true (contains? (supers flash.display.Sprite) Object))
  (assert-true (not (contains? (supers flash.display.Sprite) flash.display.Sprite)))
  (assert-true (= flash.display.Sprite (class (new flash.display.Sprite))))
 
  (let [m (new com.las3r.runtime.MultiFn *runtime* class :default)
m (. m (addMethod flash.display.Sprite (fn [s] (. s x))))
m (. m (addMethod flash.display.DisplayObject (fn [s] -1)))
m (. m (addMethod :default (fn [s] -5)))]
    (assert-true (= (m (new flash.display.Shape)) -1))
    (assert-true (= (m (new flash.display.Sprite)) 0))
    (assert-true (= (m "lkdjfdkjf") -5)) ;; Should use :default
    )
 
  )
 
;;(run-tests)