rev: release-0.9 scopes/core.sc -rw-r--r-- 90.6 KiB View raw Log this file
707492ce6d4c — Leonard Ritter * disabled a test that fails on win32 for now 3 years ago
                                                                                
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
#
      \\\
       \\\
     ///\\\
    ///  \\\

    Scopes Compiler
    Copyright (c) 2016, 2017 Leonard Ritter

    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.

    This is the scopes boot script. It implements the remaining standard
    functions and macros, parses the command-line and optionally enters
    the REPL.

fn tie-const (a b)
    if (constant? a) b
    else (unconst b)

fn cond-const (a b)
    if a b
    else (unconst b)

fn type? (T)
    rawcall icmp== (rawcall ptrtoint type usize) (rawcall ptrtoint (rawcall typeof T) usize)

fn assert-type (T)
    if (type? T)
    else
        rawcall compiler-error!
            rawcall string-join "type expected, not " (rawcall Any-repr (rawcall Any-wrap T))
fn type== (a b)
    assert-type a
    assert-type b
    rawcall icmp== (rawcall ptrtoint a usize) (rawcall ptrtoint b usize)

fn unknownof (T)
    assert-type T
    bitcast T Unknown

fn todo! (msg)
    compiler-error!
        string-join "TODO: " msg

fn error! (msg)
    __error! msg
    unreachable!;

fn typename-type? (T)
    icmp== (type-kind T) type-kind-typename
fn integer-type? (T)
    icmp== (type-kind T) type-kind-integer
fn real-type? (T)
    icmp== (type-kind T) type-kind-real
fn pointer-type? (T)
    icmp== (type-kind T) type-kind-pointer
fn function-type? (T)
    icmp== (type-kind T) type-kind-function
fn tuple-type? (T)
    icmp== (type-kind T) type-kind-tuple
fn array-type? (T)
    icmp== (type-kind T) type-kind-array
fn vector-type? (T)
    icmp== (type-kind T) type-kind-vector
fn extern-type? (T)
    icmp== (type-kind T) type-kind-extern
fn function-pointer-type? (T)
    if (pointer-type? T)
        function-type? (element-type T 0)
    else (tie-const T false)
fn typename? (val)
    typename-type? (typeof val)
fn integer? (val)
    integer-type? (typeof val)
fn real? (val)
    real-type? (typeof val)
fn pointer? (val)
    pointer-type? (typeof val)
fn array? (val)
    array-type? (typeof val)
fn vector? (T)
    vector-type? (typeof T)
fn tuple? (val)
    tuple-type? (typeof val)
fn extern? (val)
    extern? (typeof val)
fn function-pointer? (val)
    function-pointer-type? (typeof val)
fn Symbol? (val)
    type== (typeof val) Symbol
fn list? (val)
    type== (typeof val) list
fn none? (val)
    type== (typeof val) Nothing

fn Any-new (val)
    fn construct (outval)
        insertvalue (insertvalue (undef Any) (typeof val) 0) outval 1

    if (type== (typeof val) Any) val
    elseif (constant? val)
        Any-wrap val
    else
        let T = (storageof (typeof val))
        let val =
            if (tuple-type? T) val
            else
                bitcast val T
        fn wrap-error ()
            compiler-error!
                string-join "unable to wrap value of storage type "
                    Any-repr (Any-wrap T)
        if (pointer-type? T)
            #compiler-message "wrapping pointer"
            construct
                ptrtoint val u64
        elseif (extern-type? T)
            Any-new (unconst val)
        elseif (tuple-type? T)
            if (icmp== (type-countof T) 0:usize)
                construct 0:u64
            else
                wrap-error;
        elseif (integer-type? T)
            construct
                if (signed? (typeof val))
                    sext val u64
                else
                    zext val u64
        elseif (real-type? T)
            if (type== T f32)
                construct
                    zext (bitcast val u32) u64
            else
                construct
                    bitcast val u64
        else
            wrap-error;

fn raise! (value)
    __raise! (Any-new value)
    unreachable!;

fn va-empty? (...)
    icmp== (va-countof ...) 0

fn cons (...)
    let i = (va-countof ...)
    if (icmp<s i 2)
        compiler-error! "at least two parameters expected"
    let i = (sub i 2)
    let loop (i at tail) = i (va@ i ...)
    if (icmp== i 0)
        list-cons (Any at) tail
    else
        let i = (sub i 1)
        loop i (va@ i ...)
            list-cons (Any at) tail

fn list-new (...)
    fn loop (i tail)
        if (icmp== i 0) tail
        else
            let val = (va@ (sub i 1) ...)
            loop (sub i 1)
                list-cons (Any-new val) tail
    loop (va-countof ...) eol

# forward decl
fn as
fn forward-as
fn imply
fn forward-imply

fn not (x)
    bxor (imply x bool) true

fn gen-type-op2 (f)
    fn (a b flipped)
        if (type== (typeof a) (typeof b))
            f a b
        elseif flipped
            let result... = (forward-imply a (typeof b))
            if (va-empty? result...)
            else
                f result... b
        else
            let result... = (forward-imply b (typeof a))
            if (va-empty? result...)
            else
                f a result...

