Source

newspeak / Newspeak3Compilation.ns3

The default branch has multiple heads

Full commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
Newspeak3
'Newspeak3'
class Newspeak3Compilation usingPlatform: platform
 newspeakParser: ns3Parser <Newspeak3Parsing>
 mirrorLib: mirrors = NewspeakObject (
"This is the Newspeak compilation module. It includes the Newspeak compiler (Compiler) as well as a number of other classes used in compilation. For a  detailed overview of compilation see Compiler.

Classes that do not require access to the state of a compiler are defined at the module level, as siblings of the compiler.  This is true even if the class defines a phase of compilation, like the ScopeBuilder.

Relation to parsing:

Note that this module does not include a parser or AST classes.  These have utility independent of compilation, and so are available as a separate parsing module. This module requires such a parsing module as parameter. It uses this parameter to create a parser for compilation, and to subclass certain AST classes and tools for its own purposes.

The parser is instantiated upon module creation and stored in a module slot. We expect a Newspeak parser to be purely functional; hence we may share it among all compiler instances. It's not clear if this is a valid assumption in the long term.

Separating the parsing module makes it easy to change parsing strategies (though one could also define parsing here and override it in a subclass).

Other parameters:

The module uses some general purpose facilities which it expects to obtain from the underlying platform via the platform parameter.
In addition, a mirror library should be provided, as the compiler operates by querying and creating various mirrors. See the documentation of class Compiler for more discussion of the use of mirrors.

Copyright 2008 Cadence Design Systems, Inc.
Copyright 2010 Gilad Bracha, Felix Geller and Ryan Macnak
Copyright 2011 Matthias Kleine, Ryan Macnak and Cadence Design Systems
   
   Licensed under the Apache License, Version 2.0 (the ''License''); you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0"|
      
	Collection = platform collections Collection.
	Dictionary = platform collections Dictionary.
	IdentityDictionary = platform collections IdentityDictionary.
	OrderedCollection = platform collections OrderedCollection.
	Set = platform collections Set.
	SortedList = platform collections SortedCollection.
	
	Parser = ns3Parser Parser.
	astModule = ns3Parser ASTModule.
	
	ASTTool = astModule ASTTool.
      ASTCopier = astModule ASTCopier.
	ASTTraverser = astModule ASTTraverser.
      SuperFalseVisitor = astModule FalseVisitor.

      AST = astModule AST.
	AssignmentAST = astModule AssignmentAST.
	BlockAST = astModule BlockAST.
	CascadedSendAST = astModule CascadedSendAST.
	CodeBodyAST = astModule CodeBodyAST.
	MessageAST = astModule MessageAST.
      MessagePatternAST = astModule MessagePatternAST.
	MethodAST = astModule MethodAST.
	MutableSlotDefAST = astModule MutableSlotDefAST.
	NormalSendAST = astModule NormalSendAST.
	NumberAST = astModule NumberAST.
	ReturnStatAST = astModule ReturnStatAST.
      SendAST = astModule SendAST.
	SetterSendAST = astModule SetterSendAST.
	StringAST = astModule StringAST.
	SymbolAST = astModule SymbolAST.
	TupleAST = astModule TupleAST.
      VarDeclAST = astModule VarDeclAST.
	VariableAST = astModule VariableAST.
	
	Class = platform blackMarket Kernel Class.	
	Language = platform blackMarket NsMultilanguage Language.
	LanguageCompiler = platform blackMarket NsMultilanguage LanguageCompiler.
	Pragma = platform blackMarket Pragma.

	"{Newspeak-core-mirror}"  "a bunch of mirror stuff"
	SystemMetadata = mirrors SystemMetadata.
	CompiledMixinMirror = mirrors CompiledMixinMirror.
	LowLevelMixinMirror = mirrors LowLevelMixinMirror.
	LowLevelMethodMirror = mirrors LowLevelMethodMirror.
	InstanceVariableMirror = mirrors InstanceVariableMirror.

	ClassDeclarationMirror = mirrors ClassDeclarationMirror.
	
	"{Newsqueak-mixins}"
	Mixin = platform blackMarket NewsqueakMixins Mixin.
	
	"Module variables"
	parser = Parser new.
	|)
