Source

newspeak / Newspeak2StrongtalkCompilation.ns3

   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
Newspeak3
'Newspeak2Strongtalk'
class Newspeak2StrongtalkCompilation usingPlatform: platform 
                                           newspeakParser: ns2Parser <Newspeak2Parsing>
                                           mirrorLib: mirrors = (
"This is a cross-compilation module for  Newspeak to Strongtalk. It includes a Newspeak-to-Strongtalk cross 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 2009-2012 Gilad Bracha
   
   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"|

      astModule = ns2Parser ASTModule.
	Collection = platform Collections Collection.
	Dictionary = platform Collections Dictionary.
      IdentityDictionary = platform Collections IdentityDictionary.
	OrderedCollection = platform Collections OrderedCollection.
	Set = platform Collections Set.
	WriteStream = platform Collections WriteStream.
	Class = platform Kernel Class.	
	Error = platform Exceptions Error.
	Number = platform Kernel Number.
	CrLfFileStream = platform CrLfFileStream.
	
	Parser = ns2Parser Parser.

	ASTTool = astModule ASTTool.
      ASTCopier = astModule ASTCopier.
      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.
	NormalSendAST = astModule NormalSendAST.
	NumberAST = astModule NumberAST.
	ReturnStatAST = astModule ReturnStatAST.
      SendAST = astModule SendAST.
	SymbolAST = astModule SymbolAST.
	TupleAST = astModule TupleAST.
      VarDeclAST = astModule VarDeclAST.
	VariableAST = astModule VariableAST.

	"Global variables"
	
	Transcript = platform Transcript.

	"{Newspeak-core-mirror}"  "a bunch of mirror stuff"
	
	SystemMetadata = mirrors SystemMetadata.
	LowLevelMirror = mirrors mirrors Mirror.
	LowLevelMixinMirror = mirrors LowLevelMixinMirror.
	InstanceVariableMirror = mirrors InstanceVariableMirror.
	
	"Module variables"
	parser = Parser new.
	getterPool = Array new: 256.
      setterPool = Array new: 256.
	protected StringAST = astModule StringAST.
|)
(
class CompiledMixinMirror language: l header: h mirror: llm <LowLevelMixinMirror> = (
"Represents a compiled (but uninstalled) NS3 class declaration."|
	language <Language> = l.
	header <String> = h.
	lowLevelMirror <LowLevelMixinMirror> = llm.
	commentString
|)
('as yet unclassified'
category ^ <String> = (
	^lowLevelMirror category
)
category: c <String>  = (
	lowLevelMirror category: c
)
comment ^ <String> = (
	commentString ifNil:[^''].
	^commentString

)
comment: c <String> = (
	commentString: c
)
name ^ <String> = (
	^lowLevelMirror name
)) : ()
class Compiler = (
"This is the Newspeak-2-Strongtalk cross compiler. 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 produces a .dlt file that contains the Strongtalk code. Internally, the compiler manufactures low-level mirror representing the results of compilation. These mirrors are then used to produce the output file.
 
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 AST2SmalltalkCompiler, which produces Smalltalk 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. 

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:.

Once a mirror has been produced, the output* routines convert it into a .dlt file suitable as input to Strongtalk. Each class declaration is converted into a  subclass of NewspeakObject. NewspeakObject provides a class instance variable named metadata; in a defining class, the metadata holds information such as the enclosing mixin and nested mixins. 
The output sets up this metadata to connect the different classes produced in accordance with the original nesting structure given by NS2.

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: .

Classes have a class variable named EnclosingObjects_N, where N is the fully qualified name of the class. This variable holds an array of the classes enclosing objects wrt to its lexically enclosing class declaration D. The first element is the immediately enclosing object, the second, the 2nd enclosing object wrt D, etc. In general, the kth entry is the kth enclosing object wrt D.  The n+1st entry is nil.

Classes also have a class variable named MixinMetadata_N (where, again, N is the fully qualified class name).  This variable points at the metadata of the mixin corresponding to the class. This metadata includes the nested mixins, which are needed to produce the nested classes of a given class. The accessors for nested classes produce these nested classes lazily, and make use of both class variables just described - the metadata to find the mixin they need to invoke, and the enclosing object array in order to set up the new class' enclosing objects.

See AST2SmalltalkCompiler for more details.

Limitations:

The use of $_ as a synthtic name separator is problematic, as it can occur in legal Newspeak identifiers, and so clashes can occur. 

We rely on access to the Strongtalk Mirror class. If a Newspeak class has a slot named Mirror, the scheme breaks down. We should access Mirror via a synthetic name. "|

scopeMap <Dictionary[Scope, AST]> ::= Dictionary new.
scope <Scope>
scopeStack <OrderedCollection[Scope]> = OrderedCollection new.
literalTable <Dictionary[Symbol, Integer]>
input <ReadStream>
rewriter = Rewriter new.
methodCompiler = AST2SmalltalkCompiler new.
currentDepth <Integer> "The lexical nesting level of the current class; 
							top level classes are at level 0"
currentMixinUID <String>
|)
(
class AST2SmalltalkCompiler = 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.

It generates Smalltalk code, subject to certain assumptions about the structure if the enclosing Smalltalk classes.

Among these: 

Each class has a class variable named EnclosingObjects_N, where N is a per mixin unique ID (for now, just its fully qualified name, using _ as the synthetic separator), and provides a setter for it named enclosingObjects:.  For top level classes, this class variable is set to an array of size 1 with an entry set to nil.

Code that requires access to members of outer classes does so using this class variable. The lexical distance from the call to the relevant member is statically known, and is used as an index into the enclosing objects array, thereby retrieving the correct impliict receiver. The message is then sent in the normal way.

Each mixin has metadata that specifies its nested mixins in a map indexed by the fully qualified name of the mixin. The metadata also links to the actual mixin. This metadata is made available to each invocation of the mixin in a class variable named MixinMetadata_N.  The class variable can be set using the setter mixinMetadata:."| 
  resultStream
  scopeStack <OrderedCollection[Scope]>
  currentSelector <Symbol>
|setup)
(
class MessageParser = Parser (
"A specialized NS2 parser that can deal with synthetic identifiers.")
('as yet unclassified'
letter = (
		^super letter | (char: $`).
)) : ()'as yet unclassified'
blockLocalReturnNode: node <BlockLocalReturnAST> = (
	node expr apply: self.
)
boolNode: node = (
  assert: [ node apply: rewriter BoolVisitor new] message: 'Boolean node expected'.
  generate: node val printString.
)
cascadedSendNode: node <CascadedSendAST> = (

   node prevSend apply: self.
   generate: '; '.
   newline.
   node msg apply: self.
)
contextNode: node <ContextAST> = (
	variableNode: node
)
currentMethod ^ <SemanticMethod> = (
	^currentScope at: #'`currentMethod'
)
currentScope ^ <Scope> = (
	^scopeStack last
)
explicitOuterReceiverNode: node <ExplicitOuterReceiverAST> = (
  generateLeadingWhitespace: node.
  processOuterReceiverAtDepth: node depth.
)
generate: s <String> = (
	resultStream nextPutAll: s
)
generateLeadingWhitespace: node <AST> = (
	generate: ' '.
)
implicitSendNode: node <ImplicitRcvrSendNode> = (
  generateLeadingWhitespace: node.
  processOuterReceiverAtDepth: node depth.
  node msg apply: self.
)
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  = (
	generate: 'self actualClass mixin'
)
newline = (
	resultStream nextPut: Character lf; nextPut: Character cr.
)
nilNode: node = (
  assert: [ node apply: rewriter NilVisitor new] message: 'Nil node expected'.
  generate:  'nil'.
)
numberNode: node <NumberAST>  = (
	assert:[node isNumberNode] message: 'Number node expected'.
	generate: node val printString.
)
parameterDeclNode: node <ParameterAST> = (
	variableNode: node "just spit it out" "should spit out type info as well"
)
popScope ^ <Scope> = (
  ^scopeStack removeLast
)
processBinaryMessageArgument: arg  = (
	| parenthesesRequired <Boolean> |
	parenthesesRequired:: false.
	arg isAssignmentNode ifTrue:[parenthesesRequired:: true]. 
	arg isSendNode ifTrue:[
		parenthesesRequired:: (precedenceOf: arg) > 1
		].
	parenthesesRequired ifTrue:[generate: '('].
	arg apply: self.
	parenthesesRequired ifTrue:[generate: ')'].	
)
processKeywordMessageArgument: arg  = (
	| parenthesesRequired <Boolean> |
	parenthesesRequired:: false.
	arg isAssignmentNode ifTrue:[parenthesesRequired:: true]. 
	arg isSendNode ifTrue:[
		parenthesesRequired:: (precedenceOf: arg) = 3
		].
	parenthesesRequired ifTrue:[generate: '('].
	arg apply: self.
	parenthesesRequired ifTrue:[generate: ')'].	
)
processOuterReceiverAtDepth: n <Integer> = (
  n = 0 ifTrue:[^generate:'self '].
  generate: '(EnclosingObjects'.
  generate: syntheticNameSeparator.
  generate:  currentMixinUID.
  generate: ' at: '.
  generate: n printString.
  generate: ') '.	
)
pushScope: s <Scope>= (
 scopeStack addLast: s
)
result ^ <MethodMirror>  = (
	^(MethodMirror named: currentSelector) method: resultStream contents
)
returnStatNode: node <ReturnStatAST> = (
 	assert:[node isReturnStatNode] message: 'Return node expected'.
 	generate: '^'.
	node expr apply: self.
)
setup = (
	resultStream:: WriteStream on: String new.
	scopeStack:: OrderedCollection new.
)
slotsPerMethod = (
	^64
)
stringNode: node <StringAST>  = (
	assert:[node isStringNode] message: 'String node expected'.
	generate: node val printString.
)
superSendNode: node <SuperSendAST> = (
	generate: 'super '.
	node msg apply: self.
)
symbolNode: node <SymbolAST>  = (
	assert:[node isSymbolNode] message: 'Symbol node expected'.
	generate: node val printString.
)
temporaryDeclNode: node <ParameterAST> = (
	variableNode: node "just spit it out" "should spit out type info as well"
)
variableNode: node <VariableAST> = (
	generateLeadingWhitespace: node.
	generate: node name.
)'node traversal'
assignmentNode: node <AssignmentAST> = (

| i <Integer>  |
	assert: [ node isAssignmentNode] message: 'Assignment node expected'.
	node var apply: self.
	generate: ' :='.
	node expr apply: self.
)
blockNode: node <BlockAST> = (
  pushScope: (scopeMap at: node).
  generate: '['.
  node parameters do:[:p |  generate: ' :'. p apply: self].
  generate: ' '.
  node parameters isEmpty not ifTrue:[generate: '| '].
  newline.
  node body apply: self.
  generate: ']'.
  popScope.
)
charNode: node <CharAST> = (
  "add literal char to literal table"
  generate: node val printString
)
codeBodyNode: node <CodeBodyAST> = (
   node temporaries isEmpty ifFalse:[
	generate: '| '.
  	node temporaries do:[:t <TemporaryAST> | 
		t apply: self.
		generate: ' '.
		]. 
	generate: '|'.
	 newline.
	].
   node statements do:[:s | 
	s apply: self.
	generate: '.'.
	newline.
	]. 
)
messageNode: m <MessageAST> = (
| kwds <List[String]> |
  generateLeadingWhitespace: m.
  m args isEmpty ifTrue:[^generate: m sel]. "unary selector"
  m args size = 1 ifTrue:[ "binary or single keyword selector"
	generate: m sel.
	m sel = #- ifTrue:[generate: ' ']. "to avoid looking like unary negation"
	^processBinaryMessageArgument: m args first.
	]. 
  kwds:: MessageParser new kw plus parse: m sel asString readStream.
  m args with: kwds do:[:a :kw <String> | 
	generate: ' '.
	generate: kw. 
	processKeywordMessageArgument: a.
	].
)
messagePatternNode: node <MessagePatternAST> = (
| kwds <List[String]> |
  newline.
  currentSelector:: node selector.
  node parameters isEmpty ifTrue:[^generate: node selector]. "unary selector"
  node parameters size = 1 ifTrue:[ "binary or single keyword selector"
	generate: node selector.
	^node parameters first apply: self
	]. 
  kwds:: MessageParser new kw plus parse: currentSelector asString readStream.
  node parameters with: kwds do:[:p :kw <String> | 
	generate: ' '.
	generate: kw. 
	p apply: self.
	]
)
methodNode: node <MethodAST> = (
"create a Strongtalk method, whose body is the result of compiling the node's body."
| argC <integer> |

   setup.
   pushScope: (scopeMap at: node).
   node pattern apply: self.
   generate: ' '.
   newline.
   node body apply: self.
   newline.
   popScope.
)
normalSendNode: node <NormalSendAST> = (
	| parenthesesRequired <Boolean> |

 	assert: [ node isNormalSendNode] message: 'NormalSendNode expected'.
	parenthesesRequired:: false.
	node recv isAssignmentNode ifTrue:[parenthesesRequired:: true]. "(x:: true) ifTrue:[3]"
	node recv isSendNode ifTrue:[
		parenthesesRequired:: ((precedenceOf: node recv) > (precedenceOf: node)) "(a + b) bar""(foo: x)+1"
								or:[(precedenceOf: node recv) = 3] " (foo:3) bar: 2"
		].
	parenthesesRequired ifTrue:[generate: '('].
 	node recv apply: self.
	parenthesesRequired ifTrue:[generate: ')'].
 	node msg apply: self.

)
parameterNode: node <ParameterVariableAST> = (
	variableNode: node
)
receiverNode: node = (
	variableNode: node
)
superVarNode: node <SuperVarNode>  = (
	variableNode: node
)
temporaryNode: node <TemporaryVariableAST>
 = (
	variableNode: node
)'private'
precedenceOf: send <SendAST> ^ <Integer> = (

	send isCascadedSendNode ifTrue:[^3]. "Nested cascade has low priority"
	send msg sel first isLetter ifFalse: [^ 2]. "binary message"
	send msg sel last = $: ifTrue: [^ 3]. "keyword message"
	^ 1 "unary message"
)) : ()
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.
	protected readMap <Map[TemporaryAST, Integer]> = Dictionary new.
	protected writeMap <Map[TemporaryVariableAST, {Integer. Integer}]> = Dictionary new. 
	
|)
(
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
)
name = (
	^val printString asSymbol
)) : ()
class BoolVisitor = FalseVisitor ()
('as yet unclassified'
boolNode: node = (^true)) : ()
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
)
name = (
	^#thisContext
)
printOn: strm <CharOutputStream>
 = (

	super printOn: strm.
	strm nextPutAll: '(thisContext)'
)) : ()
class ContextVisitor = FalseVisitor ()
('as yet unclassified'
contextNode: node = (^true)) : ()
class ExplicitReceiverVisitor = FalseVisitor ()
('as yet unclassified'
explicitOuterReceiverNode: aNode <ExplicitOuterRcvrAST> ^ <Boolean> = (
	^true
)) : ()
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'
boolNode: node = (^false)
contextNode: node = (^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 ImplicitRecvrSendAST send: aMsg <MessageAST> depth: d <integer> = SendAST send: aMsg (
"
Represent a send of a message with an implicit receiver (aka a here send).
"| depth <Integer> ::= d. |)
('as yet unclassified'
apply: aTool <ASTTool> ^ <Self> = (
	^aTool implicitSendNode: self
)
isExpressionNode ^ <boolean> = (
	^true
)
recv ^ <VarDeclAST> = (
  ^ assert:[false] message: 'There is no receiver node. It is implicit'
)) : ()
class ImplicitRecvrVisitor = FalseVisitor ()
('as yet unclassified'
implicitSendNode: aNode <ImplicitRcvrSendAST> ^ <Boolean> = (
	^true
)) : ()
class InstVarVisitor = FalseVisitor ()
('node traversal'
instVarNode: node = (^true)) : ()
class NilAST = VariableAST (
"")
('as yet unclassified'
apply: aTool <ASTTool > ^ <Self> = (
	^aTool nilNode: self
)
name = (
	^#nil
)) : ()
class NilVisitor = FalseVisitor ()
('as yet unclassified'
nilNode: node = (^true)) : ()
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'
name = (
	^#self
)) : ()
class ReceiverVisitor = FalseVisitor ()
('node traversal'
receiverNode: node = (^true)) : ()
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
)) : ()
class SuperSendVisitor = FalseVisitor ()
('node traversal'
superSendNode: node <SuperSendAST> = (
      ^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
)
assignmentFrom: aMsg <MessageAST> decl: vd <VarDeclAST> ^ <AssignmentNode> = (


| var <VariableAST> varName <String> args selector <String> |

self assert:[aMsg args size = 1].
selector:: aMsg sel asString.
varName:: selector copyWithSize: (selector size -1).
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.

args:: aMsg args first apply: self. "recurse on RHS"
"this is where we note that a temporary is being written to; this information is necessary to determine which temporaries can be copied into closures and which have to be 'remote'"
noteWriteOf: var.     
"create an assignment"

^AssignmentAST new 
                    to: var assign: args;
                    start: aMsg start;
                    end: aMsg end                     
)
blockLocalReturnNode: node = (
	^node
)
currentScope ^ <Scope> = (


^scopeStack last
)
enclosingObjSendOfDepth: n <Integer> to: recv <AST> start: start <Integer> end: end <Integer>  ^ <NormalSendAST> = (
 

^NormalSendAST new 
         recv: recv; 
         msg:(MessageAST new sel: (enclosingObjectMsgForDepth: n); args: {}; start: start; end: end);
	   start: start; 
	   end: end.
)
enclosingObjectMsgForDepth: n <Integer> ^ <String> = (

"Compute the selector necessary for obtaining the nth enclosing object wrt to the current lexical scope "
| otable  <Dictionary[Symbol, Tuple[Class, Integer]]> ec <Class> |

"What if n has no corresponding entry in the outer table? This should not happen, as this method is called on the basis of an n value found in the table to begin with."

otable:: currentScope at: #outer.
ec:: (otable values detect:[:v | (v at:2) = (n-1)]) at: 1.
^(Compiler new enclosingObjectMsgFor: ec) asSymbol
)
explicitOuterReceiverNode: node
 = (
    assert: [node apply: ExplicitReceiverVisitor new].
    ^node
)
implicitSendNode: node
 = (
    assert: [node apply: ImplicitRecvrVisitor new].
    ^node
)
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
)
noteReadOf: t <TemporaryAST>  = (
	| lastRead <integer> |
"earliest read nested in a closure"
	lastRead:: readMap at: t ifAbsent:[readMap at: t put: currentScope end. ^self].
	"if t has not yet been read, record this read in the map and exit; otherwise, find out what the last recorded value was"
	readMap at: t put: (lastRead min: currentScope end)
	"record the minimum of the last recorded value and the end of the current block. If a read occurs in a nested block, that block will end before the enclosing block or method,  and the block's ending will be recorded"
)
noteWriteOf: t <TemporaryVariableAST>  = (
" Location of last write, and minimal block ending"
	| lastWrite <Integer> prevBlockEnd <Integer> |
	
	prevBlockEnd:: (writeMap at: t ifAbsent:[{0. 0}]) last.
	lastWrite:: Array new: 2.
	lastWrite at:1  put: t start. "record source start index of last write"
	lastWrite at: 2 put: (currentScope end min: prevBlockEnd). "record end of block of any nested write"
	writeMap at: t put: lastWrite.
)
numberNode: node = (
  assert:[node isNumberNode].
  addNumericLiteral: node val.
  ^node
)
oldProcessExplicitOuterSend: aMsg <MessageAST> atDepth: n = (


| holder <NormalSendAST>  ctxt <VariableAST> start <Integer> end <integer> 
enclosingObj <NormalSendAST>  nonMeta  <NormalSendAST> 
 |
"For n > 0, return
thisContext methodClass enclosingObject_Cn ... C0 
                                         class enclosingObject_Cn ..._C1  ...  
                                            class enclosingObject_Cn_Cn-1 msg

which is the equivalent of

outer X msg

where X is the nth lexically enclosing class. Otherwise, do a self send"

n = 0 ifTrue:[^selfSendFrom: aMsg].
start:: aMsg start.
end:: aMsg end.
ctxt:: VariableAST new name: #thisContext; start: start; end: end.

holder:: NormalSendAST new recv: ctxt;
                                             msg: (MessageAST new sel:#lexicalClass; args: {});
                                              start: start; end: end.

nonMeta:: NormalSendAST new recv: holder;
                                             msg: (MessageAST new sel:#theNonMetaClass; args: {});
                                              start: start; end: end.

enclosingObj::  enclosingObjSendOfDepth: 1 to: nonMeta start: start end: end. 

enclosingObj:: (2 to: n) inject: enclosingObj into:[:r <NormalSendAST> :i <Integer> | 
	| csend <NormalSendAST> |
	  csend::  NormalSendAST new recv: r; 
	                                               msg:(MessageAST new sel: #class; args: {}; start: start; end: end);
	                                               start: start; 
	                                               end: end.
	 enclosingObjSendOfDepth: i to: csend start: start end: end. 
	 ].
^(NormalSendAST new recv: enclosingObj; msg: aMsg; start: start; end: end) apply: self
)
processExplicitOuterReceiver: aMsg <MessageAST> = (


| selectorBinding <AST> depth <integer> |

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

"assert:[selectorBinding data  isClassDeclarationAST]."
  depth: currentDepth -  selectorBinding depth -1.
  addNumericLiteral: depth. "the backend checks that depth in 0 - 256"
 ^(ExplicitRecvrAST send: aMsg sel depth: depth) start: aMsg start; end: aMsg end
)
processExplicitOuterSend: aMsg <MessageAST> = (
"Unused at the moment"
)
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].
	({#true. #false. #nil} includes: aMsg sel) ifTrue:[^processVariable: aMsg decl: nil].
	^ selfSendFrom: aMsg
)
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"
| selectorBinding <AST> depth <integer> |

selectorBinding:: currentScope at: aMsg sel.

"assert:[selectorBinding data  isClassDeclarationAST]."
  depth: currentDepth -  selectorBinding depth.
  addNumericLiteral: depth. "the backend checks that depth in 0 - 256"
  ^(ImplicitRecvrSendAST send: (aMsg apply: self) depth: depth) start: aMsg start; end: aMsg end
)
processOuterSend: aMsg <MessageAST> = (


| holder <NormalSendAST> depth <Integer> binding <AST>  meMsg <MessageAST> |

assert:[aMsg args isEmpty]. "this had better be a unary message"
binding:: (currentScope at: #outer) at: aMsg sel.
"assert binding makes sense "
assert:[ binding isKindOf: Collection].
assert:[binding first isKindOf: Class].
assert:[binding last isKindOf: Integer].

meMsg:: MessageAST new sel: #yourself; args: {}; start: aMsg start; end: aMsg end. "hack!"
^processOuterSend: meMsg atDepth: binding last
)
processOuterSend: aMsg <MessageAST> atDepth: n = (


| holder <NormalSendAST>  ctxt <VariableAST> start <Integer> end <integer> 
enclosingObj <NormalSendAST>  nonMeta  <NormalSendAST> 
 |
"For n > 0, return
thisContext methodClass enclosingObject_Cn ... C0 
                                         class enclosingObject_Cn ..._C1  ...  
                                            class enclosingObject_Cn_Cn-1 msg

which is the equivalent of

outer X msg

where X is the nth lexically enclosing class. Otherwise, do a self send"

n = 0 ifTrue:[^selfSendFrom: aMsg].
start:: aMsg start.
end:: aMsg end.
ctxt:: VariableAST new name: #thisContext; start: start; end: end.

holder:: NormalSendAST new recv: ctxt;
                                             msg: (MessageAST new sel:#lexicalClass; args: {});
                                              start: start; end: end.

nonMeta:: NormalSendAST new recv: holder;
                                             msg: (MessageAST new sel:#theNonMetaClass; args: {});
                                              start: start; end: end.

enclosingObj::  enclosingObjSendOfDepth: 1 to: nonMeta start: start end: end. 

enclosingObj:: (2 to: n) inject: enclosingObj into:[:r <NormalSendAST> :i <Integer> | 
	| csend <NormalSendAST> |
	  csend::  NormalSendAST new recv: r; 
	                                               msg:(MessageAST new sel: #class; args: {}; start: start; end: end);
	                                               start: start; 
	                                               end: end.
	 enclosingObjSendOfDepth: i to: csend start: start end: end. 
	 ].
^(NormalSendAST new recv: enclosingObj; msg: aMsg; start: start; end: end) 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
)
selfSendFrom: aMsg <MessageAST>  ^ <MessageNode> = (


^(NormalSendAST new msg: aMsg; 
                          recv: (selfNode start: aMsg start; end: aMsg end);
                          start: aMsg start; end: aMsg end) apply: self
)
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"
| els <OrderedCollection[AST]>   
  array <NormalSendAST> 
  len <NumberAST> 
  tup <NormalSendAST>
  index <Integer>
|

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: #new:; args:{len}; start: aNode start; end: aNode end). "Array new: n"
array start: aNode start; end: aNode end.	
aNode elements size = 0 ifTrue:[^array apply: self].
index:: 0.
tup:: aNode elements inject: array into:[:r : e |  | msg <MessageAST> |
	      index:: index + 1.
	      msg:: MessageAST new sel: #at:put:; 
								args: {NumberAST new val: index; start: aNode start; end: aNode end. e}.
		msg start: aNode start; end: aNode end.
	      index = 1 
			ifTrue:[NormalSendAST new to: r send: msg; start: aNode start; end: aNode end] 
						"(Array new: n) at:1 put: e1"
	      	ifFalse:[CascadedSendAST new to: r cascade: msg; start: aNode start; end: aNode end]. "...; at: k put: ek"
		].
^((CascadedSendAST new to: tup cascade:(MessageAST new sel: #yourself; args:{}; start: aNode start; end: aNode end)) start: aNode start; end: aNode end)
	"(Array new:  n) at: 1 put:: e1 ; ...  at: n put: en; yourself"
	 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 isTemporaryAST ifTrue:[noteReadOf: vd].
^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
)'closures'
currentSegment ^ <Integer> = (
	^0 "default until we implement it properly"
)
lastWriteOf: t <TemporaryAST> ^ <Integer> = (
	^0 "default for now"
)
readsOf: t <TemporaryAST> ^ <Set[Integer]> = (
	^Set new
)
segmentOf: t <TemporaryAST> ^ <Integer> = (
	^0 "default until we get a real implementation"
)
setSegmentOf: t <TemporaryAST> to: i <Integer> = (
	"default until we get a real implementation"
)'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> ^ <BlockAST>
 = (" 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> | 
    
    blok:: rewriteInlinedBlockNode: node.
    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).
    ^blok
)
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>
    |
    assert: [node isCodeBodyNode].
    pushScopeForNode: node. 
    temps:: node temporaries collect:[:t <VarDeclAST> |
       (TemporaryAST name: t name type: t type) start: t start; end: t end.
    ]. " should note node end for these temps!"
    bodyScope:: scopeMap at: node.
    temps do:[: t | (bodyScope at: t name)  data: t". 
		setSegmentOf: t to: currentSegment."].
    statements:: OrderedCollection new.
    node statements do: [ :stat | statements add: (stat apply: self)].
    result:: CodeBodyAST new
            parameters: node parameters
            temporaries:temps
            statements: statements;
            start: node start; end: node end.
    popScope.
    scopeMap at: result put: bodyScope.
    ^result.
)
genericApplicationExpressionNode: node
 = (
    assert: [node isGenericApplicationExpressionNode].
    ^node target apply: self
)
guaranteedNode: node
 = (
    assert: [node isGuaranteedNode].
    ^node expr apply: self
)
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>
|

  assert: [ node isMethodNode ].
  literalTable:: Dictionary new.
  pattern:: node pattern apply: self.
  stmts:: node body statements.
  body::  node body apply: self.
  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.
     popScope.
   ].
 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)].
  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.
    ^node
)
superSendNode: node
 = (
    assert: [node apply: SuperSendVisitor new].
    ^node
)
symbolNode: node
 = (
    assert: [ node isSymbolNode ].
    addLiteralConstant: node val.
    ^node
)'private'
addLiteral: s <Character | Number | String | Symbol> = ( 
  (literalTable includesKey: s) ifFalse:[literalTable at: s put: literalTable size].
)
at: node error: msg
 = (
 "Simple solution for now - fix this at some point"
 Transcript show: 'error: ', msg ; cr.
 halt
)
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
)
parameters: pars matchArguments: args
 = (
 | i |
 i:: pars size.
 
 "Proceed if no. of parameter matches no. of arguments"
 pars size = args size ifFalse: [ ^ false ].
 
 "check individual arguments, starting with last one"
 i:: pars size.
 [ i > 0 ] whileTrue: [
  (args at: i) isRefNode ifFalse: [ ^ false ].
  (pars at: i) == (args at: i) decl ifFalse: [ ^ false ].
  i:: i - 1
 ].
 
 "parameters & arguments match 1-to-1, in same order"
 ^ true
)
popScope ^ <Scope> = (
  ^scopeStack removeLast
)
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.
)
enclosingMixinsOf: m <MixinMirror> ^ <Collection[MixinMirror]> = (
	| e enclosers |
	^m enclosingClassStencil enclosingClassStencils collect:[:stencil | stencil mixin]
)
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.
	(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:: m methods asOrderedCollection collect:[:s <MethodMirror> | s name].
	result addAll: (m slots asOrderedCollection collect:[: s <SlotMirror> | s name]).
	result addAll: ((m slots asOrderedCollection select:[: s | s isMutable]) 
	                         collect:[: s <SlotMirror> | s name, ':']
	                       ).
	result addAll: (m classes asOrderedCollection collect:[:s <ClassStencilMirror> | s name]).
	^result
)
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
	].
)'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].
)
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 statements do:[: s <ReturnStatementAST | SendAST>  | s apply: self].
popScope.
)
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'
accessorForNestedClassNamed: simpleName <String> in: mixinName  <String> superName: superAccessor <String> ^ <String> = (
	"Build  a method that will lazily create a nested class 'simpleName' with superclass 'nameOfSuper' via mixin application, and cache it. 
	"
	| 
	nestedName <String> 
	nestedSlot <String> 
	enclosing <String> 
	mixinMetadata <String>
	|

	nestedName:: fullyQualifySimpleName: simpleName with: mixinName.
	nestedSlot:: nestedName, syntheticNameSeparator, 'slot'.
	enclosing:: 'EnclosingObjects',  syntheticNameSeparator, mixinName.
	mixinMetadata:: 'MixinMetadata', syntheticNameSeparator,  mixinName.
		
	^simpleName , '
	| nestedClass enclosingObjectArray myNested depth |
	', nestedSlot, ' isNil ifTrue:[ 
		nestedClass := 	', mixinMetadata, ' 
			nestedMixins at: #', nestedName, '.
		myNested := (nestedClass mixin |>  (', mixinMetadata, ' Mirror on: ', superAccessor, ')) reflectee.
		myNested mixinMetadata: nestedClass reflectee metadata.
		depth := ',  enclosing, ' size + 1.
		enclosingObjectArray :=  Array new: depth. 
		enclosingObjectArray at:1 put: self. 
		2 to: depth do:[:i | 
			enclosingObjectArray at:i put:(',  enclosing, ' at: i - 1)
			].
		 myNested enclosingObjects: enclosingObjectArray.
		', nestedSlot, ' := myNested.
		].
	^', nestedSlot.
)
accessorForSuperclass: aSelector <String> inScope: s ^ <String> = (
	| dummyMethod <MethodAST> src <String>  send <NormalSendAST> |
	"compute code for accessing superclass. Probably general enough for any code that does not introduce new name bindings "
	send:: ReturnStatAST new expr: 
		(NormalSendAST new to: hereNode send: (MessageAST new send: aSelector asSymbol with:{})) .
	dummyMethod:: MethodAST new
		pattern: (MessagePatternAST new selector: #___ parameters:{}) 
		body:(CodeBodyAST new temporaries: {} statements:{send}) 
		visibility: #private.
	dummyMethod start: 2; end: 3.
	"create MethodAST representing code"
	scopeMap 
		at: dummyMethod put: currentScope;
	 	at: dummyMethod body put: currentScope;
	 	at: dummyMethod pattern put: currentScope.
	"associate AST with suitable scope"
	src:: (computeMethod: dummyMethod inScope: s) method. 
	"compile method and extract source"
	^src copyFrom: 11 to: src size-5.
	"return desired source (skipping method header)"
)
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> methodSrc <String>  hdr <ClassHeaderAST> accessor <MethdMirror>  |

hdr:: classDecl hdr.
n:: hdr name. 
methodSrc:: 
	accessorForNestedClassNamed: n 
	in:  mixinMirror name 
	superName: (accessorForSuperclass: hdr superclassName inScope:  (scopeMap at: classDecl instanceSide)).
accessor:: MethodMirror named: classDecl name asSymbol.
accessor method: methodSrc.
accessor isSynthetic: true.
mixinMirror methods addMirror: accessor.
)
currentScope ^ <Scope> = (
  ^scopeStack last
)
generateSlotAccessorsFor: m <MixinMirror> = (
"In Strongtalk,  the accessors should definitely be generated in the mixin. The Strongtalk system will take care of the rest"
| 
sn <String> 
ivs <Collection[InstanceVariableMirror]> 
|
	ivs:: m instVars collect:[:iv | iv]. "Gross - extract a collection from the mirror group"
	ivs do:[: iv  | 
		| getter  <MethodMirror> setter <MethodMirror> |
		(iv metadata at: #isSynthetic ifAbsent:[false]) ifFalse:[
			sn:: iv name.
			getter:: MethodMirror named: sn asSymbol.
			getter method: sn, ' ^', sn.
			getter isSynthetic: true.
			m methods addMirror:  getter.
			setter:: MethodMirror named: (sn, ':') asSymbol.
			setter method: sn, ': ', sn, '_val ', sn, ' := ', sn, '_val'.
			setter isSynthetic: true.					
			m methods addMirror:  setter.
			]
		]
)
initializerFor: aNode <ClassHeaderAST> ^ <MethodAST> = (

| stmts var  superMsg send  start end initHdr body copier |

 start:: aNode superConstructorCall start.
 end::  aNode  superConstructorCall end.
 copier:: ASTCopier new.
 initHdr:: aNode constructor apply: copier. "set up scope with constructor parameters"
 stmts::  aNode  slots collect:[:slot <SlotDefAST> | | aMsg <MessageAST> |
	aMsg:: MessageAST new send: (slot name, ':') asSymbol 
					   with:  {slot initializer apply: copier} ;
					   start: slot  start; end: slot end.
	NormalSendAST new msg: aMsg; 
                          recv: (selfNode start: aMsg start; end: aMsg end);
                          start: aMsg start; end: aMsg end.			
	].
"create call to superclass initializer"
 var:: VariableAST new name: #super; start: start; end: end.
 superMsg::  aNode  superConstructorCall apply: copier.
 send:: NormalSendAST new to: var send:   superMsg; start: start; end: end.
"add superclass init call as first statement"
 stmts addFirst: send. 
 stmts addAll: (aNode initExprs collect:[:ie | ie apply: copier]).
 body:: CodeBodyAST new temporaries: OrderedCollection new
                                       statements: stmts; 
                                       start: start; end: end.
 ^MethodAST new pattern: initHdr
                            body: body
                            visibility: #public; 
                            start: start; end: end.
)
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 |

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
	].