syntax-extend
    set-type-symbol! type 'call
        fn (cls ...)
            let val ok = (type@ cls 'apply-type)
            if ok
                call val cls ...
            else
                compiler-error!
                    string-join "type "
                        string-join
                            Any-repr (Any-wrap cls)
                            " has no apply-type attribute"

    set-type-symbol! list 'apply-type
        fn (cls ...)
            list-new ...
    set-type-symbol! extern 'apply-type
        fn (cls ...)
            extern-new ...
    set-type-symbol! Any 'apply-type
        fn (cls value)
            Any-new value
    set-type-symbol! Symbol 'apply-type
        fn (cls value)
            string->Symbol value
    set-type-symbol! Scope 'apply-type
        fn (cls parent)
            if (type== (typeof parent) Nothing)
                Scope-new;
            else
                Scope-new-subscope parent

    set-type-symbol! type '== (gen-type-op2 type==)
    set-type-symbol! Any '== (gen-type-op2 Any==)
    set-type-symbol! string '.. (gen-type-op2 string-join)
    set-type-symbol! list '.. (gen-type-op2 list-join)

    set-type-symbol! type 'getattr
        fn (cls name)
            let val ok = (type@ cls name)
            if ok
                return val
            else
                return;

    set-type-symbol! Symbol 'as
        fn (self destT)
            if (type== destT string)
                Symbol->string self

    set-type-symbol! Symbol '==
        gen-type-op2
            fn (a b)
                icmp== (bitcast a u64) (bitcast b u64)
    set-type-symbol! Builtin '==
        gen-type-op2
            fn (a b)
                icmp== (bitcast a u64) (bitcast b u64)

    set-type-symbol! Nothing '==
        fn (a b flipped)
            type== (typeof a) (typeof b)
    set-type-symbol! Nothing '!=
        fn (a b flipped)
            bxor (type== (typeof a) (typeof b)) true

    fn setup-int-type (T)
        set-type-symbol! T '== (gen-type-op2 icmp==)
        set-type-symbol! T '!= (gen-type-op2 icmp!=)
        set-type-symbol! T '+ (gen-type-op2 add)
        set-type-symbol! T '-
            fn (a b flipped)
                let Ta Tb = (typeof a) (typeof b)
                if (type== Ta Tb)
                    sub a b
                elseif (type== Tb Nothing)
                    sub (Ta 0) a
        set-type-symbol! T '* (gen-type-op2 mul)
        set-type-symbol! T '<< (gen-type-op2 shl)
        set-type-symbol! T '& (gen-type-op2 band)
        set-type-symbol! T '| (gen-type-op2 bor)
        set-type-symbol! T '^ (gen-type-op2 bxor)

        # more aggressive cast that converts from all numerical types
            and usize.
        set-type-symbol! T 'as
            fn hardcast (val destT)
                let vT = (typeof val)
                let destST =
                    if (type== destT usize) (storageof destT)
                    else destT
                if (integer-type? destST)
                    let valw destw = (bitcountof vT) (bitcountof destST)
                    if (icmp== destw valw)
                        bitcast val destT
                    elseif (icmp>s destw valw)
                        if (signed? vT)
                            sext val destT
                        else
                            zext val destT
                    else
                        trunc val destT
                elseif (real-type? destST)
                    if (signed? vT)
                        sitofp val destT
                    else
                        uitofp val destT

        # only perform safe casts i.e. integer / usize conversions that expand width
        # unless the value is constant
        set-type-symbol! T 'imply
            fn (val destT)
                if (constant? val)
                    hardcast val destT
                else
                    let vT = (typeof val)
                    let destST =
                        if (type== destT usize) (storageof destT)
                        else destT
                    if (integer-type? destST)
                        let valw destw = (bitcountof vT) (bitcountof destST)
                        # must have same signed bit
                        if (icmp== (signed? vT) (signed? destST))
                            if (icmp== destw valw)
                                bitcast val destT
                            elseif (icmp>s destw valw)
                                if (signed? vT)
                                    sext val destT
                                else
                                    zext val destT

        # general constructor
        set-type-symbol! T 'apply-type
            fn (destT val)
                as val destT

        fn ufdiv(a b)
            let Ta Tb = (typeof a) (typeof b)
            if (type== Ta Tb)
                fdiv (uitofp a f32) (uitofp b f32)
            elseif (type== Tb Nothing)
                fdiv 1.0 (uitofp a f32)

        fn sfdiv(a b)
            let Ta Tb = (typeof a) (typeof b)
            if (type== Ta Tb)
                fdiv (sitofp a f32) (sitofp b f32)
            elseif (type== Tb Nothing)
                fdiv 1.0 (sitofp a f32)

        if (signed? (storageof T))
            set-type-symbol! T '> (gen-type-op2 icmp>s)
            set-type-symbol! T '>= (gen-type-op2 icmp>=s)
            set-type-symbol! T '< (gen-type-op2 icmp<s)
            set-type-symbol! T '<= (gen-type-op2 icmp<=s)
            set-type-symbol! T '// (gen-type-op2 sdiv)
            set-type-symbol! T '/ sfdiv
            set-type-symbol! T '% (gen-type-op2 srem)
            set-type-symbol! T '>> (gen-type-op2 ashr)
        else
            set-type-symbol! T '> (gen-type-op2 icmp>u)
            set-type-symbol! T '>= (gen-type-op2 icmp>=u)
            set-type-symbol! T '< (gen-type-op2 icmp<u)
            set-type-symbol! T '<= (gen-type-op2 icmp<=u)
            set-type-symbol! T '// (gen-type-op2 udiv)
            set-type-symbol! T '/ ufdiv
            set-type-symbol! T '% (gen-type-op2 urem)
            set-type-symbol! T '>> (gen-type-op2 lshr)

    fn setup-real-type (T)
        fn floordiv (a b)
            sdiv (fptosi a i32) (fptosi b i32)

        # only perform safe casts: i.e. float to double
        set-type-symbol! T 'imply
            fn (val destT)
                let vT = (typeof val)
                if (real-type? destT)
                    let valw destw = (bitcountof vT) (bitcountof destT)
                    if (icmp== destw valw)
                        bitcast val destT
                    elseif (icmp>s destw valw)
                        fpext val destT

        set-type-symbol! T 'apply-type
            fn (destT val)
                as val destT

        set-type-symbol! T '== (gen-type-op2 fcmp==o)
        set-type-symbol! T '!= (gen-type-op2 fcmp!=u)
        set-type-symbol! T '> (gen-type-op2 fcmp>o)
        set-type-symbol! T '>= (gen-type-op2 fcmp>=o)
        set-type-symbol! T '< (gen-type-op2 fcmp<o)
        set-type-symbol! T '<= (gen-type-op2 fcmp<=o)
        set-type-symbol! T '+ (gen-type-op2 fadd)
        set-type-symbol! T '-
            fn (a b flipped)
                let Ta Tb = (typeof a) (typeof b)
                if (type== Ta Tb)
                    fsub a b
                elseif (type== Tb Nothing)
                    fsub (Ta 0) a
        set-type-symbol! T '* (gen-type-op2 fmul)
        set-type-symbol! T '/
            fn (a b flipped)
                let Ta Tb = (typeof a) (typeof b)
                if (type== Ta Tb)
                    fdiv a b
                elseif (type== Tb Nothing)
                    fdiv (Ta 1) a
        set-type-symbol! T '// (gen-type-op2 floordiv)
        set-type-symbol! T '% (gen-type-op2 frem)

    setup-int-type bool
    setup-int-type i8
    setup-int-type i16
    setup-int-type i32
    setup-int-type i64
    setup-int-type u8
    setup-int-type u16
    setup-int-type u32
    setup-int-type u64

    setup-int-type usize

    setup-real-type f32
    setup-real-type f64

    syntax-scope

fn string-repr (val)
    Any-string (Any val)

fn opN-dispatch (symbol)
    fn (self ...)
        let T = (typeof self)
        let op success = (type@ T symbol)
        if success
            return (op self ...)
        compiler-error!
            string-join "operation "
                string-join (Any-repr (Any-wrap symbol))
                    string-join " does not apply to value of type "
                        Any-repr (Any-wrap T)

fn op2-dispatch (symbol)
    fn (a b)
        let Ta Tb = (typeof a) (typeof b)
        let op success = (type@ Ta symbol)
        if success
            let result... = (op a b)
            if (icmp== (va-countof result...) 0)
            else
                return result...
        compiler-error!
            string-join "operation does not apply to values of type "
                string-join
                    Any-repr (Any-wrap Ta)
                    string-join " and "
                        Any-repr (Any-wrap Tb)

fn op2-dispatch-bidi (symbol fallback)
    fn (a b)
        let Ta Tb = (typeof a) (typeof b)
        let op success = (type@ Ta symbol)
        if success
            let result... = (op a b false)
            if (icmp== (va-countof result...) 0)
            else
                return result...
        let op success = (type@ Tb symbol)
        if success
            let result... = (op a b true)
            if (icmp== (va-countof result...) 0)
            else
                return result...
        if (type== (typeof fallback) Nothing)
        else
            return (fallback a b)
        compiler-error!
            string-join "operation does not apply to values of type "
                string-join
                    Any-repr (Any-wrap Ta)
                    string-join " and "
                        Any-repr (Any-wrap Tb)

fn op2-ltr-multiop (f)
    fn (a b ...)
        let loop (i result...) = 0 (f a b)
        if (icmp<s i (va-countof ...))
            let x = (va@ i ...)
            loop (add i 1) (f result... x)
        else result...

fn == (a b) ((op2-dispatch-bidi '==) a b)
fn != (a b)
    call
        op2-dispatch-bidi '!=
            fn (a b)
                bxor true (== a b)
        \ a b
fn > (a b) ((op2-dispatch-bidi '>) a b)
fn >= (a b) ((op2-dispatch-bidi '>=) a b)
fn < (a b) ((op2-dispatch-bidi '<) a b)
fn <= (a b) ((op2-dispatch-bidi '<=) a b)
fn + (...) ((op2-ltr-multiop (op2-dispatch-bidi '+)) ...)
fn - (a b) ((op2-dispatch-bidi '-) a b)
fn * (...) ((op2-ltr-multiop (op2-dispatch-bidi '*)) ...)
fn / (a b) ((op2-dispatch-bidi '/) a b)
fn // (a b) ((op2-dispatch-bidi '//) a b)
fn % (a b) ((op2-dispatch-bidi '%) a b)
fn & (a b) ((op2-dispatch-bidi '&) a b)
fn | (...) ((op2-ltr-multiop (op2-dispatch-bidi '|)) ...)
fn ^ (a b) ((op2-dispatch-bidi '^) a b)
fn << (a b) ((op2-dispatch-bidi '<<) a b)
fn >> (a b) ((op2-dispatch-bidi '>>) a b)
fn .. (...) ((op2-ltr-multiop (op2-dispatch-bidi '..)) ...)
fn countof (x) ((opN-dispatch 'countof) x)
fn unpack (x) ((opN-dispatch 'unpack) x)
fn @ (...)
    fn at (obj key)
        (op2-dispatch '@) obj
            if (constant? key)
                if (integer? key)
                    if (signed? (typeof key))
                        if (icmp<s key 0)
                            add (i64 (countof obj)) (i64 key)
                        else key
                    else key
                else key
            else key
    (op2-ltr-multiop at) ...

fn repr

fn type-mismatch-string (want-T have-T)
    .. "type " (repr want-T) " expected, not " (repr have-T)

fn assert-typeof (a T)
    if (type== T (typeof a))
    else
        compiler-error!
            type-mismatch-string T (typeof a)

fn Any-typeof (val)
    assert-typeof val Any
    extractvalue val 0

fn Any-payload (val)
    assert-typeof val Any
    extractvalue val 1

fn forward-repr (value)
    let op success = (type@ (typeof value) 'repr)
    if success
        op value
    else
        Any-repr (Any value)

fn repr (value)
    let T = (typeof value)
    let CT =
        if (type== T Any)
            Any-typeof value
        else T
    fn append-type? ()
        tie-const CT
            if (type== CT i32) false
            elseif (type== CT bool) false
            elseif (type== CT Nothing) false
            elseif (type== CT f32) false
            elseif (type== CT string) false
            elseif (type== CT list) false
            elseif (type== CT Symbol) false
            elseif (type== CT type) false
            elseif (vector-type? CT)
                let ET = (element-type CT 0)
                if (type== ET i32) false
                elseif (type== ET bool) false
                elseif (type== ET f32) false
                else true
            else true
    let op success = (type@ T 'repr)
    let text =
        if success
            op value
        else
            Any-repr (Any value)
    if (append-type?)
        .. text
            default-styler style-operator ":"
            default-styler style-type (type-name CT)
    else text

fn getattr (self name)
    let T = (typeof self)
    let op success = (type@ T 'getattr)
    if success
        let result... = (op self name)
        if (icmp== (va-countof result...) 0)
        else
            return result...
    let result success = (type@ T name)
    if success
        return result
    compiler-error!
        string-join "no such attribute "
            string-join (Any-repr (Any-wrap name))
                string-join " in value of type "
                    Any-repr (Any-wrap T)

fn empty? (x)
    == (countof x) 0:usize

fn <: (T superT)
    let loop (T) = T
    let value = (superof T)
    if (type== value superT) true
    elseif (type== value typename) false
    else
        loop value

fn type<= (T superT)
    if (type== T superT)
        return true
    <: T superT

fn forward-as (value dest-type)
    let T = (typeof value)
    if (type<= T dest-type)
        return value
    let f ok = (type@ T 'imply)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...
    let f ok = (type@ T 'as)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...

fn as (value dest-type)
    let T = (typeof value)
    if (type<= T dest-type)
        return value
    let f ok = (type@ T 'imply)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...
    let f ok = (type@ T 'as)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...
    compiler-error!
        string-join "cannot convert value of type "
            string-join (Any-repr (Any-wrap T))
                string-join " to "
                    Any-repr (Any-wrap dest-type)

fn forward-imply (value dest-type)
    let T = (typeof value)
    if (type<= T dest-type)
        return value
    let f ok = (type@ T 'imply)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...

fn imply (value dest-type)
    let T = (typeof value)
    if (type<= T dest-type)
        return value
    let f ok = (type@ T 'imply)
    if ok
        let result... = (f value dest-type)
        if (icmp!= (va-countof result...) 0)
            return result...
    compiler-error!
        string-join "cannot implicitly convert value of type "
            string-join (Any-repr (Any-wrap T))
                string-join " to "
                    Any-repr (Any-wrap dest-type)

fn Any-extract (val T)
    assert-typeof val Any
    let valT = (Any-typeof val)
    if (== valT T)
        if (constant? val)
            Any-extract-constant val
        else
            let payload = (Any-payload val)
            let storageT = (storageof T)
            if (pointer-type? storageT)
                inttoptr payload T
            elseif (integer-type? storageT)
                trunc payload T
            elseif (real-type? storageT)
                bitcast
                    trunc payload (integer-type (bitcountof storageT) false)
                    T
            else
                compiler-error!
                    .. "unable to extract value of type " (Any-repr (Any-wrap T))
    elseif (constant? val)
        compiler-error!
            type-mismatch-string T valT
    else
        error!
            .. "while extracting from Any at runtime: "
                type-mismatch-string T valT

fn string->rawstring (s)
    assert-typeof s string
    getelementptr s 0 1 0
fn char (s)
    load (string->rawstring s)

fn Syntax-anchor (sx)
    assert-typeof sx Syntax
    extractvalue (load sx) 0
fn Syntax->datum (sx)
    assert-typeof sx Syntax
    extractvalue (load sx) 1
fn Syntax-quoted? (sx)
    assert-typeof sx Syntax
    extractvalue (load sx) 2

fn Anchor-file (x)
    assert-typeof x Anchor
    extractvalue (load x) 0
fn Anchor-lineno (x)
    assert-typeof x Anchor
    extractvalue (load x) 1
fn Anchor-column (x)
    assert-typeof x Anchor
    extractvalue (load x) 2

fn Exception-anchor (sx)
    assert-typeof sx Exception
    extractvalue (load sx) 0
fn Exception-message (sx)
    assert-typeof sx Exception
    extractvalue (load sx) 1

fn list-empty? (l)
    assert-typeof l list
    icmp== (ptrtoint l usize) 0:usize

fn list-at (l)
    assert-typeof l list
    if (list-empty? l)
        tie-const l (Any-wrap none)
    else
        extractvalue (load l) 0

fn list-next (l)
    assert-typeof l list
    if (list-empty? l)
        tie-const l eol
    else
        bitcast (extractvalue (load l) 1) list

fn list-at-next (l)
    assert-typeof l list
    if (list-empty? l)
        return
            tie-const l (Any-wrap none)
            tie-const l eol
    else
        return
            extractvalue (load l) 0
            bitcast (extractvalue (load l) 1) list

fn decons (val count)
    let at next = (list-at-next val)
    if (type== (typeof count) Nothing)
        return at next
    elseif (icmp<=s count 1)
        return at next
    else
        return at
            decons next (sub count 1)

fn list-countof (l)
    assert-typeof l list
    if (list-empty? l) (tie-const l 0:usize)
    else
        extractvalue (load l) 2

fn string-countof (s)
    assert-typeof s string
    extractvalue (load s) 0

fn min (a b)
    ? (<= a b) a b

fn max (a b)
    ? (>= a b) a b

fn clamp (x mn mx)
    ? (> x mx) mx
        ? (< x mn) mn x

fn slice (obj start-index end-index)
    # todo: this should be isize
    let zero count i0 = (i64 0) (i64 (countof obj)) (i64 start-index)
    let i0 =
        if (>= i0 zero) (min i0 count)
        else (max (+ i0 count) 0:i64)
    let i1 =
        if (type== (typeof end-index) Nothing) count
        else (i64 end-index)
    let i1 =
        max i0
            if (>= i1 zero) i1
            else (+ i1 count)
    (opN-dispatch 'slice) obj (usize i0) (usize i1)

fn string-compare (a b)
    assert-typeof a string
    assert-typeof b string
    let ca = (string-countof a)
    let cb = (string-countof b)
    let cc =
        if (< ca cb) ca
        else cb
    let pa pb =
        bitcast (getelementptr a 0 1 0) (pointer-type i8)
        bitcast (getelementptr b 0 1 0) (pointer-type i8)
    let loop (i) =
        tie-const cc 0:usize
    if (== i cc)
        if (< ca cb)
            return (tie-const cc -1)
        elseif (> ca cb)
            return (tie-const cc 1)
        else
            return (tie-const cc 0)
    let x y =
        load (getelementptr pa i)
        load (getelementptr pb i)
    if (< x y)
        return (tie-const cc -1)
    elseif (> x y)
        return (tie-const cc 1)
    else
        loop (+ i 1:usize)

fn list-reverse (l tail)
    assert-typeof l list
    let tail =
        if (type== (typeof tail) Nothing) eol
        else tail
    assert-typeof tail list
    let loop (l next) = l (tie-const l tail)
    if (list-empty? l) next
    else
        loop (list-next l) (list-cons (list-at l) next)

fn set-scope-symbol! (scope sym value)
    __set-scope-symbol! scope sym (Any value)

syntax-extend
    # a supertype to be used for conversions
    let immutable = (typename-type "immutable")
    set-scope-symbol! syntax-scope 'immutable immutable

    set-typename-super! integer immutable
    set-typename-super! real immutable
    set-typename-super! array immutable
    set-typename-super! vector immutable
    set-typename-super! tuple immutable

    set-type-symbol! integer 'apply-type
        fn (cls ...)
            integer-type ...
    #set-type-symbol! real 'apply-type
        fn (cls ...)
            real-type ...
    set-type-symbol! pointer 'apply-type
        fn (cls T opt)
            let ptypefunc =
                if (none? opt) pointer-type
                else
                    assert-typeof opt Symbol
                    if (icmp== opt 'mutable) mutable-pointer-type
                    else
                        compiler-error! "invalid option passed to pointer type constructor"
            if (none? T)
                if (type== cls pointer)
                    compiler-error! "type expected"
                else
                    nullof cls
            else
                ptypefunc T
    set-type-symbol! array 'apply-type
        fn (cls ...)
            array-type ...
    set-type-symbol! vector 'apply-type
        fn (cls ...)
            vector-type ...
    set-type-symbol! ReturnLabel 'apply-type
        fn (cls ...)
            ReturnLabel-type ...
    set-type-symbol! tuple 'apply-type
        fn (cls ...)
            tuple-type ...
    #set-type-symbol! union 'apply-type
        fn (cls ...)
            union-type ...
    set-type-symbol! typename 'apply-type
        fn (cls ...)
            typename-type ...
    set-type-symbol! function 'apply-type
        fn (cls ...)
            function-type ...

    set-type-symbol! Any 'typeof Any-typeof

    set-type-symbol! Any 'imply
        fn (src destT)
            Any-extract src destT

    set-type-symbol! Syntax 'imply
        fn (src destT)
            if (type== destT Any)
                Syntax->datum src
            elseif (type== destT Anchor)
                Syntax-anchor src
            else
                Any-extract (Syntax->datum src) destT

    set-type-symbol! type '@
        fn (self key)
            let keyT = (typeof key)
            if (type== keyT Symbol)
                type@ self key
            elseif (type== keyT i32)
                element-type self key
            elseif (type== keyT Nothing)
                element-type self 0
    set-type-symbol! type 'countof type-countof

    let empty-symbol = (Symbol "")

    set-type-symbol! Parameter 'apply-type
        fn (cls params...)
            let param1 param2 param3 = params...
            let TT = (tuple (typeof param1) (typeof param2) (typeof param3))
            if (type== TT (tuple Anchor Symbol type))
                Parameter-new param1 param2 param3
            elseif (type== TT (tuple Anchor Symbol Nothing))
                Parameter-new param1 param2 Unknown
            elseif (type== TT (tuple Symbol type Nothing))
                Parameter-new (active-anchor) param1 param2
            elseif (type== TT (tuple Symbol Nothing Nothing))
                Parameter-new (active-anchor) param1 Unknown
            else
                compiler-error! "usage: Parameter [anchor] symbol [type]"

    set-type-symbol! Parameter 'return-label?
        fn (self)
            icmp== (Parameter-index self) 0

    set-type-symbol! Symbol 'call
        fn (name self ...)
            (getattr self name) self ...

    set-type-symbol! Scope 'getattr
        fn (self key)
            if (constant? self)
                let value success = (Scope@ self key)
                if success
                    Any-extract-constant value
            else
                let value = (Scope@ self key)
                return value

    set-type-symbol! Scope '@
        fn (self key)
            let value success = (Scope@ self key)
            return
                if (constant? self)
                    Any-extract-constant value
                else value
                success

    set-type-symbol! list 'countof list-countof
    set-type-symbol! list 'getattr
        fn (self name)
            if (== name 'at)
                list-at self
            elseif (== name 'next)
                list-next self
            elseif (== name 'count)
                list-countof self
    set-type-symbol! list '@
        fn (self i)
            let loop (x i) = (tie-const i self) (i32 i)
            if (< i 0)
                Any none
            elseif (== i 0)
                list-at x
            else
                loop (list-next x) (- i 1)
    set-type-symbol! list 'slice
        fn (self i0 i1)
            # todo: use isize
            let i0 i1 = (i64 i0) (i64 i1)
            let skip-head (l i) =
                tie-const i0 self
                tie-const i0 (i64 0)
            if (< i i0)
                skip-head (list-next l) (+ i (i64 1))
            let count = (i64 (list-countof l))
            if (== (- i1 i0) count)
                return l
            let build-slice (l next i) =
                tie-const i1 l
                tie-const i1 eol
                tie-const i1 i
            if (== i i1)
                list-reverse next
            else
                build-slice (list-next l) (list-cons (list-at l) next) (+ i 1:i64)

    fn list== (a b)
        label xreturn (value)
            return (tie-const (tie-const a b) value)
        if (icmp!= (list-countof a) (list-countof b))
            xreturn false
        let loop (a b) = (tie-const b a) (tie-const a b)
        if (list-empty? a)
            xreturn true
        let u v = (list-at a) (list-at b)
        let uT vT = ('typeof u) ('typeof v)
        if (not (type== uT vT))
            xreturn false
        let un vn = (list-next a) (list-next b)
        if (type== uT list)
            if (list== (imply u list) (imply v list))
                loop un vn
            else
                xreturn false
        elseif (Any== u v)
            loop un vn
        else
            xreturn false

    set-type-symbol! list '==
        fn (a b flipped)
            if (type== (typeof a) (typeof b))
                list== a b

    fn gen-string-cmp (op)
        fn (a b flipped)
            if (type== (typeof a) (typeof b))
                op (string-compare a b) 0

    set-type-symbol! string '== (gen-string-cmp ==)
    set-type-symbol! string '!= (gen-string-cmp !=)
    set-type-symbol! string '< (gen-string-cmp <)
    set-type-symbol! string '<= (gen-string-cmp <=)
    set-type-symbol! string '> (gen-string-cmp >)
    set-type-symbol! string '>= (gen-string-cmp >=)

    let rawstring = (pointer i8)
    set-scope-symbol! syntax-scope 'rawstring (pointer i8)
    set-type-symbol! string 'imply
        fn (self destT)
            if (type== destT rawstring)
                getelementptr self 0 1 0

    set-type-symbol! string 'countof string-countof
    set-type-symbol! string '@
        fn string-at (s i)
            assert-typeof s string
            let i = (i64 i)
            if (< i 0:i64)
                return (tie-const i 0:i8)
            let len = (i64 (string-countof s))
            if (>= i len)
                return (tie-const (tie-const len i) 0:i8)
            let s = (bitcast (getelementptr s 0 1 0) (pointer i8))
            load (getelementptr s i)
    set-type-symbol! string 'slice
        fn (self i0 i1)
            string-new
                getelementptr (string->rawstring self) i0
                - i1 i0

    set-scope-symbol! syntax-scope 'min (op2-ltr-multiop min)
    set-scope-symbol! syntax-scope 'max (op2-ltr-multiop max)

    syntax-scope

fn Any-list? (val)
    assert-typeof val Any
    type== ('typeof val) list

fn maybe-unsyntax (val)
    if (type== ('typeof val) Syntax)
        extractvalue (load (as val Syntax)) 1
    else val

fn powi (base exponent)
    assert-typeof base i32
    assert-typeof exponent i32
    let loop (result cur exponent) =
        tie-const exponent 1
        tie-const exponent base
        exponent
    if (icmp== exponent 0) result
    else
        loop
            if (icmp== (band exponent 1) 0) result
            else
                mul result cur
            mul cur cur
            lshr exponent 1

# print function
fn print (...)
    fn print-element (val)
        let T = (typeof val)
        if (== T string)
            io-write! val
        else
            io-write! (repr val)

    let loop (i) = 0
    if (< i (va-countof ...))
        if (> i 0)
            io-write! " "
        let arg = (va@ i ...)
        print-element arg
        loop (+ i 1)
    else
        io-write! "\n"

fn print-spaces (depth)
    assert-typeof depth i32
    if (icmp== depth 0)
    else
        io-write! "    "
        print-spaces (sub depth 1)

fn walk-list (on-leaf l depth)
    let loop (l) = l
    if (list-empty? l) true
    else
        let at next =
            list-at-next l
        let value =
            maybe-unsyntax at
        if (Any-list? value)
            print-spaces depth
            io-write! ";\n"
            walk-list on-leaf
                as value list
                add depth 1
        else
            on-leaf value depth
            true
        loop next

fn typify (f types...)
    let vacount = (va-countof types...)
    let loop (i types) = 0 (nullof (array-type type (usize vacount)))
    if (== i vacount)
        return
            __typify f vacount (bitcast (allocaof types) (pointer type))
    let T = (va@ i types...)
    let types = (insertvalue types T i)
    loop (+ i 1) types

fn compile (f opts...)
    let vacount = (va-countof opts...)
    let loop (i flags) = 0 0:u64
    if (== i vacount)
        return
            __compile f flags
    let flag = (va@ i opts...)
    if (not (constant? flag))
        compiler-error! "symbolic flags must be constant"
    assert-typeof flag Symbol
    loop (+ i 1)
        | flags
            if (== flag 'dump-disassembly) compile-flag-dump-disassembly
            elseif (== flag 'dump-module) compile-flag-dump-module
            elseif (== flag 'dump-function) compile-flag-dump-function
            elseif (== flag 'dump-time) compile-flag-dump-time
            elseif (== flag 'no-opts) compile-flag-no-opts
            else
                compiler-error!
                    .. "illegal flag: " (repr flag)

fn compile-glsl (f target opts...)
    let vacount = (va-countof opts...)
    let loop (i flags) = 0 0:u64
    if (== i vacount)
        return
            __compile-glsl f target flags
    let flag = (va@ i opts...)
    if (not (constant? flag))
        compiler-error! "symbolic flags must be constant"
    assert-typeof flag Symbol
    loop (+ i 1)
        | flags
            if (== flag 'dump-disassembly) compile-flag-dump-disassembly
            elseif (== flag 'dump-module) compile-flag-dump-module
            elseif (== flag 'dump-function) compile-flag-dump-function
            elseif (== flag 'dump-time) compile-flag-dump-time
            elseif (== flag 'no-opts) compile-flag-no-opts
            else
                compiler-error!
                    .. "illegal flag: " (repr flag)

fn syntax-error! (anchor msg)
    let T = (typeof anchor)
    if (== T string)
        if (none? msg)
            __error! anchor
            unreachable!;
    set-anchor!
        if (== T Any)
            let T = ('typeof anchor)
            if (== T Syntax)
                Syntax-anchor (as anchor Syntax)
            else
                as anchor Anchor
        elseif (== T Syntax)
            Syntax-anchor anchor
        else anchor
    __anchor-error! msg
    unreachable!;

syntax-extend
    fn gen-type-op2 (op)
        fn (a b flipped)
            if (type== (typeof a) (typeof b))
                op a b
    set-type-symbol! type '< (gen-type-op2 <:)
    set-type-symbol! type '<=
        gen-type-op2
            fn (a b)
                if (type== a b) true
                else (<: a b)
    set-type-symbol! type '> (gen-type-op2 (fn (a b) (<: b a)))
    set-type-symbol! type '>=
        gen-type-op2
            fn (a b)
                if (type== a b) true
                else (<: b a)

    let Macro = (typename "Macro")
    let BlockScopeFunction =
        pointer
            function
                ReturnLabel (unknownof list) (unknownof Scope)
                \ list list Scope
    set-typename-storage! Macro BlockScopeFunction
    set-type-symbol! Macro 'apply-type
        fn (cls f)
            assert-typeof f BlockScopeFunction
            bitcast f Macro
    set-type-symbol! Macro 'as
        fn (self destT)
            if (type== destT function)
                bitcast self BlockScopeFunction
            elseif (type== destT BlockScopeFunction)
                bitcast self BlockScopeFunction
    # support for calling macro functions directly
    set-type-symbol! Macro 'call
        fn (self at next scope)
            (bitcast self BlockScopeFunction) at next scope

    fn block-scope-macro (f)
        Macro
            as (compile (typify f list list Scope))
                BlockScopeFunction
    fn scope-macro (f)
        block-scope-macro
            fn (at next scope)
                let at scope = (f (list-next at) scope)
                return (cons at next) scope
    fn macro (f)
        block-scope-macro
            fn (at next scope)
                return (cons (f (list-next at)) next) scope

    # dotted symbol expander
    # --------------------------------------------------------------------------

    fn dotted-symbol? (env head)
        let s = (Symbol->string head)
        let sz = (countof s)
        let loop (i) = (unconst 0:usize)
        if (== i sz)
            return (unconst false)
        elseif (== (@ s i) (char "."))
            return (unconst true)
        loop (+ i 1:usize)

    fn split-dotted-symbol (head start end tail)
        let s = (Symbol->string head)
        let loop (i) = (unconst start)
        if (== i end)
            # did not find a dot
            if (== start 0:usize)
                return (cons head tail)
            else
                return (cons (Symbol (slice s start)) tail)
        if (== (@ s i) (char "."))
            let tail =
                # no remainder after dot
                if (== i (- end 1:usize)) tail
                else # remainder after dot, split the rest first
                    split-dotted-symbol head (+ i 1:usize) end tail
            let dot = '.
            if (== i 0:usize)
                # no prefix before dot
                return (cons (unconst dot) tail)
            else
                # prefix before dot
                return
                    cons (Symbol (slice s start i)) dot tail
        loop (+ i 1:usize)

    # infix notation support
    # --------------------------------------------------------------------------

    fn get-ifx-symbol (name)
        Symbol (.. "#ifx:" (Symbol->string name))

    fn make-expand-define-infix (order)
        fn expand-define-infix (args scope)
            let prec token func = (decons args 3)
            let prec =
                as (as prec Syntax) i32
            let token =
                as (as token Syntax) Symbol
            let func =
                if (== ('typeof func) Nothing) token
                else
                    as (as func Syntax) Symbol
            set-scope-symbol! scope (get-ifx-symbol token)
                list prec order func
            return none scope

    fn get-ifx-op (env op)
        let sym = (Syntax->datum (as op Syntax))
        if (== ('typeof sym) Symbol)
            @ env (get-ifx-symbol (as sym Symbol))
        else
            return
                unconst (Any none)
                unconst false

    fn has-infix-ops? (infix-table expr)
        # any expression of which one odd argument matches an infix operator
            has infix operations.
        let loop (expr) = expr
        if (< (countof expr) 3:usize)
            return (unconst false)
        let expr = (list-next expr)
        let at next = (decons expr)
        let result ok = (get-ifx-op infix-table at)
        if ok
            return (unconst true)
        loop expr

    fn unpack-infix-op (op)
        let op-prec op-order op-func = (decons (as op list) 3)
        return
            as op-prec i32
            as op-order Symbol
            as op-func Symbol

    fn infix-op (infix-table token prec pred)
        let op ok =
            get-ifx-op infix-table token
        if ok
            let op-prec = (unpack-infix-op op)
            ? (pred op-prec prec) op (Any none)
        else
            syntax-error! token
                "unexpected token in infix expression"

    fn rtl-infix-op (infix-table token prec pred)
        let op ok =
            get-ifx-op infix-table token
        if ok
            let op-prec op-order = (unpack-infix-op op)
            if (== op-order '<)
                ? (pred op-prec prec) op (Any none)
            else
                unconst (Any none)
        else
            syntax-error! token
                "unexpected token in infix expression"

    fn parse-infix-expr (infix-table lhs state mprec)
        assert-typeof infix-table Scope
        assert-typeof lhs Any
        assert-typeof state list
        assert-typeof mprec i32
        let loop (lhs state) = lhs state
        if (empty? state)
            return lhs state
        let la next-state = (decons state)
        let op = (infix-op infix-table la mprec >=)
        if (== ('typeof op) Nothing)
            return lhs state
        let op-prec op-order op-name = (unpack-infix-op op)
        let rhs-loop (rhs state) = (decons next-state)
        if (empty? state)
            loop (Any (list op-name lhs rhs)) state
        let ra = (list-at state)
        let lop = (infix-op infix-table ra op-prec >)
        let nextop =
            if (== ('typeof lop) Nothing)
                rtl-infix-op infix-table ra op-prec ==
            else lop
        if (== ('typeof nextop) Nothing)
            loop (Any (list op-name lhs rhs)) state
        let nextop-prec = (unpack-infix-op nextop)
        let next-rhs next-state =
            parse-infix-expr infix-table rhs state nextop-prec
        rhs-loop next-rhs next-state

    #---------------------------------------------------------------------------

    # install general list hook for this scope
    # is called for every list the expander would otherwise consider a call
    fn list-handler (topexpr env)
        let sxexpr = (as (list-at topexpr) Syntax)
        let expr expr-anchor = (Syntax->datum sxexpr) (Syntax-anchor sxexpr)
        if (!= ('typeof expr) list)
            return topexpr env
        let expr = (as expr list)
        let head-key = (Syntax->datum (as (list-at expr) Syntax))
        let head =
            if (== ('typeof head-key) Symbol)
                let head success = (@ env (as head-key Symbol))
                if success head
                else head-key
            else head-key
        if (== ('typeof head) Macro)
            let head = (as head Macro)
            let next = (list-next topexpr)
            let expr env = (head expr next env)
            let expr = (Syntax-wrap expr-anchor (Any expr) false)
            return (as (as expr Syntax) list) env
        elseif (has-infix-ops? env expr)
            let at next = (decons expr)
            let expr =
                parse-infix-expr env at next (unconst 0)
            let next = (list-next topexpr)
            let expr = (Syntax-wrap expr-anchor expr false)
            return (list-cons expr next) env
        else
            return topexpr env

    # install general symbol hook for this scope
    # is called for every symbol the expander could not resolve
    fn symbol-handler (topexpr env)
        let at next = (decons topexpr)
        let sxname = (as at Syntax)
        let name name-anchor = (as sxname Symbol) (Syntax-anchor sxname)
        if (dotted-symbol? env name)
            let s = (Symbol->string name)
            let sz = (countof s)
            let expr =
                Any (split-dotted-symbol name (unconst 0:usize) sz eol)
            let expr = (Syntax-wrap name-anchor expr false)
            return (cons expr next) env
        return topexpr env

    set-scope-symbol! syntax-scope 'Macro Macro
    set-scope-symbol! syntax-scope 'block-scope-macro block-scope-macro
    set-scope-symbol! syntax-scope 'scope-macro scope-macro
    set-scope-symbol! syntax-scope 'macro macro
    set-scope-symbol! syntax-scope (Symbol "#list")
        compile (typify list-handler list Scope)
        #compile (typify list-handler list Scope)
    set-scope-symbol! syntax-scope (Symbol "#symbol")
        compile (typify symbol-handler list Scope)

    # (define name expr ...)
    fn expand-define (expr)
        let defname = (list-at expr)
        let content = (list-next expr)
        list syntax-extend
            list set-scope-symbol! 'syntax-scope
                list quote defname
                cons do content
            'syntax-scope

    fn make-expand-and-or (flip)
        fn (expr)
            if (list-empty? expr)
                syntax-error! "at least one argument expected"
            elseif (== (list-countof expr) 1:usize)
                return (list-at expr)
            let expr = (list-reverse expr)
            let loop (result head) = (decons expr)
            if (list-empty? head)
                return result
            let tmp =
                Parameter-new
                    Syntax-anchor (as (list-at head) Syntax)
                    \ 'tmp Unknown
            loop
                Any
                    list do-in
                        list let tmp '= (list-at head)
                        list if tmp
                            if flip tmp
                            else result
                        list 'else
                            if flip result
                            else tmp
                list-next head

    set-scope-symbol! syntax-scope 'define (macro expand-define)
    set-scope-symbol! syntax-scope 'and (macro (make-expand-and-or false))
    set-scope-symbol! syntax-scope 'or (macro (make-expand-and-or true))
    set-scope-symbol! syntax-scope 'define-infix>
        scope-macro (make-expand-define-infix '>)
    set-scope-symbol! syntax-scope 'define-infix<
        scope-macro (make-expand-define-infix '<)
    syntax-scope

# (define-macro name expr ...)
# implies builtin names:
    args : list
define define-macro
    macro
        fn "expand-define-macro" (expr)
            let name body = (decons expr)
            list define name
                list macro
                    cons fn '(args) body

# (define-scope-macro name expr ...)
# implies builtin names:
    args : list
    scope : Scope
define-macro define-scope-macro
    let name body = (decons args)
    list define name
        list scope-macro
            cons fn '(args syntax-scope) body

# (define-block-scope-macro name expr ...)
# implies builtin names:
    expr : list
    next-expr : list
    scope : Scope
define-macro define-block-scope-macro
    let name body = (decons args)
    list define name
        list block-scope-macro
            cons fn '(expr next-expr syntax-scope) body

define-macro assert
    fn assertion-error! (constant anchor msg)
        let assert-msg =
            .. "assertion failed: "
                if (== (typeof msg) string) msg
                else (repr msg)
        if constant
            compiler-error! assert-msg
        else
            syntax-error! anchor assert-msg
    let cond body = (decons args)
    let sxcond = (as cond Syntax)
    let anchor = (Syntax-anchor sxcond)
    let tmp =
        Parameter-new anchor 'tmp Unknown
    list do
        list let tmp '= cond
        list if tmp
        list 'else
            cons assertion-error!
                list constant? tmp
                active-anchor;
                if (empty? body)
                    list (repr (Syntax->datum sxcond))
                else body

# (. value symbol ...)
define-macro .
    fn op (a b)
        let sym = (as (as b Syntax) Symbol)
        list getattr a (list quote sym)
    let a b rest = (decons args 2)
    let loop (rest result) = rest (op a b)
    if (list-empty? rest) result
    else
        let c rest = (decons rest)
        loop rest (op result c)

fn = (obj value)
    (op2-dispatch '=) obj value
    return;

define-infix< 50 =
#define-infix> 70 :
define-infix> 100 or
define-infix> 200 and
define-infix> 240 |
define-infix> 250 ^
define-infix> 260 &

define-infix> 300 <
define-infix> 300 >
define-infix> 300 <=
define-infix> 300 >=
define-infix> 300 !=
define-infix> 300 ==

define-infix> 300 <:
#define-infix> 300 <>
#define-infix> 300 is

define-infix< 400 ..
define-infix> 450 <<
define-infix> 450 >>
define-infix> 500 -
define-infix> 500 +
define-infix> 600 %
define-infix> 600 /
define-infix> 600 //
define-infix> 600 *
#define-infix< 700 **
define-infix> 750 as
define-infix> 800 .
define-infix> 800 @
#define-infix> 800 .=
#define-infix> 800 @=
#define-infix> 800 =@

#-------------------------------------------------------------------------------
# references
#-------------------------------------------------------------------------------

define reference
    typename "reference"

do
    fn deref (val)
        let T = (typeof val)
        if (T <: reference)
            load (bitcast val (storageof T))
        else val

    fn passthru-overload (sym func)
        set-type-symbol! reference sym (fn (a b flipped) (func (deref a) (deref b)))
    passthru-overload '== ==; passthru-overload '!= !=
    passthru-overload '< <; passthru-overload '<= <=
    passthru-overload '> >; passthru-overload '>= >=
    passthru-overload '& &; passthru-overload '| |; passthru-overload '^ ^
    passthru-overload '+ +; passthru-overload '- -
    passthru-overload '/ /; passthru-overload '/ /
    passthru-overload '// //; passthru-overload '// //
    passthru-overload '% %
    passthru-overload '<< <<; passthru-overload '>> >>
    passthru-overload '.. ..; passthru-overload '.. ..
    set-type-symbol! reference 'getattr
        fn "reference-getattr" (self name)
            getattr (bitcast self (storageof (typeof self))) name

    set-type-symbol! reference 'repr
        fn (self)
            forward-repr (load self)

    set-type-symbol! reference 'imply
        fn (self destT)
            let ptrtype = (storageof (typeof self))
            if (type== destT ptrtype)
                bitcast self ptrtype
            else
                (load (bitcast self ptrtype)) as destT

    set-type-symbol! reference '=
        fn (self value)
            let ET = (element-type (storageof (typeof self)) 0)
            store (imply value ET) self
            true

    set-type-symbol! reference 'apply-type
        fn "reference-apply-type" (cls element)
            if (type== cls reference)
                fn make-reference-type (ET)
                    let T = (typename (.. "&" (type-name ET)))
                    set-typename-super! T reference
                    set-typename-storage! T (mutable-pointer-type ET)
                    T

                # due to auto-memoization, we'll always get the same type back
                    provided the element type is a constant
                assert (constant? element)
                assert-typeof element type
                if (element <: reference)
                    compiler-error!
                        .. "cannot create reference type of reference type "
                            repr element
                make-reference-type element
            else
                let ET = (storageof cls)
                bitcast (imply element ET) cls

define-block-scope-macro var
    fn element-typeof (value)
        let T = (typeof value)
        if (T <: reference)
            element-type (storageof T) 0
        else T

    let args = (list-next expr)
    let name token rest = (decons args 2)
    let token = (token as Syntax as Symbol)
    if (token == '=)
        let value rest = (decons rest)
        let tmp = (Parameter 'tmp)
        let T = (Parameter 'T)
        return
            cons
                list let tmp '= value
                list let T '= (list element-typeof tmp)
                list let name '= (list (list reference T) (list alloca T))
                #list let name '= (list alloca T)
                list (do =) name tmp
                next-expr
            syntax-scope
    elseif (token == '@)
        let size token rest = (decons rest 2)
        let token = (token as Syntax as Symbol)
        if (token == ':)
            let deftype rest = (decons rest)
            return
                cons
                    list let name '= (list alloca-array deftype (list usize size))
                    next-expr
                syntax-scope
        else
            syntax-error! (active-anchor)
                "syntax: var <name> @ <size> : <type>"
    else
        syntax-error! (active-anchor)
            "syntax: var <name> = <value> | <name> @ <size> : <type>"

define-macro global
    fn element-typeof (value)
        let T = (typeof value)
        if (T <: reference)
            element-type (storageof T) 0
        else T

    let name token rest = (decons args 2)
    let token = (token as Syntax as Symbol)
    if (token == '=)
        let value rest = (decons rest)
        let tmp = (Parameter 'tmp)
        let T = (Parameter 'T)
        list define name
            list let tmp '= value
            list let T '= (list element-typeof tmp)
            list let name '= (list (list reference T) (list malloc T))
            list (do =) name tmp
            name
    elseif (token == '@)
        let size token rest = (decons rest 2)
        let token = (token as Syntax as Symbol)
        if (token == ':)
            let deftype rest = (decons rest)
            list define name
                list let name '= (list malloc-array deftype (list usize size))
                name
        else
            syntax-error! (active-anchor)
                "syntax: global <name> @ <size> : <type>"
    else
        syntax-error! (active-anchor)
            "syntax: global <name> = <value> | <name> @ <size> : <type>"

#-------------------------------------------------------------------------------
# module loading
#-------------------------------------------------------------------------------

define package
    let package = (Scope)
    set-scope-symbol! package 'path
        list "./?.sc"
            "./?/init.sc"
            .. compiler-dir "/?.sc"
            .. compiler-dir "/?/init.sc"
    set-scope-symbol! package 'modules (Scope)
    package

syntax-extend
    fn make-module-path (pattern name)
        let sz = (countof pattern)
        let loop (i start result) =
            unconst 0:usize
            unconst 0:usize
            unconst ""
        if (i == sz)
            return (.. result (slice pattern start))
        if ((@ pattern i) != (char "?"))
            loop (i + 1:usize) start result
        else
            loop (i + 1:usize) (i + 1:usize)
                .. result (slice pattern start i) name

    fn exec-module (expr eval-scope)
        let expr-anchor = (Syntax-anchor expr)
        let f = (compile (eval expr eval-scope))
        let rettype =
            element-type (element-type ('typeof f) 0) 0
        let ModuleFunctionType = (pointer (function (ReturnLabel (unknownof Any))))
        let fptr =
            if (rettype == Any)
                f as ModuleFunctionType
            else
                # build a wrapper
                let expr =
                    list
                        list let 'tmp '= (list f)
                        list unconst (list Any-new 'tmp)
                let expr = ((Syntax-wrap expr-anchor (Any expr) false) as Syntax)
                let f = (compile (eval expr (globals)))
                f as ModuleFunctionType
        fptr;

    fn require (name)
        let package = (unconst package)
        assert-typeof name Symbol
        let namestr = (Symbol->string name)
        fn load-module (name)
            let modules = (package.modules as Scope)
            let content ok = (@ modules name)
            if ok
                return content (unconst true)
            let loop (patterns) = (package.path as list)
            if (empty? patterns)
                return (unconst (Any none)) (unconst false)
            let pattern patterns = (decons patterns)
            let pattern = (pattern as string)
            let module-path = (make-module-path pattern namestr)
            if (not (file? module-path))
                loop patterns
            let expr = (list-load module-path)
            let eval-scope = (Scope (globals))
            set-scope-symbol! eval-scope 'module-path module-path
            let content = (exec-module expr eval-scope)
            set-scope-symbol! modules name content
            return content (unconst true)
        let content ok = (load-module name)
        if ok
            return content
        io-write! "no such module '"
        io-write! (Symbol->string name)
        io-write! "' in paths:\n"
        let loop (patterns) = (package.path as list)
        if (empty? patterns)
            abort!;
            unreachable!;
        let pattern patterns = (decons patterns)
        let pattern = (pattern as string)
        let module-path = (make-module-path pattern namestr)
        io-write! "    "
        io-write! module-path
        io-write! "\n"
        loop patterns

    set-scope-symbol! syntax-scope 'require require
    syntax-scope

define-scope-macro locals
    # export locals as a chain of two scopes: a scope that contains
        all the constant symbols, and a scope that contains the dynamic
        ones.
    let constant-scope = (Scope)
    let tmp = (Parameter 'tmp)
    let loop (last-key result) = (unconst none) (unconst (list tmp))
    let key value =
        Scope-next syntax-scope (Any last-key)
    if (('typeof key) == Nothing)
        return
            cons do
                list let tmp '= (list Scope constant-scope)
                result
            syntax-scope
    else
        loop (unconst key)
            if (('typeof key) == Symbol)
                let key = (key as Symbol)
                let keyT = ('typeof value)
                if ((keyT == Parameter) or (keyT == Label))
                    cons
                        list set-scope-symbol! tmp (list quote key) value
                        result
                else
                    set-scope-symbol! constant-scope key value
                    result
            else
                # skip
                result

define-macro import
    let name = (decons args)
    let name = (name as Syntax as Symbol)
    list define name
        list require
            list quote name

#define llvm_eh_sjlj_setjmp
    extern 'llvm.eh.sjlj.setjmp (function i32 (pointer i8))

fn xpcall (f errorf)
    let pad = (alloca exception-pad-type)
    let old-pad =
        set-exception-pad pad
    if (== operating-system 'windows)
        if ((catch-exception pad (inttoptr 0 (pointer i8))) != 0)
            set-exception-pad old-pad
            errorf (exception-value pad)
        else
            let result... = (f)
            set-exception-pad old-pad
            result...
    else
        if ((catch-exception pad) != 0)
            set-exception-pad old-pad
            errorf (exception-value pad)
        else
            let result... = (f)
            set-exception-pad old-pad
            result...

fn format-exception (exc)
    if (('typeof exc) == Exception)
        let exc = (exc as Exception)
        format-message (Exception-anchor exc)
            .. (default-styler style-error "error:")
                \ " " (Exception-message exc)
    else
        .. "exception raised: " (repr exc) "\n"

fn prompt (prefix preload)
    __prompt prefix
        if (none? preload) ""
        else preload

#-------------------------------------------------------------------------------
# match
#-------------------------------------------------------------------------------

# earliest form of match macro - doesn't do elaborate patterns yet, just
    simple switch-case style comparisons
define-macro match
    let value rest = (decons args)
    let tmp = (Parameter 'tmp)

    fn vardef? (val)
        (('typeof val) == Symbol) and ((@ (val as Symbol as string) 0) == (char "$"))

    fn match-pattern (src sxkey)
        assert-typeof src Parameter
        assert-typeof sxkey Syntax
        let anchor = (sxkey as Anchor)
        let key = (sxkey as Any)
        let result =
            if (('typeof key) == list)
                let key = (key as list)
                if (empty? key)
                    list 'empty? src
                else
                    let head rest = (decons key)
                    let head = (head as Syntax as Symbol)
                    if (head == 'quote)
                        list '== src sxkey
                    # better support generic iterator
                    #elseif (head == 'list)
                        fn process-list-args (anchor src rest)
                            if (empty? rest)
                                list (list 'empty? src)
                            else
                                let tmp tmprest = (Parameter 'tmp) (Parameter 'rest)
                                let x rest = (decons rest)
                                cons
                                    list 'not (list 'empty? src)
                                    list do-in
                                        list let tmp tmprest '= (list 'decons src)
                                        match-pattern tmp (x as Syntax)
                                    process-list-args anchor tmprest rest
                        cons 'and
                            list '== (list typeof src) list
                            process-list-args anchor src rest
                    elseif (head == 'or)
                        if ((countof rest) < 2)
                            error! "'or' needs two arguments"
                        fn process-or-args (src rest)
                            let a rest = (decons rest)
                            if ((countof rest) <= 1)
                                let b = (decons rest)
                                list 'or
                                    match-pattern src (a as Syntax)
                                    match-pattern src (b as Syntax)
                            else
                                list 'or
                                    match-pattern src (a as Syntax)
                                    process-or-args src rest
                        process-or-args src rest
                    else
                        error!
                            .. "invalid pattern: " (repr key)
            elseif (vardef? key)
                let sym = (Symbol (slice (key as Symbol as string) 1))
                list do-in
                    list let sym '= src
                    true
            else
                # simple comparison
                list '== src key
        #print result
        Syntax-wrap anchor (Any result) false

    fn process (i src expr)
        if (empty? expr)
            error! "else expected"
        let pair rest = (decons expr)
        let key dst = (decons (pair as Syntax as list))
        let kkey = (key as Syntax as Any)
        let keytype = ('typeof kkey)
        if ((keytype == Symbol) and (kkey == 'else))
            cons (cons 'else dst) '()
        else
            cons
                cons
                    ? (i == 0) 'if 'elseif
                    match-pattern src (key as Syntax)
                    dst
                process (i + 1) src rest
    cons do
        list let tmp '= value
        process (unconst 0) tmp rest

#-------------------------------------------------------------------------------
# various C related sugar
#-------------------------------------------------------------------------------

# labels safecast to function pointers
set-type-symbol! Closure 'imply
    fn (self destT)
        if (function-pointer-type? destT)
            let ET = (rawcall element-type destT 0)
            let sz = (trunc (rawcall type-countof ET) i32)
            if (rawcall function-type-variadic? ET)
                compiler-error! "cannot typify to variadic function"
            let loop (i args...) = sz
            if (icmp== i 1)
                let result =
                    compile (typify self args...)
                if (destT != ('typeof result))
                    syntax-error! (Label-anchor (Closure-label self))
                        .. "function does not compile to type " (repr destT)
                            \ " but has type " (repr ('typeof result))
                return (imply result destT)
            else
                let i-1 = (sub i 1)
                loop i-1 (rawcall element-type ET i-1) args...

# a nullptr type that casts to whatever null pointer is required
syntax-extend
    let NullType = (typename "NullType")
    set-typename-storage! NullType (pointer void)
    set-type-symbol! NullType 'imply
        fn (self destT)
            if (pointer-type? destT)
                nullof destT
    set-type-symbol! NullType '==
        fn (a b flipped)
            if flipped
                if (pointer-type? (storageof (typeof a)))
                    icmp== (ptrtoint a usize) 0:usize
            else
                if (pointer-type? (storageof (typeof b)))
                    icmp== (ptrtoint b usize) 0:usize
    let null = (nullof NullType)
    set-scope-symbol! syntax-scope 'NullType NullType
    set-scope-symbol! syntax-scope 'null null
    syntax-scope

# support assignment syntax
set-type-symbol! pointer '=
    fn (self value)
        store
            value as (element-type (typeof self) 0)
            self
        true

# pointer comparisons
set-type-symbol! pointer '==
    fn (a b flipped)
        if flipped
            icmp== (ptrtoint (a as (typeof b)) usize) (ptrtoint b usize)
        else
            icmp== (ptrtoint a usize) (ptrtoint (b as (typeof a)) usize)

# pointer cast to element type executes load
set-type-symbol! pointer 'as
    fn (self destT)
        if (type== destT (element-type (typeof self) 0))
            load self
# also supports mutable pointer safecast to immutable pointer
set-type-symbol! pointer 'imply
    fn (self destT)
        if (type== destT (pointer-type (element-type (typeof self) 0)))
            bitcast self destT

# support getattr syntax
set-type-symbol! pointer 'getattr
    fn (self name)
        let ET = (element-type (typeof self) 0)
        let op success = (type@ ET 'getattr&)
        if success
            let result... = (op self name)
            if (icmp== (va-countof result...) 0)
            else
                return result...
        getattr (load self) name

# support @
set-type-symbol! pointer '@
    fn (self index)
        let index =
            if (none? index) 0:usize # simple dereference
            else index
        let ET = (element-type (typeof self) 0)
        (reference ET) (getelementptr self (usize index))

# extern cast to element type/pointer executes load/unconst
set-type-symbol! extern 'imply
    fn (self destT)
        let ET = (element-type (typeof self) 0)
        if (type== destT (pointer ET))
            unconst self
        else
            forward-imply (load self) destT

set-type-symbol! extern 'as
    fn (self destT)
        forward-as (load self) destT

# support assignment syntax for extern
set-type-symbol! extern '=
    fn (self value)
        let ET = (element-type (typeof self) 0)
        store (imply value ET) self
        true

# support @ for extern
set-type-symbol! extern '@
    fn (self value)
        @ (unconst self) value

do
    fn unenum (val)
        let T = (typeof val)
        if (T <: CEnum)
            bitcast val (storageof T)
        else val

    # support for downcast
    set-type-symbol! CEnum 'imply
        fn (self destT)
            let ST = (storageof (typeof self))
            if (type== destT ST)
                bitcast self ST

    fn passthru-overload (sym func)
        set-type-symbol! CEnum sym (fn (a b flipped) (func (unenum a) (unenum b)))

    passthru-overload '!= ==; passthru-overload '== ==
    passthru-overload '< <; passthru-overload '<= <=
    passthru-overload '> >; passthru-overload '>= >=
    passthru-overload '+ +; passthru-overload '- -
    passthru-overload '* *; passthru-overload '/ /
    passthru-overload '// //; passthru-overload '% %
    passthru-overload '<< <<; passthru-overload '>> >>
    passthru-overload '| |
    passthru-overload '^ ^
    passthru-overload '& &

# support for C struct initializers
set-type-symbol! CStruct 'apply-type
    fn (cls args...)
        let sz = (va-countof args...)
        if (icmp== sz 0)
            nullof cls
        else
            let T = (storageof cls)
            let keys... = (va-keys args...)
            let loop (i instance) = 0 (nullof cls)
            if (icmp<s i sz)
                let key = (va@ i keys...)
                let arg = (va@ i args...)
                let k =
                    if (key == unnamed) i
                    else
                        typename-field-index cls key
                let ET = (element-type T k)
                loop (add i 1)
                    insertvalue instance (imply arg ET) k
            else
                instance

# access reference to struct element from pointer/reference
set-type-symbol! CStruct 'getattr&
    fn (self name)
        let ET = (element-type (typeof self) 0)
        let idx = (typename-field-index ET name)
        if (icmp>=s idx 0)
            # cast result to reference
            let val = (getelementptr self 0 idx)
            (reference (element-type (typeof val) 0)) val

# support for basic C union initializer
set-type-symbol! CUnion 'apply-type
    fn (cls)
        nullof cls

# access reference to union element from pointer/reference
set-type-symbol! CUnion 'getattr&
    fn (self name)
        let ET = (element-type (typeof self) 0)
        let idx = (typename-field-index ET name)
        if (icmp>=s idx 0)
            let FT = (element-type ET idx)
            # cast pointer to reference to alternative type
            (reference FT)
                bitcast self
                    if (mutable? (typeof self))
                        pointer FT 'mutable
                    else
                        pointer FT

fn pointer-call (self ...)
    label docall (dest ET)
        let sz = (va-countof ...)
        let count = (trunc (rawcall type-countof ET) i32)
        let variadic = (rawcall function-type-variadic? ET)
        let loop (i args...) = sz
        if (icmp== i 0)
            rawcall dest args...
        else
            let i-1 = (sub i 1)
            let arg = (va@ i-1 ...)
            if ((not variadic) or (icmp<s i count))
                let argtype = (rawcall element-type ET i)
                loop i-1 (imply arg argtype) args...
            else
                loop i-1 arg args...

    let ET = (rawcall element-type (typeof self) 0)
    let ST = (rawcall superof ET)
    if (type== ST function)
        docall self ET
    elseif (function-pointer-type? ET) # can also call pointer to pointer to function
        docall (load self) (rawcall element-type ET 0)
    else
        (load self) ...

# extern call attempts to cast arguments to correct type
set-type-symbol! extern 'call
    fn (self ...)
        pointer-call self ...

#-------------------------------------------------------------------------------
# using
#-------------------------------------------------------------------------------

fn merge-scope-symbols (source target filter)
    let scope-loop (source) = (unconst source)
    let loop (last-key) = (unconst none)
    let key value =
        Scope-next source (Any last-key)
    if (not (('typeof key) == Nothing))
        if (('typeof key) == Symbol)
            let key = (key as Symbol)
            if
                or (none? filter)
                    do
                        let keystr = (key as string)
                        string-match? filter keystr
                set-scope-symbol! target key value
        loop key
    let parent = (Scope-parent source)
    if (parent != null)
        scope-loop parent

define-scope-macro using
    let name rest = (decons args)
    let nameval = (name as Syntax as Any)
    if ((('typeof nameval) == Symbol) and ((nameval as Symbol) == 'import))
        let name rest = (decons rest)
        let name = (name as Syntax as Symbol)
        let module = ((require name) as Scope)
        merge-scope-symbols module syntax-scope
        return (unconst (list do)) syntax-scope
    let pattern =
        if (empty? rest) '()
        else
            let token pattern rest = (decons rest 2)
            let token = (token as Syntax as Symbol)
            if (token != 'filter)
                syntax-error! (active-anchor)
                    "syntax: using <scope> [filter <filter-string>]"
            let pattern = (pattern as Syntax as string)
            list pattern
    # attempt to import directly if possible
    label process (src)
        if (empty? pattern)
            merge-scope-symbols src syntax-scope
        else
            merge-scope-symbols src syntax-scope ((@ pattern 0) as string)
        return (unconst (list do)) syntax-scope
    if (('typeof nameval) == Symbol)
        let sym = (nameval as Symbol)
        let src ok = (@ syntax-scope sym)
        if ok and (('typeof src) == Scope)
            process (src as Scope)
    elseif (('typeof nameval) == Scope)
        process (nameval as Scope)
    return
        list syntax-extend
            cons merge-scope-symbols name 'syntax-scope pattern
            'syntax-scope
        syntax-scope

#-------------------------------------------------------------------------------
# tuples
#-------------------------------------------------------------------------------

set-type-symbol! tuple 'countof
    fn (self)
        countof (typeof self)

set-type-symbol! tuple '@
    fn (self at)
        extractvalue self (usize at)

fn tupleof (...)
    let sz = (va-countof ...)
    # build tuple type
    let loop (i result...) = sz
    if (icmp>s i 0)
        let i = (sub i 1)
        let T = (va@ i ...)
        loop i (typeof T) result...
    else
        # build tuple
        let loop (i result) = 0 (nullof (tuple result...))
        if (icmp<s i sz)
            let T = (va@ i ...)
            loop (add i 1)
                insertvalue result T i
        else
            result

#-------------------------------------------------------------------------------
# arrays
#-------------------------------------------------------------------------------

set-type-symbol! array 'countof
    fn (self)
        countof (typeof self)

set-type-symbol! array '@
    fn (self at)
        let val = (i32 at)
        if (constant? val)
            extractvalue self val
        else
            load (getelementptr (allocaof self) 0 val)

fn arrayof (T ...)
    let count = (va-countof ...)
    let loop (i result) = 0 (nullof (array T (usize count)))
    if (i < count)
        let element = (va@ i ...)
        loop (i + 1)
            insertvalue result (imply element T) i
    else result

#-------------------------------------------------------------------------------
# iterators
#-------------------------------------------------------------------------------

fn range (a b c)
    let num-type = (typeof a)
    let step =
        if (c == none)
            num-type 1
        else c
    let from =
        if (b == none)
            num-type 0
        else a
    let to =
        if (b == none) a
        else b
    fn ()
        return
            label (f fdone x)
                if (x < to)
                    f (x + step) x
                else
                    fdone;
            unconst from

fn zip (a b)
    let iter-a init-a = (a)
    let iter-b init-b = (b)
    fn ()
        return
            fn (fret fdone t)
                let a = (@ t 0)
                let b = (@ t 1)
                iter-a
                    label (next-a at-a...)
                        iter-b
                            label (next-b at-b...)
                                fret
                                    tupleof next-a next-b
                                    \ at-a... at-b...
                            \ fdone b
                    \ fdone a
            tupleof init-a init-b

define-macro for
    let loop (it params) = args (unconst '())
    if (empty? it)
        error! "'in' expected"
    let sxat it = (decons it)
    let at = (sxat as Syntax as Symbol)
    if (at != 'in)
        loop it (cons sxat params)
    let generator-expr body = (decons it)
    let params = (list-reverse params)
    let iter = (Parameter 'iter)
    let start = (Parameter 'start)
    let next = (Parameter 'next)
    let loop = (Symbol "#loop")
    list do
        list let iter start '= (list generator-expr)
        list label 'break '()
        list iter
            list label loop (cons next params)
                list label 'continue '()
                    list iter loop 'break next
                cons do body
                list 'continue
            \ 'break start

define-macro while
    let cond-expr body = (decons args)
    list do
        list label 'break '()
        list let 'continue '()
        list if cond-expr
            cons do body
            list 'continue

#-------------------------------------------------------------------------------
# vectors
#-------------------------------------------------------------------------------

fn vectorof (T ...)
    let count = (va-countof ...)
    let loop (i result) = 0 (nullof (vector T (usize count)))
    if (i < count)
        let element = (va@ i ...)
        loop (i + 1)
            insertelement result (imply element T) i
    else result

fn vector-signed-dispatch (fsigned funsigned)
    fn (a b)
        if (signed? (element-type (typeof a) 0))
            fsigned a b
        else
            funsigned a b

set-type-symbol! integer 'vector+ add
set-type-symbol! integer 'vector- sub
set-type-symbol! integer 'vector* mul
set-type-symbol! integer 'vector// (vector-signed-dispatch sdiv udiv)
set-type-symbol! integer 'vector% (vector-signed-dispatch srem urem)
set-type-symbol! integer 'vector& band
set-type-symbol! integer 'vector| bor
set-type-symbol! integer 'vector^ bxor
set-type-symbol! integer 'vector<< shl
set-type-symbol! integer 'vector>> (vector-signed-dispatch ashr lshr)
set-type-symbol! integer 'vector== icmp==
set-type-symbol! integer 'vector!= icmp!=
set-type-symbol! integer 'vector> (vector-signed-dispatch icmp>s icmp>u)
set-type-symbol! integer 'vector>= (vector-signed-dispatch icmp>s icmp>=u)
set-type-symbol! integer 'vector< (vector-signed-dispatch icmp<s icmp<u)
set-type-symbol! integer 'vector<= (vector-signed-dispatch icmp<=s icmp<=u)

set-type-symbol! real 'vector+ fadd
set-type-symbol! real 'vector- fsub
set-type-symbol! real 'vector* fmul
set-type-symbol! real 'vector/ fdiv
set-type-symbol! real 'vector% frem
set-type-symbol! real 'vector== fcmp==o
set-type-symbol! real 'vector!= fcmp!=u
set-type-symbol! real 'vector> fcmp>o
set-type-symbol! real 'vector>= fcmp>=o
set-type-symbol! real 'vector< fcmp<o
set-type-symbol! real 'vector<= fcmp<=o

fn vector-op2-dispatch (symbol)
    fn (a b flipped)
        if (type== (typeof a) (typeof b))
            let Ta = (element-type (typeof a) 0)
            let op success = (type@ Ta symbol)
            if success
                let result... = (op a b)
                if (icmp== (va-countof result...) 0)
                else
                    return result...

set-type-symbol! vector '+ (vector-op2-dispatch 'vector+)
set-type-symbol! vector '- (vector-op2-dispatch 'vector-)
set-type-symbol! vector '* (vector-op2-dispatch 'vector*)
set-type-symbol! vector '/ (vector-op2-dispatch 'vector/)
set-type-symbol! vector '// (vector-op2-dispatch 'vector//)
set-type-symbol! vector '% (vector-op2-dispatch 'vector%)
set-type-symbol! vector '& (vector-op2-dispatch 'vector&)
set-type-symbol! vector '| (vector-op2-dispatch 'vector|)
set-type-symbol! vector '^ (vector-op2-dispatch 'vector^)
set-type-symbol! vector '== (vector-op2-dispatch 'vector==)
set-type-symbol! vector '!= (vector-op2-dispatch 'vector!=)
set-type-symbol! vector '> (vector-op2-dispatch 'vector>)
set-type-symbol! vector '>= (vector-op2-dispatch 'vector>=)
set-type-symbol! vector '< (vector-op2-dispatch 'vector<)
set-type-symbol! vector '<= (vector-op2-dispatch 'vector<=)

set-type-symbol! vector 'countof
    fn (self)
        type-countof (typeof self)

set-type-symbol! vector 'unpack
    fn "vector-unpack" (v)
        let count = (type-countof (typeof v))
        let loop (i result...) = count
        if (i == 0:usize) result...
        else
            let i = (sub i 1:usize)
            loop i
                extractelement v i
                result...

set-type-symbol! vector '@
    fn (self x)
        if (integer? x)
            extractelement self x

set-type-symbol! vector 'slice
    fn (self i0 i1)
        if ((constant? i0) and (constant? i1))
            let usz = (sub i1 i0)
            let loop (i mask) = i0 (nullof (vector i32 usz))
            if (icmp<u i i1)
                loop (add i 1:usize) (insertelement mask (i32 i) (sub i i0))
            else
                shufflevector self self mask
        else
            compiler-error! "slice indices must be constant"

fn vector-reduce (f v)
    let loop (v) = v
    let sz = (countof v)
    # special cases for low vector sizes
    if (sz == 1:usize)
        extractelement v 0
    elseif (sz == 2:usize)
        f
            extractelement v 0
            extractelement v 1
    elseif (sz == 3:usize)
        f
            f
                extractelement v 0
                extractelement v 1
            extractelement v 2
    elseif (sz == 4:usize)
        f
            f
                extractelement v 0
                extractelement v 1
            f
                extractelement v 2
                extractelement v 3
    else
        let hsz = (sz >> 1:usize)
        let fsz = (hsz << 1:usize)
        if (fsz != sz)
            compiler-error! "vector size must be a power of two"
        let a = (slice v 0 hsz)
        let b = (slice v hsz fsz)
        loop (f a b)

fn any? (v)
    vector-reduce bor v
fn all? (v)
    vector-reduce band v

set-type-symbol! vector '..
    fn (a b flipped)
        let Ta Tb = (typeof a) (typeof b)
        if (not (vector-type? Ta))
            return;
        if (not (vector-type? Tb))
            return;
        let ET = (element-type Ta 0)
        if (not (type== ET (element-type Tb 0)))
            return;
        if (type== Ta Tb)
            let usz = (mul (type-countof (typeof a)) 2:usize)
            let sz = (trunc usz i32)
            let loop (i mask) = 0 (nullof (vector i32 usz))
            if (icmp<u i sz)
                loop (add i 1) (insertelement mask i i)
            else
                shufflevector a b mask
        else
            let asz = (type-countof (typeof a))
            let bsz = (type-countof (typeof b))
            let count = (add asz bsz)
            let loop (i result) = 0:usize (nullof (vector ET count))
            if (icmp<u i asz)
                loop (add i 1:usize)
                    insertelement result (extractelement a i) i
            elseif (icmp<u i count)
                loop (add i 1:usize)
                    insertelement result (extractelement b (sub i asz)) i
            else result

#-------------------------------------------------------------------------------
# REPL
#-------------------------------------------------------------------------------

fn compiler-version-string ()
    let vmin vmaj vpatch = (compiler-version)
    .. "Scopes " (string-repr vmin) "." (string-repr vmaj)
        if (vpatch == 0) ""
        else
            .. "." (string-repr vpatch)
        " ("
        if debug-build? "debug build, "
        else ""
        \ compiler-timestamp ")"

fn print-logo ()
    io-write! "  "; io-write! (default-styler style-number "\\\\\\"); io-write! "\n"
    io-write! "   "; io-write! (default-styler style-type "\\\\\\"); io-write! "\n"
    io-write! " "; io-write! (default-styler style-comment "///")
    io-write! (default-styler style-sfxfunction "\\\\\\"); io-write! "\n"
    io-write! (default-styler style-comment "///"); io-write! "  "
    io-write! (default-styler style-keyword "\\\\\\")

fn read-eval-print-loop ()
    fn repeat-string (n c)
        let loop (i s) =
            tie-const n (usize 0)
            tie-const n ""
        if (i == n)
            return s
        loop (i + (usize 1))
            .. s c

    fn leading-spaces (s)
        let len = (i32 (countof s))
        let loop (i) = (tie-const len 0)
        if (i == len)
            return s
        let c = (@ s i)
        if (c != (char " "))
            return (string-new (string->rawstring s) (usize i))
        loop (i + 1)

    fn blank? (s)
        let len = (i32 (countof s))
        let loop (i) =
            tie-const len 0
        if (i == len)
            return (unconst true)
        if ((@ s i) != (char " "))
            return (unconst false)
        loop (i + 1)

    print-logo;
    print " "
        compiler-version-string;

    let global-scope = (globals)
    let eval-scope = (Scope global-scope)
    let loop (preload cmdlist counter) =
        unconst ""
        unconst ""
        unconst 0
    #dump "loop"
    fn make-idstr (counter)
        .. "$" (Any-string (Any counter))

    let idstr = (make-idstr counter)
    let promptstr =
        .. idstr " "
            default-styler style-comment "▶"
    let promptlen = ((countof idstr) + 2:usize)
    let cmd success =
        prompt
            ..
                if (empty? cmdlist) promptstr
                else
                    repeat-string promptlen "."
                " "
            preload
    if (not success)
        return;
    fn endswith-blank (s)
        let slen = (countof s)
        if (slen == 0:usize) (unconst false)
        else
            (@ s (slen - 1:usize)) == (char " ")
    let enter-multiline = (endswith-blank cmd)
    #dump "loop 1"
    let terminated? =
        (blank? cmd) or
            (empty? cmdlist) and (not enter-multiline)
    let cmdlist =
        .. cmdlist
            if enter-multiline
                slice cmd 0 -1
            else cmd
            "\n"
    let preload =
        if terminated? (unconst "")
        else (leading-spaces cmd)
    if (not terminated?)
        loop (unconst preload) cmdlist counter
    xpcall
        label ()
            let expr = (list-parse cmdlist)
            let expr-anchor = (Syntax-anchor expr)
            let f = (compile (eval expr eval-scope))
            let rettype =
                element-type (element-type ('typeof f) 0) 0
            let ModuleFunctionType = (pointer (function (ReturnLabel (unknownof Any))))
            let fptr =
                if (rettype == Any)
                    f as ModuleFunctionType
                else
                    # build a wrapper
                    let expr =
                        list
                            list let 'tmp '= (list f)
                            list unconst (list Any-new 'tmp)
                    let expr = ((Syntax-wrap expr-anchor (Any expr) false) as Syntax)
                    let f = (compile (eval expr global-scope))
                    f as ModuleFunctionType
            set-anchor! expr-anchor
            let result = (fptr)
            if (('typeof result) != Nothing)
                set-scope-symbol! eval-scope (Symbol idstr) result
                print idstr "=" result
                loop (unconst "") (unconst "") (counter + 1)
            else
                loop (unconst "") (unconst "") counter
        label (exc)
            io-write!
                format-exception exc
            loop (unconst "") (unconst "") counter

#-------------------------------------------------------------------------------
# main
#-------------------------------------------------------------------------------

fn print-help (exename)
    print "usage:" exename "[option [...]] [filename]
Options:
-h, --help                  print this text and exit.
-v, --version               print program version and exit.
-s, --signal-abort          raise SIGABRT when calling `abort!`.
--                          terminate option list."
    exit 0
    unreachable!;

fn print-version ()
    print
        compiler-version-string;
    print "Executable path:" compiler-path
    exit 0
    unreachable!;

fn run-main (args...)
    let argcount = (va-countof args...)
    let loop (i sourcepath parse-options) = 1 none true
    if (i < argcount)
        let k = (i + 1)
        let arg = (va@ i args...)
        if (parse-options and ((@ arg 0) == (char "-")))
            if ((arg == "--help") or (arg == "-h"))
                print-help args...
            elseif ((== arg "--version") or (== arg "-v"))
                print-version;
            elseif ((== arg "--signal-abort") or (== arg "-s"))
                set-signal-abort! true
                loop k sourcepath parse-options
            elseif (== arg "--")
                loop k sourcepath false
            else
                print
                    .. "unrecognized option: " arg
                        \ ". Try --help for help."
                exit 1
                unreachable!;
        elseif (sourcepath == none)
            loop k arg parse-options
        else
            print
                .. "unrecognized argument: " arg
                    \ ". Try --help for help."
            exit 1
            unreachable!;

    if (sourcepath == none)
        read-eval-print-loop;
    else
        let expr = (list-load sourcepath)
        let eval-scope = (Scope (globals))
        set-scope-symbol! eval-scope 'module-path sourcepath
        let f = (compile (eval expr eval-scope))
        let ModuleFunctionType = (pointer (function void))
        if (function-pointer-type? ('typeof f))
            call (inttoptr (Any-payload f) ModuleFunctionType)
        else
            error! "function pointer expected"
        exit 0
        unreachable!;

run-main (args)
true