(
class Compiler = LanguageCompiler (
"The compiler has three main entry points: compileClassSource:Within:, compileClassHeader: within: and compileMethodSource:within:. These compile an entire class declaration, a class header, and a method, respectively. 

The compiler returns low level (e.g., VM level) objects representing the results of compilation.
These results are described in some detail in the individual methods. The results are never installed by the compiler. The compiler does not know or care whether it is running in the service of a live system. If the compiler is invoked from such a system, the caller may choose to install the results. This should be done as an atomic modification, since the results may be interdependent (e.g., a nested class and its enclosing class). 

Compilation begins with parsing, followed by a pass on the resulting AST to compute the scope. The scope is stored as a shadow tree of the AST. Specifically, the slot scopeMap stores a dictionary mapping AST nodes to scopes. This mapping is computed by ScopeBuilder.

Optimization note: 
This can be optimized, so that we only compute the scope of a class side, and then use it as a basis for computing the scope of each method. This would prevent us from holding onto the scopes for all methods when compiling a class. Likewise, we can avoid holding onto the scopes of all nested classes. 
** end note

When compiling an individual method, we also rewrite its AST into a lower level AST, and submit that to the AST2ByteCodeCompiler, which produces byte code.  If we are compiling a class declaration or a class header, we compute the overall structure of the resulting mixin, including any required synthetic members.

The NS2 implementation involves a considerable amount of synthetic code, dealing with accessors, nested classes, slot initialization, superclass initialization and the primary constructor. 

Nested classes are distinct for every instance of an outer class. Hence, every outer class has synthetic fields that hold the class objects for its nested classes. These fields are always accessed by a getter method which lazily initializes the field. The name of the getter method is the simple name of the inner class. The field, in contrast, is named X_slot, where X is the fully qualified name of the inner class' mixin. This is necessary to prevent it from clashing with nested classes with the same simple name elsewhere in the hierarchy. See accessorStringForNestedClassNamed:fullName:superName: .

The creation of classes is based on producing a low level mixin mirror for the class.

Nested classes also have an enclosingObject slot pointing at the object that created them, and a getter for it. See ensureEnclosingObjectAccessFor:.

The primary constructor induces a synthetic class method of the same name, which calls a synthetic  instance method of the same name on a freshly created instance. Within that instance method is the code for all the slot initializers, as well as the superclass constructor call. See processConstructorFor:inClass:."|

scopeMap <Dictionary[Scope, AST]> ::= Dictionary new.
scope <Scope>
scopeStack <OrderedCollection[Scope]> = OrderedCollection new.
literalTable <IdentityDictionary[Symbol, Integer]>
rewriter = Rewriter new.
methodCompiler = AST2ByteCodeCompiler new.
currentDepth <Integer> "The lexical nesting level of the current class; 
							top level classes are at level 0"

language = Delay computation: [Language newspeak3].
	 
|)
(
class AST2ByteCodeCompiler = ASTTool (
"The compiler is a visitor on an AST that has been processed by the rewriter.
It is a subtype of  ASTTool[Self] - that is, its methods do not return individual results, but instead
side effect state within the compiler.

The compiler decides what instructions to generate at a somewhat abstract level, and asks
a code generator object to actually produce the instruction stream.

The code generator deals with issues like whether to use regular or wide instructions,
what the actual instruction codes are, what the actual offsets for branches are etc.,
so the compiler can abstract from these details. One can almost think of this as producing
assembly.

The trickiest part of the byte code compiler is deciding when to pop the result of an expression. Subexpressions leave their result on the operand stack, but top level expressions need not, since the result is not used. Furthermore, the VM does not clean up the operand stack upon return from a method, it seeems, so we are obligated to leave an empty operand stack on method exit.

There would appear to be a space-time tradeoff - we can spend cycles popping results, or we can allocate a larger operand stack. But since we always need to clean it up, the time is always lost so we should optimize for space.

In straight line code, the situation is simple: keep track of the depth of the stack, and pop it to zero at the end of a statement. However, once we have conditional branches, we need to ensure that the last statement in a branch leaves its result, because it is in fact a subexpression.

However, this is not true in case of loops!

We do not need to retain the result of the last statement of a non-inlined closure. This is its value, but the rewriter  already takes care of this by inserting a local return.

The compiler tracks whether we are at the start of a statement or not using the boolean slot statementStarting. When traversing nodes that may have subexpressions, the current value of statementStarting is always saved before traversing subexpressions, and restored afterwards. The convention is to store the current value of statementStarting into a local named shouldPop (since we should pop the operand stack if we are at the start of a statement, i.e., the expression is a top level one and its value will not be used).

The value of shouldPop is used when there is a choice between generating a popping or non-popping version of a bytecode. It is not, however, used to pop the results of individual subexpressions. Rather than clutter the logic with tests of shouldPop (or statementStarting) everywhere, we ensure that the method statementEnd is called at the end of each statement. It pops the stack as needed. Since only top level expressions will be popped, this does not change the maximal operand stack size; it only centralizes the handling.

The statementEnd method is called by CodeBodyAST, which traverses the statement lists. Also, when traversing a CodeBodyAST, statementStarting is set to true before each statement is handled - except for the last statment, whose result we may need as noted above.

statmentEnd needs to know how many pops to perform. Whenever we start a new CodeBodyAST, we must remember the depth of the operand stack at that time (stored in statementBaselineStackDepth). At the end of each statement, we want to pop the stack down to that depth. This complication could be avoided if we chose to have every expression consider whether it was top level or not.

Keeping track of operand stack depth is not as simple as it seems.
Closure code appears inline (regardless of whether execution is inlined!). Code in a non-inlined closure starts executing with an empty operand stack, but the depth of the method must be sufficient for the block.

To complicate matters further, the actual size of the activation is simply the sum of the number of parameters, number of locals and maximal operand stack size.

We must ensure sufficient space for any given closure defined in the method. The space required for a closure is the sum of its arity, the number of values copied into it, and its maximal operand stack size. Because the closure must explicitly initialize its locals to nil on startup, its operand stack will include sufficient space for its temporaries.

Ideally, we'd track the operand stack depth for the method and for each closure within it separately. Though it seems that the actual required depth would be the maximum of all these, that is simplistic.

We really need to compute the required context size which is the maximum of:

#method formals + #method locals + method operand stack size

#closure formals + #closure copy downs + closure operand stack size

assuming that the locals of the closure are accounted for in the stack size.

Then, the actual operand stack size we specify for the method is

context size - #method formals - #method locals

We don't do this yet.  What we do instead is often suboptimal, but sometimes insufficient. We compute the cumulative maximum operand stack size for all code in the method, including closures. The idea was that this would be conservative and simple, but in fact it may fail if a closure has a large number of arguments and copy-downs, and the actual operand stack usage is small."| 
  cgen <CodeGenerator> = CodeGenerator new.
  storeVisitor <StoreVisitor> = StoreVisitor generator: cgen.  
  popAndStoreVisitor <PopAndStoreVisitor> = PopAndStoreVisitor generator: cgen. 
  debugInfo <DebugInfo> = DebugInfo new.
  result <LowLevelMethodMirror>
  statementStarting ::= true.
  statementBaselineStackDepth <Integer> = 0.
  maxClosureContextSize <Integer> ::= 0.
  scopeStack <OrderedCollection[Scope]> = OrderedCollection new.

  offsetStack <OrderedCollection[Integer]> = OrderedCollection new. "see codeBodyNode:"
  contextDepth <Integer> ::= 0.
|)
(
class CodeGenerator = (
"Handles actual byte code generation.  Defines slots corresponding to constants in the Squeak/Newspeak instruction set, as well as the ste of special selectors that are handled magically by the Squeak VM (per the Smalltalk blue book)."| 
code = LowLevelMethodMirror new .

optimize ::= true.
longJumps ::= false. 
shortJumpFailureBlock ::= [].

noOfTemps ::= 1. "temp0 always allocated"
stackMax ::= 0.
currentStackDepth ::= 0.

"Constants for the instruction set"
 
"stack manipulation instructions"
  pushInstVar = 0.
  pushTemp = 16.
  pushLiteralConst = 32.
  pushLiteralVar = 64.
  storeAndPopInstVar = 96.
  storeAndPopTemp = 104.
  pushReceiver = 112.
  pushTrue = 113.
  pushFalse = 114.
  pushNil = 115.
  pushNibble = 116. 
  pushZero = 117.
  pushOne = 118.
  pushTwo= 119.

  extendedPush = 128.
  extendedStore = 129.
  extendedStoreAndPop = 130.
  wide = 132.
  store = 160.
  storeAndPop = 192.
  push = 64.
  pop = 135.
  pushLit = 96.
  dupTos = 136.
  pushActiveContext = 137.
  
  pushImplicitReceiver = 127. "for now"
  dynamicSuperSend = 126. 
" like extended super send, but find superclass dynamically"
  outerSend = 139. "Explicit outer send"

" send instructions"
  extendedSend = 131.
  extendedSendWide = 132.
  superSend = 133.
  extendedSuperSend = 134.
  specialSend = 176.
  sendBlockCopy = 200.
  basicSend = 208.

"closure instructions"
  pushArray = 138.
  pushRemoteTemp = 140.
  storeRemoteTemp = 141.
  storeAndPopRemoteTemp = 142.
  pushClosure = 143.

"jump instructions"
  jump = 144.
  popAndJumpOnFalse = 152.
  longJump = 160.
  popAndLongJumpOnTrue = 168.
  popAndLongJumpOnFalse = 172.
  maxJump = 1023.
  minJump = -1024.
  bits9to11 = 16r700.

"return instructions"
  returnReceiver = 120. 
  returnTrue = 121.
  returnFalse = 122.
  returnNil = 123.
  return = 124.
  blockReturn = 125.

  slotsPerMethod = 64.
  specialSelectors = Dictionary new.
|{#+. #-. #<. #>. #<=. #>=. #=. #~=. #*. #/. #\\. #@. 
#bitShift:. #//. #bitAnd:. #bitOr:. 
#at:. #at:put:. #size. #next. #nextPut:. #atEnd.
#==.
#class. #blockCopy:. #value. #value:. #do:. #new. #new:. #x. #y}
with: (specialSend to: basicSend -1) do:[:sel <Symbol> :i <Integer> |
  specialSelectors at: sel put: i.
  ])
('Unclassified'
bci
 = (
    "Answers the current bci."
    ^ code size
)
close ^ <LowLevelMethodMirror>
 = (
    "To be called at the end of code generation."
    code maxStack: (stackMax + code argCount + code maxLocals  max: maxClosureContextSize). "; klass:: methodsEnclosingMixin  implementationMirror implementationClass " 
    ^code
)
dup = (
  code byte: dupTos. "136"
  incrementStackDepthBy: 1.
)
isSpecialSelector: sel <Symbol> ^ <Boolean> = (
  ^specialSelectors includesKey: sel
)
label: pos
 = (
	"
	Defines a target for the (forward) jump at pos
	and fixes the jump offset. Since a label corresponds
	to a join of two execution branches, no information
	on previous instructions may be used for optimizations
	of future instructions.
	"
	| offs |
	offs:: code size - pos.
	longJumps
		ifTrue: [
			"self assert: [0 <= offs and: [ offs < 16r100000000 ] ]."
			code wordAt: pos - 3 put: offs
		]
		ifFalse: [
			(0 <= offs and: [ offs < 16r100 ]) ifFalse: [ shortJumpFailureBlock value. super halt ].
			code byteAt: pos put: offs
		].
	code killLast
)
length: block
 = (
	"Answers the code length in bytes for the code generated by block."
	| d |
	d:: self bci.
	block value.
	^ self bci - d
)
literalIndexFor: s <Symbol> ^ <Integer> = (
  "Look the symbol up in the literal table and get its index"
  ^literalTable at: s
)
or
 = (
    "Answers fixup address."
    longJumps
        ifTrue: [code byte: (HCodeTable at: #orL) word: 0]
        ifFalse: [code byte: (HCodeTable at: #orS) byte: 0].
    ^ code size
)
popTos
 = (
    code byte: pop.
    decrementStackDepthBy: 1.
)
pushANibble: n <Integer> = (
  assert:[n > -2 and:[n <3]] message: 'nibble must be between -2 and 5'.
  code byte: pushNibble + n + 1.
   incrementStackDepthBy: 1.
)
pushBoolFalse = (
    code byte: pushFalse.
   incrementStackDepthBy: 1.
)
pushBoolTrue = (
    code byte: pushTrue.
   incrementStackDepthBy: 1.
)
pushGlobalVar: assoc
 = (
    code byte: (HCodeTable at: #pushGlobalVar) oop: assoc
)
pushInstanceVariable: n <Integer>
 = (
	assert: [ 0 <= n and:[n < 254] ].
       incrementStackDepthBy: 1.
       n < 8 ifTrue:[code byte: pushInstVar + n. ^self].
	 n < 64 ifTrue:[code byte: extendedPush; byte: n. ^self].
	code byte: wide; byte: push; byte: n.
)
pushLiteral: lit <Symbol | Character | Number> = (
	| val |
	lit isNumber ifTrue:[ | const |
			(lit >= -1 and:[lit <= 2]) ifTrue:[
					lit = 1 ifTrue:[^pushOneObj].
					lit = 0 ifTrue:[^pushZeroObj].
					lit = 2 ifTrue:[^pushTwoObj].
					lit = -1 ifTrue:[^pushMinusOneObj].
				]
		].
	pushLiteralIndex: (literalIndexFor: lit).
)
pushNilObj = (
    code byte: pushNil.
    incrementStackDepthBy: 1.
)
pushSelf
 = (
	code byte: pushReceiver.
	incrementStackDepthBy: 1.
)
pushTemporary: n
 = (
      incrementStackDepthBy: 1.
	n <= 6 	ifTrue: [ code byte: pushTemp + n.	^ self ]. "7? role of self?"
	code byte: extendedPush; byte: 64+ n.
)
pushTos
 = (
    code pushTos.
    incrementStackDepthBy: 1.
)
sendSpecial: sel <Symbol> = (
   code byte: (specialSelectors at: sel).
)
storeAndPopGlobalVar: assoc
 = (
    code byte: (HCodeTable at: #storeGlobalVarPop) oop: assoc
)
storeAndPopInstanceVariable: offset <Integer>
 = (
   assert:[offset >= 0 and:[offset < 254]]. 
   decrementStackDepthBy: 1.
   offset <  8 ifTrue:[code byte: storeAndPopInstVar + offset. ^self]. "96 + offset"
   offset <  64 ifTrue:[code byte: extendedStoreAndPop; byte: offset. ^self].
"130; offset"
   code byte: wide; byte: storeAndPop; byte: offset. "132; 192; offset"
)
storeAndPopTemporary: n <Integer>
 = (
	assert: [ n >= 0 and:[n <64] ].
	decrementStackDepthBy: 1.
	n < 8 	ifTrue: [ code byte: storeAndPopTemp+ n.^ self ]."104 + n"
	code byte: extendedStoreAndPop; byte: 64+n. "130; 64+n"
)
superSend: sel <Symbol>  noOfArgs: n <Integer> = (
"Not used at the moment; when the VM supports dynamic super sends, that may change"
    | selIndex <Byte> |
    selIndex:: literalIndexFor: sel.
    assert: [n >= 0 and:[n < 256]] 
	message: 'number of arguments must be between 0 and 255'.
    assert:[selIndex >= 0 and: [selIndex < 256]]
	message: 'selector index must be between 0 and 255'.
   decrementStackDepthBy: n.
    code byte: dynamicSuperSend; "126"
            byte: n; byte: selIndex.
)'as yet unclassified'
argCount: n = (
	code argCount: n
)
blockCopy = ( 
    decrementStackDepthBy: 1.
"this instruction pops two things off the stack: the receiver of blockCopy:, and its argument; it pushes the result (a block). This yields a net decrement of 1"
    code byte: sendBlockCopy
)
decrementStackDepthBy: n = (
"Reduce the current height of the operand stack"
	currentStackDepth:: currentStackDepth - n.
	 assert:[currentStackDepth >= 0] 
	message: 'Stack depth must not be negative'.
)
ensureBaselineStackDepth = (
	[currentStackDepth > statementBaselineStackDepth] whileTrue:[popTos]
)
ensureEmptyStack = (
	[currentStackDepth > 0] whileTrue:[popTos]
)
incrementStackDepthBy: n = (
"Increase the current height of the operand stack. Keep track of the maximum operand stack height seen in this method (that's the whole point of tracking the stack height - we need this to create a CompiledMethod"
	currentStackDepth:: currentStackDepth + n.
	stackMax:: stackMax max: currentStackDepth.
)
jumpBy: offset <Integer>  = (

| adjust <Integer> |
	assert:[offset <= maxJump and:[offset >= minJump]]
	message: 'offset out of range'.
"might be nice to return the bci that we need to patch later; same with popJumps"
      adjust:: "((offset bitAnd: bits9to11) + 4) \\ 7" offset // 256 + 4 .
	code byte: longJump + adjust ;
	 "bits 9-11 of offset "
	        byte:  (offset bitAnd: 16rFF). "bits 1-8 of offset"
)
literals: ls
 = (
    code literals: ls.
)
maxLocals ^ <Integer> = (
	^code maxLocals
)
maxLocals: n <Integer> = (
	code maxLocals: n
)
methodName: n <Symbol> = (
	code selector: n
)
normalSend: sel <Symbol> noOfArgs: n <Byte> 
 = (
    | op <Byte> data <Byte> selIndex <Byte>|

    decrementStackDepthBy: n.
    (isSpecialSelector: sel) ifTrue:[^sendSpecial: sel].
"problem with blockCopy: which only applies if the receiver is a block"
    selIndex:: literalIndexFor: sel.
    assert: [n >= 0 and:[n < 256]] message: 'n must be between 0 and 255'.
    assert:[selIndex >= 0 and: [selIndex < 256]] 
	message: 'literal index must be between 0 and 255'.
    (selIndex > 15 or:[n > 2])  ifTrue:[ "need an extended send"
       (n  < 8 and:[selIndex < 32]) ifTrue:[
          op:: extendedSend. "131"
          data:: n*32 + selIndex. "replace multiplication by bitshift?"
          code byte: op; byte: data.
          ^self
          ].
       op:: extendedSendWide. "132"
       code byte: op; byte: n; byte: selIndex.
	^self
    ].

    op:: basicSend. "208"
    code byte:  n*16 + op + selIndex."replace multiplication by bitshift?"
)
patchJump: index <Integer> with: targetData <Integer> = (

	code byteAt: index - 1 
		put: ((code byteAt: index - 1) bitOr: ((targetData bitAnd: bits9to11)  >> 8)).
	code byteAt: index 
		put: ((code byteAt: index) bitOr: (targetData bitAnd: 16rFF)). "bits 1-8 of targetdata"
)
patchPopAndJump: index <Integer> with: targetData <Integer> = (
	code byteAt: index - 1 
	      put: ((code byteAt: index - 1) bitOr: ((targetData bitAnd: 16r300)  >> 8)).
	code byteAt: index
		put: ((code byteAt: index) bitOr: (targetData bitAnd: 16rFF))
)
popAndJumpOn: bool <Boolean> by: offset <Integer>  = (
	| popAndJump <Integer> |
	assert:[offset < maxJump] message: 'Offset exceeds max jump'.
	assert:[offset >= 0] message: 'offset must not be negative'.
	decrementStackDepthBy: 1.
	popAndJump:: bool  ifTrue:[popAndLongJumpOnTrue] 
						ifFalse:[popAndLongJumpOnFalse].
	code byte: popAndJump + ((offset bitAnd: 16r300) bitShift: -8 ); 
	"bits 9-10 of offset"
	        byte: (offset bitAnd: 16rFF). "bits 1-8 of offset"
)
pushClosureOfArity: n <Integer> copying: m <Integer> length: s <Integer>  = (
"	143   10001111 llllkkkk jjjjjjjj iiiiiiii	Push Closure Num Copied llll Num Args kkkk BlockSize jjjjjjjjiiiiiiii"
	incrementStackDepthBy: 1.
	decrementStackDepthBy: m.
	assert:[ n >= 0 and: [n < 16]] 
	message: 'closure arity must be between 0 and 15'.
	assert:[ m >= 0 and: [m < 16]]
	message: 'm must be between 0 and 15'.
	code byte: pushClosure; byte: m*16 + n; byte: s >> 8; byte: (s bitAnd: 255)
)
pushEmptyArray: n <Integer> = (
"	138 	10001010 jkkkkkkk 				Push (Array new: kkkkkkk) (j = 0)"
	assert:[n < 128] message: 'Array size must be < 128'.
	incrementStackDepthBy: 1.
	code byte: pushArray; byte: n. "138; n"
)
pushExplicitOuterReceiver: n <Number> = (
   	incrementStackDepthBy: 1.
	assert:[n >= 0 and:[n <= 256]] message: 'Explicit outer - n out of range'.
   	code byte: outerSend; "139"
   		  byte: (literalIndexFor: n).	
)
pushFullArray: n <Integer> = (
"	138 	10001010 jkkkkkkk 	
			Pop kkkkkkk elements into: (Array new: kkkkkkk) (j = 1)"
	assert:[n < 128] message: 'Array size > 128'.
	decrementStackDepthBy: n.
	incrementStackDepthBy: 1.
	code byte: pushArray; byte: 128 + n. "138; 128 + n"
)
pushImplicitRcvr: sel <Symbol>  = (
    | selIndex <Byte> |
    selIndex:: literalIndexFor: sel.
    assert:[selIndex >= 0 and: [selIndex < 256]]
	message: 'implicit send selector index out of range'.
   incrementStackDepthBy: 1.
    code byte: pushImplicitReceiver; "127"
            byte: selIndex.
)
pushLiteralIndex: litIndex <Integer> = (
  assert:[litIndex < 256 and:[litIndex >= 0]].
  incrementStackDepthBy: 1.
  litIndex < 32 ifTrue:[
	code byte: pushLiteralConst + litIndex. 
	^self
	]. 
  litIndex < 64 ifTrue:[
	  code byte: extendedPush; byte:  litIndex + 128.
	^self
	]. 
  code byte: wide; byte: pushLit; byte:  litIndex.
)
pushMinusOneObj = (
	code byte: pushNibble.
	 incrementStackDepthBy: 1.
)
pushMixinClass = (
"The mixin class will be stored in the final literal -added after the end of the literal array"
	pushLiteralIndex: literalTable size + 1
)
pushOneObj = (
	code byte: pushOne.
	 incrementStackDepthBy: 1.
)
pushRemoteTemporary: n <Integer> at: j <Integer>
 = (
"	140 	10001100 kkkkkkkk jjjjjjjj 		
				Push Temp At kkkkkkkk In Temp Vector At: jjjjjjjj"
      incrementStackDepthBy: 1.
	code byte: pushRemoteTemp; byte: n; byte: j. "140; n; j"
)
pushThisContext = (
      incrementStackDepthBy: 1.
	code byte: pushActiveContext
)
pushTwoObj = (
	code byte: pushTwo.
	 incrementStackDepthBy: 1.
)
pushZeroObj = (
	code byte: pushZero.
	 incrementStackDepthBy: 1.
)
returnBoolFalse = (
    code byte: returnFalse.
)
returnBoolTrue = (
    code byte: returnTrue.
)
returnFromBlock = (
    code byte: blockReturn.
    decrementStackDepthBy: 1.
)
returnNilObj = (
    code byte: returnNil.
)
returnObject = (
    code byte: return.
    decrementStackDepthBy: 1.
)
returnSelf = (
    code byte: returnReceiver.
)
storeAndPopRemoteTemporary: n <Integer> at: j <Integer>
 = (
"	142 	10001110 kkkkkkkk jjjjjjjj 		
				Pop and Store Temp At kkkkkkkk In Temp Vector At: jjjjjjjj"
	decrementStackDepthBy: 1.
	code byte: storeAndPopRemoteTemp; byte: n; byte: j. "142; n; j"
)
storeInstanceVariable: offset <Integer>
 = (
     	assert:[offset >= 0 and:[offset < 254]]
	message: 'slot offset must be between 0 and 253'. 
     	offset <  64 ifTrue:[code byte: extendedStore; byte: offset. ^self]. "129; offset"
	code byte: wide; byte: store; byte: offset. "132; 160; offset"
)
storeRemoteTemporary: n <Integer> at: j <Integer>
 = (
"	141 	10001101 kkkkkkkk jjjjjjjj 		
				Store Temp At kkkkkkkk In Temp Vector At: jjjjjjjj"
	code byte: storeRemoteTemp; byte: n; byte: j. "141; n; j"
)
storeTemporary: n <Integer>
 = (
	assert: [ n >= 0 and:[n <64] ] 
	message: 'Loca l var index must be between 0 and 63'.
	code byte: extendedStore; byte: 64+n. "129; 64+n"
))
class DebugInfo = (
"Debugger information."|
	private sourceMapping <MutableMap[Integer, Interval]> = Dictionary new.
	localVariables <MutableList[LocalVariableDebugInfo]> = OrderedCollection new.
|)
('as yet unclassified'
addInfoForLocal: varInfo <SemanticVarDecl> = (

	| info |
	info: LocalVariableDebugInfo new.
	info name: varInfo data name.
	info zeroOriginOffset: varInfo offset.
	info	remoteVector: nil.
	info contextDepth: contextDepth.
	^localVariables addLast: info.
)
addInfoForRemote: varInfo <SemanticVarDecl> in: remoteVarInfo <SemanticVarDecl> = (

	| info |
	info: LocalVariableDebugInfo new.
	info name: varInfo data name.
	info zeroOriginOffset: varInfo offset.
	info	remoteVector: remoteVarInfo data name.
	info contextDepth: contextDepth.
	^localVariables addLast: info.
)
mapPC: pc <Integer> to: src <interval> = (
	sourceMapping at: pc put: src
)
mapperForContext: ctxt = (
	^DebugMapper forContext: ctxt usingDebugInfo: self.
)
sourceMap ^ <SortedList[Association[Integer, Interval]]> = (
	| assocs <List[Association[Integer, Interval]]> |
	assocs:: sourceMapping associations.
	^(SortedList 
		new: assocs size 
		sortBlock:[:a <Association[Integer, Interval]> :b <Association[Integer, Interval]> | 
			a key < b key
			]) addAll: assocs; yourself
))
class DebugMapper forContext: ctxt usingDebugInfo: dbgInfo = (
""|
	context <MethodContext> = ctxt.
	debugInfo <DebugInfo> = dbgInfo.
	myDepth <Integer> = self depthOfContext: ctxt.
|)
('as yet unclassified'
astForContextAtDepth: targetDepth <Integer> ^<AST> = (
	|
	returnContext
	|
	myDepth >= targetDepth ifFalse: [deny].
	
	returnContext:: NormalSendAST new
		recv: hereNode;
		msg: (MessageAST new
			sel: #'@context';
			args: {}).
		
	(myDepth - targetDepth) timesRepeat: [
		returnContext:: NormalSendAST new
			recv: (NormalSendAST new
				recv: returnContext;
				msg: (MessageAST new 
					sel: #closure;
					args: {}));
			msg: (MessageAST new 
				sel: #outerContext;
				args: {})].
	^returnContext	
)
contextAtDepth: targetDepth <Integer> ^<MethodContext> = (
	|
	returnContext
	|
	myDepth >= targetDepth ifFalse: [deny].
	
	returnContext: context.
	(myDepth - targetDepth) 
		timesRepeat: [returnContext: returnContext closure outerContext].
	^returnContext	
)
depthOfContext: ctxt <MethodContext> ^<Integer>= (
	^ctxt closure isNil 
		ifTrue: [0 "method"] 
		ifFalse: [1 + (depthOfContext: ctxt closure outerContext)]
)
getValueOf: varName <Symbol> ^<Object> = (
	| info |
	info:: mostLocalInfoFor: varName.
	
	^info remoteVector isNil
		ifTrue:  [(contextAtDepth: info contextDepth) tempAt: info zeroOriginOffset + 1]
		ifFalse: [(getValueOf: info remoteVector) at: info zeroOriginOffset + 1]
)
getterAstFor: varName <Symbol> ^<SendAST> = (
	| info |
	info:: mostLocalInfoFor: varName.
	
	^info remoteVector isNil
		ifTrue:  [^NormalSendAST new 
			recv: (astForContextAtDepth: info contextDepth);
			msg: (MessageAST new
				sel: #tempAt:;
				args: {NumberAST new val: info zeroOriginOffset + 1})]
		ifFalse: [^NormalSendAST new
			recv: (getterAstFor: info remoteVector);
			msg: (MessageAST new
				sel: #at:;
				args: {NumberAST new val: info zeroOriginOffset + 1})]
)
localNames = (

	| names |
	names: OrderedCollection new.

	debugInfo localVariables do: [:info |
		(info validPCRange includes: pc) & info isSynthetic not ifTrue: [
			names include: info name ]].
	^names
)
mostLocalInfoFor: varName <Symbol> ^<LocalVarDebugInfo> = (
	
	| bestInfo |
	debugInfo localVariables do: [:info |
		(info name = varName and: [info validPCRange includes: pc]) ifTrue: [
			(bestInfo isNil or: [info contextDepth > bestInfo contextDepth]) ifTrue: [
				bestInfo:: info]]].
	bestInfo notNil ifFalse: [deny].
	^bestInfo
)
pc = (
	^context pc
)
setterAstFor: varName <Symbol> putting: newVal <AST> ^<SendAST> = (
	| info |
	info:: mostLocalInfoFor: varName.
	
	^info remoteVector isNil
		ifTrue:  [^NormalSendAST new 
			recv: (astForContextAtDepth: info contextDepth);
			msg: (MessageAST new
				sel: #tempAt:put:;
				args: {
					NumberAST new val: info zeroOriginOffset + 1.
					newVal})]
		ifFalse: [^NormalSendAST new
			recv: (getterAstFor: info remoteVector);
			msg: (MessageAST new
				sel: #at:put:;
				args: {NumberAST new val: info zeroOriginOffset + 1.
					newVal})]
))
class LocalVariableDebugInfo = (
"Debugger information for a local."|
      name <Symbol>
	validPCRange <Interval>
	zeroOriginOffset <Integer> "in remoteVector if not nil, otherwise in context"
	remoteVector <Symbol | nil>
	contextDepth <Integer> "0 = method, 1 = closure, 2 = nested closure, ... "
	
|)
('as yet unclassified'
isSynthetic ^<Boolean> = (
	"remoteVector or setter temp: debugger will not want to report these"
	^name includes: $@
))
class PopAndStoreVisitor generator: gen = StoreVisitor generator: gen (
"A visitor for issuing pop-and-store instructions. In some situations, one does not want to keep the result of a store on the operand stack, and this visitor is used in those cases. This allows us to take advantage o fthe dedicated instructions for op and store, rather than doing a store and then an explicit pop")
('as yet unclassified'
temporaryNode: node <TemporaryVariableAST> = (
	(isRemote: node) ifFalse:[
		"('direct storeAndPop ', node name) out."
		cgen storeAndPopTemporary: (indexOfVar: node).
	] ifTrue:[
		"('remote storeAndPop ', node name) out."
		cgen storeAndPopRemoteTemporary: (indexOfVar: node)
			at: (indexOfVar: (vectorOf: node))
	]
))
class StoreVisitor generator: gen = (| cgen = gen. |)
('node traversal'
parameterNode: node <ParameterAST>
 = (
	halt. "an error - cannot store into a parameter"
)
receiverNode: node <ReceiverAST>
 = (
	halt. "an error - cannot store into the receiver"
)
superVarNode: node <SuperVarAST>
 = (
	halt. "an error - cannot store into super"
)
temporaryNode: node <TemporaryVariableAST> = (
	(isRemote: node) ifFalse:[
		"('direct store ', node name) out."
		cgen storeTemporary: (indexOfVar: node).
	] ifTrue:[
		"('remote store ', node name) out."
		cgen storeRemoteTemporary: (indexOfVar: node)
			at: (indexOfVar: (vectorOf: node))
	]
))'as yet unclassified'
addDebugInfo: sourceInterval <Interval> = (

	debugInfo mapPC: pc to: sourceInterval
)
addLocalVar: v <VarDeclAST> = (
| i <Integer> localVariableDebugInfo |
	(indexOfVar:v) isNil ifFalse: [^self]. "setterTemp is declared in each expansion of setter sends but we only need one --Ryan"

	i:: nextOffset.
	
	localVariableDebugInfo:: addVar: v at: i.
	"(v name , ' will be at ', i printString) out."

	cgen maxLocals: (cgen maxLocals max: i+1).
	
	"cgen maxLocals out."
	^ localVariableDebugInfo
)
addVar: v <VarDeclAST> at: i <Integer> = (

	(currentScope at: v name) offset: i.
	^ debugInfo addInfoForLocal: (currentScope at: v name).
)
arrayNode: node <ArrayAST> = (
	node elements isNil ifTrue: [
		cgen pushEmptyArray: node size.
	] ifFalse: [
		node elements do: [:ea | ea apply: self].
		cgen pushFullArray: node size.
	].
)
blockLocalReturnNode: node <BlockLocalReturnAST> = (
"do a local return"
| shouldPop <Boolean>  |
  shouldPop:: statementStarting.
   statementStarting:: false.
   node expr apply: self.
   cgen returnFromBlock.	
   statementStarting:: shouldPop.
)
boolNode: node = (
  assert: [ node isBoolNode] message: 'Boolean node expected'.
  node val ifTrue:[cgen pushBoolTrue]
               ifFalse:[cgen pushBoolFalse].
)
cascadedSendNode: node <CascadedSendAST> = (
| isSuperSend <Boolean> shouldPop <Boolean> |

   shouldPop:: statementStarting.
   statementStarting:: false.
   isSuperSend:: false "node recv apply: SuperVarVisitor new".
"cascaded super sends need more work; not supported right now"
   node recv apply: self.
   isSuperSend ifTrue:[
       cascadeSuper: node prevSend depth: 1.
       generateSuperSend: node.
      ]
      ifFalse:[
         cascadeNormal: node prevSend depth:1.
         cgen popTos.
         node msg apply: self.
         generateSend: node.
      ].
   statementStarting:: shouldPop.
)
closureNode: node <ClosureAST> = (
	| blockPos <Integer> savedStackDepth <Integer> savedStackMax <Integer> |

	node copiedValues do: [:each | each apply: self].
		
	"do this after pushing copied values!"
	pushScope: (scopeMap at: node).  pushOffsetCounter. contextDepth: contextDepth + 1.

	cgen
		pushClosureOfArity: node parameters size
		copying: node copiedValues size
		length: 0 "needs patching".

	blockPos: cgen bci.
	savedStackDepth:: cgen currentStackDepth.	
	savedStackMax:: cgen stackMax.
	cgen stackMax: 0.
	 

	(node pushNilCount) timesRepeat: [cgen pushNilObj]. 
	"These nils establish the temp frame for temps other than params and copied values. They contribute to the operand stack size, obviating the need to directly include the number of local variables in the context size"
	node body apply: self.
	
	maxClosureContextSize:: 
		maxClosureContextSize max: (node parameters size + node copiedValues size + cgen stackMax).
	cgen currentStackDepth: savedStackDepth.
	cgen stackMax: savedStackMax.
	
	
	cgen patchJump: blockPos with: cgen bci - blockPos. "patch jump over block body"

	popScope. popOffsetCounter. contextDepth: contextDepth - 1.
)
contextNode: node = (
  assert: [ node isContextNode ] message: 'Context expected'.
  cgen pushThisContext.
)
currentMethod ^ <SemanticMethod> = (
	^currentScope at: #'`currentMethod'
)
currentScope ^ <Scope> = (
	^scopeStack last
)
doReturnBool: b <Boolean> = (
"decide whether to do an NLR or not"
  b ifTrue:[cgen returnBoolTrue] ifFalse:[cgen returnBoolFalse].
)
doReturnNil = (
"decide whether to do an NLR or not"
  cgen returnNilObj.
)
doReturnSelf = (
"decide whether to do an NLR or not"
  cgen returnSelf.
)
explicitOuterReceiverNode: aNode <ExplicitOuterReceiverAST> = (
	cgen pushExplicitOuterReceiver: aNode depth.
)
generateSuperSend: node <SendAST> = (
  node msg apply: self.

  cgen superSend: node msg sel noOfArgs: node msg args size.
  addDebugInfo:  (node start to: node msg end).
)
implicitSendNode: node <ImplicitRcvrSendNode> = (
| shouldPop <Boolean>  |
  shouldPop:: statementStarting.
  statementStarting:: false.
  cgen pushImplicitRcvr: node msg sel.
  node msg apply: self.
  cgen normalSend: node msg sel noOfArgs: node msg args size.
  addDebugInfo:  (node msg start to: node msg end).
  statementStarting:: shouldPop.
)
isRemote: node ^ <Boolean> = (
	^(currentScope at: node name asSymbol) remote
)
literalArray ^  <Array[Character | Number | String | Symbol]> = (
	|  literals <Array[Character | Number | String  Symbol]> |
	   literals:: Array new: literalTable size.
	   literalTable keysAndValuesDo:[:k : v | literals at: v + 1 put: k].
	   ^literals
)
mixinClassNode: node  = (
	cgen pushMixinClass.
)
nextOffset = (
	|  next |
	next:: offsetStack removeLast.
	offsetStack addLast: next + 1.
	^next
)
nilNode: node = (
  assert: [ node isNilNode ] message: 'Nil node expected'.
  cgen pushNilObj.
)
numberNode: node <NumberAST>  = (
	assert:[node isNumberNode] message: 'Number node expected'.
	cgen pushLiteral: node val.
)
pc = (
	^cgen code compiledMethodSize + 1
)
popAndStoreInto: v <VarDeclAST> = (
   v apply: popAndStoreVisitor. 
)
popOffsetCounter = (
	offsetStack removeLast.
)
popScope ^ <Scope> = (
  ^scopeStack removeLast
)
processLiteralMessagesOf: node <MethodAST> = (

	| pragmas |
	pragmas: OrderedCollection new.

	node body literalMessages ifNotNil: [:bodyLitMessages |
		bodyLitMessages do: [:messageAST |
			pragmas add: (Pragma
				keyword: messageAST sel
				arguments: (messageAST args collect: 
					[:symbolAST | symbolAST val]) asArray)
		].
	].

	cgen code pragmas: pragmas.
)
pushOffsetCounter = (
	offsetStack addLast: 0.
)
pushScope: s <Scope>= (
 scopeStack addLast: s
)
returnStatNode: node <ReturnStatAST> = (
| shouldPop <Boolean>  |
   assert:[node isReturnStatNode] message: 'Return node expected'.
  shouldPop:: statementStarting.
"if expr is self, true, false or nil do something special"
   (node expr isReceiverNode) ifTrue:[^doReturnSelf].
   (node expr isBoolNode) ifTrue:[^doReturnBool: node expr val].
   (node expr isNilNode) ifTrue:[^doReturnNil].
"maybe handle -1, 0, 1, 2 as well?"
   statementStarting:: false.
   node expr apply: self.
   doReturn.
   statementStarting:: shouldPop.
)
setup = (
	cgen:: CodeGenerator new.
  	storeVisitor:: StoreVisitor generator: cgen.  
  	debugInfo:: DebugInfo new.
	contextDepth:: 0.
)
slotsPerMethod ^ <Integer> = (
	^cgen slotsPerMethod "must expose this to higher levels of compiler so synthetic methods can be built correctly"
)
statementEnd = (
	"We must ensure that the operand stack is empty when a method terminates. Statements can leave unused results on the stack. Therefore, at the end of a statement we want to pop the stack back to its original depth before the statement started its baseline depth. This is not aways 0.  Blocks can occur in the midst of an expression, and have a non-zero baseline."
	cgen ensureBaselineStackDepth.
	"statementBaselineStackDepth:: cgen currentStackDepth."
	 "statementStarting:: true" "set up for next statement"
)
stringNode: node <StringAST>  = (
	assert:[node isStringNode] message: 'String node expected'.
	cgen pushLiteral: node val.
)
symbolNode: node <SymbolAST>  = (
	assert:[node isSymbolNode] message: 'Symbol node expected'.
	cgen pushLiteral: node val.
)'node traversal'
assignmentNode: node <AssignmentAST> = (

| i <Integer>  shouldPop <Boolean> |
	assert: [ node isAssignmentNode] message: 'Assignment node expected'.
	shouldPop:: statementStarting.
	statementStarting:: false. 
	node expr apply: self.
      shouldPop ifTrue:[popAndStoreInto: node var] 
			    ifFalse:[storeInto: node var] .
	statementStarting:: shouldPop.
	addDebugInfo: (node var start to: node expr end).
)
charNode: node <CharAST> = (
  "add literal char to literal table"
  cgen pushLiteral: node val
)
codeBodyNode: node <CodeBodyAST> = (
	|
	stmtSize <Integer>
	i <Integer>
	shouldPop <Boolean>
	noOfLocals <Integer> 
	j <Integer>
	depth <Integer>
	localVariableDebugInfos
	startPC
	validPCRange
	|

	"This could be a method body, a closure body, part of an inlined block, or a setter send.  Each method body and closure body needs to have separate indexing for temps because their activations will be separate MethodContexts.  Inlined blocks and setter sends should continue to use the same indexing as their enclosing method or closure.  To accomplish this, we use a stack of counters."
	
	localVariableDebugInfos:: OrderedCollection new.
	startPC:: pc.
	
	localVariableDebugInfos addAll:
		(node parameters collect: [:p | addLocalVar: p]).
		
	"Copied values are included at the beginning of temporaries thanks to the Rewriter."
		
	node temporaries do: [:t | 
		| 	varInfo <SemanticVarDecl> remoteVarInfo  <SemanticVarDecl>  |
		varInfo:: currentScope at: t name.
		varInfo remote 
			ifFalse: [localVariableDebugInfos add: (addLocalVar: t)]
			ifTrue:[ 
				remoteVarInfo::  currentScope at: varInfo remoteVector name.
				localVariableDebugInfos add:
					(debugInfo addInfoForRemote: varInfo in: remoteVarInfo)]].

   stmtSize:: node statements size.
   shouldPop:: statementStarting.
   i:: 1.
   depth:: statementBaselineStackDepth.
   statementBaselineStackDepth::  cgen currentStackDepth.
   node statements do:[:s | 
	i < stmtSize 
			ifTrue:[statementStarting:: true] 
			ifFalse:[statementStarting:: shouldPop].
	s apply: self.
	statementStarting ifTrue:[statementEnd].
	i:: i + 1.
	].
  validPCRange:: startPC to: pc.
  localVariableDebugInfos do: [:each | each validPCRange: validPCRange].
  statementBaselineStackDepth::  depth.
)
ifNode: node <IfAST> = (
| ifPos <Integer>  shouldPop <Boolean> endThen <Integer> depth <Integer> thenDepth <Integer> |
"issues: utilizing short jumps; nested blocks and popping"
  shouldPop:: statementStarting.
  statementStarting:: false. 
  node cond apply: self.
  cgen popAndJumpOn: node ifTrue not by: 0. "jump to else (but needs patching)"
  statementStarting:: shouldPop.
  ifPos:: cgen bci. "remember patch address"
  depth:: cgen currentStackDepth.
  assert:[node then isBlockNode and:[node then parameters isEmpty]]
	message: 'Nullary block expected for then clause'.
  pushScope:: scopeMap at: node then body.
  node then body apply: self.
  thenDepth: cgen currentStackDepth.
  popScope.
  node else isNil ifTrue:[endThen:: cgen bci.]
	ifFalse:[
		assert:[node else isBlockNode and:[node else parameters isEmpty]]
			message: 'Nullary block expected for else clause'.
		cgen currentStackDepth: depth.
		cgen jumpBy: 0.
		"need jump over else segment (but needs patching)"
		endThen:: cgen bci.
		pushScope:: scopeMap at: node else body.
		node else body apply: self.
		popScope.
		cgen patchJump: endThen with: cgen bci - endThen.
		"patch jump over else"
		].
	cgen patchPopAndJump: ifPos with: endThen - ifPos.
	"patch the jump after the test so it comes to end of the then block"
	cgen currentStackDepth: (thenDepth max: cgen currentStackDepth).
	"if one of the branches did a non-local return, the operand stack depth will differ between them. The smaller is the NLR, which doesn't matter, as control will leave the method, so we keep the larger one."
	shouldPop ifFalse:[
			cgen currentStackDepth: (cgen currentStackDepth max: depth+1)
			].
	" If shouldPop is false we  want to assume the if left a result on the stack, even if it did not because both branches ended in an NLR"
	statementStarting:: shouldPop.
)
loopNode: node <LoopAST> = (
| topOfLoop <Integer>  shouldPop <Boolean> whilePos <Integer> depth <Integer> skope <Scope> |
  shouldPop:: statementStarting.
  statementStarting:: false. 
  node body isNil ifFalse:[pushScope:: scopeMap at: node body].

  depth:: cgen currentStackDepth.
  node prologue apply: self.

  [cgen currentStackDepth > depth] whileTrue:[cgen popTos].
 "Ensure prologue maintains stack depth to prevent overflowing it during say nested loops."
  topOfLoop:: cgen bci + 1.
  skope:: scopeMap at: node cond ifAbsent:[nil].
  skope isNil ifFalse:[pushScope:: skope]. 
  node cond  apply: self. 
  skope isNil ifFalse:[popScope].
  cgen popAndJumpOn: node isWhileTrue not by: 0. 
  statementStarting:: shouldPop.
  whilePos:: cgen bci. "remember patch address"
  node body isNil ifFalse:[
	node body apply: self.
	[cgen currentStackDepth > depth] whileTrue:[cgen popTos].
 "Ensure loop body maintains stack depth to prevent overflowing it during loop execution."
	popScope.
	].
  cgen jumpBy: topOfLoop - cgen bci - 3. "jump to top of loop"
  cgen patchPopAndJump: whilePos with: cgen bci - whilePos.
 "patch the jump after the test so it comes to end of the then block"
  cgen pushNilObj. "result of loop message"
  statementStarting:: shouldPop.
)
messageNode: m <MessageAST> = (
  m args do:[:a <ExpressionAST> | a apply: self].
)
messagePatternNode: node <MessagePatternAST> = (
  node parameters do:[:p | addLocalVar: p]
)
methodNode: node <MethodAST> = (
"create a compiled method, whose body is the result of compiling the node's body."
| argC <integer> |

   setup.
   pushScope: (scopeMap at: node).  pushOffsetCounter.
   currentScope at: #'`currentMethod' put: (SemanticMethod decl: node).
   argC:: node pattern parameters size.
   cgen maxLocals: 0.
  " node pattern apply: self. Parems will be added by the code body"
   cgen methodName: node pattern selector; argCount: argC; literals: literalArray.
   node body apply: self.
   cgen code debugInfo: debugInfo. "set debug info"
   processLiteralMessagesOf: node.
   currentMethod frameSize: cgen maxLocals.
   popScope. popOffsetCounter.
   result:: cgen close.
)
normalSendNode: node <NormalSendAST> = (
| shouldPop <Boolean>  |
   assert: [ node isNormalSendNode] message: 'NormalSendNode expected'.
   shouldPop:: statementStarting.
   statementStarting:: false.
   node recv apply: self.
   node msg apply: self.
   generateSend: node.
   statementStarting:: shouldPop.
)
parameterNode: node <ParameterAST> = (
	cgen pushTemporary: (indexOfVar: node).
)
receiverNode: node = (
  assert: [ node isReceiverNode] message: 'Receiver node expected'.
  cgen pushSelf.
)
returnInstVarMethodNode: node <ReturnInstVarMethodAST>
  ^ <LowLevelMethodMirror> = (
  "create an empty compiled method with appropriate flags"
   result:: LowLevelMethodMirror new selector: node selector; 
			returnOnlyField: node index source: currentMethodSource.
   ^result
)
returnSelfMethodNode: node <ReturnSelfMethodAST> ^ <LowLevelMethodMirror>  = (
  "create an empty compiled method with appropriate flags"
   result:: LowLevelMethodMirror new selector: node selector; 
                                                         returnOnlySelf: currentMethodSource.
   ^result
)
superSendNode: node <SuperSendNode> = (
| shouldPop <Boolean>  |
  shouldPop:: statementStarting.
  cgen pushSelf.
  generateSuperSend: node.
  statementStarting:: shouldPop.
)
superVarNode: node <SuperVarNode>  = (
"Not used right now;  when the VM supports dynamic super sends, that will change"
  cgen pushSelf.
)
temporaryNode: node <TemporaryVariableAST> = (
	(isRemote: node) ifFalse: [
		"('direct read ', node name) out."
		cgen pushTemporary: (indexOfVar: node).
	] ifTrue: [
		"('remote read ', node name) out."
		cgen pushRemoteTemporary: (indexOfVar: node) at: (indexOfVar: (vectorOf: node))
	].
)'private'
cascadeNormal: node <SendAST> depth: n <Integer> = (
  node isCascadedSendNode 
     ifFalse:[cgen dup"n timesRepeat:[cgen dup]"]
     ifTrue:[cascadeNormal: node prevSend depth: n + 1].
   node msg apply: self.
   generateSend: node.
   cgen popTos.
   cgen dup.
)
cascadeSuper: node <SendAST> depth: n <Integer> = (
  node isCascadedSendNode 
     ifFalse:[n timesRepeat:[cgen dup]]
     ifTrue:[cascadeSuper: node prevSend depth: n + 1].
   generateSuperSend: node.
   cgen popTos.
)
currentMethodSource ^ <String> = (
  ^outer Compiler input contents
)
doReturn = (
"decide whether to do an NLR or not"
	cgen returnObject.
)
generateSend: node <SendNode>  = (
"build debug info:"

   cgen normalSend: node msg sel noOfArgs: node msg args size.
    addDebugInfo:  (node start to: node msg end).
)
indexOfVar: v <VarDeclAST> ^ <Integer> = (
   ^(currentScope at: v name asSymbol) offset
)
storeInto: v <VarDeclAST> = (
   v apply: storeVisitor. 
)
vectorOf: v <VarDeclAST> ^ <VarDelcAST> = (
   ^(currentScope at: v name asSymbol) remoteVector
))
class MixinClassNode = AST (
"A special AST node to represent access to the mixin class stored in a method. Recall that outer classes have accessors for their nested classes; these lazily manufacture the class, cache it, and later access the cached value.

To do this, the accessor must apply the mixin of the nested class to the superclass. Said mixin is nested within the mixin that defined the accessor (the mixin of the outer class declaration), and can be accessed via the outer mixin's metadata slot.

The issue then is how to get the outer mixin.  In Squeak, for example, the outer mixin is stored in the last literal of every one of its methods (what Squeak calls the ''methodClass''). To reach it, we must push the last literal of the method on to the operand stack.

However, the accessor method is not specified at the byte code level; that would be tedious, and also tied to a specific implementation (the Squeak byte codes). It is much better to specify the method via an AST that is compiled (we could use source code, but the use of synthetic names makes that problematic). 

In order to specify access to the mixin in the accessor method, we need to provide an AST that corresponds to the idea of ''accessing my mixin''. This is what this class does.

The rewriter leaves this node untouched, while the lower layers of the compiler that deal with code generation produce suitable code for it - e.g., Squeak byte codes.

")
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool mixinClassNode: self
)
isExpressionNode = (
	^true	
))
class Rewriter = ASTTool (
"A visitor that rewrites the AST into a form more suitable for compilation to the Squeak VM.

It may be possible to combine the pass that constructs the scopes with the rewriting pass, but this may be messy once we start inlining blocks etc."| 
	scope <Scope> 
	scopeStack <OrderedCollection[Scope]> = OrderedCollection new.
	|)
(
class ArrayAST = AST (
"To use pushFullArray/pushEmptyArray"|
	elements <OrderedCollection[AST] | nil>
	size <Integer>
|)
('as yet unclassified'
apply: tool = (
	^tool arrayNode: self.
)
isExpressionNode = (
	^true
))
class BlockLocalReturnAST expression: x start: s end: e = AST (
"This class represents a 'local return' (LR) -  a return from a block to its caller, as opposed to the caller of its enclosing method (a 'non-local return' or NLR).

An actual return statement in a block means an NLR; an LR is implicit in the source language, and occurs on the last statement of the block, unless that statement is a true return (NLR).  However, the back end of the compiler requires that this information be represented explicitly. This node does that."|
 expr <ExpressionAST> = x.
|start: s. end: e)
('as yet unclassified'
apply: aTool <ASTTool>  = (
	^aTool blockLocalReturnNode: self
))
class BoolAST withValue: aBool <Boolean> start: s end: e = VariableAST (
""| val = aBool. |start: s. end: e)
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool boolNode: self
)
isBoolNode = (
	^true
)
name = (
	^val printString asSymbol
))
class ClosureAST for: block withCopiedValues: cv = BlockAST (|
	copiedValues = cv.
	pushNilCount ::= 0.
|body: block body)
('as yet unclassified'
apply: aTool = (
	^aTool closureNode: self
))
class ContextAST = VariableAST (
"Represents uses of thisContext. I expect these to be restricted in future versions. Currently, we use it for outer sends and super sends")
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool contextNode: self
)
isContextNode = (
	^true
)
name = (
	^#thisContext
)
printOn: strm <CharOutputStream>
 = (

	super printOn: strm.
	strm nextPutAll: '(thisContext)'
))
class ExplicitRecvrAST send: sym <Symbol> depth: d <Integer> = AST (
"Represents ats the receiver of an explicit outer send."|
	outerClassName <Symbol> = sym.
	depth <Integer> = d.
	selector <Symbol>
|)
('as yet unclassified'
apply: aTool <ASTTool> ^ <Self> = (
	^aTool explicitOuterReceiverNode: self
)
isExplicitRcvrNode ^ <Boolean> = (
	^true
)
isExpressionNode ^ <Boolean> = (
	^true
))
class FalseVisitor = SuperFalseVisitor (
"Extends the standard FalseVisitor with methods for dealing with the node types introduced by the rewriter..")
('as yet unclassified'
arrayNode: n = (
	^false
)
boolNode: node = (^false)
closureNode: node = (
	^false
)
contextNode: node = (^false)
explicitOuterReceiverNode: aNode <ExplicitOuterRcvrAST> ^ <Boolean> = (
	^false
)
ifNode: aNode <IfAST> ^ <Boolean> = (
	^false
)
implicitSendNode: aNode <ImplicitRcvrSendAST> ^ <Boolean> = (
	^false
)
loopNode: aNode <LoopAST> ^ <Boolean> = (
	^false
)
nilNode: node = (^false)
parameterNode: aNode <ParameterAST> ^ <Boolean> = (
	^false
)
receiverNode: aNode <ReceiverAST> ^ <Boolean> = (
	^false
)
returnInstVarMethodNode: aNode <ReturnInstVarMethodAST> ^ <Boolean> = (
	^false
)
returnSelfMethodNode: aNode <ReturnSelfMethodAST> ^ <Boolean> = (
	^false
)
superSendNode: aNode <SuperSendAST> ^ <Boolean> = (
	^false
)
superVarNode: aNode <SuperVarAST> ^ <Boolean> = (
	^false
)
temporaryNode: aNode <TemporaryVariableAST> ^ <Boolean> = (
	^false
)
variableNode: aNode = (
	^false
))
class IfAST if: expr <ExpressionAST> is: val  <Boolean> then: block1 <BlockAST> else: block2 <BlockAST> = AST (
""| 
  cond <ExpressionAST> = expr.
  ifTrue  <Boolean> = val.
  then <BlockAST> = block1.
  else <BlockAST> = block2.
  |assert: [expr isExpressionNode].
    assert: [block1 isBlockNode].
    assert: [block2 isNil or:[block2 isBlockNode]])
('as yet unclassified'
isExpressionNode ^ <boolean> = (
	^true
)'visiting'
apply: aTool <ASTTool>
 = (
    ^aTool ifNode: self
)) : ('as yet unclassified'
emptyBlock = (
	| b |
	b:: BlockAST new body: (CodeBodyAST new parameters: {}; temporaries: {}; statements: {NilAST new}).
	scopeMap at: b body put: nil.
	^b
)'public access'
if: expr <ExpressionAST> is: val <Boolean> then: block  <BlockAST> ^ <Instance>
 = (
  ^if: expr is: val then: block else: emptyBlock
)
isIfNode ^ <Boolean>
 = (
    ^ true
))
class ImplicitRecvrSendAST send: aMsg <MessageAST> = SendAST send: aMsg (
"
Represent a send of a message with an implicit receiver (aka a here send).
")
('as yet unclassified'
apply: aTool <ASTTool> ^ <Self> = (
	^aTool implicitSendNode: self
)
isExpressionNode ^ <boolean> = (
	^true
)
isImplicitSendNode = (
	^true
)
recv ^ <VarDeclAST> = (
  ^ assert:[false] message: 'There is no receiver node. It is implicit'
))
class LoopAST = AST (
"This node represents a while loop, and its various routines act as constructors that map from various looping constructs into a while loop. In some cases (like whileTrue:) this is trivial, in others it is a bit more involved.

The general form of the loop is:

prologue;
while (cond = whileTrue) { body}

Ergo, prologue represents some code that sets up the loop (e.g., the initialization of the loop variable when encoding a for loop into a while loop);
whileTrue is true if the loop continues as long as the test condition holds, and false if the loop runs as long as the condition does not hold;
cond is the aforementiond test condition; body is the body of the loop."| 
isWhileTrue <Boolean> 
prologue <CodeBodyAST> ::= 
	CodeBodyAST new 
			parameters: OrderedCollection new;
			temporaries: OrderedCollection new;
			statements: OrderedCollection new.
cond <CodeBodyAST> 
body <CodeBodyAST>  |)
('as yet unclassified'
isExpressionNode ^ <boolean> = (
	^true
)'public access'
apply: aTool <ASTTool>
 = (
    ^aTool loopNode: self
)
do: n <Integer> timesRepeat: block <BlockAST>
 = (
	|
	skope	<Scope>
	loopVarName <Symbol>
	var <ParameterAST>
	|
	skope:: scopeMap at: block body.

	"introduce counter variable"
	loopVarName:: '.i' asSymbol.
	var:: (ParameterAST name: loopVarName type: nil) start: block start; end: block end.	
	skope at: loopVarName put: (SemanticVarDecl decl:{var. 0}) ifThere: [ halt ].
	assert:[block body parameters isEmpty].
	block body parameters add: var.

	"translate n timesRepeat: [blockBody]  into 1 to: n do: [ :.i | blockBody]"
	from: (NumberAST new val: 1; start: block start; end: block end) to: n do: block
)
from: first <AST> to: last <AST> by: step <AST> do: block <BlockAST>
 = (
	|
	blockScope		<Scope>	
	counterVar		<TemporaryAST>
	counter		<TemporaryVariableAST>
	limitNeeded		<Boolean>
	limitName		<Symbol>
	limitVar		<TemporaryAST>
	limit			<LiteralAST | VariableAST>
	condSel			<Symbol>
	condArg		<MutableList[ExpressionAST]>
	condExpr		<ExpressionAST>
	condBody		<CodeBodyAST>
	condStats		<MutableList[StatementAST]>
	incArg			<MutableList[ExpressionAST]>
	incExpr			<ExpressionAST>
	incStat			<StatementAST>
	|
	"preliminaries"
	assert: [ step isNumberNode and:[step val isInteger] ].
	assert: [ block isBlockNode ].
	blockScope:: scopeMap at: block body.

	"loop counter (= block parameter)"
	counterVar:: TemporaryAST name: block parameters removeFirst name type: nil.
	counter:: TemporaryVariableAST name:  counterVar name  start: block start end: block end.
	
	"introduce counter limit variable if needed"
	(limitNeeded:: last isLiteralNode not)
		ifFalse: [
			"no limit variable needed - use last directly since there's no computation involved"
			limit:: last
		]
		ifTrue: [
			limitName:: '.limit' asSymbol.
			limitVar:: TemporaryAST name: limitName type: nil.
			limitVar start: block start; end: block end.
			prologue temporaries add: limitVar.
			blockScope at: limitName put: (SemanticVarDecl decl: {limitVar. 0}) ifThere: [ assert:[false] ].
			limit:: TemporaryVariableAST name: limitName start: block start end: block end.
		].
	
	"setup loop condition => introduce condition block for whileTrue: loop"
	condSel::
		step val < 0
			ifTrue: [ #<= ]
			ifFalse: [ #>= ].
	condArg:: OrderedCollection new add: counter ; yourself.
	condExpr:: NormalSendAST new to: limit send: (MessageAST new send: condSel with: condArg).
	"limit <= counter OR limit >= counter"
	condStats:: OrderedCollection new add: condExpr ; yourself.
	condBody::
		CodeBodyAST new
			parameters: OrderedCollection new;
			temporaries: OrderedCollection new;
			statements: condStats;
			start: block start; end: block end.

	"add counter increment to loop body"
	incArg:: OrderedCollection new add: counter ; yourself.
	incExpr:: NormalSendAST new to: step send: (MessageAST new send: #+ with: incArg).
	incExpr start: block start; end: block end.
	"step + counter"
	incStat:: AssignmentAST new to: counter assign: incExpr. 
	incStat start: block start; end: block end.
	"counter := step + counter"
	block body statements add: incStat.

	"setup prologue"
	prologue temporaries add: counterVar.
	prologue statements add: (AssignmentAST new to: counter assign: first).
	"counter := first"
	limitNeeded ifTrue: [
		"initialize limit variable - note that this must be done *after* setting up the counter because of possible side effects"
		prologue statements add: (AssignmentAST new to: limit assign: last). ".limit := last"
	].
	
	"initialize loop instance variables"
	cond:: condBody.
	isWhileTrue:: true.
	body:: block body
)
from: first <AST> to: last <AST> do: block <BlockAST>
 = (
	from: first to: last by: (NumberAST new val: 1) do: block
)
repeat: block <BlockAST>
 = (
    assert: [block isBlockNode].
    cond:: block body.
    cond statements add: (BoolAST withValue: true start: cond end end: cond end).
    isWhileTrue:: true.
    body:: nil
)
while: b1 <BlockAST>  is: v <Boolean> do: b2 <BlockAST>
 = (
    assert: [b1 isBlockNode].
    assert: [b2 isBlockNode].
    cond:: b1 body.
    isWhileTrue:: v.
    body:: b2 body
)
while: v <Boolean> do: b <BlockAST>
 = (
    assert: [b isBlockNode].
    cond:: b body.
    isWhileTrue:: v.
    body:: nil
))
class NeedsCopyFinder for: codebody = ASTTraverser (
"This class will be renamed BlockBodyAnalyzer.
A closure needs to copy variables that are read but defined in the outer scope.  At the point of this anaylsis, indirection has already been added so there should be no reads to an order context and (if this block is nested) outer closures have already copied what they need, so outer reads should only be one level out.
"|
	depth ::= 0.
	
	shadowing = Dictionary new.
	needsToCopy = Set new.
	includesSetterSend ::= false.
	pushNilCount ::= 0.
|codebody apply: self.
	
	includesSetterSend ifTrue: [pushNilCount: pushNilCount + 1])
('as yet unclassified'
codeBodyNode: node <CodeBodyAST> = (
	depth:: depth + 1.	
	self commonCodeBodyNode: node.
	depth:: depth - 1.
)
commonCodeBodyNode: node = (

	node parameters do: [:each | self shadow: each name].
	node temporaries do: [:each | self shadow: each name].
		
	depth = 1 ifTrue: [pushNilCount: pushNilCount + node temporaries size].

	(codeBodySlotInitializers: node temporaries isSeq: node isSeq)
		do: [:each | each apply: self].
	node statements
		do: [:each | each apply: self].	
)
inlinedBlockNode: node <BlockAST> = (
	"Don't increase depth."
	self commonCodeBodyNode: node body
)
isShadowed: var <Symbol> ^<Boolean> = (
	^(shadowing at: var ifAbsent: [^false]) <= depth
)
normalSendNode: node <NormalSendAST> = (
	
	"temp reads and writes are here sends"
	(isHereNode: node recv) ifTrue: [^self processHereSend: node msg].
	
	(isInlineableSend: node) ifTrue: [^self processInlineableSend: node].
	
	super normalSendNode: node
)
processHereSend: aMsg <MessageAST> = (
	| binding <AST> |
	aMsg apply: self.  "Must come first.  If this is a setter for a temp, any args in the message are evaluated before the assignment."

	binding:: currentScope at: aMsg sel ifAbsent: [MessageAST new].
	binding isVarDeclNode ifTrue: [
		aMsg sel last = $: ifTrue:[
			"it is a temporary write"
			| varName |
			varName:: (aMsg sel asString copyUpToLast: $: ) asSymbol.
			self variableWrite: varName.
		] ifFalse:[
			"it is a parameter or temporary read"
			self variableRead: aMsg sel
		].
		^self
	].
	binding isDebugMappedLocalEntry ifTrue: [
		(aMsg sel last = $: 
			ifTrue:[binding setterAst: aMsg args first]
			ifFalse:[binding getterAst]) apply: self
	].
)
processInlineableSend: node <NormalSendAST> = (
|  
recv <AST> msg <MessageAST> sel <Symbol> nOfArgs <Integer> 
arg1 <AST> arg2 <AST> arg3 <AST> 
|
"Prepare arguments for inlined message sends"
recv:: node recv.
msg:: node msg.
sel:: node msg sel.
nOfArgs:: msg args size.
nOfArgs >= 1 ifTrue: [ arg1:: msg args at: 1 ].
nOfArgs  >= 2 ifTrue: [ arg2:: msg args at: 2 ].
nOfArgs  >= 3 ifTrue: [ arg3:: msg args at: 3 ].
 
"Hardwired ifTrue: / ifFalse: messages"
sel = #ifTrue: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #ifFalse: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #ifTrue:ifFalse: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. inlinedBlockNode: arg2. ^self].
sel = #ifFalse:ifTrue: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. inlinedBlockNode: arg2. ^self].
 
"Hardwired whileTrue: / whileFalse: messages"
sel = #whileTrue
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #whileFalse 
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #whileTrue:
	ifTrue: [inlinedBlockNode: recv. inlinedBlockNode: arg1. ^self].
sel = #whileFalse: 
	ifTrue: [inlinedBlockNode: recv. inlinedBlockNode: arg1. ^self].
 
"Hardwired repeat / timesRepeat: / to:do: / to:by:do: messages"
sel = #repeat  
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #timesRepeat:
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #to:do:
	ifTrue: [ depth = 1 ifTrue: [pushNilCount: pushNilCount + 2]. recv apply: self. arg1 apply: self. inlinedBlockNode: arg2. ^self].
sel = #to:by:do:  
	ifTrue: [ depth = 1 ifTrue: [pushNilCount: pushNilCount + 2]. recv apply: self. arg1 apply: self. arg2 apply: self. inlinedBlockNode: arg3. ^self].
	"The extra push nils are for the temps introduced by the loops, which this visitor would otherwise not see because we don't actually generate the LoopAST that would introduce them at this point.  Ugly."
	
assert: [false] message: 'Unexpected message for inlining'.
)
setterSendNode: node <SetterSendAST> = (
	
	"An overestimate, since 
	1) if this is a store to a local, no setter temp is required"
	depth = 1 ifTrue: [includesSetterSend:: true].
	
	self normalSendNode: node. "to do the here send processing"
)
shadow: var <Symbol> = (
	"('shadowing ' , var , ' at ', depth printString )out.
	"
	shadowing at: var ifPresent: [:e|] ifAbsentPut: [depth]
)
variableNode: node <VariableAST> = (
	assert: [{#'_here'. #self. #super. #outer. #true. #false. #nil. #thisContext} includes: node name]
)
variableRead: var <Symbol> = (
	
	(isShadowed: var) ifTrue: [^nil].
	
	(currentScope at: var) remote ifTrue: [
		^variableRead: (currentScope at: var) remoteVector name
	].

	needsToCopy add: var.
)
variableWrite: var <Symbol> = (
	
	(isShadowed: var) ifTrue: [^nil].

	(currentScope at: var) remote ifTrue: [
		^variableRead: (currentScope at: var) remoteVector name
	].

	assert: [false] message: var, ' should have been made indirect'.
))
class NeedsIndirectionFinder for: codebody = ASTTraverser (
"This class will be renamed CodyBodyAnalyzer.

A temp needs to be put in an indirection vector if
-it is written to in a nested closure
-it is written to its defining codebody after being read in a nested closure

Inlined blocks do not count as nested closures, though any temps defined in an inlined block that are read before written need to be nil'ed to maintain the illusion that they are closures (to be implemented later).



m = (
| a b var |
a:: [ var ].
b:: [ var: 0 ].
)"|
	depth ::= 0.
		
	shadowing = Dictionary new.
	needsIndirection ::= Set new.
	hasNestedRead = Set new.
	
	includesSetterSend ::= false.
|codebody apply: self.
	
	needsIndirection:: needsIndirection select: [:ea |
		in: codebody temporaries anySatisfy: [:t | ea = t name].
	])
('as yet unclassified'
codeBodyNode: node <CodeBodyAST> = (
	depth:: depth + 1.
	self commonCodeBodyNode: node.
	depth:: depth - 1.
)
commonCodeBodyNode: node = (

	depth > 1 ifTrue: [
		node parameters do: [:each | self shadow: each name].
		node temporaries do: [:each | self shadow: each name].
	].
	
	(codeBodySlotInitializers: node temporaries isSeq: node isSeq)
		do: [:each | each apply: self].
	node statements
		do: [:each | each apply: self].
)
inlinedBlockNode: node <BlockAST> = (
	"Don't increase depth."
	self commonCodeBodyNode: node body
)
isShadowed: var <Symbol> ^<Boolean> = (
	^(shadowing at: var ifAbsent: [^false]) <= depth
)
normalSendNode: node <NormalSendAST> = (
	
	"temp reads and writes are here sends"
	(isHereNode: node recv) ifTrue: [^self processHereSend: node msg].
	
	(isInlineableSend: node) ifTrue: [^self processInlineableSend: node].
	
	super normalSendNode: node
)
processHereSend: aMsg <MessageAST> = (
	| binding <AST> |
	aMsg apply: self.  "Must come first.  If this is a setter for a temp, any args in the message are evaluated before the assignment."

	binding:: currentScope at: aMsg sel ifAbsent: [MessageAST new].
	binding isVarDeclNode ifTrue: [
		aMsg sel last = $: ifTrue:[
			"it is a temporary write"
			| varName |
			varName:: (aMsg sel asString copyUpToLast: $: ) asSymbol.
			self variableWrite: varName.
		] ifFalse:[
			"it is a parameter or temporary read"
			self variableRead: aMsg sel
		].
		^self
	].
	binding isDebugMappedLocalEntry ifTrue: [
		(aMsg sel last = $: 
			ifTrue:[binding setterAst: aMsg args first]
			ifFalse:[binding getterAst]) apply: self
	].
)
processInlineableSend: node <NormalSendAST> = (
|  
recv <AST> msg <MessageAST> sel <Symbol> nOfArgs <Integer> 
arg1 <AST> arg2 <AST> arg3 <AST> 
|
"Prepare arguments for inlined message sends"
recv:: node recv.
msg:: node msg.
sel:: node msg sel.
nOfArgs:: msg args size.
nOfArgs >= 1 ifTrue: [ arg1:: msg args at: 1 ].
nOfArgs  >= 2 ifTrue: [ arg2:: msg args at: 2 ].
nOfArgs  >= 3 ifTrue: [ arg3:: msg args at: 3 ].
 
"Hardwired ifTrue: / ifFalse: messages"
sel = #ifTrue: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #ifFalse: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #ifTrue:ifFalse: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. inlinedBlockNode: arg2. ^self].
sel = #ifFalse:ifTrue: 
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. inlinedBlockNode: arg2. ^self].
 
"Hardwired whileTrue: / whileFalse: messages"
sel = #whileTrue
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #whileFalse 
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #whileTrue:
	ifTrue: [inlinedBlockNode: recv. inlinedBlockNode: arg1. ^self].
sel = #whileFalse: 
	ifTrue: [inlinedBlockNode: recv. inlinedBlockNode: arg1. ^self].
 
"Hardwired repeat / timesRepeat: / to:do: / to:by:do: messages"
sel = #repeat  
	ifTrue: [inlinedBlockNode: recv. ^self].
sel = #timesRepeat:
	ifTrue: [recv apply: self. inlinedBlockNode: arg1. ^self].
sel = #to:do:
	ifTrue: [recv apply: self. arg1 apply: self. inlinedBlockNode: arg2. ^self].
sel = #to:by:do:  
	ifTrue: [recv apply: self. arg1 apply: self. arg2 apply: self. inlinedBlockNode: arg3. ^self].
	
assert: [false] message: 'Unexpected message for inlining'.
)
returnStatNode: node <ReturnStatAST> = (
	node expr apply: self
)
setterSendNode: node <SetterSendAST> = (
	
	"An overestimate, since 
	1) if this is a store to a local, no setter temp is required"
	depth = 1 ifTrue: [includesSetterSend:: true].
	
	self normalSendNode: node. "to do the here send processing"
)
shadow: var <Symbol> = (
	"('shadowing ' , var , ' at ', depth printString )out.
	"
	shadowing at: var ifPresent: [:e|] ifAbsentPut: [depth]
)
variableNode: node <VariableAST> = (
	assert: [{#'_here'. #self. #super. #outer. #true. #false. #nil. #thisContext} includes: node name]
)
variableRead: var <Symbol> = (

	assert: [var isSymbol].

	(isShadowed: var) ifTrue: [^nil].

	depth > 1 ifTrue: [
		hasNestedRead add: var.
	].
)
variableWrite: var <Symbol> = (

	assert: [var isSymbol].

	(isShadowed: var) ifTrue: [^nil].
	
	"one being the code body that declaring the variable we're considering"
	depth > 1 ifTrue: [ 
		"this is a nested write, must indirect"
		needsIndirection add: var.
	] ifFalse: [
		(hasNestedRead includes: var) ifTrue: [ 
			"write after nested read, must indirect"
			needsIndirection add: var.
		].
	].

))
class NilAST = VariableAST (
"")
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool nilNode: self
)
isNilNode = (
	^true
)
name = (
	^#nil
))
class ParameterAST name: n type: t = VarDeclAST name: n type: t (
"")
('Unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool parameterDeclNode: self
)
printOn: strm <CharOutputStream>
 = (

	super printOn: strm.
	strm nextPutAll: '(', name, ')'
)'as yet unclassified'
variableClass ^ <ParameterVariableAST class> = (
	^ParameterVariableAST
))
class ParameterVariableAST name: n start: s end: e = VariableAST (
""name: n. start: s. end: e)
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool parameterNode: self
))
class ReceiverAST = VariableAST (
"")
('Unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool receiverNode: self
)
printOn: strm <CharOutputStream>
 = (

	super printOn: strm.
	strm nextPutAll: '(self)'
)'as yet unclassified'
isReceiverNode= (
	^true
)
name = (
	^#self
))
class ReturnSelfMethodAST selector: s <Symbol> var: v <ReceiverAST> = AST (
" This class represents a method with exactly one statement, which is a return
  of the receiver.  Since Squeak, like Smalltalk-80, optimizes this case
  by creating a special method without any bytecodes at all, we want to recognize it.
  The rewriter will replace MethodASTs representing such methods with instances
  of this class. The compiler will then process these nodes appropriately.
  "| var <ReceiverAST> = v.  selector <Symbol> = s.  |)
('visiting'
apply: tool <ASTTool> = (
  ^tool returnSelfMethodNode: self.
))
class SuperSendAST send: aMsg <MessageAST> = SendAST send: aMsg (
"This code is currently unused.  
Unlike Smalltalk, super calls in Newspeak cannot be statically bound.
Hence, we cannot use the Squeak VM's  super send byte codes. Currently, super sends are rewritten into a complex call structure by the rewriter, to ensure the correct binding of super.

When the Newspeak VM is modified to support dynamic binding of super sends, we will probably use this node and allied code,  which can easily be processed by the byte code compiler and code generator.")
('Unclassified'
apply: aTool <ASTTool> ^ <Self> = (
	^aTool superSendNode: self
)
recv ^ <SuperVarAST> = (
  ^SuperVarAST new
)'as yet unclassified'
isExpressionNode ^ <boolean> = (
	^true
)
isSuperSendNode = (
	^true
))
class SuperVarAST = VarDeclAST name: #super type: nil (
"")
('Unclassified'
apply: aTool <ASTTool> ^ <Self> = (
	^aTool superVarNode: self
))
class TemporaryAST name: n type: t = VarDeclAST name: n type: t (
"")
('Unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool temporaryDeclNode: self
)
printOn: strm <CharOutputStream>
 = (

	super printOn: strm.
	strm nextPutAll: '(', name, ')'
)'as yet unclassified'
isTemporaryAST ^ <Boolean> = (
	^true
)
variableClass ^ <TemporaryVariableAST class> = (
	^TemporaryVariableAST
))
class TemporaryVariableAST name: n start: s end: e = VariableAST (
"This node represents reference to a temporary variable."name: n.  start: s. end: e)
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool temporaryNode: self
))'as yet unclassified'
addLiteralConstant: s <Character | Number | String | Symbol> = ( 
  (literalTable includesKey: s) ifFalse:[literalTable at: s put: literalTable size].
)
addNumericLiteral: n <Number> = ( 
   addLiteralConstant: n
)
arrayNode: node <ArrayAST> = (
	node elements isNil ifTrue: [
		^node
	] ifFalse: [
		^ArrayAST new 
			elements: (node elements collect: [:ea | ea apply: self]);
			size: node elements size 
	]
)
assignmentFrom: aMsg <MessageAST> decl: vd <VarDeclAST> ^ <AssignmentNode> = (


| var <VariableAST> varName <String> arg semantic |

assert:[aMsg args size = 1].
varName:: aMsg sel asString copyUpToLast: $:.
assert:[(currentScope at: varName asSymbol) isTemporaryAST].
"what about setter methods - then we might have an inst var? this cannot happen, because this is only called when processing variables"
var:: TemporaryVariableAST name: varName
		                   		start: aMsg start
                               		end: aMsg end.

arg:: aMsg args first. "recurse on RHS"
  
"create an assignment"

^AssignmentAST new 
                    to: var assign: (arg apply: self);
                    start: aMsg start;
                    end: aMsg end                     
)
blockLocalReturnNode: node = (
	^node
)
codeBodySlotInitializers: temporaries <OrderedCollection[SlotDefAST]> isSeq: isSeq <Boolean>
 ^ <OrderedCollection[NormalSendAST]> = (
	
	^(temporaries reject: [:slot | slot initializer isNil]) collect: [ :slot <SlotDefAST> |
		| aMsg <MessageAST> slotInitializer <ExpressionAST> |
	 	slotInitializer:: slot initializer.
		isSeq ifFalse: [slotInitializer:: delayFor: slotInitializer].
		aMsg:: MessageAST new
			send: (slot name,':') asSymbol with: {slotInitializer};
			start: slot start;
			end: slot end.
		NormalSendAST new
			msg: aMsg;
			recv: (hereNode start: aMsg start; end: aMsg end);
			start: aMsg start;
			end: aMsg end.
	]
)
currentScope ^ <Scope> = (


^scopeStack last
)
declareSetterTempFor: node <CodeBodyAST> ^ <Boolean>  = (
	"Generate a synthetic temporary variable for use in compiling setter sends. This is only done if the node being processed contains setter sends
	"
	| sTempDecl <TemporaryAST> settersIncluded <Boolean> |
	pushScopeForNode: node.
	settersIncluded:: (NeedsIndirectionFinder for: node) includesSetterSend.
	settersIncluded ifTrue: [
		sTempDecl:: (TemporaryAST name: setterTempName type: nil) start:0; end: 0.
		currentScope
			at: setterTempName put: (SemanticVarDecl decl:{sTempDecl. currentDepth}); 
				"getter"
			at: (setterTempName asString, ':') asSymbol put: sTempDecl. 
				"setter"	
		].
	popScope.
	^settersIncluded
)
delayFor: expression <ExpressionAST> ^<ExpressionAST> = (
	"Duplicated from Compiler because Rewriter has a seperate scope stack"

	"_here Delay computation: [expression]"
	| 
	sscope <Scope>
	block <BlockAST>
	codebody <CodeBodyAST>
	delay <ExpressionAST>
	|
	
	sscope:: Scope new.
	sscope superScope: currentScope.
	
	delay:: NormalSendAST new
		recv: (NormalSendAST new recv: hereNode; msg: (MessageAST new sel: #Delay; args: {}));
		msg: (MessageAST new sel: #computation:; args: {
			block:: BlockAST new body: (
				 codebody:: CodeBodyAST new
					parameters: OrderedCollection new;
					 temporaries: OrderedCollection new;
					statements: {expression}
			)
		}).
		
	scopeMap at: codebody put: sscope.
	scopeMap at: block put: sscope.
	^delay
)
explicitOuterReceiverNode: node
 = (
    assert: [node isExplicitRcvrNode].
    ^node
)
implicitSendNode: node
 = (
    assert: [node isImplicitSendNode].
    ^node
)
initializerForRemoteVector: itvname sized: itvsize = (
	"_here itvname: (_here Array new: itvsize)"
	"^NormalSendAST new
		to: hereNode
		send: (MessageAST new
			send: (itvname , ':') asSymbol
			with: { NormalSendAST new
				to: (NormalSendAST new to: hereNode send: (MessageAST new send: #Array with:{}))
				send: (MessageAST new send: #new: with: {NumberAST new val: itvsize})
			}
		)"

	"_here itvname: (<pushEmptyArray: itvsize>)"
	^NormalSendAST new
		to: hereNode
		send: (MessageAST new
			send: (itvname , ':') asSymbol
			with: {ArrayAST new size: itvsize})
)
isHereNode: aNode <AST> ^ <Boolean> = (

	aNode isVariableNode ifFalse:[^false].
	(isPseudoVariableNode: aNode) ifTrue:[^false].

	assert:[aNode name = #'_here'].
	^true
)
isInlineableConditional: node <NormalSendAST> ^ <Boolean> = (
	({#ifTrue:. #ifFalse:. #ifTrue:ifFalse:. #ifFalse:ifTrue:} includes: node msg sel)
	     ifFalse:[^false].
	node msg args do:[:a <AST> |  (isRemovableBlock: a withArgs: 0) ifFalse: [ ^ false ]].
	^true
)
isInlineableLoop: node <NormalSendAST> ^ <Boolean>= (
| selector <Symbol>  args |
selector:: node msg sel.
args:: node msg args.
	({#whileTrue. #whileFalse. #whileTrue:. #whileFalse:. #repeat} includes:  selector)
	   ifTrue:[args do:[:a |  (isRemovableBlock: a withArgs: 0) ifFalse: [ ^ false ]].
		^isRemovableBlock: node recv withArgs: 0.
		].
	
	(selector = #timesRepeat:) ifTrue:[^isRemovableBlock: args last withArgs: 0].
	({#to:do:. #to:do:by:}  includes:  selector) ifFalse:[^false].
	(isRemovableBlock: args last withArgs: 1) ifFalse:[^false].
	(selector = #to:do:) ifTrue:[^true].
	args size = 3 ifFalse:[^false].
)
isInlineableSend: node <NormalSendAST> ^ <Boolean> = (
	^(isInlineableConditional: node) or:[isInlineableLoop: node]
)
isOuterNode: aNode <AST> ^ <Boolean> = (


aNode isVariableNode ifFalse:[^false].
^aNode name = #outer
)
isPseudoVariableNode: aNode <VariableAST> ^ <Boolean> = (


^aNode name = #self or:[aNode name = #super or:[aNode name = #outer or:[aNode name = #thisContext]]]
)
isSuperNode: aNode <VariableAST> ^ <Boolean> = (
	aNode isVariableNode ifFalse:[^false].
	^aNode name =  #super 
)
mixinApplication: node <MixinApplicationAST> = (
	| msg |
"For now, just compile it as a regular message send"
	msg:: MessageAST new
			send: #apply:
			with: (OrderedCollection with: node superclassExpr);
			start: node start;
			end: node end.

	^(NormalSendAST new
		to: node mixinExpr send: msg;
		start: node start;
		end: node end) apply: self
)
mixinClassNode: node = (
	^node
)
nilNode: node <NilAST> = (
	"Possibily" #BOGUS.
	^node
)
numberNode: node = (
  assert:[node isNumberNode].
  addNumericLiteral: node val.
  ^node
)
parameterNode: node <ParameterVariableAST> = (
	#BOGUS. "Shouldn't be visiting this twice."
	^node
)
processExplicitOuterReceiver: aMsg <MessageAST> = (


| binding <AST> depth <integer> |

assert:[aMsg args isEmpty]. "this had better be a unary message"
binding:: currentScope at: aMsg sel.

"assert:[binding data  isClassDeclarationAST]."
  depth: currentDepth -  binding depth -1.
  addNumericLiteral: depth. "the backend checks that depth in 0 - 256"
 ^(ExplicitRecvrAST send: aMsg sel depth: depth) start: aMsg start; end: aMsg end
)
processImplicitOuterSend: aMsg <MessageAST> atDepth: n <Integer> ^ <SendNode> = (
"In this case, we don't care about the depth; but when compiling to other platforms, we might, so we maintain the API"
  ^(ImplicitRecvrSendAST send: (aMsg apply: self)) start: aMsg start; end: aMsg end
)
processInlineableSend: node <NormalSendAST> ^ <IfAST | LoopAST> = (
 
 |  
  recv <AST> msg <MessageAST> sel <Symbol> nOfArgs <Integer> 
  arg1 <AST> arg2 <AST> arg3 <AST> 
|

 "Prepare arguments for inlined message sends"
 recv:: node recv.
 msg:: node msg.
 sel:: node msg sel.
 nOfArgs:: msg args size.
 nOfArgs >= 1 ifTrue: [ arg1:: msg args at: 1 ].
 nOfArgs  >= 2 ifTrue: [ arg2:: msg args at: 2 ].
 nOfArgs  >= 3 ifTrue: [ arg3:: msg args at: 3 ].
 
	 "Hardwired ifTrue: / ifFalse: messages"
 sel = #ifTrue: ifTrue: [^IfAST if: (recv apply: self) is: true then: (rewriteInlinedBlockNode: arg1)].
 sel = #ifFalse:  ifTrue: [^IfAST if: (recv apply: self) is: false then: (rewriteInlinedBlockNode: arg1)].
 sel = #ifTrue:ifFalse:  ifTrue: [
	^IfAST if: (recv apply: self) is: true then: (rewriteInlinedBlockNode: arg1) 
	                                    else: (rewriteInlinedBlockNode: arg2)
	].
 sel = #ifFalse:ifTrue:  ifTrue: [
	^IfAST if: (recv apply: self) is: false then: (rewriteInlinedBlockNode: arg1) 
	                                     else: (rewriteInlinedBlockNode: arg2)
	].
 
 "Hardwired whileTrue: / whileFalse: messages"
 sel = #whileTrue ifTrue: [^LoopAST new while: true do: (rewriteInlinedBlockNode: recv)].
 sel = #whileFalse ifTrue: [^LoopAST new while: false do: (rewriteInlinedBlockNode: recv)].
 sel = #whileTrue:  ifTrue: [
	^LoopAST new while: (rewriteInlinedBlockNode: recv) 
	                       is: true 
	                       do: (rewriteInlinedBlockNode: arg1)
	].
 sel = #whileFalse:  ifTrue: [
	^LoopAST new while: (rewriteInlinedBlockNode: recv) 
	                       is: false 
	                       do: (rewriteInlinedBlockNode: arg1)
	].
 
 "Hardwired repeat / timesRepeat: / to:do: / to:by:do: messages"
 sel = #repeat   ifTrue: [^LoopAST new repeat: (rewriteInlinedBlockNode: recv)].
 sel = #timesRepeat:  ifTrue: [
	^LoopAST new do: (recv apply: self) timesRepeat: (rewriteInlinedBlockNode: arg1)
	].
 sel = #to:do:   ifTrue: [
	^LoopAST new from: (recv apply: self) to: (arg1 apply: self) do: (rewriteInlinedBlockNode: arg2)
	].
 sel = #to:by:do:  ifTrue: [
	^LoopAST new from: (recv apply: self) to: (arg1 apply: self) by: (arg2 apply: self) do: (rewriteInlinedBlockNode: arg3)
	].
 assert:[false]. "should not happen!"
 ^node
)
processMappedVariable: aMsg <MessageAST> decl: binding <DebugMappedLocalEntry> = (

	^(aMsg sel last = $:
		ifTrue:[binding setterAst: aMsg args first]
		ifFalse:[binding getterAst]) apply: self
)
processVariable: aMsg <MessageAST> decl: vd <VarDeclAST>  ^ <AssignmentNode | VariableNode> = (


^aMsg sel last = $:
   ifTrue:[assignmentFrom: aMsg decl: vd]"it is a temporary write"
   ifFalse:[variableFrom: aMsg decl: vd]
"it is a parameter or temporary read"
)
receiverNode: node <ReceiverAST> = (
	^ node
)
rewriteInlinedBlockNode: node <BlockAST> ^ <BlockAST> = (
"An empty block evaluates to nil when called. This method performs the necessary transformation if the block is empty; otherwise it recursively rewrites the block body. This rewrite is done on all blocks, regardless of whether they are inlined."
	| 
	blok <BlockAST> 
      params <Collection[ParameterAST]>  
      bodyScope <Scope> 	
	| 
    assert: [ node isBlockNode ].
    params:: node parameters collect:[:p <VarDeclAST> | 
	 (ParameterAST name: p name type: p type)  start: p start; end: p end.
	].
    bodyScope:: scopeMap at: node body.
    params do:[:t | (bodyScope at: t name) data: t].
    addNumericLiteral: node parameters size.
    blok:: BlockAST new body: (node body apply: self).
    blok body parameters: params.
    node body statements isEmpty 
       ifTrue:[blok body statements add: (NilAST new start: node body start; end: node body end)].
    ^blok
)
selfNode ^ <VariableAST> = (
"shouldn't this be a ReceiverAST?"
"generate a an AST representing self; used for implicit self sends"
^VariableAST new name: #self; start: 0; end: 0
)
setterSendNode: node <SetterSendAST> ^ <AST> = (
| 
setterBinding <AST>
sTemp <TemporaryVariableAST> 
sTempAssign <AssignmentAST> 
message <MessageAST> 
send <NormalSendAST>  
cb <CodeBodyAST>  
|
	assert: [node isSetterSendNode ].
	setterBinding:: currentScope at: node msg sel ifAbsent: [MessageAST new].
	setterBinding isVarDeclNode ifTrue: [^processVariable: node msg decl: setterBinding].
	"This is an assignment to a temporary - no special handling needed"
	"Otherwise, rewrite the setter send as follows:
		setter:: exp 
		=>
		t:=exp. setter: t. t
	This is much less wasteful than creating a block etc. per the spec.
		"
	sTemp:: TemporaryVariableAST name: setterTempName start: 0 end: 0.
	sTempAssign:: AssignmentAST new 
		to: sTemp assign: (node msg args first apply: self).  
	"t := exp"
	message:: MessageAST new sel: node msg sel; args: {sTemp}.
	send:: (NormalSendAST new to: node recv send: message) apply: self.
	"setter: t"
	cb:: (CodeBodyAST new 
			parameters: OrderedCollection new;
			temporaries: {};
			statements: {sTempAssign. send. sTemp})."t:=exp. setter: t. t"
	scopeMap at: cb put: currentScope.
	^cb
)
setterTempName = (
	^#'@setterTemp'
)
temporaryNode: node <TemporaryVariableAST> = (
	"Possibily " #BOGUS.
	^node
)
tupleNode: aNode <TupleAST> = (
"should rewrite into a tree representing the expression
(Array new:  n) at: 1 put:: e1 ; ...  at: n put: en; yourself
where n is the size of the tuple"

"
The above scheme requires that 1 through n are added to the literal frame.  Existing code includes large tuple literals that when compiled this way exceed the limit for literals.  So for now we rewrite to (Array braceStream: n) nextPut: e1; ... nextPut: en; contents
"

| els <OrderedCollection[AST]>   
  array <NormalSendAST> 
  len <NumberAST> 
  tup <NormalSendAST>
  index <Integer>
|

aNode elements size <= 7 "arbitrary, but it must be less than the max stack size" ifTrue: [
	^(ArrayAST new elements: aNode elements; size: aNode elements size) apply: self].


len:: NumberAST new val: aNode elements size.
len start: aNode start; end: aNode end.
array:: NormalSendAST new
	to:(NormalSendAST new 
			to: selfNode 
			send:  (MessageAST new sel:#Array; args:{}; start: aNode start; end: aNode end) "Array"
			) 
		send: (MessageAST new sel: #braceStream:; args:{len}; start: aNode start; end: aNode end). "Array braceStream: n"
array start: aNode start; end: aNode end.	
aNode elements size = 0 ifTrue:[
		^(NormalSendAST new
			to: array
			send: (MessageAST new sel: #contents; args: {})
		) apply: self
	].
index:: 0.
tup:: aNode elements inject: array into:[:r : e |  | msg <MessageAST> |
	      index:: index + 1.
	      msg:: MessageAST new sel: #nextPut:; 
								args: {e}.
		msg start: aNode start; end: aNode end.
	      index = 1 
			ifTrue:[NormalSendAST new to: r send: msg; start: aNode start; end: aNode end] 
						"(Array braceStream: n) nextPut: e1"
	      	ifFalse:[CascadedSendAST new to: r cascade: msg; start: aNode start; end: aNode end]. "...; nextPut: ek"
		].
^((CascadedSendAST new to: tup cascade:(MessageAST new sel: #contents; args:{}; start: aNode start; end: aNode end)) start: aNode start; end: aNode end)
	"(Array braceStream: n) nextPut: e1; ... nextPut: en; contents"
	 apply: self
"visit elements"
"els:: aNode elements do:[:e <SendAST> | e apply: self].
^TupleAST new elements: els"
)
variableFrom: aMsg <MessageAST> decl: vd <VarDeclAST>  ^ <VariableNode> = (
| VarClass <Class> |

assert:[aMsg args isEmpty].
vd isNil ifTrue:[
	^(VariableAST new name: aMsg sel;
		            start: aMsg start;
                        end: aMsg end) apply: self
	].

^vd variableClass name: aMsg sel
		            start: aMsg start
                        end: aMsg end                    
)
variableNode: aNode <VariableAST> = (
	aNode name = #self ifTrue:[^ReceiverAST new start: aNode start; end: aNode end].
	aNode name = #nil ifTrue:[^NilAST new start: aNode start; end: aNode end].
	aNode name = #true ifTrue:[^BoolAST withValue: true start: aNode start end: aNode end].
	aNode name = #false ifTrue:[^BoolAST withValue: false start: aNode start end: aNode end].		
	aNode name = #thisContext ifTrue:[^ContextAST new start: aNode start; end: aNode end].
	"recognize inst vars for accessor methods? handle temps etc."
	^aNode
)'node traversal'
assignmentNode: node <AssignmentAST> ^ <AssignmentAST>
 = (
    assert: [ node isAssignmentNode ]. "note write to target variable!"
    ^AssignmentAST new to: (node var apply: self) assign: (node expr apply: self);
                                      start: node start; end: node end
)
blockNode: node <BlockAST> ^ <ClosureAST> = (
" This method should only be called on a block that is not going to be inlined.

There are two things that require rewriting in blocks.

1. a.  Non-empty blocks must have their body rewritten recursively
    b. Empty blocks need a nil expression in them.
    c. All blocks must have their parameters rewritten from generic VarDecls to ParameterASTs. 
2. If the last statement in a block is not a return, the block returns
the expression to its caller. So the last expression needs to be replaced by a 'local return'.

We accomplish (1) by calling rewriteInlinedBlockNode:, and then do  (2) explicitly.

The reason for this separation is that step (1) is always needed; step (2) is only needed if the block is not inlined.
"
	| blok <BlockAST> last <AST> needsCopy <NeedsCopyFinder> closure <ClosureAST> copiedVarNames <List[Symbol]> copiedValues <List[TemporaryVariableAST]> setterTempNeeded <Boolean>  | 

	copiedVarNames: OrderedCollection new.
	needsCopy::(NeedsCopyFinder for: node body).
	needsCopy needsToCopy do: [:var <Symbol> |	
			"(var , ' will be copied') out."
			copiedVarNames addFirst: var.
			
			node body temporaries addFirst: (
				MutableSlotDefAST new
					slotDecl: (TemporaryAST name: var type: nil);
					initializer: nil
			).
			(scopeMap at: node) at: var put:
				(SemanticVarDecl decl: {TemporaryAST name: var type: nil. nil}).
	].		
		copiedValues:: copiedVarNames collect: [:var <Symbol> | 
			TemporaryVariableAST name: var start: 0 end: 0].
    setterTempNeeded:: declareSetterTempFor: node body.    
    blok:: rewriteInlinedBlockNode: node.

    setterTempNeeded ifTrue:[blok body temporaries addLast: ((scopeMap at: node body) at: setterTempName) data]. 
	"add setterTemp to rewritten body as needed"
    blok body statements last isReturnStatNode 
		ifFalse:["last expression in a block is returned by it"
			last:: blok body statements removeLast.
			blok body statements add: (BlockLocalReturnAST 
											expression: last start: last start end: last end) 
			].
    scopeMap at: blok put: (scopeMap at: node).


	closure:: ClosureAST for: blok withCopiedValues: copiedValues.
	scopeMap at: closure put: (scopeMap at: blok).
	closure pushNilCount: needsCopy pushNilCount.
	
    ^closure
)
cascadedSendNode: node <CascadeSendAST> ^ <CascadeSendAST>
 = ( 
 | prevSend msg |
 assert: [node isCascadedSendNode].
 prevSend:: node prevSend apply: self.
 msg:: node msg apply: self.

 ^CascadedSendAST new to: prevSend cascade: msg
)
charNode: node <CharAST> = (
  addLiteralConstant: node val.
  ^node
)
codeBodyNode: node <CodeBodyAST> ^ <CodeBodyAST> = (
    | 
       bodyScope <Scope>
       statements <OrderedCollection[StatementAST]>
       temps <OrderedCollection[TemporaryAST]> 
       result <CodeBodyAST>
	itv <TemporaryAST>
	i <Integer>
	finder <NeedsIndirectionFinder>
    |
	assert: [node isCodeBodyNode].
	pushScopeForNode: node. 
	bodyScope:: scopeMap at: node.

	temps:: node temporaries collect:[:t <VarDeclAST> |
		(TemporaryAST name: t name type: t type) start: t start; end: t end.
	].
	temps do: [:t <TemporaryAST> | (bodyScope at: t name) data: t].

	statements:: OrderedCollection new.

 	finder:: NeedsIndirectionFinder for: node.
	finder needsIndirection isEmpty ifFalse: [
		"introduce an indirect temp vector aka remote vector"
		itv:: TemporaryAST name: ('@indirectionVector',scopeStack size printString) asSymbol type: nil.	
		bodyScope
			at: itv name put: (SemanticVarDecl decl: {itv. currentDepth}); "getter"
			at: (itv name,':') asSymbol put: (VarDeclAST name: itv name type: nil). "setter"
		temps addLast: itv. "N.B. addLAST, copied values must be at beginning"
		
		"initialize itv in the very first statement"
		statements add: ((initializerForRemoteVector: itv name sized: finder needsIndirection size) apply: self)
	].

	i::0.
	finder needsIndirection do: [:varname <Symbol> |
		assert: [(bodyScope at: varname) remote not].
		(bodyScope at: varname)
					remote: true;
					remoteVector: itv;
					offset: i.
		i:: i+1.
	].

	"add statements which initialize temps"
	(codeBodySlotInitializers: node temporaries isSeq: node isSeq)
		do: [:ea | statements add: (ea apply: self)].

	"add actual statements in code body"
	node statements do: [:stat | statements add: (stat apply: self)].

	result:: CodeBodyAST new
            parameters: node parameters
            temporaries: temps
            statements: statements;
		literalMessages: node literalMessages;
            start: node start; end: node end.
	popScope.
	scopeMap at: result put: bodyScope.
	^result.
)
ifNode: node <ifAST> ^ <ifAST>
 = (
 assert: [ node isIfNode ].
 ^node
)
loopNode: node <LoopAST> ^ <LoopAST>
 = (
    ^node
)
messageNode: node <MessageAST> ^ <MessageAST>
 = (
    | args |
    assert: [node isMessageNode].
    args:: OrderedCollection new.
    node args do: [ :arg | args add: (arg apply: self)].
    addLiteral: node sel.
    ^MessageAST new send: node sel with: args; start: node start; end: node end
)
messagePatternNode: node <MessagePatternAST> ^ <MessagePatternAST> = (
  | params <OrderedCollection[ParameterAST]>  patternScope <Scope> |

  params:: node parameters collect:[:p <VarDeclAST> | 
     (ParameterAST name: p name type: p type)  start: p start; end: p end.
  ].
  patternScope:: scopeMap at: node.
  params do:[:p | (patternScope at: p name) data: p].
  ^MessagePatternAST new selector: node selector parameters: params;
                                           start: node start; end: node end.
)
methodNode: node <MethodAST> ^ <MethodAST | 
                                                                       ReturnSelfMethodAST | 
                                                                       ReturnInstVarMethodAST>
 = (
| 
pattern <MessagePatternAST>  
stmts <OrderedCollection[StatementAST]>
rs <ReturnStatAST> 
body <CodeBodyAST>
result <MethodAST>
setterTempNeeded <Boolean>
|

  assert: [ node isMethodNode ].
  literalTable:: Dictionary new.
  pattern:: node pattern apply: self.
  stmts:: node body statements.
  setterTempNeeded:: declareSetterTempFor: node body. 
  body::  node body apply: self.
  setterTempNeeded ifTrue:[body temporaries addLast: ((scopeMap at: node body) at: setterTempName) data]. 
  "add setterTemp to rewritten body as needed"
  body parameters: pattern parameters.
  (body statements isEmpty not and:[body statements last isReturnStatNode])
     ifFalse:[body statements addLast:( ReturnStatAST new expr: (ReceiverAST new  start: body end; end: body end); start: body end; end: body end)].
  (stmts size = 1 and:[stmts first isReturnStatNode]) ifTrue:[
"We recognize the special cases for methods whose body is ^self
or ^iv for some inst var iv"
     pushScopeForNode: node body.
     rs:: stmts first "apply: self  <- huh? already done when processing body".
     popScope.
     (rs expr isReceiverNode)  ifTrue:[
		^ReturnSelfMethodAST selector: node pattern selector var: rs expr
		].
   ].
 result:: MethodAST new 
   pattern: pattern
   body: body
   visibility: node visibility.
 scopeMap at: result put: (scopeMap at: node).
^result
)
normalSendNode: node <NormalSendAST> ^ <AST>
 = (
 | 
  recv <AST> msg <MessageAST> sel <Symbol> nOfArgs <Integer> 
  arg1 <AST> arg2 <AST> arg3 <AST> 
|

 assert: [ node isNormalSendNode ].

  (isHereNode: node recv)
    ifTrue:[^processHereSend: node msg].
  (isOuterNode: node recv)
    ifTrue:[^processExplicitOuterReceiver: node msg].
  (isSuperNode: node recv)
    ifTrue:[^SuperSendAST send: (node msg apply: self)].

  (isInlineableSend: node) ifTrue:[^processInlineableSend: node].
 "Prepare arguments for inlined message sends"

  recv:: node recv apply: self.
  msg:: node msg apply: self.
  sel:: msg sel.

  ^NormalSendAST new to: recv send: msg; start: node start; end: node end
)
returnInstVarMethodNode: node
 = (
 ^node
)
returnStatNode: node <ReturnStatAST> ^ <ReturnStatAST>
 = (
    assert: [node isReturnStatNode].
    ^ReturnStatAST new expr: (node expr apply: self); 
                                      start: node start; end: node end
)
stringNode: node
 = (
    assert: [ node isStringNode ].
    addLiteralConstant: node val asSymbol.
    ^node
)
superSendNode: node
 = (
    assert: [node isSuperSendNode ].
    ^node
)
symbolNode: node
 = (
    assert: [ node isSymbolNode ].
    addLiteralConstant: node val.
    ^node
)'patterns'
keywordPatternNode: aNode <KeywordPatternAST> ^ <NormalSendAST> = (
"rewrite to message send: (Pattern keywords: (...) patterns: (...))"
|
	patClass <NormalSendAST>	
	kwpatsMessage <MessageAST>
|
patClass:: NormalSendAST new 
				to: selfNode
				send: (MessageAST new 
							sel: #Pattern; 
							args: {}; 
							start: aNode start; end: aNode end).

kwpatsMessage::  MessageAST new
					sel: #keywords:patterns: ;
					args: { aNode keywords . aNode patterns };
					start: aNode start; end: aNode end.
					
					
^ (NormalSendAST new
	to: patClass
	send: kwpatsMessage) apply: self.
)
literalPatternNode: aNode <LiteralPatternAST> ^ <NormalSendAST> = (
"rewrite to message send: (Pattern literal: (...))"
|
	patClass <NormalSendAST>	
	literalMessage <MessageAST>
|

patClass:: NormalSendAST new 
				to: selfNode
				send: (MessageAST new 
							sel: #Pattern; 
							args: {}; 
							start: aNode start; end: aNode end).

literalMessage::  MessageAST new
					sel: #literal: ;
					args: { aNode literal };
					start: aNode start; end: aNode end.
					
^ (NormalSendAST new
	to: patClass
	send: literalMessage) apply: self.
)
variablePatternNode: aNode <VariablePatternAST> ^ <NormalSendAST> = (
"rewrite to message send: (Pattern new Patterns new ImmutableSlotPattern new patternName: ...; yourself)"
|
	patInst patsInst slotInst
	patNameMsg
	st <Integer> ed <Integer>	
	send create
|
st: aNode start. ed: aNode end.

send:: [ :sym :rcv | 
	NormalSendAST new
		to: rcv
		send: (MessageAST new sel: sym; args: {}; start: st; end: ed)
].

patInst:: send value: #new value: (send value: #Pattern value: selfNode).
patsInst:: send value: #new value: (send value: #Patterns value: patInst).
slotInst:: send value: #new value: (send value: #ImmutableSlotPattern value: patsInst).

patNameMsg:: MessageAST new 
				sel: #patternName:; 
				args: { SymbolAST new val: aNode variableName; start: st; end: ed }; 
				start: st; end: ed.

^ ((CascadedSendAST new 
		to: (NormalSendAST new to: slotInst send: patNameMsg; start: st; end: ed)
		cascade: (MessageAST new sel: #yourself; args: {}; start: st; end: ed)) start: st; end: ed)
  	apply: self.
)
wildcardPatternNode: aNode <WildcardPatternAST> ^ <NormalSendAST> = (
"rewrite to message send: (Pattern wilddcard)"
|
	patClass <NormalSendAST>	
	wildcardMessage <MessageAST>
|
patClass:: NormalSendAST new 
				to: selfNode
				send: (MessageAST new 
							sel: #Pattern; 
							args: {}; 
							start: aNode start; end: aNode end).

wildcardMessage::  MessageAST new
					sel: #wildcard ;
					args: {};
					start: aNode start; end: aNode end.
					
^ (NormalSendAST new
	to: patClass
	send: wildcardMessage) apply: self.
)'private'
addLiteral: s <Character | Number | String | Symbol> = ( 
  (literalTable includesKey: s) ifFalse:[literalTable at: s put: literalTable size].
)
isRemovableBlock: block <BlockAST> withArgs: nofArgs <Integer> ^ <Boolean>
 = (
 "
 Private.
 Answers true if block can be removed (inlined)
 within another block, answers false otherwise.
 "
 | s |
 block isBlockNode ifFalse: [ ^ false ].
 block parameters size = nofArgs  ifFalse: [ ^ false ].
 ^ true
)
popScope ^ <Scope> = (
  ^scopeStack removeLast
)
processHereSend: aMsg <MessageAST> = (

	| binding <AST> |
	binding:: currentScope at: aMsg sel ifAbsent: [MessageAST new].
	
	binding isMessagePatternNode 
	   ifTrue:["this is a message send for a lexically defined method"
		^processImplicitOuterSend: aMsg atDepth: binding depth 
		].
	binding isVarDeclNode
		ifTrue: [^ processVariable: aMsg decl: binding].
	binding isDebugMappedLocalEntry
		ifTrue: [^ processMappedVariable: aMsg decl: binding].
		
	({#true. #false. #nil} includes: aMsg sel) ifTrue:[^processVariable: aMsg decl: nil].
	^ processImplicitOuterSend: aMsg atDepth: 0
)
pushScope: s <Scope> = (
  scopeStack addLast: s
)
pushScopeForNode: n <AST> = (
  scopeStack addLast: (scopeMap at:n)
))
class ScopeBuilder nestedIn: initialScope <Scope> atLevel: initialDepth <Integer> = ASTTool ("The scope builder is a visitor on the AST. It computes a tree of scopes that shadows the AST itself.  More precisely, it computes a mapping from ASTs to their scopes. This allows us to get to the appropriate scope for an abstract syntax node without pollluting the AST with extraneous data like scopes.

We could associate each node in the AST with the scope in which it is found, but this would be overkill. Instead, only nodes that actually introduce new scopes (such as class sides, message patterns, code bodies and blocks) actually get mapped in this manner. The intent is that later phases of compilation will visit the tree and look up the scopes at the points where they are introduced.

The builder starts at a given node, in the context of some mixin, described by a mirror.  This is because, in an incremental environment, we may not have the complete AST for a module, but instead be asked to process a part of that module, such as a nested class, slot definition or method. The surrounding scope can be computed from the mirror representing the immediately enclosing mixin.

Then we traverse the tree, creating and populating new scopes as needed. We maintain a stack of scopes (scopeStack) that initially contains only the surrounding scope.  Scopes get pushed on to the stack when we encounter a node that introduces a scope, and popped when we finish with that node. The scopes are chained to their super scopes (the scope below them on the stack).

A possible optimization is to avoid a traversal of an entire side of a class.
One can process only a side without its subtrees (i.e., methods and nested classes). These can be visited later,  as long as we ensure that the processing of the subtree begins with a proper super scope on top of the scope stack."| 
  scopeStack = OrderedCollection new.
  
  currentDepth ::= initialDepth. "The lexical nesting level of the class declaration currently 
						being visited; top level classes are level 0"
|pushScope: initialScope)
('access'
visitMethod: aNode <MethodAST> within: m <MixinMirror> ^ <Dictionary[AST, Scope]> = (
   ^visitNode: aNode within: m
)
visitNode: aNode <AST> within: m <MixinMirror> ^ <Dictionary[AST, Scope]> = (
   pushScope:(buildScopeFor: m).
   aNode apply: self.
   ^scopeMap
)'as yet unclassified'
buildScopeFor: m <MixinMirror> ^ <Scope> = (
	^prvtScopeFor: m.
)
classNode: aNode <ClassDeclarationAST> = (
| vs <Scope> |

	currentScope at: aNode name 
		put: (SymbolTableEntry for:{MessagePatternAST new selector: aNode name. currentDepth}).
	vs:: Scope new. "establish instance side scope"
	currentDepth:: currentDepth + 1.
	aNode hdr slots do:[:v <SlotDeclAST> | 
		vs at: v name put: (SymbolTableEntry for:{MessagePatternAST new selector: v name. currentDepth}).
    		  v isMutable ifTrue:[vs at: (v name asString, ':') asSymbol put: (SymbolTableEntry for:{MessagePatternAST new selector: (v name asString, ':') asSymbol. currentDepth}) "setter"]
    	 ].
	self nestScope: vs.
  	aNode instanceSide apply: self.
	popScope.
  	aNode classSide apply: self.
	currentDepth:: currentDepth - 1.
)
codeBodyNode: aNode <CodeBodyAST> = (


| ts <Scope> |
"establish local slot scope"

ts:: Scope new.
aNode temporaries do:[:t <SlotDefAST> | 
                          ts at: t name put: (SemanticVarDecl decl:{t slotDecl. currentDepth}); " getter"
                              at: (t name asString, ':') asSymbol put: t slotDecl "setter"
                         ].
ts end: aNode end. "we need to know where this scope ends"
nestScope: ts.
scopeMap at: aNode put: ts.
"visit statements"

aNode temporaries do: [:t | 	t initializer isNil ifFalse: [t initializer apply: self]].
aNode statements do:[: s <ReturnStatementAST | SendAST>  | s apply: self].
popScope.
)
enclosingMixinsOf: m <MixinMirror> ^ <Collection[MixinMirror]> = (
	"top to bottom"
	
	| current mixins |
	mixins:: OrderedCollection new.
	current:: m.
	[current isNil] whileFalse: [
		mixins addFirst: current.
		current: current enclosingClass.
	].
	^mixins
)
keywordPatternNode: n = (
	"do nothing"
)
literalPatternNode: n = (
	"do nothing"
)
mixinClassNode: aNode = (
	"do nothing"
)
prvtScopeFor: c <MixinMirror> ^<Scope> = (
"When incrementally compiling a nested class, we need to reconstruct its scope."

| 
s <Scope> 
outerMixins <Collection[MixinMirror]>
depth <Integer>
|

outerMixins:: enclosingMixinsOf: c."should use a cleaner API"
currentDepth:: outerMixins size - 1.
depth:: 0.
outerMixins do:[: o |
	
	s:: Scope new superScope: s.
	
	depth = 0 ifTrue: [
		"Top level to pretend it has an accessor at a level enclosing it."
		s at: o simpleName asSymbol
		put: (SymbolTableEntry for:{MessagePatternAST new selector: o simpleName asSymbol. depth-1}).
	].
	
	(selectorsFor: o) do:[: sel | s at: sel 
		                              put: (SymbolTableEntry for:{MessagePatternAST new selector: sel. depth})].
	depth:: depth + 1.
	].

^s
)
selectorsFor: m <MixinMirror> ^ <Collection[Symbol]> = (
"Should add a convenience method to mirrors to do this"
| result <Collection[Symbol]> |
	result:: OrderedCollection new.
	result addAll: (m instanceSide methods collect:[:s <MethodMirror> | s name]).
	result addAll: (m instanceSide slots collect:[: s <SlotMirror> | s name]).
	result addAll: ((m instanceSide slots select:[: s | s isMutable]) 
	                         collect:[: s <SlotMirror> | s name, ':']
	                       ).
	result addAll: (m instanceSide nestedClasses collect:[:s <ClassStencilMirror> | s simpleName]).
	^result
)
setterSendNode: aNode <SetterSendAST> = (
"visit recvr and msg"
aNode recv apply: self.
aNode msg apply: self.
)
sideNode: aNode <SideAST> = (

scopeMap at: aNode put: currentScope.

"visit methods"

aNode categories do:[: c <CategoryAST> | 
                        c methods do:[:m <MethodAST> | m apply: self]
        ].
"visit nested classes"

aNode nestedClasses do:[:nc <ClassDeclarationAST> | 
	nc apply: self
	].
)
wildcardPatternNode: node = (
	"do nothing"
)'node traversal'
blockNode: aNode <BlockAST> = (


| ps <Scope> |

ps:: Scope new.
"establish parameter scope"
aNode parameters do:[:p <VarDeclAST> | ps at: p name put: (SemanticVarDecl decl: {p. currentDepth})].
nestScope: ps.
"visit body"
aNode body apply: self.
scopeMap at: aNode put: (scopeMap at: aNode body).
popScope "pop the parameter scope, ps"
)
cascadedSendNode: aNode <CascadedSendAST> = (

"generic traversal code"
"visit receiver and messages"

aNode prevSend apply: self.
aNode msg apply: self.
)
charNode: aNode <CharAST> = (


"do nothing"
)
classHeaderNode: aNode = (


aNode constructor apply: self.
aNode slots do:[:s |  s initializer ifNotNil: [:i | i apply: self]].
aNode initExprs do:[: e | e apply: self].
)
messageNode: aNode <MessageAST> = (

"generic traversal code"
"visit arguments"
aNode args do:[:a <SendAST> | a apply: self]
)
messagePatternNode: aNode <MessagePatternAST> = (


| ps <Scope> |

ps:: Scope new.
"establish parameter scope"
aNode parameters do:[:p <VarDeclAST> | ps at: p name put: (SemanticVarDecl decl: {p. currentDepth})].
nestScope: ps.
scopeMap at: aNode put: ps.
"the pattern scope, ps, must be popped by the caller"
"establish type parameter scope - skip for now"
)
methodNode: aNode <MethodAST> = (


"register method in current scope"
currentScope at: aNode pattern selector put: (SymbolTableEntry for: {aNode pattern. currentDepth}).
"visit pattern"
aNode pattern apply: self.
"visit body"
aNode body apply: self.
scopeMap at: aNode put: (scopeMap at: aNode body).
popScope "Pop pattern scope"
)
mixinApplication: node <MixinApplicationAST> = (


	node mixinExpr apply: self.
	node superclassExpr apply: self
)
normalSendNode: aNode <NormalSendAST> = (

"generic traversal code"
"visit recvr and msg"

aNode recv apply: self.
aNode msg apply: self.
)
numberNode: aNode <NumberAST> = (


"do nothing"
)
returnStatNode: aNode <ReturnStatAST> = (

"generic traversal code"
"visit expression"
aNode expr apply: self
)
stringNode: aNode <StringAST> = (


"do nothing"
)
symbolNode: aNode <SymbolAST> = (


"do nothing"
)
tupleNode: aNode <TupleAST> = (


"visit elements"
aNode elements do:[:e <SendAST> | e apply: self]
)
varDeclNode: aNode <VarDeclAST> = (


"Do nothing. It could arguably add aNode's data to current scope - but in practice, the context knows better how to do this"
)
variableNode: aNode <VariableAST> = (
   assert:[aNode name = #'_here' or:[isPseudoVariableNode: aNode]]
	message: 'Unexpected variable name'.
)'private'
currentScope ^ <Scope> = (
  ^scopeStack last
)
isPseudoVariableNode: aNode <VariableAST> ^ <Boolean> = (


^aNode name = #self or:[aNode name = #super or:[aNode name = #outer or:[aNode name = #thisContext]]]
)
nestScope: s <Scope> = (

"Hook up a new lexically nested scope, and push onto the scope stack"
  s superScope: currentScope.
  pushScope: s
)
popScope ^ <Scope> = (
   ^scopeStack removeLast
)
pushScope: s <Scope> = (
  scopeStack addLast: s
)) : ('as yet unclassified'
new ^ <Instance> = (
	^self nestedIn: Scope new atLevel: 0
))'as yet unclassified'
accessorASTForNestedClassNamed: simpleName <String> fullName: nestedName  <String> superName: nameOfSuper <String> ^<MethodAST> = (
	"Build an AST for a method that would lazily create a nested class 'simpleName' with superclass 'nameOfSuper' via mixin application, and cache it. It would be more convenient to create the method as source code, but it would be syntactically invalid because of the synthetic member names. Also, access to the current mixin is more involved at the source level.
	
The generated code has the form


simpleName = (
	nestedName`slot isNil ifTrue:[ 
		nestedName_slot:: (
	     	((myMixin instVarAt: metadataSlotIndex) 
			nestedMixins at: #nestedName
			) mixin	apply: nameOfSuper 
					withName: ('nestedName`', hash asString) asSymbol
	
		).
		nestedName`slot enclosingObject: self. 
		].
	^nestedName`slot
)	
	
where myMixin is the mixin of the current method - which is pointed to via the method's literal table (see class MixinClassNode for details).
	"
	| 	mixinAccessor <String> enclosingObjectMsg <String>	
			mixinSlotName <String> ncslot <NormalSendAST>
		nilCheck <NormalSendAST> superCall <NormalSendAST> 
		myMixin <NormalSendAST>
		metadataSlotIndex <NumberAST> metadataNode <NormalSendAST>
		nestedClassNode <normalSendAST>  mixinNode  <NormalSendAST>
		hashCode <NormalSendAST> 
		hashString <NormalSendAST> separator <StringLiteral> 
		suffix <NormalSendAST> prefix <StringAST> str <NormalSendAST>
		nm <NormalSendAST> applyMixin <NormalSendAST> 
		setSlot <NormalSendAST> setEnclosingObject <NormalSendAST> 
		blockBody <CodeBodyAST> block <BlockAST> if <NormalSendAST> 
		ret <ReturnStatAST> body <CodeBodyAST> |

	enclosingObjectMsg:: SystemMetadata 
							sourceCodeForSettingEnclosingObjectOf: nestedName.
	mixinAccessor:: SymbolAST new val: (SystemMetadata 
						sourceCodeForAccessingMixinOf: nestedName).
	mixinSlotName:: SystemMetadata mixinSlotNameFor: nestedName.
	ncslot:: [NormalSendAST new to: hereNode 
				send: (MessageAST new send: mixinSlotName asSymbol with:{}; 
										start: 1; end: mixinSlotName size
					    ); start: 1; end:  mixinSlotName size
			].  "generator for  nc`slot"
	
	nilCheck:: NormalSendAST new to: ncslot value 
							send: (MessageAST  new send: #isNil with:{}; 
													start: mixinSlotName size + 2; 
													end: mixinSlotName size + 6
								); start: 1; end: mixinSlotName size + 6.  "nc`slot isNil"
	
	superCall:: NormalSendAST new to: hereNode 
						send: (MessageAST  new send: nameOfSuper asSymbol 
												with:{}; start: 1; end: nameOfSuper size
							); start: 1; end: nameOfSuper size. "nameOfSuper"
							
	metadataSlotIndex:: NumberAST new val: 14 "(Class instVarIndexFor: 'metadata')".
	myMixin:: NormalSendAST new to: MixinClassNode new 
							send: (MessageAST new send: #value  with:{}; 
							 						start: 1; end: 5 
								); start: 1; end: 5. 
								
	metadataNode:: NormalSendAST new to: myMixin 
							send: (MessageAST new send: #instVarAt:  with:{metadataSlotIndex}; 
							 						start: 1; end: mixinAccessor val size
								); start: 1; end: mixinAccessor val size. 
								"mixinClass instVarAt: metadataSlotIndex"
	nestedClassNode:: NormalSendAST new to: metadataNode  
							send: (MessageAST new send: #nestedMixins  with:{}; 
							 						start: 1; end: mixinAccessor val size
								); start: 1; end: mixinAccessor val size. "(mixinClass instVarAt: metadataSlotIndex) nestedMixins"

	mixinNode:: NormalSendAST new to: nestedClassNode  
							send: (MessageAST new send: #at:  with:{mixinAccessor}; 
							 						start: 1; end: mixinAccessor val size
								); start: 1; end: mixinAccessor val size. "(mixinClass instVarAt: metadataSlotIndex) nestedMixins at: mixinAccessor"
																	
	hashCode:: NormalSendAST new to: hereNode 
					send:  (MessageAST  new send: #hash with:{}; 
											start: 1; end: 4
							); start: 1; end: 4. "hash"
							
	hashString:: NormalSendAST new to: hashCode 
								send: (MessageAST  new send: #asString with:{}; 
														start: hashCode end + 2; 
														end: hashCode end + 9
									); start: hashCode start; 
									end: hashCode end + 9. "hash asString"
									
	separator:: StringAST new val: '`'; start: 1; end: 1.
	prefix:: StringAST new val: nestedName, '`'; start: 1; end: nestedName size + 1. 
	"'nestedName`'"
	suffix:: NormalSendAST new to: hashString 
				send:  (MessageAST  new send: #, with:{separator}; 
										start: hashString end +2; 
										end: hashString end + 2
					); start: hashString start; end: hashString end + 2. "hash asString, '`'"
	
	str:: NormalSendAST new to: prefix 
						send:  (MessageAST  new send: #, with:{suffix}; 
												start: prefix end + 2; 
												end: prefix end + 2
							); start: prefix start; end: prefix end + 2. "'nestedName`', hash asString, '`'"
							
	nm:: NormalSendAST new to: str 
						send: (MessageAST  new send: #asSymbol with:{};
												start: str end + 2; 
												end: str end + 9
							); start: str start; end: str end + 9. 
							"'(nestedName`', hash asString, '`') asSymbol"
							
      applyMixin::  NormalSendAST new to:
		(NormalSendAST new to: mixinNode 
						send: (MessageAST new send: #mixin with: {};
												start: mixinNode end + 2; 
												end: mixinNode end  + 6
							); start: mixinNode start; end: mixinNode end + 6
		) 
		"((mixinClass instVarAt: metadataSlotIndex) nestedClasses at: mixinAccessor) mixin"
		send: (MessageAST new  send: #apply:withName: with:{superCall. nm}; start: 1; end: nm end);
		start: 1; end: nm end. 
"((mixinClass instVarAt: metadataSlotIndex) nestedClasses at: mixinAccessor) mixin apply: nameOfSuper 
						withName: (nestedName`', hash asString, '`') asSymbol"
		
	setSlot:: NormalSendAST new to: hereNode 
					send: 	(MessageAST new send: (mixinSlotName, ':') asSymbol 
												with: {applyMixin}; 
												start:  nilCheck end + 9;
												 end: applyMixin end
							); start: nilCheck end + 9; end: applyMixin end. 
"nc`slot:: NC mixin apply: nameOfSuper 
					withName: (nestedName`', hash asString, '`') asSymbol"
	
      setEnclosingObject:: NormalSendAST new to: ncslot value 
										send: (MessageAST  new 
												send: #setEnclosingObjectSlot: "enclosingObjectMsg asSymbol"
												with: {selfNode}; 
												start: mixinSlotName size + setSlot end + 3; 
												end: mixinSlotName size + setSlot end + 30
											); start: 1; 
											end: mixinSlotName size + setSlot end  + 30. 
											"nc`slot enclosingObject: self"
											
	blockBody:: CodeBodyAST new parameters: {}
									temporaries: {}
									statements:{setSlot. setEnclosingObject};
					start: setSlot start; end: setEnclosingObject end.
	block:: BlockAST new body: blockBody; 
					start: blockBody start; end: blockBody end +1.
	if:: NormalSendAST new to: nilCheck 
				send: (MessageAST  new send: #ifTrue: with: {block}; 
										start: nilCheck end + 2; 
										end: block end
					); start: nilCheck start; 
						end: block end. "nc`slot isNil ifTrue:[...]"
					
	ret:: ReturnStatAST new expr: (
				ncslot value
					start: if end + 3; end:  if end + 3 + mixinSlotName size
				);
				start: if end + 2; end: if end + 3 + mixinSlotName size. "^nc`slot"
	
	body:: CodeBodyAST new parameters:{}
							 temporaries:{}
							 statements: {if. ret}; start: if start; end: ret end.
	^MethodAST new pattern:( MessagePatternAST new selector:  simpleName asSymbol
														parameters:{};
														start: 1; end: simpleName size
			);
					 body: body; start: 1; end: body end + 1.
)
compileClassHeader: src <ReadStream> of: classDecl <MixinMirror> ^ <MixinRep> = (
	| rep <MixinRep> newMirror <LowLevelMixinMirror> oldMirror <LowLevelMixinMirror> enclosing <NS2ClassStencilMirror> |
		"Works by appending () to src and compiling as complete class source
		Then adds existing non-synthetic methods and nested class accessors/slots to result"	
	enclosing::classDecl enclosingClass.
	enclosing isNil 
		ifTrue:[
			rep:: compileClassSource: (src contents, '()') readStream within: nil.
			newMirror:: rep first lowLevelMirror.
			] "classDecl is top level class"
		ifFalse:[
			rep:: compileClassSource: (src contents, '()') readStream within: enclosing "mixin".
			newMirror:: rep last first first lowLevelMirror
			]."classDecl is nested class"
	classDecl instanceSide nestedClasses  do:[:nc <ClassStencilMirror> | | nSlotName <String> |
		nSlotName:: slotNameForNestedClassNamed: nc simpleName 
		                   within:  (enclosing isNil ifTrue: [classDecl name] ifFalse: [enclosing name]).
		
		newMirror instVars addMirror: (InstanceVariableMirror named: nSlotName asSymbol)
		].
	"add existing nested class slots into result"
	oldMirror:: classDecl compiledMixinMirror lowLevelMirror.
	oldMirror methods do:[:m <LowLevelMethodMirror>  | 
		(m isSynthetic not or:[m isNestedClassAccessor]) ifTrue:[newMirror methods addMirror: m]	
		].
	oldMirror classMixin methods do:[:m <LowLevelMethodMirror>  | 
		(m isSynthetic not or:[m isNestedClassAccessor]) ifTrue:[newMirror classMixin methods addMirror: m]	
		].
	"copy existing methods and nested class accessors into result"
	self generateSlotAccessorsFor: newMirror.
	"reindex as changes in slots may have moved synthetic slots for nested classes"
	^rep
)
compileClassSource: src <ReadStream> within: enclosing <MixinMirror> ^  <MixinRep>   = (
" the input is source code for a class declaration and a mirror on the enclosing class of the class to be
compiled. The result is a pair of type MixinRep, defined recursively as:

MixinRep ={CompiledMixinMirror. Collection[MixinRep]}

It is a tuple whose first element is an uninstalled low level mirror representing an enclosing
class, and whose second element is a collection of MixinReps, each of which represents one of the nested classes of the enclosing class.

The actual MixinRep returned depends on whether we are compiling a top level class. If so, enclosing is nil, and we return a MixinRep representing said top level class and all its nested classes (recursively).

Otherwise, we return a MixinRep which represents the enclosing class and the nested class that was given in the source (and all its nested classes recursively).
"

| tree <AST>  mixinRep  <MixinRep> |
  tree:: parser classDefinition parse: src.
  saveInput: src.
  setScopeFor: tree in: enclosing. "scope construction phase"

  mixinRep:: enclosing isNil
	ifTrue: [ classNode: tree ]
	ifFalse: [ compileNestedClassAST: tree into: enclosing ].

  scopeMap:: Dictionary new. 
  ^ mixinRep
)
compileExpressionSource: src <ReadStream | String> inContext: aContext <MethodContext> inMixin: enclosing <MixinMirror> ^<LowLevelMethodMirror>
= (
	"Compile a DoIt method.  If aContext is not nil, compile a DoItIn:ctxt method where accesses to names in scope of the context are rewritten to access through the context.  Cog closures complicate this rewriting compared to BlockContexts, as access might be rather indirect.  Also, in cases where a temp is only a copied value and not in an remote indirection vector, it would be impractical to handle writes such that they actually track down all places where the temp lives and update them.  In these cases, we should merely find the most local copy, which I believe is what closure compiled Squeak does."
	|
	body <CodeBodyAST>
	stm <ReadStream>
	method <MethodAST>
	result <LowLevelMethodMirror>
	|
	assert: [aContext isNil or: [aContext method methodClass language isNewspeakLanguage3]] message: 'Context is not NS3!'.
	
	"Parse as a code body"
	src isString ifTrue: [stm:: src readStream] ifFalse: [stm:: src].
	body:: parser codeBody parse: stm.
	saveInput: stm.
	
	"Ensure last statement is a return statement"
	body statements isEmpty ifFalse: [body statements last isReturnStatNode ifFalse:[
		| last |
		last:: body statements removeLast.
		body statements add: (ReturnStatAST new expr: last; start: last start; end: last end) 
	]].

	"Put into a method"
	method:: MethodAST new
		pattern: (aContext isNil
			ifTrue: [MessagePatternAST new selector: #DoIt parameters: {}]
			ifFalse: [MessagePatternAST new selector: #DoItIn: parameters: 
				{VarDeclAST name: #'@context' type: nil}]);
		body: body;
		visibility: #public.
	
	"Build scope"
	
	aContext isNil ifTrue: [
		setScopeFor: method in: (enclosing).
	] ifFalse: [
		| debugInfo debugMapper |
		debugInfo:: (compileMethodSource: aContext method getSource asString readStream within: enclosing) debugInfo. "Resets scope, so do first"
		setScopeFor: method in: (enclosing).
		debugMapper:: debugInfo mapperForContext: aContext.
		debugMapper localNames do: [:name <Symbol> |
			currentScope at: name put: 
				(DebugMappedLocalEntry name: name mapper: debugMapper).
			currentScope at: (name,':') asSymbol put: 
				(DebugMappedLocalEntry name: name mapper: debugMapper).
		].
	].
	
	"Rewrite and compile"
	(method apply: rewriter) apply: methodCompiler.
 	result: methodCompiler result.
	result src: stm contents.
	scopeMap:: Dictionary new.
	^result
)
compileNestedClassAST: tree <ClassDeclarationAST> into: enclosingClass <ClassDeclarationMirror> ^ <MixinRep> = (
	| 
		nestedClassMixinReps <List[MixinRep]>
		enclosingMirror <CompiledMixinMirror>
		lowMirror <LowLevelMixinMirror>
	|
		enclosingMirror:: enclosingClass compiledMixinMirror.
		lowMirror:: enclosingMirror lowLevelMirror.
		
		nestedClassMixinReps:: compileNestedClass: tree within: lowMirror.
		generateSlotAccessorsFor: lowMirror.
		
		 
		
		^ { enclosingMirror . nestedClassMixinReps }.
		"what about other nested classes of enclosing? Not the compiler's responsibility; they are unchanged, and the surrounding reflection system should add them to the mixin rep"
)
currentScope ^ <Scope> = (
  ^scopeStack last
)
delayFor: expression <ExpressionAST> ^<ExpressionAST> = (
	"_here Delay computation: [expression]"
	| 
	sscope <Scope>
	block <BlockAST>
	codebody <CodeBodyAST>
	delay <ExpressionAST>
	|
	
	sscope:: Scope new.
	sscope superScope: currentScope.
	
	delay:: NormalSendAST new
		recv: (NormalSendAST new recv: hereNode; msg: (MessageAST new sel: #Delay; args: {}));
		msg: (MessageAST new sel: #computation:; args: {
			block:: BlockAST new body: (
				 codebody:: CodeBodyAST new
					parameters: OrderedCollection new;
					 temporaries: OrderedCollection new;
					statements: {expression}
			)
		}).
		
	scopeMap at: codebody put: sscope.
	scopeMap at: block put: sscope.
	^delay
)
generateSlotAccessorsFor: m <MixinMirror> = (
"we could let the accessors be generated in the mixin. However, we want to optimize mixin application, so it is best if an initial set of accessors is compiled into the mixin."
| 
sn <String> 
ivIndices <SequenceableCollection[Integer]> 
ivs <Collection[InstanceVariableMirror]> 
|
	ivs:: m instVars collect:[:iv | iv]. "Gross - extract a collection from the mirror group"
      ivIndices:: 1 to: ivs size.
	ivs with: ivIndices do:[: iv :n | 
		| getter  <LowLevelMethodMirror> setter <LowLevelMethodMirror> |
		sn:: iv name.
		getter:: (LowLevelMethodMirror new selector: sn asSymbol)
									method: (Mixin getterPool at:n).
		getter metadata at: #isSynthetic put: true.
		
		m methods addMirror:  getter.
		setter:: (LowLevelMethodMirror new 
									selector: (sn, ':') asSymbol
									) method: (Mixin setterPool at:n).
		setter metadata at: #isSynthetic put: true.					
		m methods addMirror:  setter.
		
		(sn endsWith: '`slot') ifTrue: [
			getter metadata at: #isNestedClassAccessor put: true.
			setter metadata at: #isNestedClassAccessor put: true.
		].
	]
)
initializerSelectorNameFor: selector = (

	^ ('initializer`', selector) asSymbol
)
makePrimaryFactoryFor: hdr <ClassHeaderAST> = (

"Manufacture a method with the given class header's primary constructor's signature, and body that creates a new instance of the class and calls its initializer"

|  newInstance calls body msgFromConstructor args start end cons  initializerSelectorName |

cons:: hdr constructor apply: ASTCopier new.

start:: cons start.
end:: cons end.

newInstance:: NormalSendAST new 
                         to:  selfNode send: (MessageAST new 
                                                                              send: #basicNew 
                                                                              with: {};
                                                                              start: start; end: end
                                                                          ); "self basicNew"
                         start: start; end: end.

args:: hdr constructor parameters collect:[:vd <VarDeclAST> | 
	NormalSendAST new to: hereNode
	                                send: (MessageAST new send: vd name with: {}; 
	                                                                     start: vd start; end: vd end
	                                         );
	                              start: vd start; end: vd end
	].

initializerSelectorName:: initializerSelectorNameFor: cons selector.
msgFromConstructor:: MessageAST new send:  initializerSelectorName with: args.
msgFromConstructor start: start; end: end.

calls:: OrderedCollection new add: (ReturnStatAST new 
                                                           expr:(
                                                                      NormalSendAST new 
                                                                           to: newInstance 
                                                                           send: msgFromConstructor;
                                                                           start: start; end: end
                                                                      ) ;
                                                             start: start; end: end
                                                        );
                                               yourself.
body:: CodeBodyAST new temporaries: OrderedCollection new statements: calls;
						 start: start; end: end.
^MethodAST new pattern: cons body: body visibility: #public; 
				start: start; end: end.
)
methodNode: aNode <MethodAST> ^ <LowLevelMethodMirror> = (

| tree <AST> |
  tree:: aNode apply: rewriter.  "rewrite ast"
  tree apply: methodCompiler.	 "final pass: visit rewritten ast"
"pop scope?"
  ^(methodCompiler result) src: (sourceForNode: aNode)
)
nestScope: s <Scope> = (
"Hook up a new lexically nested scope, and push onto the scope stack"
  s setSuperScope: currentScope.
  pushScope: s
)
popScope ^ <Scope> = (
   ^scopeStack removeLast
)
processClassSideOf: aNode <ClassAST> ofMixin: mixinMirror <LowLevelMixinMirror> = (
| primaryFactory <MethodMirror> factoryAST <MethodAST> |
	processFactoryFor: aNode in: mixinMirror.
	processSide: aNode classSide ofMixin: mixinMirror. "compile class methods"
)
processFactoryFor: aNode <ClassAST> in: mixinMirror <LowLevelMixinMirror> = (
|  factory <MethodMirror> side <SideAST> factoryAST <MethodAST> scopeBuilder <ScopeBuilder> savedScopeMap <Dictionary[AST, Scope]> |
	processFactoryFor: aNode hdr inScope: (scopeMap at: aNode classSide) in: mixinMirror.
)
processFactoryFor: aNode <ClassHeaderAST> inScope: s in: mixinMirror <LowLevelMixinMirror> = (
|  factory <MethodMirror> side <SideAST> factoryAST <MethodAST> scopeBuilder <ScopeBuilder> savedScopeMap <Dictionary[AST, Scope]> |
 	factoryAST:: makePrimaryFactoryFor: aNode.
	(processMethod: factoryAST inScope: s in: mixinMirror)
		metadata at: #isConstructor put: true.

	"need to build scope for factory before visiting it"
)
processInitializerFor: aNode <ClassAST> in: mixinMirror <LowLevelMixinMirror> = (
	processInitializerFor: aNode hdr inScope: (scopeMap at: aNode instanceSide) in: mixinMirror.
)
processInitializerFor: aNode <ClassHeaderAST>  inScope: s <Scope> in: mixinMirror <LowLevelMixinMirror> = (
|   initializerASTs <List[MethodAST]> |

	#BOGUS yourself. 
	"The superclass clause is not a property of the mixin; this method is specific to the application. That said, all applications derived from the class declaration will share it"
	processMethod: (superConstructorMethodFor: aNode) inScope:  s in: mixinMirror. 
 	initializerASTs:: allInitializersFor: aNode in: mixinMirror.
	initializerASTs do:[: init <MethodAST> |
		processMethod: init inScope: s in: mixinMirror.
		]
)
processInstanceSideOf: aNode <ClassAST> ofMixin: mixinMirror <LowLevelMixinMirror> ^ <Collection[MixinRep]> = (
| side <SideAST> |
	processInitializerFor: aNode in: mixinMirror.
	side:: aNode instanceSide.
	processSide: side ofMixin: mixinMirror. "compile instance methods"
	^compileNestedClassesOf: side within: mixinMirror. "gather nested classes"
)
processMethod: aNode <MethodAST> inScope: s <Scope>  in: mixinMirror <LowLevelMixinMirror> = (
|  scopeBuilder <ScopeBuilder> method <LowLevelMethodMirror> |

	scopeBuilder:: ScopeBuilder nestedIn: s atLevel: currentDepth.
	aNode apply: scopeBuilder.
"need to build scope for method before visiting it"
	method:: methodNode: aNode.
	method metadata at: #isSynthetic put: true.
	mixinMirror methods addMirror: method.
	^method
"install method"	
)
processSide: side <SideAST> ofMixin: mixinMirror <LowLevelMixinMirror> = (
  side categories do:[:cat |  | mirr <MethodMirror> |
                     cat methods do:[:m | 
	"who checks that the methods do not conflict with each other or with another slot or class in the same enclosing class? The mirror or the compiler?"
	                         	mirr:: methodNode: m.
					  	mirr metadata at: #category put: cat name.
                               	mixinMirror methods addMirror: mirr.
                                 ].
                     ].
)
pushScope: s <Scope> = (
  scopeStack addLast: s
)
resetScope = (
	scopeMap: Dictionary new.
)
saveInput: src <ReadStream> = (
  src position: 1.
  input: src. "save the input"
)
setScopeFor: aNode <AST> in: enclosing <MixinMirror| Nil> = (

| scopeBuilder <ScopeBuilder> |

  pushScope: Scope new.
  enclosing isNil ifFalse:[nestScope:: ScopeBuilder new buildScopeFor: enclosing].
						 "establish enclosing scope"

  currentDepth:: currentScope depth - 1. 
"There should be one scope for each enclosing class, plus the dummy initial scope."

  scopeBuilder:: ScopeBuilder nestedIn: currentScope atLevel: currentDepth.
  aNode apply: scopeBuilder.
  "scopeMap:: scopeBuilder scopeMap."
)
sourceForNode: node <AST> ^ <String> = (
	| savedPos <Integer> pos <Integer> len <Integer> s <String> |
	savedPos:: input position.
	len: (node end - node start) + 1.
	s:: String new: len.
	input position: node start -1.
	input next: len into: s startingAt:1.
	input position: savedPos.
	^s
)
superConstructorCallFor:  aNode <ClassHeaderAST> ^ <NormalSendAST> = (
"create call to super constructor method"
| 
var  <VariableAST> 
send <NormalSendAST>
start <Integer> 
end <Integer>  
copier <ASTCopier>
superMsg <MessageAST>
args <List[VariableAST]> 
|

	start:: aNode superConstructorCall start.
	end::  aNode  superConstructorCall end.
	copier:: ASTCopier new.
	var:: VariableAST new name: #self; start: start; end: end.
	args:: aNode constructor parameters collect:[:p <VarDeclAST> |
			hereSendFrom: p
		].
	superMsg::  MessageAST new 
		send: (superConstructorNameFor: aNode) with: args; 
		start: start; end: end.
	send:: NormalSendAST new to: var send: superMsg; start: 	start; end: end.	
	^send
)
superConstructorMethodFor:  aNode <ClassHeaderAST> ^ <MethodAST> = (
| 
start <Integer> 
end <Integer>
stmts <List[StmtAST]> 
var  <VariableAST> 
initHdr <MessagePatternAST>
superMsg <MessageAST> 
send <NormalSendAST>
body  <CodeBodyAST>
copier <ASTCopier>
|

	start:: aNode superConstructorCall start.
	end::  aNode  superConstructorCall end.
	copier:: ASTCopier new.
	initHdr:: aNode constructor apply: copier. "set up scope with constructor parameters"
	initHdr selector:(superConstructorNameFor: aNode).
	"create call to superclass initializer"
	stmts:: OrderedCollection new. 
	var:: VariableAST new name: #super; start: start; end: end.
	superMsg::  aNode  superConstructorCall apply: copier.
	superMsg sel: (initializerSelectorNameFor: superMsg sel).
	send:: NormalSendAST new to: var send: superMsg; start: start; end: end. 
	stmts addFirst: send.
	body:: CodeBodyAST new temporaries: OrderedCollection new
                                       	statements: stmts;
                                      	start: start; end: end.
	^MethodAST new pattern: initHdr
                            body: body
                            visibility: #private;
                            start: start; end: end	
)
superConstructorNameFor: aNode <ClassHeaderAST> ^ <Symbol> = (
	^(aNode name, '`superInit`', aNode constructor selector) asSymbol 
)
syntheticNameSeparator ^ <String> = (
  ^Language syntheticNameSeparator	
)
syntheticNameSeparatorCharacter ^ <Character> = (
  ^Language syntheticNameSeparatorCharacter	
)'nested classes - private'
compileNestedClasses: nestedClasses <Collection[ClassDeclarationAST]> within: mixinMirror <LowLevelMixinMirror> ^ <List[MixinRep]> = (

| results <List[MixinRep]> |
      results:: OrderedCollection new.
	nestedClasses do:
		[ :nc <ClassDeclarationAST> |  | nSlotName <String> |
		nc hdr category: mixinMirror category, '-nested'.
		nSlotName:: slotNameForNestedClassNamed: nc name 
		                   within: mixinMirror name.
		mixinMirror instVars addMirror: (InstanceVariableMirror named: nSlotName).
		results add: (classNode: (nestedMixinWrapperFor: nc in: mixinMirror)). "make 'mixin' (a Smalltalk subclass of ProtoObject) for nested class"
		createNestedClassAccessorFrom: nc within: mixinMirror 
		].
	^results
)
compileNestedClassesOf: aNode <SideAST> within: mixinMirror <LowLevelMixinMirror> ^ <Collection[MixinRep]> = (
"where do we check that nested classes do not conflict with each other, or with methods or slots?"
	^compileNestedClasses: aNode nestedClasses within: mixinMirror
)
createNestedClassAccessorFrom: classDecl <ClassDeclarationAST> within: mixinMirror <LowLevelMixinMirror> = (
 
"Create an accessor method for the nested class represented by the incoming class tree.
This accessor will lazily generate the nested class when its enclosing instance is first asked for it.
"
| n <String>  accessorString <String> ast <MethodAST> nestedName <String> hdr <ClassHeaderAST> |

hdr:: classDecl hdr.
n:: hdr name. 
nestedName:: fullyQualifySimpleName: hdr name with: mixinMirror name.
ast:: accessorASTForNestedClassNamed: n fullName: nestedName superName: hdr superclassName.
(processMethod: ast inScope: (scopeMap at: classDecl instanceSide) superScope in: mixinMirror)
	metadata at: #isNestedClassAccessor put: true.
)
fullyQualifySimpleName: sn <Symbol> with: fqp <Symbol> ^ <Symbol> = (
	^SystemMetadata fullyQualifySimpleName: sn with: fqp
)
nestedMixinWrapperFor: nested <ClassDeclarationAST> in: outerClass <MixinMirror>  ^ <ClassDeclarationAST> = (

"Wrap a class declaration to make it look like a nested mixin within outerClass should. This includes making the name be the fully qualified name, and hiding the superclass "
| wrapper <ClassDeclarationAST> |

wrapper:: nested clone.
wrapper hdr: nested hdr clone.
wrapper hdr name: (fullyQualifySimpleName: nested name with: outerClass name).
^wrapper
)
slotNameForNestedClassNamed: ncn <String> within: outerName <String> ^ <String> = (
	^SystemMetadata mixinSlotNameFor:(
								fullyQualifySimpleName: ncn 
		                  			 with: outerName
					). "(fullyQualifySimpleName: ncn  with: outerName), '_slot'"
)'private'
allInitializersFor: aNode <ClassHeaderAST> in: mixinMirror <MixinMirror> ^ <Collection[MethodAST]> = (
"2nd argument unused!"
" Because the init sequence may not fit in a single method (because too many literals are needed for all the setters and getters, we produce an init method that calls a number of private  sub-initializers. This main initializer routine first calls the superclass  main initializer, then calls the subinitializers to set all the slots, and then any initialization code in the header."
| 
start <integer>
end <Integer>
stmts <List[StmtAST]> 
initHdr <MessagePatternAST>
body <CodeBodyAST>  
slots <Collection[StmtAST]>
subs <Collection[MethodAST]>
copier <ASTCopier>
|

	start:: aNode superConstructorCall start.
	end::  aNode  superConstructorCall end.
	copier:: ASTCopier new.
	initHdr:: aNode constructor apply: copier. "set up scope with constructor parameters"
	initHdr selector: (initializerSelectorNameFor: initHdr selector).	
	subs:: subInitializersFor: aNode. "compute (empty) subinitializers"
	
	slots:: aNode slots collect:[:slot <SlotDefAST> |
		| aMsg <MessageAST> slotInitializer <ExpressionAST> |
		slotInitializer:: slot initializer apply: copier.
		aNode isSeq ifFalse: [slotInitializer:: delayFor: slotInitializer].
		aMsg:: MessageAST new 
			send: (slot name, ':') asSymbol with:  {slotInitializer};
			start: slot start;
			end: slot end.
		NormalSendAST new msg: aMsg; 
			recv: (selfNode start: aMsg start; end: aMsg end);
			start: aMsg start; end: aMsg end.
	].

	(1 to: slots size) with: slots do:[:n :stmt |
		(subs at: n  // methodCompiler slotsPerMethod + 1) body statements add: stmt
	]. "populate subinit methods with slot initialization code"
	stmts:: OrderedCollection new. 
	
"create call to superclass initializer"
	stmts addFirst: (superConstructorCallFor: aNode). "add superclass init call as first statement"

	1 to: subs size -1 do:[:i | stmts add: (sendForSub: (subs at: i))]. "create calls to subinitializers"
	stmts addAll: (aNode  initExprs collect:[:ie  <ExpressionAST> | ie   apply: copier]). "process initializer code"

	body:: CodeBodyAST new temporaries: OrderedCollection new
                                       	statements: stmts;
                                      	start: start; end: end.

	subs at: subs size put: (MethodAST new pattern: initHdr
                            body: body
                            visibility: #public;
                            start: start; end: end). "package method"
	^subs
)
computeMixinFrom: aNode <ClassHeaderAST> ^ <LowLevelMixinMirror> = (


| ivNames <Collection[String]> mixinMirror <LowLevelMixinMirror> hdrString <String>  |

  ivNames::   aNode slots collect:[:s | s name].
  mixinMirror::  LowLevelMixinMirror named: aNode name isMeta: false.
  ivNames do:[:iv | 
		mixinMirror instVars addMirror: (InstanceVariableMirror named: iv)
		].
   hdrString:: input contents copyFrom: aNode start to: aNode end.
 ^(CompiledMixinMirror language: language header: hdrString mirror: mixinMirror)
					category: aNode category;
					comment: (aNode classComment isNil 
									ifTrue:[''] 
									ifFalse:[aNode classComment]
									).
)
enclosingObjectMsgFor: mirror <MixinMirror> ^ <String> = (
  ^enclosingObjectMsgFromName: mirror name
)
enclosingObjectMsgFromName: nm <String> ^ <String> = (
  ^'enclosingObject', syntheticNameSeparator, nm 
)
getInstanceVariables: aClassHeaderNode <ClassHeaderAST> ^ <String> = (

 "returns the language specific slots - e.g. instance variables as a string"
^aClassHeaderNode  slots inject:'' into:[:s <String> :v <SlotDefAST>  | s, v name, ' '].
)
hereNode ^ <VariableAST> = (
	
"generate a an AST representing _here; used for here sends. We use a string so that we can represent a name that is not a legal identier"
	#BOGUS. "_here is in fact a legal identifier. At some point, all uses should be tracked down and replaced with @here, which really is illegal since it would be interpreted as a binary message."
^VariableAST new name: #'_here'; start: 0; end: 0.
)
hereSendFrom: arg <VarDeclAST>  ^ <MessageNode> = (

^NormalSendAST new to: hereNode send: (MessageAST new send: arg name with: {};
					start: arg start; end: arg end
				); 
                        start: arg start; end: arg end
)
selfNode ^ <VariableAST> = (

"generate a an AST representing self; used for implicit self sends"
^VariableAST new name: #self; start: 0; end: 0
)
sendForSub: sub <MethodAST> ^ <NormalSendAST> = (

"Create a single call to a sub-initializer from the main initiializer "
| args <Collection[SendAST]> |

  args::  sub pattern parameters collect:[:arg | hereSendFrom: arg].
  ^ (NormalSendAST new to: selfNode send: (
	MessageAST new send: sub selector
					   with: args ;
					   start: sub  start; end:   sub end
					)) start: sub start; end: sub end
					
)
subInitializer: n <Integer> for: aNode <ClassHeaderAST>  ^ <MethodAST> = (

|  initHdr <MessagePatternAST> body <CodeBodyAST>  |

initHdr:: aNode constructor apply: ASTCopier new. "set up scope with constructor parameters"
initHdr selector: (subinitializer: n nameFor: aNode).
body:: CodeBodyAST new temporaries: OrderedCollection new
                                       statements: OrderedCollection new;
							start: aNode start; end: aNode end.

^MethodAST new pattern: initHdr
                           body: body
                           visibility: #private;
                            start: aNode start; end: aNode end.
)
subInitializersFor: aNode  <ClassHeaderAST>  ^ <Array[MethodAST]> = (

| subs <Collection[MethodAST]>  noSubs <Integer>  |
  noSubs:: aNode slots size // methodCompiler slotsPerMethod + 1.
  subs:: Array new: noSubs + 1.
  1 to: noSubs do:[:n <Integer> | 
		subs at: n put: (subInitializer: n for: aNode)
	].
  ^subs
)
subinitializer: n <Integer> nameFor: aNode  <ClassHeaderAST>  ^ <Symbol> = (
| prefix <String> suffix <String> fqn <String> |

  prefix::  ( aNode name,  syntheticNameSeparator, n printString,  syntheticNameSeparator, 'init').
  suffix:: aNode constructor parameters size = 0 
                    ifTrue:['']
                    ifFalse:[
				aNode constructor parameters size = 1
					ifTrue:[':']
					ifFalse:[syntheticNameSeparator, aNode constructor selector]
	].
  ^(prefix, suffix) asSymbol
)'public access'
classNode: aNode <ClassDeclarationAST> ^ <MixinRep> = (
"type MixinRep = {CompiledMixinMirror. {MixinRep}}"
| mixinMirror <LowLevelMixinMirror> nestedClasses <Collection[MixinRep]> |
  assert:[aNode hdr category notNil] message: 'No category for class header'.
  mixinMirror:: computeMixinFrom: aNode hdr.
  currentDepth::currentDepth + 1.
  nestedClasses:: processInstanceSideOf: aNode ofMixin: mixinMirror lowLevelMirror.
  generateSlotAccessorsFor: mixinMirror lowLevelMirror. 
"must be called after nested classes are processed, so all synthetic slots have been added"
  processClassSideOf: aNode ofMixin: mixinMirror lowLevelMirror classMixin.
  currentDepth::currentDepth - 1.
  ^{mixinMirror. nestedClasses}
)
compileMethodSource: src <ReadStream | String> within: enclosing <MixinMirror>  
       			    ^ <LowLevelMethodMirror>
= (
| tree <AST> result <LowLevelMethodMirror> stm <ReadStream> | 
#BOGUS yourself. "Make sure we take the line below out when new src control is in use"
  src isString ifTrue: [stm:: src readStream] ifFalse: [stm:: src].
  tree:: parser methodDecl parse: stm.
  saveInput: stm.
  setScopeFor: tree in:  (enclosing). "scope construction phase"
  result::methodNode: tree. "rewrite and compile"
  scopeMap:: Dictionary new.
  ^result
)
compileNestedClass: nc <ClassDeclarationAST> within: mixinMirror <LowLevelMixinMirror> ^ <List[MixinRep]> = (
	^compileNestedClasses: (OrderedCollection with: nc) within: mixinMirror.
))
class DebugMappedLocalEntry name: nom mapper: mapper = SymbolTableEntry for: {nil. nil} (
"Describe the class in this comment."|
	name = nom.
	debugMapper = mapper.
|)
('as yet unclassified'
getterAst = (
	^debugMapper getterAstFor: name.
)
isDebugMappedLocalEntry = (
	^true
)
isMessagePatternNode = (
	^false
)
isMethodNode = (
	^false
)
isVarDeclNode = (
	^false
)
setterAst: newVal = (
	^debugMapper setterAstFor: name putting: newVal.
))
class Scope = (
"A generic scope facility."| 
superScope 
bindings =  IdentityDictionary new.
end
|)
('access'
at: aKey put: aValue = (


^self bindings at: aKey put: aValue
)
at: aKey put: aValue ifThere: aBlock = (

    "Associates aValue with aKey and answers aValue if aKey
    was absent. Otherwise answers the value of aBlock."
    | wasAbsent |
    self assert: [aKey isSymbol] 
	message:['Attempt to ok up non-symbol ',aKey printString, ' in scope'].
    wasAbsent:: false.
    bindings at: aKey ifAbsent: [bindings at: aKey put: aValue. wasAbsent:: true].
    ^ wasAbsent
        ifTrue: [aValue]
        ifFalse: [aBlock value]
)
at: key = (

	"Answers the value associated with aKey in this or one the super scopes or fails if aKey is absent"
	^self at: key ifAbsent: [self error: 'Key ', key, ' not found!']
)
at: key ifAbsent: blk = (

    "Answers the value associated with aKey in this or one of the superScopes or the value of aBlock if aKey is absent."

	"Optimization note: This is written using [nil] blocks to avoid passing 
		non-clean blocks dynamically down the scope structure."

	| val <T> |
	(val:: self bindings at: key ifAbsent: [ nil ]) notNil
		ifTrue: [ ^val ].
	self superScope isNil
		ifTrue: [ ^blk value ].
	(val:: self superScope at: key ifAbsent: [ nil ]) notNil
		ifTrue: [ ^val ].
	^blk value
)
clear = (
	self bindings keys do:[:k | self bindings removeKey: k].
)
includesIndex: key = (
"should this search the superscope?"
    ^ self bindings includesKey: key
)
includesIndexLocally: key <NameType > ^ <Boolean> = (


^self bindings includesKey: key.
)
removeKey: key = (


self bindings removeKey: key
)
removeKey: key ifAbsent: blk = (


self bindings removeKey: key ifAbsent: blk
)
within: scope = (
    "Creates and initializes a new (sub)scope within scope."
      self superScope: scope.
  )'as yet unclassified'
depth ^ <Integer> = (
	superScope ifNil:[^0].
	^superScope depth + 1.
)
printOn: stm = (
	stm nextPutAll: 'Scope('.
	superScope printOn: stm.
	bindings keysAndValuesDo: [:k :v |
		stm space.
		k printOn: stm.].
	stm nextPutAll: ')'.
)
setSuperScope: sc = (
	
	superScope isNil
		ifTrue: [superScope: sc]
		ifFalse: [superScope setSuperScope: sc]
))
class SemanticMethod decl: d <MethodAST> = SemanticNode onAST: d (
"Semantic info for a method declaration. Things like the frame size"|
frameSize <Integer>
|)
()
class SemanticNode onAST:  ast = (
"Represents semantic information about a construct."|
tree = ast.
|)
()
class SemanticVarDecl decl: d <VarDeclAST> = SymbolTableEntry for: d (
"Semantic info for a variable: slot, local or parameter."|
  offset <Integer>
  remote ::= false.
  remoteVector <SemanticVarDecl>
|)
('as yet unclassified'
isTemporaryAST ^ <Boolean> = (
	^data isTemporaryAST
)
setIndex: i <Integer> InVector: v <VarDeclAST> = (
	assert: remote message: 'Var Decl is not remote'.
	remoteVector:: v.
	offset:: i.
)
variableClass ^ <Class> = (
	^data variableClass
))
class SymbolTableEntry for: datum = (| 
  sym  
  data = datum first.  
  depth = datum last.  
|)
('as yet unclassified'
isMethodNode = (^self data  isMethodNode)'testing'
isMessagePatternNode = (^self data  isMessagePatternNode)
isVarDeclNode = (^self data isVarDeclNode)) : ('as yet unclassified'
forMessage: selector atDepth: depth = (
	^ SymbolTableEntry for: { MessagePatternAST new selector: selector . depth }.
))'as yet unclassified'
PERFORMANCE_NOTE = (
	"The compiler could generate better code in the following areas:
	
	1) In some cases, it emits storeIntoTemp followed by pop instead of popIntoTemp.
	2) Often it generates code to nil out a slot/temp that has yet to be used.  However, in addressing this one must remember explicit initialization to nil is important for temps read before written in an inlined block.
	3) It is not necessary to remember the argument to a setter send when the send is a top level statement that is not a return statement.
	4) It could inline ifNil:/ifNotNil: as the Squeak compiler does.
	5) It could inline and:/or:
	"
)
assert: c = (
	self assert: c message: 'Assert failed'.
)
in: collection anySatisfy: predicate = (
	collection do: [:each | 
		(predicate value: each) ifTrue: [^true].
	].
	^false
))