msgFromConstructor:: MessageAST new send: cons selector 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> ^ <MethodMirror> = (

| 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 superScope: currentScope.
  pushScope: s
)
outputClassMethodsOf: m <ClassMixinMirror> to: strm <WriteStream> = (
	strm nextPutAll: '! (Delta mirrorFor: #'.
	strm nextPutAll: m  name.
	strm nextPutAll:  ') classSide methodsFor: ''unclassified''!
	'.
	strm nextPutAll: 'enclosingObjects: eos EnclosingObjects_', m name, ' := eos !
	'.
	strm nextPutAll: 'mixinMetadata: mmd MixinMetadata_', m name, ' := mmd !
	'.
	m lowLevelMirror classMixin methods do:[:mtd <MethodMirror> |
		strm nextChunkPut: mtd method.
		strm nextPutAll: ' 
		'
		].
	strm nextPutAll: ' !
	'
)
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"
)
processConstructorFor: aNode <ClassHeaderAST> inMixin: mixinMirror <LowLevelMixinMirror> = (

"eliminate"
| initializer <MethodMirror> primaryFactory <MethodMirror> |
 
  initializer:: methodNode: (initializerFor: aNode). 
  mixinMirror methods addMirror: initializer.
"install initializer"
  primaryFactory::  methodNode:(makePrimaryFactoryFor: aNode). 
  mixinMirror classMixin methods addMirror: primaryFactory.
"install constructor"
)
processFactoryFor: aNode <ClassAST> in: mixinMirror <LowLevelMixinMirror> = (
|  factory <MethodMirror> side <SideAST> factoryAST <MethodAST> scopeBuilder <ScopeBuilder> savedScopeMap <Dictionary[AST, Scope]> |

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

	processMethod: (superConstructorMethodFor: aNode hdr) inScope:  (scopeMap at: aNode instanceSide) in: mixinMirror. "doesn't really belong in the mixin"
 	initializerASTs:: allInitializersFor: aNode hdr in: mixinMirror.
	initializerASTs do:[: init <MethodAST> |
		processMethod: init inScope:  (scopeMap at: aNode instanceSide) 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> = (
|  method <MethodMirror> |

	method:: computeMethod: aNode inScope: s.
	method isSynthetic: true.
	mixinMirror methods addMirror: 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.
                               	mixinMirror methods addMirror: mirr.
                                 ].
                     ].
)
pushScope: s <Scope> = (
  scopeStack addLast: s
)
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> |
	"^String withAll: (input copyFrom: node start to: node end"
	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.
	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, syntheticNameSeparator,  'superInit', syntheticNameSeparator, aNode constructor selector) asSymbol 
)
syntheticNameSeparator ^ <String> = (
  ^'_'	
)
syntheticNameSeparatorCharacter ^ <Character> = (
  ^$_	
)'final output'
outputClass: m <ClassMixinMirror> to: strm <WriteStream> = (
	outputClassDecl: m to: strm.
	outputMethodsOf: m to: strm.
	outputClassMethodsOf: m to: strm.
)
outputClassDecl: m <ClassMixinMirror> to: strm <WriteStream> = (
	strm nextPutAll: 'Delta define: #'.
	strm nextPutAll: m  name.
	strm nextPutAll: ' as: (
	(Class subclassOf: ''NewspeakObject'' instanceVariables:'''.
	m  lowLevelMirror instVars do:[: ivm | 
		strm nextPutAll: ' '.
		strm nextPutAll: ivm name
		].
	strm nextPutAll:  ''') 
classVariables: ''MixinMetadata'.
	strm nextPutAll: syntheticNameSeparator.
	strm nextPutAll:  m name.
	strm nextPutAll:  ' EnclosingObjects'.
	strm nextPutAll: syntheticNameSeparator.
	strm nextPutAll: m name.
	strm nextPutAll: ''')! 
'.
	strm nextPutAll: '(Delta mirrorFor: #'.
	strm nextPutAll: m  name.
	strm nextPutAll: ') revision: ''$Revision: 0.0 $''! 
'.
	strm nextPutAll: '(Delta mirrorFor: #'.
	strm nextPutAll: m  name.
	strm nextPutAll: ') group: ''newspeak''! 
'.		
	strm nextPutAll: '(Delta mirrorFor: #'.
	strm nextPutAll: m  name.
	strm nextPutAll: ') comment: '.
	strm nextPutAll: m comment printString.
	strm nextPutAll: '! 
'.			
)
outputMethodsOf: m <ClassMixinMirror> to: strm <WriteStream> = (
	strm nextPutAll: '! (Delta mirrorFor: #'.
	strm nextPutAll: m  name.
	strm nextPutAll: ') methodsFor: ''unclassified''!
	'.
	m lowLevelMirror methods do:[:mtd <MethodMirror> |
		strm nextChunkPut: mtd method.
		strm nextPutAll: '
'
		].
	strm nextPutAll: ' !
	'
)
outputNestingHookupForRep: m <MixinRep> to: strm <WriteStream> within: enclosing  = (

	enclosing isNil ifTrue:[
		strm nextPutAll: m first name.
		strm nextPutAll: ' enclosingObjects: (Array with: nil)!
		'.
		strm nextPutAll: m first name.
		strm nextPutAll:  ' metadata enclosingMixin: '. 
		strm nextPutAll: 'nil !
		'.
		strm nextPutAll: m first name.
		strm nextPutAll:  ' mixinMetadata: '. 
		strm nextPutAll: m first name.
		strm nextPutAll: ' metadata !
		'.
		^self
		].
	strm nextPutAll: enclosing name.
	strm nextPutAll: ' metadata addNestedClass: '.
	strm nextPutAll: m first name.
	strm nextPutAll: '. ! 
	'.
	strm nextPutAll: m first name.
	strm nextPutAll:  ' metadata enclosingMixin: '. 
	strm nextPutAll: enclosing name.
	strm nextPutAll: ' !
	'
)
outputRep: m <MixinRep> to: strm <WriteStream> within: enclosing = (
	outputClass: m first to: strm.
	outputNestingHookupForRep: m to: strm within: enclosing.
	m last do:[:rep <MixinRep>  | outputRep: rep to: strm within: m first].
)'nested classes - private'
compileNestedClasses: nestedClasses <Collection[ClassDeclarationAST]> within: mixinMirror <LowLevelMixinMirror> ^ <Collection[MixinRep]> = (

| results <OrderedCollection[MixinRep]> |
      results:: OrderedCollection new.
	nestedClasses do:
		[ :nc <ClassDeclarationAST> |  
			| nSlotName <String> nSlot <InstanceVariableMirror> |
		nc hdr category: mixinMirror category, '-nested'.
		nSlotName:: slotNameForNestedClassNamed: nc name 
		                   within: mixinMirror name.
		nSlot:: InstanceVariableMirror named: nSlotName.
		nSlot metadata at: #isSynthetic put: true.
		mixinMirror instVars addMirror: nSlot.
		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
)
fullyQualifySimpleName: sn <Symbol> with: fqp <Symbol> ^ <Symbol> = (
	^(SystemMetadata fullyQualifySimpleName: sn with: fqp) copyReplaceAll: '`' with:'_'
)
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 shallowCopy.
wrapper hdr: nested hdr shallowCopy.
wrapper hdr name: (fullyQualifySimpleName: nested name with: outerClass name).
^wrapper
)
slotNameForNestedClassNamed: ncn <String> within: outerName <String> ^ <String> = (
	^(SystemMetadata mixinSlotNameFor:(
								fullyQualifySimpleName: ncn 
		                  			 with: outerName
					)) copyReplaceAll: '`' with:'_'. 
)
superAccessorStringFor: sname <String> inClass: mixinMirror<LowLevelMixinMirror> ^ <String> = (

"Determine at what lexical level an accessor for sname exists, and create a string that will access it from klass.
The string will have the form self enclosingObject_C0_ ...Cn   ... enclosingObject_Cn  sname, where n >= 0 is the number of lexical levels one needs to traverse to reach the definition of sname. 
If no lexically visible definition is found, assume it is inherited and revert to n = 0 (a simple self send)."

| 
enclosings <String>  oClass <Class> enclosingMixins <Collection[MixinMirror]>  
enclosingNames <Collection[Symbol]> count <Integer>
| 
"!!"
count:: 0.
(mixinMirror methods includesMirrorNamed: sname asSymbol) ifTrue:[^'self ', sname].
enclosings:: ''.
enclosingMixins:: mixinMirror enclosingMixins reverse.
enclosingMixins do:[:oc <MixinMirror> |
	(oc methods includesMirrorNamed: sname asSymbol) 
	      ifFalse:[count:: count + 1]
	      ifTrue:[
			enclosingNames::  enclosingMixins collect:[:c | enclosingObjectMsgFor: c]
			                                                      from: 1 
			                                                      to: count.
                   enclosings:: enclosingNames fold:[:ocn1 <Symbol> :ocn2 <Symbol> | ocn1, ' class ', ocn2].
		       ^'thisContext lexicalClass ', enclosings, ' ', sname
		]
	].
^'self ', sname
)'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"
	subs:: subInitializersFor: aNode. "compute (empty) subinitializers"
	
	slots::  aNode  slots collect:[:slot <SlotDefAST> | | aMsg <MessageAST> |
						aMsg:: MessageAST new send: (slot name, ':') asSymbol 
					   						with:  {slot initializer apply: copier} ;
					  						 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
)
computeMethod: aNode <MethodAST> inScope: s <Scope> = (
|  scopeBuilder <ScopeBuilder>  |

	scopeBuilder:: ScopeBuilder nestedIn: s atLevel: currentDepth.
	aNode apply: scopeBuilder.
"need to build scope for method before visiting it"
	^methodNode: aNode.
)
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 
)
ensureEnclosingObjectAccessFor: mixinMirror <LowLevelMixinMirror> = (

"Need a different enclosingObject slot with respect to each lexical scope"
"We use the class' fully qualified name to produce a uniquely named enclosing object 
slot for each class in the inheritance chain, so they never conflict"
| enclosingObjectMsg <Symbol> |

  enclosingObjectMsg:: enclosingObjectMsgFor: mixinMirror.
  mixinMirror classMixin instVars addMirror: (InstanceVariableMirror named: enclosingObjectMsg).  "add  class instance variable to reference enclosing instance"
)
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"
^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
)
selectorForMethodAST: aMethodAST = (
	^aMethodAST pattern selector
  )
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'
classHeaderNode: aNode <ClassHeaderAST> ^ <CompiledMixinMirror> = (
| mixinMirror <LowLevelMixinMirror> t <{OrderedCollection[T]. Integer}> |
"eliminate?"
 assert:[aNode category notNil] message: 'No category for class header node '.
 mixinMirror::  computeMixinFrom: aNode.					
"Need to ensure we only call this routine if the class whose header we are processing already exists in the enclosing class"
"Create class constructor + initializer routine"
 processConstructorFor: aNode inMixin: mixinMirror lowLevelMirror.
^mixinMirror
)
classNode: aNode <ClassDeclarationAST> ^ <MixinRep> = (
"type MixinRep = {CompiledMixinMirror. {MixinRep}}"
| mixinMirror <LowLevelMixinMirror> nestedClasses <Collection[MixinRep]> priorMixinUID <String> |
  assert:[aNode hdr category notNil] message: 'No category for class header'.
  mixinMirror:: computeMixinFrom: aNode hdr.
  priorMixinUID:: currentMixinUID.
  currentMixinUID::  mixinMirror name.
  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.
  currentMixinUID:: priorMixinUID.
  ^{mixinMirror. nestedClasses}
)
compileClassHeader: src <ReadStream> within: enclosing <MixinMirror> ^ <CompiledMixinMirror> = (
| tree <AST> mirror <CompiledMixinMirror>  |
	tree:: parser classHeader parse: src.
  	saveInput: src.
 	setScopeFor: tree in: enclosing.
 	mirror:: classHeaderNode: tree.
 	scopeMap:: Dictionary new.
	^mirror
)
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>  file <CrLfFileStream> |
  tree:: parser classDefinition parse: src.
  saveInput: src.
  setScopeFor: tree in: enclosing. "scope construction phase"
  mixinRep:: classNode: tree.
  scopeMap:: Dictionary new.
  file:: CrLfFileStream forceNewFileNamed: mixinRep first name , '-andNested.dlt'.

  outputRep: mixinRep to: file within: enclosing.
  file close.
  enclosing isNil ifTrue:[mixinRep] ifFalse:[{enclosing. mixinRep}].
"shouldn't we convert enclosing to a CompileMixinMirror?"
)
compileMethodSource: src <ReadStream> within: enclosing <MixinMirror>  
       			    ^ <MethodMirror>
= (
| tree <AST> result <MethodMirror>  | 
  tree:: parser methodDecl parse: src.
  saveInput: src.
  setScopeFor: tree in:  enclosing. "scope construction phase"
  result::methodNode: tree. "rewrite and compile"
  scopeMap:: Dictionary new.
  ^result
)
compileNestedClass: nc <ClassDeclarationAST> within: mixinMirror <LowLevelMixinMirror> ^ <Collection[MixinRep]> = (
	^compileNestedClasses: (OrderedCollection with: nc) within: mixinMirror.
)
language = (

^#NewspeakLanguage2  
)
parserClass = (
 
^WrappingNS2Parser 
)) : ()
class MethodMirror named: s <Symbol> = LowLevelMirror (
"A descriptor for a Smalltalk method or accessor."| 
	selector <Symbol> = s.
	method <String>  "Smalltalk code"
	isSynthetic <Boolean> ::= false.
	src <String> "Newspeak source - optional"
	|)
('as yet unclassified'
name ^ <Symbol> = (
	^selector
)) : ()
class Scope = (
"A generic scope facility.

The text below describes the intended scheme for handling closures using the Cog VM's closure support. It is not yet implemented.

To support efficient compilation of closures, each scope tracks how many temporary variables need to ''remote''. 

A remote temporary is one that is closed over by a nested closure, and cannot reliably be copied down into the closure upon closure creation.  Any temporary that might be written to after closure creation is necessarily remote.

Remote temps are allocated in an array rather than directly in their activation. All the remote temps in a given scope are alllocated in a single array, the remote temp vector. Each remote temp is uniquely identified by an index into th eremote temp vector.

Closures nested within the scope get a reference to the remote temp vector. They can and read and write a temporary by modifying the vector using the index associated with the temporary.

Typically, the first instruction in the code of a closure or method allocates the remote temp vector (if one is needed). This is supported by a special byte code, pushArray.

Reads and writes to a remote temp take the form of at: i and at: i put: v sends where i is the index of the remote temp and v is the value being written to it.

A temporary variable is considered remote iff:

a. It is written to in a closure nested within its defining method or closure.
b. It is read in in a closure c nested within its defining method or closure, and written to after the end of c.

"| 
  superScope 
  bindings =  IdentityDictionary new.
	public end <Integer>
 |)
('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.
)) : ()
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'
encode: comment <String> withoutDoubleQuotesOn: stream <WriteStream>  = (
	"Replace double quotes in comments with pairs of single quotes."

	1 to: comment size do:
		[:i |
		(comment at:i) = $" ifTrue: [stream nextPut: $'; nextPut: $']
		       ifFalse:[stream nextPut: (comment at: i)].
          ].	
)) : ()