1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
|
% $Id$
\documentclass[11pt]{report}
\usepackage{fleqn,a4wide,modefs,math,prooftree,scaladefs,vquote}
\newcommand{\ifqualified}[1]{}
\newcommand{\iflet}[1]{}
\newcommand{\ifundefvar}[1]{}
\newcommand{\iffinaltype}[1]{}
\newcommand{\ifpackaging}[1]{}
\newcommand{\ifnewfor}[1]{}
\renewcommand{\todo}[1]{#1}
\newcommand{\notyet}{\footnote{not yet implemented.}}
\title{Report on the Programming Language Scala}
\date{\today}
\author{
Martin Odersky
}
\sloppy
\begin{document}
\maketitle
%\todo{`:' as synononym for $\EXTENDS$?}
\chapter{Rationale}
\input{rationale-chapter}
\comment{
\chapter{Change Log}
5 August 2001: Changed from join patterns in function definitions to
when clauses.
5 August 2001: Introduced guard part in case expressions.
5 August 2001: Dropped overload modifier.
5 August 2001: Dropped \verb@=>@ as an alternative for \verb@=@ in
definitions.
5 August 2001: Dropped \verb@nil@ type.
5 August Replaced \verb@&@ operator for parallel composition by
\verb@fork@ function.
5 August 2001: Added chapter on Concurrency (\sref{sec:concurrency}).
7 August 2001: Made explicit in the grammar that block-local
definitions do not have modifiers.
7 August 2001: Introduced permitted but redundant modifier `private'
for guards.
9 August 2001: Replaced qualified identifiers in class definitions by
modifiers \verb@new@ and \verb@override@.
9 August 2001: Tightened rules for member access, so that superclass
ordering is irrelevant. See definition of qualified expansion in
\sref{sec:names}.
9 August 2001: Guarded choice now always picks tectually first enabled
guard, rather than an arbitrary one.
16 August 2001: Unary postfix operators now have lower precedence than
unary infix.
16 August 2001: Use `=' instead of `:=' for assignment.
16 August 2001: Changed scope rules so that scope of a definition
always extends to the whole enclosing block or template, plus an
anti forward-dependency rule for value definitions.
16 August 2001: Changed Grammar to allow repeated data definitions
only with extends clauses of simple type, so that parameter names
cannot be used.
16 August 2001: Changed Grammar to drop NxStat, etc (the context-free language
is not affected by the change).
23 August 2001: Eliminated unboxed types.
23 August 2001: Eliminated recursive value definitions; changed rules
for pattern value definitions.
26 August 2001: Clarified indentation rules.
26 August 2001: Adapted meaning of \verb@null@ to value types.
26 August 2001: Apply local type inference in class instance expressions.
23 Sep 2001: Changed $\arrow$ in closures to $\Arrow$.
23 Sep 2001: Changed record types to refinements.
25 Oct 2001: Simplified and generalized class and module
design. Classes and modules can now appear anywhere; modules are no
longer parameterized.
25 Oct 2001: Dropped aspects (for the time being).
29 Oct 2001:
Tuple and function types are now shorthands for predefined
classes. Tuples are no longer covariant.
29 Oct 2001:
Introduced $n$-ary functions and changed syntax for function types.
29 Oct 2001:
Dropped static part of classes. Classes now define a constructor
function of the same name.
29 Oct 2001:
Generalized rules for overloading slightly.
29 Oct 2001:
Dropped modifiers for guards.
29 Oct 2001:
Disambiguated syntax for pattern matching cases with guards.
2 Nov 2001: Changed private and protected to their meaning in Java.
2 Nov 2001: Introduced packagings.
5 Nov 2001: Dropped value parameters in class aliases.
14 Nov 2001: Fixed rule for subtyping of overloaded
function. Tightened scope of value parameters.
15 Nov 2001: Changed `with' to `if' as pattern guard and simplified
pattern syntax.
15 Nov 2001: Changed `data' to `case class'.
20 Nov 2001: Case classes need no longer be `final'.
30 Nov 2001: Introduced `qualified' classes, with unqualified classes
being the default.
4 Dec 2001: Introduced interfaces (\sref{sec:interfaces})
4 Dec 2001: Changed rules which members are inherited (\sref{sec:members}).
4 Dec 2001: Changed rules for compound types with refinements to match
those for templates (\sref{sec:compound-types}).
6 Dec 2001: Dropped modifiers `virtual' and `new'.
6 Dec 2001: `new' is again mandatory in instance creation expressions.
10 Dec 2001: Dropped concurrency constructs in language.
11 Dec 2001: Changed name from `Funnel' to `Scala'.
18 Dec 2001: Slight change of syntax for anonymous functions.
29 Dec 2001: Case classes define accessors for parameters
6 Feb 2002: Import clauses defined only for stable identifiers.
6 Feb 2002: Dropped restriction that classes may not have
inherited abstract members.
6 Feb 2002: Reclassified `new' as Expr4
6 Feb 2002: Dropped interface keyword
6 Feb 2002: Changed syntax of `if'.
6 Feb 2002: Introduced constructor types.
6 Feb 2002: Eliminated class aliases.
6 Feb 2002: Replaced user-defined value definitions by comprehensions.
6 Feb 2002: Tightened conditions on well-formed base class sequence.
6 Feb 2002: Changed root class hierarchy.
7 Feb 2002: Tightened rules on forward references.
7 Feb 2002: Only prefix operators are now `-', `+', `!'. They are
translated to method calls of their operand.
}
\subsection*{Status of This Document}
The present document defines slightly more than what is implemented in
the current compiler. But I have tried to mark all omissions that
still exist.
\part{Language Definition}
\chapter{Lexical Syntax}
This chapter defines the syntax of Scala tokens. Tokens are
constructed from symbols in the following character sets:
\begin{enumerate}
\item Whitespace characters.
\item Lower case letters \verb@`a' | ... | `z'@ and
upper case letters \verb@`A' | ... | `Z' | `$\Dollar$' | `_'@.
\item Digits \verb@`0' | ... | `9'@.
\item Parentheses \verb@`(' | `)' | `[' | `]' | `{' | `}'@.
\item Delimiter characters \verb@`\' | `'' | `"' | `.' | `;' | `,'@.
\item Operator characters. These include all printable ASCII characters
which are in none of the sets above.
\end{enumerate}
These sets are extended in the usual way to unicode\notyet (i.e.\ as in Java).
Unicode encodings \verb@`\uXXXX'@ are also as in Java.
\section{Identifiers}
\syntax\begin{verbatim}
op \=::= \= special {special} [`_' [id]]
varid \>::= \> lower {letter $|$ digit} [`_' [id]]
id \>::= \> upper {letter $|$ digit} [`_' [id]]
\> | \> varid
\> | \> op
\end{verbatim}
There are two ways to form an identifier. First, an identifier can
start with a letter which can be followed by an arbitrary sequence of
letters and digits. Second, an identifier can be start with a special
character followed by an arbitrary sequence of special characters.
In both cases, the identifier prefix may be immediately followed
by an underscore `\verb@_@' character and another string of characters
that by themselves make up an identifier. As usual, a longest match
rule applies. For instance, the string
\begin{verbatim}
big_bob++=z3
\end{verbatim}
decomposes into the three identifiers \verb@big_bob@, \verb@++=@, and
\verb@z3@. The rules for pattern matching further distinguish between
{\em variable identifiers}, which start with a lower case letter, and
{\em constant identifiers}, which do not.
The `\verb@\$@' character is reserved for compiler-synthesized identifiers.
User programs are not allowed to define identifiers which contain `\verb@\$@'
characters.
The following names are reserved words instead of being members of the
syntactic class \verb@id@ of lexical identifiers.
\begin{verbatim}
abstract as case class constr
def do else extends final
false for if is import
new null object override package
private protected super this trait
true type val var with
yield
_ : = => <- <: >: # @
\end{verbatim}
The unicode operator `\verb@=>@' has the ascii equivalent
`$=>$', which is also reserved\notyet.
\example
Here are examples of identifiers:
\begin{verbatim}
x \=Object \=maxIndex \=p2p \=empty_?
+ \> +_field
\end{verbatim}
\section{Symbols}
\syntax\begin{verbatim}
symbolLit ::= `\'` id
\end{verbatim}
A symbol literal has the form \verb@'x@ where $x$ is an identifier.
Such a symbol literal is a shorthand for the application
\begin{verbatim}
scala.Symbol("x")
\end{verbatim}
of the facotry method for the standard case class \verb@Symbol@ to the string "x".
\section{Braces and Semicolons}
A semicolon `\verb@;@' is implicitly inserted after every closing brace
if there is a new line character between closing brace and the next
regular token after it, except if that token cannot legally start a
statement.
The tokens which cannot legally start a statement
are the following delimiters and reserved words:
\begin{verbatim}
else extends with yield do as is
, . ; : = => <- <: >: # @ ) ] }
\end{verbatim}
\section{Literals}
There are literals for integer numbers (of types \verb@Int@ and \verb@Long@),
floating point numbers (of types \verb@Float@ and \verb@Double@), characters, and
strings. The syntax of these literals is in each case as in Java.
\syntax\begin{verbatim}
literal \=::= \= intLit
\> | \> floatLit
\> | \> charLit
\> | \> stringLit
\> | \> symbolLit
intLit \>::= \> ``as in Java''
floatLit \>::= \> ``as in Java''
charLit \>::= \> ``as in Java''
stringLit \>::= \> ``as in Java''
\end{verbatim}
\section{Whitespace and Comments}
Tokens may be separated by whitespace characters (ascii codes 0 to 32)
and/or comments. Comments come in two forms:
A single-line comment is a sequence of characters which starts with
\verb@//@ and extends to the end of the line.
A multi-line comment is a sequence of characters between \verb@/*@ and
\verb@*/@. Multi-line comments may be nested.
\chapter{\label{sec:names}Identifiers, Names and Scopes}
\syntax\begin{verbatim}
Id \=::= \= id | `+' | `-' | `!'
QualId \>::> \= Id {`.' Id}
\end{verbatim}
Names in Scala identify types, values, functions, and classes which
are collectively called {\em entities}. Names are introduced by
definitions, declarations (\sref{sec:defs}) or import clauses
(\sref{sec:import}), which are collectively called {\em binders}.
There are three different name spaces, one each for types
(\sref{sec:types}), terms (\sref{sec:exprs}), and constructors
(\sref{sec:constrs}). The same name may designate a type, a term, and
a constructor, depending on the context where the name is used. A
class definition (\sref{sec:classes}) defines conceptually both a type
and a constructor, so its defined name is introduced in both name
spaces.
A definition or declaration has a {\em scope} in which the entity
defined by a single name can be accessed using a simple name. Scopes
are nested, and a definition or declaration in some inner scope {\em
shadows} a definition in an outer scope that contributes to the same
name space. Furthermore, a definition or declaration shadows bindings
introduced by a preceding import clause, even if the import clause is
in the same block. Import clauses, on the other hand, only shadow
bindings introduced by other import clauses in outer blocks.
\todo{Examples}
A reference to an unqualified identifier $x$ of kind $K$ where $K$ is
either term, type or constructor, is bound by the unique binder, which
\begin{itemize}
\item defines an entity $x$ with name $x$ and kind $K$, and
\item shadows all other binders that define entities with name $x$
and kind $K$.
\end{itemize}
It is an error if no such binder exists. If $x$ is bound by an import
clause, then the simple name $x$ is taken to be equivalent to the
qualified name to which $x$ is mapped by the import clause. If $x$ is bound by a definition or declaration,
then $x$ refers to the entity of kind $K$ introduced by that
binder. In that case, the type of $x$ is the type of the referenced
entity.
A reference to a qualified identifier $e.x$ of kind $K$ refers to the
member of kind $K$ of the type $T$ of $e$. It is an error if $T$ is
not an object type (\sref{def:object-type}). The type of $e.x$ is the
member type of the referenced entity in $T$.
\chapter{\label{sec:types}Types}
\syntax\begin{verbatim}
Type \=::= \= Type1 `=>' Type
\> |\> `(' [Types] `)' `=>' Type
\> |\> Type1
Type1 \>::= \> SimpleType {with SimpleType} [Refinement]
SimpleType \>::= \> StableId
\> |\> SimpleType `#' Id
\> |\> Path `.' type
\> |\> SimpleType TypeArgs
\> |\> `(' Type ')'
Types \>::= \> Type {`,' Type}
\end{verbatim}
We distinguish between first-order types and type constructors, which
take type parameters and yield types. A subset of first-order types
called {\em value types} represents sets of (first-class) values.
Value types are either {\em concrete} or {\em abstract}. Every
concrete value type can be represented as a {\em class type}, i.e.\ a
type designator (\sref{sec:type-desig}) that refers to a
class\footnote{We assume that objects and packages also
implicitly define a class (of the same name as the object or package,
but inaccessible to user programs).} (\sref{sec:classes}),
or as a {\em compound type} (\sref{sec:compound-types})
consisting of class types and possibly
also a refinement (\sref{sec:refinements}) that further constrains the
types of its members.
A shorthands exists for denoting function types
(\sref{sec:function-types}). Abstract value types are introduced by
type parameters and abstract type bindings (\sref{sec:typedcl}).
Parentheses in types are used for grouping.
Non-value types capture properties of
identifiers that are not values
(\sref{sec:synthetic-types}). There is no syntax to express these
types directly in Scala.
\section{Paths}\label{sec:paths}
\syntax\begin{verbatim}
StableId \=::= \= Id
\> |\> Path `.' Id
\> |\> [Ident '.'] super `.' Id
Path \>::=\> StableId
\> |\> [Ident `.'] this
\end{verbatim}
Paths are not types themselves, but they can be a part of named types
and in that way form a central role in Scala's type system.
A path is one of the following.
\begin{itemize}
\item
The empty path $\epsilon$ (which cannot be written explicitly in user programs).
\item
\verb@C.this@, where \verb@C@ references a class.
The path \verb@this@ is taken as a shorthand for \verb@C.this@ where
\verb@C@ is the class directly enclosing the reference.
\item
\verb@p.x@ where \verb@p@ is a path and \verb@x@ is a stable member of \verb@p@.
{\em Stable members} are members introduced by value or object
definitions, as well as packages.
\item
\verb@C.super.x@ where \verb@C@ references a class and \verb@x@ references a
stable member of
one of the base types of \verb@C@.
The path \verb@super.x@ is taken as a shorthand for \verb@C.super.x@ where
\verb@C@ is the class directly enclosing the reference.
\end{itemize}
A {\em stable identifier} is a path which ends in an identifier.
\section{Value Types}
\subsection{Singleton Types}
\label{sec:singleton-type}
\syntax\begin{verbatim}
SimpleType ::= Path `.' type
\end{verbatim}
A singleton type is of the form \verb@p.type@, where \verb@p@ is a
path. The type denotes the set of values consisting of
exactly the value denoted by \verb@p@.
\subsection{Type Projection}
\label{sec:type-project}
\syntax\begin{verbatim}
SimpleType ::= SimpleType # Id
\end{verbatim}
A type projection \verb@T # x@ references the type member named
\verb@x@ of type \verb@T@. \verb@T@ must be either a singleton type,
or a non-abstract class type, or a Java class type (in either of the
last two cases, it is guaranteed that \verb@T@ has no abstract type
members).
\subsection{Type Designators}
\label{sec:type-desig}
\syntax\begin{verbatim}
SimpleType ::= StableId
\end{verbatim}
A type designator refers to a named value type. It can be simple or
qualified. All such type designators are shorthands for type projections.
Specifically, the unqualified type name $t$ where $t$ is bound in some
class, object, or package $C$ is taken as a shorthand for
\verb@C.this.type # t@. If $t$ is not bound in a class, object, or
package, then \verb@t@ is taken as a shorthand for
\verb@$\epsilon$.type # t@.
A qualified type designator has the form \verb@p.t@ where \verb@p@ is
a path (\sref{}) and $t$ is a type name. Such a type designator is
equivalent to the type projection \verb@p.type # x@.
\example
Some type designators and their expansions are listed below. We assume
a local type parameter \verb@t@, a value \verb@mytable@
with a type member \verb@Node@ and the standard class \verb@scala.Int@,
\begin{verbatim}
t \=$\epsilon$.type # t
Int \>scala.type # Int
scala.Int \>scala.type # Int
mytable.Node \>mytable.type # Node
\end{verbatim}
\subsection{Parameterized Types}
\label{sec:param-types}
\syntax\begin{verbatim}
SimpleType \=::= \= SimpleType TypeArgs
TypeArgs \>::= \> `[' Types `]'
\end{verbatim}
A parameterized type $T[U_1, ..., U_n]$ consists of a type designator
$T$ and type parameters $U_1 \commadots U_n$ where $n \geq 1$. $T$
must refer to a type constructor which takes $n$ type parameters $a_1,
..., a_n$ with lower bounds $L_1, ..., L_n$ and upper bounds $U_1,
..., U_n$.
The parameterized type is well-formed if each actual type parameter
{\em conforms to its bounds}, i.e.\ $L_i\sigma <: T_i <: U_i\sigma$ where $\sigma$
is the substitution $[a_1 := T_1, ..., a_n := T_n]$.
\example\label{ex:param-types}
Given the partial type definitions:
\begin{verbatim}
class HashMap[a <: Ord, b] { ... }
class List[a] { ... }
type I = Ord { ... }
\end{verbatim}
the following parameterized types are well formed:
\begin{verbatim}
HashMap[I, String]
List[I]
List[List[Boolean]]
\end{verbatim}
\example Given the type definitions of \ref{ex:param-types},
the following types are ill-formed:
\begin{verbatim}
HashMap[I] \=// illegal: wrong number of parameters
HashMap[List[I], Boolean] \>// illegal: type parameter not within bound
\end{verbatim}
\subsection{Compound Types}
\label{sec:compound-types}
\syntax\begin{verbatim}
Type \=::= \= SimpleType {with SimpleType} [Refinement]
Refinement \>::=\> `{' [RefineStat {`;' RefineStat}] `}'
RefineStat \>::=\> Dcl
\> |\> type TypeDef {`,' TypeDef}
\> |\>
\end{verbatim}
A compound type \verb@T$_1$ with ... with T$_n$ {R}@ represents
objects with members as given in the component types $T_1 \commadots
T_n$ and the refinement \verb@{R}@. Each component type $T_i$ must be a
class type and the base type sequence generated by types $T_1
\commadots T_n$ must be well-formed (\sref{sec:basetypes-wf}). A
refinement \verb@{R}@ contains declarations and type
definitions. Each declaration or definition in a refinement must
override a declaration or definition in one of the component types
$T_1 \commadots T_n$. The usual rules for overriding (\sref{})
apply. If no refinement is given, the empty refinement is implicitly
added, i.e. \verb@T$_1$ with ... with T$_n$@ is a shorthand for
\verb@T$_1$ with ... with T$_n$ {}@.
\subsection{Function Types}
\label{sec:function-types}
\syntax\begin{verbatim}
SimpleType \=::= \= Type1 `=>' Type
\> |\> `(' [Types] `)' `=>' Type
\end{verbatim}
The type \verb@(T$_1$, ..., T$_n$) => U@ represents the set of function
values that take arguments of types $T_1 \commadots T_n$ and yield
results of type $U$. In the case of exactly one argument type
\verb@S => T@ is a shorthand for \verb@(S) => T@. Function types
associate to the right, e.g.\ \verb@(S) => (T) => U@ is the same as
\verb@(S) => ((T) => U)@.
Function types are shorthands for class types that define \verb@apply@
functions. Specifically, the $n$-ary function type $(T_1 \commadots
T_n)U$ is a shorthand for the class type
\verb@Function$\,n$[$T_1 \commadots T_n$,U]@. Such class
types are defined in the Scala library for \verb@n@ between 0 and 9 as follows.
\begin{verbatim}
package scala;
trait Function$\,n$[-T$_1$, ..., -T$_n$, +R] {
def apply(x$_1$: T$_1$, ..., x$_n$: T$_n$): R;
override def toString() = "<function>";
}
\end{verbatim}
Hence, function types are covariant in their result type, and
contravariant in their argument types.
\section{Non-Value Types}
\label{sec:synthetic-types}
The types explained in the following do not denote sets of values, nor
do they appear explicitely in programs. They are introduced in this
report as the internal types of defined identifiers.
\subsection{Method Types}
\label{sec:method-types}\todo{Change Syntax}
A method type is denoted internally as $(ps)U$, where $(ps)$ is a
parameter section $(x_1: T_1 \commadots x_n: T_n)$ for some $n \geq 0$
and $U$ is a (value or method) type. This type represents named
methods that take arguments $x_1 \commadots x_n$ of types $T_1
\commadots T_n$ and that return a result of type $U$.
Method types associate to the right: $(ps_1)(ps_2)U$ is treated as
$(ps_1)((ps_2)U)$.
A special case are types of methods without any parameters. They are
written here $[]T$, following the syntax for polymorphic method types
(\sref{sec:poly-types}). Parameterless methods name expressions that
are re-evaluated each time the parameterless method name is
referenced.
Method types do not exist as types of values. If a method name is used
as a value, its type is implicitly converted to a corresponding
function type (\sref{sec:impl-conv}).
\example The declarations
\begin{verbatim}
def a: Int
def b (x: Int): Boolean
def c (x: Int) (y: String, z: String): String
\end{verbatim}
produce the typings
\begin{verbatim}
a: [] Int
b: (x: Int) Boolean
c: (x: Int) (y: String, z: String) String
\end{verbatim}
\subsection{Polymorphic Method Types}
\label{sec:poly-types}
A polymorphic method type is denoted internally as \verb@[tps]T@ where
\verb@[tps]@ is a type parameter section
\verb@[a$_1$ <: L$_1$ >: U$_1$, ..., a$_n$ <: L$_n$ >: U$_n$] T@
for some $n \geq 0$ and \verb@T@ is a
(value or method) type. This type represents named methods that
take type arguments \verb@S$_1$, ..., S$_n$@ which
conform (\sref{sec:param-types}) to the lower bounds
\verb@S$_1$, ..., S$_n$@ and the upper bounds
\verb@U$_1$, ..., U$_n$@ and that yield results of type \verb@T@.
\example The declarations
\begin{verbatim}
def empty[a]: List[a]
def union[a <: Comparable[a]] (x: Set[a], xs: Set[a]): Set[a]
\end{verbatim}
produce the typings
\begin{verbatim}
empty \=: [a >: All <: Any] List[a]
union \>: [a >: All <: Comparable[a]] (x: Set[a], xs: Set[a]) Set[a] .
\end{verbatim}
\subsection{Overloaded Types}
\label{sec:overloaded-types}
\newcommand{\overload}{\la\mbox{\sf and}\ra}
More than one values or methods are defined in the same scope with the
same name, we model
An overloaded type consisting of type alternatives $T_1 \commadots
T_n$ $(n \geq 2)$ is denoted internally $T_1 \overload \ldots
\overload T_n$.
\example The definitions
\begin{verbatim}
def println: Unit;
def println(s: String): Unit = ...;
def println(x: Float): Unit = ...;
def println(x: Float, width: Int): Unit = ...;
def println[a](x: a)(tostring: a => String): Unit = ...
\end{verbatim}
define a single function \verb@println@ which has an overloaded
type.
\begin{verbatim}
println: \= [] Unit $\overload$
\> (s: String) Unit $\overload$
\> (x: Float) Unit $\overload$
\> (x: Float, width: Int) Unit $\overload$
\> [a] (x: a) (tostring: a => String) Unit
\end{verbatim}
\example The definitions
\begin{verbatim}
def f(x: T): T = ...;
val f = 0
\end{verbatim}
define a function \verb@f@ which has type \verb@(x: T)T $\overload$ Int@.
\section{Base Types and Member Definitions}
Types, bounds and base types of class members depend on the way the
members are referenced. Central here are three notions, namely:
\begin{enumerate}
\item the notion of the base type sequence of a type $T$,
\item the notion of a type $T$ seen as a member of some class $C$ from some
prefix type $S$,
\item the notion of a member binding of some type $T$.
\end{enumerate}
These notions are defined mutually recursively as follows.
1. The {\em base type sequence} of a type is a sequence of class types,
given as follows.
\begin{itemize}
\item
The base types of a class type \verb@C@ are the base types of class
\verb@C@.
\item
The base types of an aliased type are the base types of its alias.
\item
The base types of an abstract type are the base types of its upper bound.
\item
The base types of a parameterized type \verb@C[T$_1$, ..., T$_n$]@ are the base types
of type \verb@C@, where every occurrence of a type parameter $a_i$
of \verb@C@ has been replaced by the corresponding parameter type $T_i$.
\item
The base types of a singleton type \verb@p.type@ are the base types of
the type of \verb@p@.
\item
The base types of a compound type
\verb@T$_1$ with ... with T$_n$ with {R}@ is the concatenation of the
base types of all \verb@T$_i$@'s, except that later base types replace
earlier base types which are instances of the same class.
\end{itemize}
2. The notion of a type \verb@T@
{\em seen as a member of some class \verb@C@ from some prefix type
\verb@S@} makes sense only if the prefix type \verb@S@
has a type instance of class \verb@C@ as a base type, say
\verb@S' # C[T$_1$, ..., T$_n$]@. Then we define as follows.
\begin{itemize}
\item
If \verb@S = $\epsilon$.type@, then $T$ seen as a member of $C$ from $S$ is $T$ itself.
\item Otherwise, if \verb@T@ is the $i$'th type parameter of some class \verb@D@, then
\begin{itemize}
\item
If \verb@S@ has a base type \verb@D[U$_1$, ..., U$_n$]@, for some type parameters
\verb@[U$_1$, ..., U$_n$]@, then \verb@T@ seen as a member of $C$ from $S$ is $U_i$.
\item
Otherwise, if $C$ is defined in a class $C'$, then
\verb@T@ seen as a member of $C$ from $S$ is the same as $T$ seen as
a member of $C'$ from $S'$.
\item
Otherwise, if $C$ is not defined in another class, then
\verb@T@ seen as a member of $C$ from $S$ is $T$ itself.
\end{itemize}
\item
Otherwise,
if \verb@T@ is the singleton type \verb@D.this.type@ for some class \verb@D@
then
\begin{itemize}
\item
If \verb@D@ is a subclass of \verb@C@ and
\verb@S@ has a type instance of class $D$ among its base types.
then \verb@T@ seen as a member of $C$ from $S$ is $S$.
\item
Otherwise, if $C$ is defined in a class $C'$, then
\verb@T@ seen as a member of $C$ from $S$ is the same as $T$ seen as
a member of $C'$ from $S'$.
\item
Otherwise, if $C$ is not defined in another class, then
\verb@T@ seen as a member of $C$ from $S$ is $T$ itself.
\end{itemize}
\item
If $T$ is some other type, then the described mapping is performed
to all its type components.
\end{itemize}
If \verb@T@ is a possibly parameterized class type, where $T$'s class
is defined in some other class $D$, and \verb@S@ is some prefix type,
then we use ``\verb@T@ seen from \verb@S@'' as a shorthand for
``\verb@T@ seen as a member of $D$ from $S$.
3. The {\em member bindings} of a type $T$ are all bindings $d$ such that
there exists a type instance of some class $C$ among the base types of $T$
and there exists a definition or declaration $d'$ in $C$
such that $d$ results from $d'$ by replacing every
type $T'$ in $d'$ by $T'$ seen as a member of $C$ from $T$.
The {\em definition} of a type projection \verb@S # t@ is the member
binding $d$ of the type \verb@t@ in \verb@S@. In that case, we also say
that \verb@S # t@ {\em is defined by} \verb@d@.
\section{Relations between types}
We define two relations between types.
\begin{quote}\begin{tabular}{l@{\tab}l@{\tab}l}
\em Type equivalence & $T \equiv U$ & $T$ and $U$ are interchangeable
in all contexts.
\\
\em Conformance & $T \conforms U$ & Type $T$ conforms to type $U$.
\end{tabular}\end{quote}
\subsection{Type Equivalence}
\label{sec:type-equiv}
Equivalence $(\equiv)$ between types is the smallest congruence\footnote{ A
congruence is an equivalence relation which is closed under formation
of contexts} such that the following holds:
\begin{itemize}
\item
If $t$ is defined by a type alias \verb@type t = T@, then $t$ is
equivalent to $T$.
\item
If a path $p$ has a singleton type \verb@q.type@, then
\verb@p.type $\equiv$ q.type@.
\item
If \verb@O@ is defined by an object definition, and \verb@p@ is a path
consisting only of package or object selectors and ending in \verb@O@, then
\verb@O.this.type $\equiv$ p.type@.
\item
Two compound types are equivalent if their component types are
pairwise equivalent and their refinements are equivalent. Two
refinements are equivalent if they bind the same names and the
modifiers, types and bounds of every declared entity are equivalent in
both refinements.
\item
Two method types are equivalent if they have equivalent result
types, both have the same number of parameters, and corresponding
parameters have equivalent types as well as the same \verb@def@ or
\verb@*@ modifiers. Note that the names of parameters do not matter
for method type equivalence.
\item
Two polymorphic types are equivalent if they have the same number of
type parameters, and, after renaming one set of type parameters by
another, the result types as well as lower and upper bounds of
corresponding type parameters are equivalent.
\item
Two overloaded types are equivalent if for every alternative type in
either type there exists an equivalent alternative type in the other.
\end{itemize}
\subsection{Conformance}
\label{sec:subtyping}
The conformance relation $(\conforms)$ is the smallest
transitive relation that satisfies the following conditions.
\begin{itemize}
\item Conformance includes equivalence. If $T \equiv U$ then $T \conforms U$.
\item For every value type $T$, \verb@scala.All <: T <: scala.Any@.
\item For every value type \verb@T <: scala.AnyRef@ one has \verb@scala.AllRef <: T@.
\item A type variable or abstract type $t$ conforms to its upper bound and
its lower bound conforms to $t$.
\item A class type or parameterized type $c$ conforms to any of its basetypes, $b$.
\item A type projection \verb@T # t@ conforms to \verb@U # t@ if
\verb@T@ conforms to \verb@U@.
\item A parameterized type \verb@T[T$_1$, ..., T$_n$]@ conforms to
\verb@T[U$_1$, ..., U$_n$]@ if
the following three conditions hold for $i = 1 \commadots n$.
\begin{itemize}
\item
If the $i$'th type parameter of $T$ is declared covariant, then $T_i <: U_i$.
\item
If the $i$'th type parameter of $T$ is declared contravariant, then $U_i <: T_i$.
\item
If the $i$'th type parameter of $T$ is declared neither covariant
nor contravariant, then $U_i \equiv T_i$.
\end{itemize}
\item A compound type \verb@T$_1$ with ... with T$_n$ {R}@ conforms to
each of its component types \verb@T$_i$@.
\item If $T \conforms U_i$ for $i = 1 \commadots n$ and for every
binding of a type or value $x$ in $R$ there exists a member binding of
$x$ in $T$ which is more specific, then $T$ conforms to
the compound type \verb@T$_1$ with ... with T$_n$ {R}@.
\item If
$T'_i$ conforms to $T_i$ for $i = 1 \commadots n$ and $U$ conforms to $U'$
then the method type $(x_1: T_1 \commadots x_n: T_n) U$ conforms to
$(x_1: T'_1 \commadots x_n: T'_n) U'$.
\item If, assuming
$L'_1 \conforms a_1 \conforms U'_1 \commadots L'_n \conforms a_n \conforms U'_n$
one has $L_i \conforms L'_i$ and $U'_i \conforms U_i$
for $i = 1 \commadots n$, as well as $T \conforms T'$ then the polymorphic type
$[a_1 >: L_1 <: U_1 \commadots a_n >: L_n <: U_n] T$ conforms to the polymorphic type
$[a_1 >: L'_1 <: U'_1 \commadots a_n >: L'_n <: U'_n] T'$.
\item
An overloaded type $T_1 \overload \ldots \overload T_n$ conforms to each of its alternative types $T_i$.
\item
A type $S$ conforms to the overloaded type $T_1 \overload \ldots \overload T_n$
if $S$ conforms to each alternative type $T_i$.
\end{itemize}
A declaration or definition in some compound type of class type $C$
is {\em more specific} than another
declaration of the same name in some compound type or class type $C'$.
\begin{itemize}
\item
A value declaration \verb@val x: T@ or value definition
\verb@val x: T = e@ is more specific than a value declaration
\verb@val x: T'@ if $T <: T'$.
\item
A type alias
$\TYPE;t=T$ is more specific than a type alias $\TYPE;t=T'$ if
$T \equiv T'$.
\item
A type declaration \verb@type t >: L <: U@ is more specific that
a type declaration \verb@type t >: L' <: U'@ if \verb@L' <: L@ and \verb@U <: U'@.
\item
A type or class definition of some type $t$ is more specific than an abstract
type declaration \verb@type t >: L <: U@ if
\verb@L <: t <: U@.
\end{itemize}
The \verb@<:@ relation forms a partial order between types. The {\em
least upper bound} or the {\em greatest lower bound} of a set of types
is understood to be relative to that order.
\section{Type Erasure}
\label{sec:erasure}
A type is called {\em generic} if it contains type arguments or type variables.
{\em Type erasure} is a mapping from (possibly generic) types to
non-generic types. We write $|T|$ for the erasure of type $T$.
The erasure mapping is defined as follows.
\begin{itemize}
\item The erasure of a type variable is the erasure of its upper bound.
\item The erasure of a parameterized type $T[T_1 \commadots T_n]$ is $|T|$.
\item The erasure of a singleton type \verb@p.type@ is the
erasure of the type of \verb@p@.
\item The erasure of a type projection \verb@T # x@ is \verb@|T| # x@.
\item The erasure of a compound type $T_1;\WITH;\ldots;\WITH;T_n\{R\}$ is $|T_1|$.
\item The erasure of every other type is the type itself.
\end{itemize}
\section{Implicit Conversions}
\label{sec:impl-conv}
If $S \conforms T$, then values of type $S$ are implicitly {\em
converted} to values type of $T$ in situations where a value of type
$T$ is required. A conversion between two number types in \verb@Int@,
\verb@Long@, \verb@Float@, \verb@Double@ creates a value of the target
type representing the same number as the source. When used in an
expression, a value of type \verb@Byte@, \verb@Char@, \verb@Short@ is
always implicitly converted to a value of type \verb@Int@.
The following implicit conversions are applied to expressions of
method type that are used as values, rather than being applied to some
arguments.
\begin{itemize}
\item
A parameterless method $m$ of type $[] T$
is converted to type $T$ by evaluating the expression to which $m$ is bound.
\item
An expression $e$ of polymorphic type $[a_1 \extends S_1 \commadots
a_n \extends S_n]T$ which does not appear as the function part of
a type application is converted to type $T$
by determining with local type inference
(\sref{sec:local-type-inf}) instance types $U_1
\commadots U_n$ for the type variables $a_1 \commadots a_n$ and
implicitly embedding $e$ in the type application
$e[U_1 \commadots U_n]$ (\sref{sec:type-app}).
\item
An expression $e$ of monomorphic method type
$(ps_1) \ldots (ps_n) U$ of arity $n > 0$
which does not appear as the function part of an application is
converted to a function type by implicitly embedding $e$ in
the following term, where $x$ is a fresh variable:
\begin{verbatim}
(val $x$ = $e$ ; $(ps_1) \ldots \Arrow \ldots \Arrow (ps_n) \Arrow x;(ps_1);\ldots;(ps_n)$)
\end{verbatim}
This conversion is not applicable to functions with call-by-name
parameters (\sref{sec:parameters}) of type $[]T$, because its result
would violate the well-formedness rules for anonymous functions
(\sref{sec:closures}). Hence, methods with call-by-name
parameters always need to be applied to arguments immediately.
\end{itemize}
If $p$ is a path (\sref{sec:paths}), then $p$ is implicitly converted to a
value of type \verb@p.type@ if the context requires it.
\chapter{Basic Declarations and Definitions}
\label{sec:defs}
\syntax\begin{verbatim}
Dcl \=::=\= val ValDcl {`,' ValDcl}
\> |\> var VarDcl {`,' VarDcl}
\> |\> def FunDcl {`,' FunDcl}
\> |\> constr ConstrDcl {`,' ConstrDcl}
\> |\> type TypeDcl {`,' TypeDcl}
Def \>::=\> val PatDef {`,' PatDef}
\> |\> var VarDef {`,' VarDef}
\> |\> def FunDef {`,' FunDef}
\> |\> constr ConstrDef {`,' ConstrDef}
\> |\> type TypeDef {`,' TypeDef}
\> |\> ClsDef
\end{verbatim}
\iflet{$\LET$ ValDef {`,' ValDef}}
A {\em declaration} introduces names and assigns them types. It can
appear as one of the statements of a class definition
(\sref{sec:templates}) or as part of a refinement in a compound
type (\sref{sec:refinements}).
A {\em definition} introduces names
that denote terms or types. It can form part of a module or class or
it can be local to a block. Both declarations and definitions produce
{\em bindings} that associate type names with type definitions or
bounds, and that associate term names with types.
The scope of a name introduced by a declaration or definition is the
whole statement sequence containing the binding. However, there is a
restriction on forward references: In a statement sequence $s_1 \ldots
s_n$, if a simple name in $s_i$ refers to an entity defined by $s_j$
where $j \geq i$, then all statements between and including $s_i$ and
$s_j$ must be pure statements (\sref{sec:statements}).
{\em Pure} definitions can be evaluated without any side effect.
Function, type, class, or object definitions are always pure. A value
definition is pure if its right-hand side expression is pure. Pure
expressions are paths, literals, as well as typed expressions
\verb@e: T@ where \verb@e@ is pure.
\comment{
Every basic definition may introduce several defined names, separated
by commas. These are expanded according to the following scheme:
\bda{lcl}
\VAL;x, y: T = e && \VAL; x: T = e \\
&& \VAL; y: T = x \\[0.5em]
\LET;x, y: T = e && \LET; x: T = e \\
&& \VAL; y: T = x \\[0.5em]
\DEF;x, y (ps): T = e &\tab\mbox{expands to}\tab& \DEF; x(ps): T = e \\
&& \DEF; y(ps): T = x(ps)\\[0.5em]
\VAR;x, y: T := e && \VAR;x: T := e\\
&& \VAR;y: T := x\\[0.5em]
\TYPE;t,u = T && \TYPE; t = T\\
&& \TYPE; u = t\\[0.5em]
\eda
}
All definitions have a ``repeated form'' where the initial
definition keyword is followed by several constituent definitions
which are separated by commas. A repeated definition is
always interpreted as a sequence formed from the
constituent definitions. E.g.\ the function definition
\verb@def f(x) = x, g(y) = y@ expands to
\verb@def f(x) = x; def g(y) = y@ and
the type definition
\verb@type T$_1$, T$_2$ <: B$_2$@ expands to
\verb@type T$_1$; type T$_2$ <: B$_2$@.
\section{Value Declarations and Definitions}
\label{sec:valdef}
\syntax\begin{verbatim}
Dcl \=::= \= val ValDcl {`,' ValDcl}
ValDcl \>::= \> Id `:' Type
Def \>::= \> val PatDef {`,' PatDef}
PatDef \>::= \> Pattern `=' Expr
\end{verbatim}
A value declaration \verb@val x: T@ introduces \verb@x@ as a name of a value of
type \verb@T@.
A value definition \verb@val x: T = e@ defines $x$ as a name of the value
that results from the evaluation of $e$. The type $T$ may be omitted
if it can be determined using local type inference
(\sref{sec:local-type-inf}). The type of the expression $e$ must
conform to type $T$.
Evaluation of the value definition implies evaluation of its
right-hand side $e$. The effect of the value definition is to bind
$x$ to the value of $e$ converted to type $T$.
Value definitions can alternatively have a pattern
(\sref{sec:patterns}) as left-hand side. If $p$ is some pattern other
than a simple name or a name followed by a colon and a type, then the
value definition \verb@val p = e@ is expanded as follows:
1. If the pattern $p$ has bound variables $x_1 \commadots x_n$, where $n > 1$:
\begin{verbatim}
val $\Dollar$x = e.match {case p => scala.Tuple$\,n$(x$_1$, ..., x$_n$)}
val x$_1$ = $\Dollar$x._1
...
val x$_n$ = $\Dollar$x._n .
\end{verbatim}
Here, \verb@$\Dollar$x@ is a fresh name. The class
\verb@Tuple$\,n$@ is defined for $n = 2,...,9$ in package
\verb@scala@.
2. If $p$ has a unique bound variable $x$:
\begin{verbatim}
val x = e.match { case p => x }
\end{verbatim}
3. If $p$ has no bound variables:
\begin{verbatim}
e.match { case p => ()}
\end{verbatim}
\example
The following are examples of value definitions
\begin{verbatim}
val pi = 3.1415;
val pi: double = 3.1415; \=// equivalent to first definition
val Some(x) = f(); \>// a pattern definition
val x :: xs = mylist; \>// an infix pattern definition
\end{verbatim}
The last two definitions have the following expansions.
\begin{verbatim}
val x = f().match { case Some(x) => x }
val x$\Dollar$ = mylist.match { case x :: xs => scala.Tuple2(x, xs) }
val x = x$\Dollar$._1;
val xs = x$\Dollar$._2;
\end{verbatim}
\iflet{
\section{Let Definitions}
\label{sec:letdef}
\syntax\begin{verbatim}
PureDef \=::= \= $\LET$ ValDef {`,' ValDef}
ValDef \>::= \> Id [`:' Type] `=' Expr
\end{verbatim}
A let definition $\LET;x: T = e$ defines $x$ as a name of the value
that results from the delayed evaluation of $e$. The type $T$ must be
a concrete value type (\sref{sec:types}) and the type of the
expression $e$ must conform to $T$. The effect of the let definition
is to bind the left-hand side $x$ to the result of evaluating $e$
converted to type $T$. However, the expression $e$ is not evaluated
at the point of the let definition, but is instead evaluated the first
time $x$ is dereferenced during execution of the program (which might
be never at all). An attempt to dereference $x$ again in the course of
evaluation of $e$ leads to a run-time error. Other threads trying to
dereference $x$ while $e$ is being evaluated block until evaluation is
complete.
The type $T$ may be omitted if it can be determined using local type
inference (\sref{sec:local-type-inf}).
}
\section{Variable Declarations and Definitions}
\label{sec:vardef}
\syntax\begin{verbatim}
Dcl \=::= \= var VarDcl {`,' VarDcl}
Def \>::= \> var ValDef {`,' ValDef}
VarDcl \>::=\> Id `:' Type
VarDef \>::=\> Id [`:' Type] `=' Expr
\> |\> Id `:' Type `=' `_'
\end{verbatim}
\ifundefvar{
PureDef \>::= \> $\VAR$ ValDcl {`,' ValDcl}
}
A variable declaration \verb@var x: T@ is equivalent to declarations
of a {\em getter function} \verb@x@ and a {\em setter function}
\verb@x_=@, defined as follows:
\begin{verbatim}
def x: T
def x_= (y: T): unit
\end{verbatim}
An implementation of a class containing variable declarations
may define these variables using variable definitions, or it may
define setter and getter functions directly.
A variable definition \verb@var x: T = e@ introduces a mutable
variable with type \verb@T@ and initial value as given by the
expression \verb@e@. The type $T$ can be omitted,
in which case the type of $e$ is assumed.
A variable definition \verb@var x: T = _@ introduces a mutable
variable with type \verb@T@ and a default initial value.
The default value depends on the type \verb@T@ as follows:
\begin{quote}\begin{tabular}{ll}
\verb@0@ & if $T$ is \verb@int@ or one of its subrange types, \\
\verb@0L@ & if $T$ is \verb@long@,\\
\verb@0.0f@ & if $T$ is \verb@Float@,\\
\verb@0.0d@ & if $T$ is \verb@double@,\\
\verb@false@ & if $T$ is \verb@boolean@,\\
\verb@()@ & if $T$ is \verb@unit@, \\
\verb@null@ & for all other types $T$.
\end{tabular}\end{quote}
Both forms of variable defintion also introduce a getter function
\verb@x@ which returns the value currently assigned to the variable,
as well as a setter function \verb@x_=@ which changes the value
currently assigned to the variable. The functions have the same
signatures as for a variable declaration.
\example The following example shows how {\em properties} can be
simulated in Scala. It defines a class \verb@TimeOfDayVar@ of time
values with updatable integer fields representing hours, minutes, and
seconds. Its implementation contains tests that allow only legal
values to be assigned to these fields. The user code, on the other
hand, accesses these fields just like normal variables.
\begin{verbatim}
class TimeOfDayVar with {
private var h: int = 0, m: int = 0, s: int = 0;
def hours \== h;
def hours_= (h: int) \>= \=if (0 <= h && h < 24) this.h = h
\> \>else new DateError().throw;
def minutes \>= m
def minutes_= (m: int) \>= if (0 <= m && m < 60) this.m = m
\> \>else new DateError().throw;
def seconds \>= s
def seconds_= (s: int) \>= if (0 <= s && s < 60) this.s = s
\> \>else new DateError().throw;
}
val t = new TimeOfDayVar;
d.hours = 8; d.minutes = 30; d.seconds = 0;
d.hours = 25; \=// throws a DateError exception
\end{verbatim}
\section{Type Declarations and Type Aliases}
\label{sec:typedcl}
\label{sec:typealias}
\syntax\begin{verbatim}
Dcl \=::= \= type TypeDcl {`,' TypeDcl}
TypeDcl \>::= \> Id [>: Type] [<: Type]
Def \>::= \> type TypeDef {`,' TypeDef}
TypeDef \>::= \> Id `=' Type
\end{verbatim}
A {\em type declaration} \verb@type t >: L <: U@ declares \verb@t@ to
be an abstract type with lower bound type \verb@L@ and upper bound
type \verb@U@. If such a declaration appears as a member declaration
of a type, implementations of the type may implement \verb@t@ with any
type \verb@T@ for which \verb@L <: T <: U@. Either or both bounds may
be omitted. If the lower bound \verb@L@ is missing, the bottom type
\verb@scala.All@ is assumed. If the upper bound \verb@U@ is missing,
the top type \verb@scala.Any@ is assumed.
A {\em type alias} \verb@type t = T@ defines \verb@t@ to be an alias
name for the type \verb@T@. Type declarations and type aliases are
collectively called {\em type bindings}.
The scope rules for definitions (\sref{sec:defs}) and type parameters
(\sref{sec:funsigs}) make it possible that a type name appears in its
own bound or in its right-hand side. However, it is a static error if
a type alias refers recursively to the defined type itself. That is,
the type \verb@T@ in a type alias \verb@type t = T@ may not refer
directly or indirectly to the name \verb@t@. It is also an error if
an abstract type is directly or indirectly its own bound.
\example The following are legal type declarations and definitions:
\begin{verbatim}
type IntList = List[Integer];
type T extends Comparable[T];
\end{verbatim}
The following are illegal:
\begin{verbatim}
type Abs = Comparable[Abs]; \=// recursive type alias
type S <: T; \>// S, T are bounded by themselves.
type T <: S;
type T <: Object with T; \>// T is abstract, may not be part of
\>// compound type
type T >: Comparable[T.That]; \>// Cannot select from T.
\>// T is a type, not a value
\end{verbatim}
\section{Function Declarations and Definitions}
\label{sec:defdef}
\label{sec:funsigs}
\syntax\begin{verbatim}
Dcl \=::= \= def FunDcl {`,' FunDcl}
FunDcl \>::= \> Id [FunTypeParamClause] {ParamClause} `:' Type
Def \>::= \> def FunDef {`,' FunDef}
FunDef \>::= \> Id [FunTypeParamClause] {ParamClause} [`:' Type]
\>\> `=' Expr
FunTypeParamClause \>::=\> `[' TypeDcl {`,' TypeDcl} `]'
ParamClause \>::=\> `(' [Param {`,' Param}] `)'
Param \>::= \> [def] Id `:' Type [*]
\end{verbatim}
A function declaration has the form \verb@def f psig: T@, where
\verb@f@ is the function's name, \verb@psig@ is its parameter
signature and \verb@T@ is its result type. A function definition
\verb@f psig:T = e@ also includes a {\em function body} \verb@e@,
i.e.\ an expression which defines the function's result. A parameter
signature consists of an optional type parameter clause \verb@[tps]@,
followed by zero or more value parameter clauses
\verb@(ps_1) \ldots (ps_n)@. Such a declaration or definition
introduces a value with a (possibly polymorphic) method type whose
parameters and result type are as given.
A type parameter clause \verb@tps@ consists of one or more type
declarations (\sref{sec:typedcl}), which introduce type parameters,
possibly with bounds. The scope of a type parameter \verb@a@ includes
the whole signature, including any of the type parameter bounds as
well as the function body, if it is present.
A value parameter clause \verb@ps@ consists of zero or more formal
parameter bindings such as \verb@x: T@, which bind value
parameters and associate them with their types. The scope of a formal
value parameter name \verb@x@ is the function body, if one is
given. Both type parameter names and value parameter names must be
pairwise distinct.
Value parameters may be prefixed by \verb@def@, e.g.\
\verb@\DEF;x:T@. The type of such a parameter is then the
parameterless method type \verb@[]T@. This indicates that the
corresponding argument is not evaluated at the point of function
application, but instead is evaluated at each use within the
function. That is, the argument is evaluated using {\em call-by-name}.
\example The declaration
\begin{verbatim}
def while (def cond: Boolean) (def stat: Unit): Unit
\end{verbatim}
produces the typing
\begin{verbatim}
while: (cond: [] Boolean) (stat: [] Unit) Unit
\end{verbatim}
which indicates that both parameters of \verb@while@ are evaluated using
call-by-name.
The type of the function body must conform to the function's declared
result type, if one is given. If the function definition is not
recursive, the result type may be omitted, in which case it is
determined from the type of the function body.
\section{Overloaded Definitions}
\label{sec:overloaded-defs}
\todo{change}
An overloaded definition is a set of \verb@n > 1@ value or function
definitions in the same scope that define the same name, binding it to
types \verb@T_1 \commadots T_n@, respectively. The individual
definitions are called {\em alternatives}. Alternatives always need
to specify the type of the defined entity completely. All
alternatives must have the same modifiers. It is an error if the types
of two alternatives \verb@T_i@ and \verb@T_j@ have the same erasure
(\sref{sec:erasure}). An overloaded definition defines a single
entity, of type \verb@T_1 \overload \ldots \overload T_n@
(\sref{sec:overloaded-types}).
%This must be a well-formed
%overloaded type
\section{Import Clauses}
\label{sec:import}
\syntax\begin{verbatim}
Import \=::=\> import ImportExpr {`,' ImportExpr}
ImportExpr \>::=\> StableId `.' (Id | `_' | ImportSelectors)
ImportSelectors \>::=\> `{' {ImportSelector `,'} (ImportSelector | `_') `}'
ImportSelector \>::=\> Id [`=>' Id | `=>' `_']
\end{verbatim}
An import clause has the form $import;e.I$ where \verb@e@ is a stable
identifier (\sref{sec:paths}) and \verb@I@ is an import expression.
The import expression determines a set of names of members of \verb@e@
which are made available without qualification. The most general form
of an import expression is a list of {\em import selectors}
\begin{verbatim}
{ x$_1$ => y$_1$, ..., x$_n$ => y$_n$, _ }
\end{verbatim}
for $n \geq 0$, where the final wildcard `\verb@_@' may be absent. It
makes available each member \verb@e.x$_i$@ under the unqualified name
\verb@y$_i$. I.e.\ every import selector \verb@x$_i$ => y$_i$@ renames
\verb@e.x$_i$@ to
\verb@y$_i$. If a final wildcard is present, all members \verb@z@ of
\verb@e@ other than \verb@x$_1$, ..., x$_n$@ are also made available
under their own unqualfied names.
If destination in an import selector is a wildcard, the import
selector hides access to the source member. For instance, the import
selector \verb@x => _@ ``renames'' \verb@x@ to the wildcard symbol
(which is unaccessible as a name in user programs), and thereby
effectively prevents unqualified access to \verb@x@. This is useful if
there is a final wildcard in the same import selector list, which
imports all members not mentioned in previous import selectors.
The import selector \verb@x$_i$
\begin{itemize}
\item
An import selet
If the import selector is an identifier, as in \verb@import e.x@, then
\verb@x@ can be accessed without qualification.
\item
If the import selector is
, an clause makes members
expression $e$ available without qualification. The expression $e$
must be a stable identifier $r$, possibly followed by an explicit type
$T$. If no type is given, the type of $r$ is assumed. For every
simple name $x$ of a non-private member of $T$, the simple name $x$ is
introduced as an alias for $r.x$ in the remainder of the block or
template that follows the import clause.
An import clause with multiple expressions $\IMPORT;e_1
\commadots e_n$ is interpreted as a sequence of import clauses
$\IMPORT;e_1 \ldots \IMPORT;e_n$.
\example Consider the module definition:
\begin{verbatim}
module M with { def z = 0; def inc(x: Int): Int = x + 1 }
\end{verbatim}
Then the block
\verb@{ import M; inc(z) }@
is equivalent to the block \verb@{ M.inc(M.z) }@.
\comment{
The compiler expands the import clause to a sequence of definitions as
is described below. Assume first that the imported expression $e$ is a
stable identifier $r$. For every simple name $x$ of a member of $r$,
the compiler generates an alias definition (\sref{sec:aliasing}) of
$x$ for $r.x$. If there are several members of $r$ that have the same
simple name $x$ but different qualified names, only the member
identified (\sref{sec:names}) by the simple name $x$ is imported.
\subsection*{Alias Definitions}
\label{sec:aliasing}
With the exception of guards (which are never members of classes or
objects) it is always possible to define aliases for defined
entities. An alias definition of the \ifqualified{(possibly qualified)} name $X$ for
the entity $Y$ takes one of the following forms.
If $Y$ defines a type, then the alias definition is \verb@type X = Y@
(or the parameterized analogue if $Y$ is a type constructor).
If $Y$ defines a parameterless method of type $[]T$, then the alias definition is
\bda{l}
\DEF;X: T = Y \enspace.\eda
If $Y$ defines a monomorpic method of type $(ps_1)\ldots(ps_n)T$,
then the alias definition is
\bda{l}
\DEF;X(ps_1) \ldots (ps_n): T = Y(ps_1)\ldots (ps_n) \enspace.\eda
If $Y$ defines a polymorphic method of type $[a_1 \extends S_1 \commadots a_m \extends S_m](ps_1)\ldots(ps_n) T$,
then the alias definition is
\bda{l}
\DEF;X[a_1 \extends S_1 \commadots a_m \extends S_m](ps_1) \ldots (ps_n): T =
Y[a_1 \commadots a_m](ps_1)\ldots (ps_n) \enspace.
\eda
If $Y$ defines an overloaded function of type $T_1 \overload \ldots
\overload T_n$, then the alias definition consists of $n$ function
definitions, which correspond to the alternatives $T_1 \commadots T_n$
of the overloaded type.
If $Y$ is defined by a value (\sref{sec:valdef}),
let (\sref{sec:letdef}) or module (\sref{sec:modules}) definition, then the alias
definition is $\VAL;X = Y$.
If $Y$ defines a parameterless class, then the alias definition is
$\CLASS;X = Y$. If $Y$ defines a class with parameters $[a_1
\extends S_1 \commadots a_m \extends S_m](ps_1) \ldots (ps_n)$,
then the alias definition is
\bda{l}
\CLASS;X;[a_1\extends S_1 \commadots a_m \extends S_m](ps_1) \ldots (ps_n) = Y[a_1 \commadots a_m](ps_1) \ldots (ps_n)
\enspace.
\eda
\example Some alias definitions are:
\begin{verbatim}
module L = scala.lang;
type T = L.List[Int];
def println(s: String) = L.System.println(s);
val out = L.System.out;
class IntList = L.List[Int];
class Nil[a] = L.Nil[a];
\end{verbatim}
}
\chapter{Classes and Modules}
\label{sec:globaldefs}
\syntax\begin{verbatim}
PureDef \=::= \= [case] class ClassDef {`,' ClassDef}
\> | \> module ModuleDef {`,' ModuleDef}
\end{verbatim}
Classes (\sref{sec:classes}) and modules
(\sref{sec:modules}) are both defined in terms of {\em templates}.
\section{Templates}
\label{sec:templates}
\syntax\begin{verbatim}
Template \=::= \= Constr {$\WITH$ Constr} [$\WITH$ `(' {TemplateStat `;'} `)']
\end{verbatim}
Templates define the type signature, behavior and initial state of a
class of objects. They form part of instance creation expressions,
class definitions, and module definitions. A template
$sc;\WITH;mc_1;\WITH;\ldots;\WITH;mc_n;\WITH;(stats)$ consists of a
constructor invocation $sc$ which defines the template's {\em
superclass}, constructor invocations $mc_1 \commadots mc_n$ $(n \geq
0)$, which define the template's {\em mixin classes}, and a statement
sequence $stats$ which contains additional member definitions for the
template. The {\em least proper supertype} of a template is the class
type or compound type (\sref{sec:compound-types}) consisting of its
superclass and mixin classes. The superclass of a template must be a
subtype of the superclass of each mixin class.
Member definitions define new members or overwrite members in the
superclass and the mixin classes. If the template forms part of a
class definition, $stats$ may also contain declarations of abstract
members. The type of each non-private definition or declaration of a
template must be equivalent to a type which does not refer to any
private members of that template.
\subsection{Constructor Invocations}
\label{sec:constr-invoke}
\syntax\begin{verbatim}
Constr \=::= \= StableId [TypeArgs] {ArgumentExpr}
\end{verbatim}
Constructor invocations define the type, members, and initial state of
objects created by an instance creation expression, or of parts of an
object's definition which are inherited by a class or module
definition. A constructor invocation is a designator or function
application whose type is a class constructor type \verb@class T@, for
some type \verb@T@.
\subsection{Base Classes}
\label{sec:base-classes}
For every template, class type and constructor invocation we define two
sequences of class types: the {\em base classes} and {\em mixin base
classes}. Their definitions are as follows.
The {\em mixin base classes} of a template
$sc;\WITH;mc_1;\WITH;mc_n;\WITH;(stats)$ are obtained by
concatenating, for each $i = 1 \commadots n$, the mixin base classes
of the mixin $mc_i$. The mixin base classes of a class type $C$ are
the mixin base classes of the template represented by $C$, followed by
$C$ itself. The mixin base classes of a constructor invocation of type
\verb@class T@ are the mixin base classes of class \verb@T@.
The {\em base classes} of a template consist of the base classes of
its superclass, followed by the template's mixin base classes. The
base classes of class \verb@scala.Any@ consist of just the
class itself. The base classes of some other class type $C$ are the
base classes of the template represented by $C$, followed by $C$
itself. The base classes of a constructor invocation of type \verb@class T@
are the base classes of \verb@T@.
If two classes in the base class sequence of a template refer to the
same class definition, then that definition must define an interface
(\sref{sec:interfaces}), and both references must have the same
qualifiers and parameters (if any).
\subsection{Evaluation}
The evaluation of a template or constructor invocation depends on
whether the template defines an object or is a superclass of a
constructed object, or whether it is used as a mixin for a defined
object. In the second case, the evaluation of a template used as a
mixin depends on an {\em actual superclass}, which is known at the
point where the template is used in a definition of an object, but not
at the point where it is defined. The actual superclass is used in the
determination of the meaning of \verb@super@ (\sref{sec:this-super}).
We therefore define two notions of template evaluation: (Plain)
evaluation (as a defining template or superclass) and mixin evaluation
with a given superclass $sc$. These notions are defined for templates
and constructor invocations as follows.
A {\em mixin evaluation with superclass $sc$} of a template
$sc';\WITH;mc_1;\WITH;mc_n;\WITH;(stats)$ consists of mixin
evaluations with superclass $sc$ of the mixin constructor invocations
$mc_1 \commadots mc_n$ in the order they are given, followed by an
evaluation of the statement sequence $stats$. Within $stats$ the
actual superclass refers to $sc$. A mixin evaluation with superclass
$sc$ of a class constructor invocation $ci$ consists of an evaluation
of the constructor function and its arguments in the order they are
given, followed by a mixin evaluation with superclass $sc$ of the
template represented by the constructor invocation.
An {\em evaluation} of a template
$sc;\WITH;mc_1;\WITH;mc_n;\WITH;(stats)$ consists of an evaluation of
the superclass constructor invocation $sc$ (of type $S$, say),
followed by a mixin evaluation with superclass $sc$ of the template. An
evaluation of a class constructor invocation $ci$ consists of an
evaluation of the constructor function and its arguments in
the order they are given, followed by an evaluation of the template
represented by the constructor invocation.
\subsection{Template Members}
\label{sec:members}
The object resulting from evaluation of a template has directly bound
members and inherited members. Members can be abstract or concrete.
These are defined as follows.
\begin{enumerate}
\item
A {\em directly bound} member is an entity introduced by a member
definition or declaration in the template's statement sequence. The
member is called {\em abstract} if it is introduced by a declaration,
{\em concrete} otherwise.
\item
A {\em concrete inherited} member is a non-private, concrete member of
one of the template's base classes $B$, except if a member with the
same \ifqualified{qualified} name is already directly bound in the template, or is
directly bound in a base class of the template which is a subclass of
$B$, or is a directly bound, non-private, concrete member of a base
class which succeeds $B$ in the base class sequence of the template.
\item
An {\em abstract inherited} member is a non-private, abstract member
of one of the template's base classes $B$, except if a member with the
same \ifqualified{qualified} name is already directly bound in the template, or is a
concrete inherited member, or is a directly bound, non-private member
of a base class which succeeds $b$ in the base class sequence of the
template.
\end{enumerate}
The type of a member $m$ is determined as follows: If $m$ is defined
in $stats$, then its type is the type as given in the member's
declaration or definition. Otherwise, if $m$ is inherited from the
base class $B[T1 \commadots T_n]$, $B$'s class declaration has formal
parameters $[a_1 \commadots a_n]$, and $M$'s type in $B$ is $U$, then
$M$'s type in $C$ is $U[a_1 := T_1
\commadots a_n := T_n]$.
\ifqualified{
Members of templates have internally qualified names $Q\qex x$ where
$x$ is a simple name and $Q$ is either the empty name $\epsilon$, or
is a qualified name referencing the module or class that first
introduces the member. A basic declaration or definition of $x$ in a
module or class $M$ introduces a member with the following qualified
name:
\begin{enumerate}
\item
If the binding is labelled with an \verb@override $Q$@\nyi{Override
with qualifier} modifier,
where $Q$ is a fully qualified name of a base class of $M$, then the
qualified name is the qualified expansion (\sref{sec:names}) of $x$ in
$Q$.
\item
If the binding is labelled with an \verb@override@ modifier without a
base class name, then the qualified name is the qualified expansion
of $x$ in $M$'s least proper supertype (\sref{sec:templates}).
\item
An implicit \verb@override@ modifier is added and case (2) also
applies if $M$'s least proper supertype contains an abstract member
with simple name $x$.
\item
If no \verb@override@ modifier is given or implied, then if $M$ is
labelled \verb@qualified@, the qualified name is $M\qex x$. If $M$ is
not labelled \verb@qualified@, the qualified name is $\epsilon\qex x$.
\end{enumerate}
}
\example Consider the class definitions
\begin{verbatim}
class A with { def f: Int = 1 ; def g: Int = 2 ; def h: Int = 3 }
abstract class B with { def f: Int = 4 ; def g: Int }
abstract class C extends A with B with { def h: Int }
\end{verbatim}
Then class \verb@C@ has a directly bound abstract member \verb@h@. It
inherits member \verb@f@ from class \verb@B@ and member \verb@g@ from
class \verb@A@.
\ifqualified{
\example\label{ex:compound-b}
Consider the definitions:
\begin{verbatim}
qualified class Root extends Any with { def r1: Root, r2: Int }
qualified class A extends Root with { def r1: A, a: String }
qualified class B extends A with { def r1: B, b: Double }
\end{verbatim}
Then \verb@A with B@ has members
\verb@Root::r1@ of type \verb@B@, \verb@Root::r2@ of type \verb@Int@,
\verb@A::a:@ of type \verb@String@, and \verb@B::b@ of type \verb@Double@,
in addition to the members inherited from class \verb@Any@.
}
\subsection{Overriding}
\label{sec:overriding}
A template member $M$ that has the same \ifqualified{qualified} name as a
non-private member $M'$ of a base class (and that belongs to the same
namespace) is said to {\em override} that member. In this case the
binding of the overriding member $M$ must be more specific
(\sref{sec:subtyping}) than the binding of the overridden member $M'$.
Furthermore, the overridden definition may not be a class or module
definition or a type alias. Method definitions may only override
other method definitions (or the methods implicitly defined by a
variable definition). They may not override value or let definitions.
Finally, the following restrictions on modifiers apply to $M$ and
$M'$:
\begin{itemize}
\item
$M$ must not be labelled \verb@private@.
\item
If $M'$ is not abstract, then $M$ must be labelled \verb@override@.
\item
If $M'$ is labelled \verb@protected@, then $M$ must also be
labelled \verb@protected@.
\iffinaltype{
\item
$M'$ may be labelled \verb@final@ only if it is an abstract type
binding.
}
\end{itemize}
\example\label{ex:compound-a}
Consider the definitions:
\begin{verbatim}
abstract class Root with { type T extends Root }
abstract class A extends Root with { type T extends A }
abstract class B extends Root with { type T extends B }
\end{verbatim}
Then the compound type \verb@A with B@ is not well-formed because the
binding of \verb@T@ in \verb@A with B@ is
\verb@type T extends B@,
which fails to be more specific than the binding of same name in type
\verb@A@. The problem can be solved by adding a refinement
(\sref{sec:refinements}) which further constrains
\verb@T@. E.g., \verb@A with B with { type T extends A with B }@.
%\begin{verbatim}
%A with B with { type T extends A with B }
%\end{verbatim}
\subsection{Modifiers}
\label{sec:modifiers}
\syntax\begin{verbatim}
Modifier \=::= \= final
\> | \> private
\> | \> protected
\> | \> override [Qualid]
\> |\> abstract
\end{verbatim}
Member definitions may be preceded by modifiers which
affect the \ifqualified{qualified names, }accessibility and usage of the identifiers
bound by them. If several modifiers are given, their order does not
matter, but the same modifier may not occur repeatedly. Modifiers
preceding a repeated definition apply to all constituent definitions.
The rules governing the validity and meaning of a modifier are as
follows.
\begin{itemize}
\item
The \verb@abstract@ modifier is used in class definitions. It is
mandatory if the class has abstract members. Classes with
\verb@abstract@ members cannot be instantiated
(\sref{sec:inst-creation}) with a constructor invocation unless
followed by mixin constructors or statements which override all
abstract members of the class.
\item
The \verb@final@ modifier applies to class member definitions and to
class definitions. A \verb@final@ function, value, or variable may not
be overridden in subclasses. A
\verb@final@ class may
not be used as superclass or mixin class in a class definition or
instance creation expression.
Excepted from this rule are only
\begin{itemize}
\item classes whose definitions are nested within the definition
of the final class itself, and
\item classes whose definition occurs within the same statement
sequence as the definition of the final class.
\end{itemize}
\iffinaltype{
A non-abstract final class is also called a {\em
leaf class}. When used in a binding of an abstract type, \verb@final@
restricts the possible instances of the abstract type to leaf
classes (see also \sref{sec:typedcl}).
}
\verb@final@ is redundant for modules and non-abstract type bindings.
\item
The \verb@private@ modifier can be used with any definition in a
template. Private identifiers can be accessed only from within the template
that defines them. Furthermore, accesses are not permitted in
packagings (\sref{sec:topdefs}) other than the one containing the
definition. Private members are not inherited by subclasses and they
may not override definitions in superclasses.
\verb@private@ may not be combined in one modifier list with
\verb@protected@, \verb@abstract@, \verb@final@ or
\verb@override@.
\item
The \verb@protected@ modifier applies to class member definitions.
Protected members can be accessed from within the template of the defining
class as well as in all templates that have the defining class as a base class.
Furthermore, accesses from the template of the defining class are not
permitted in packagings other than the one
containing the definition. A protected identifier $x$ may be used as
a member name in a selection $r.x$ only if $r$ is one of the reserved
words \verb@this@ and
\verb@super@, or if $r$'s type conforms to a type-instance of a class
which contains the access.
\item
The \verb@override@ modifier applies to member definitions. If a
definition of a simple name $x$ is preceded by
\verb@override@, the definition is taken to override
(\sref{sec:overriding}) a member in the least proper supertype
(\sref{sec:templates}) which is identified by the simple name $x$.
The \verb@override@ modifier may be followed by a qualified name. If
a definition of a simple name $x$ is preceded by
\verb@override $Q$@, the definition is taken to override
a member in the base class referenced by the qualified name $Q$ which
is identified by the simple name $x$. In both cases, there must exist
such a member according to the rules of (\sref{sec:names}).
\verb@override@ may not be combined in one modifier list with
\verb@private@.
\ifqualified{
\item
The \verb@qualified@ modifier applies to class or module
definitions. When present, all non-overriding member definitions of
the class or module (named $M$, say) introduce names which are
qualified by $M$. When absent, non-overriding member definitions of
the class or module introduce names which are qualified by the empty
string $\epsilon$.
}
\end{itemize}
\comment{
\example A useful idiom to prevent clients of a class from
constructing new instances of that class is to declare the class
\verb@final@ and \verb@abstract@:
\begin{verbatim}
abstract final class C (x: Int) with {
def nextC = C(x + 1) with {}
}
val empty = new C(0) with {}
\end{verbatim}
For instance, in the code above clients can create instances of class
$C$ only by calling the \verb@nextC@ method of an existing \verb@C@
object; it is not possible for clients to create objects of class
\verb@C@ directly. Indeed the following two lines are both in error:
\begin{verbatim}
C(0) \=// ERROR: C is an interface, may not be instantiated.
C(0) with {} \>// ERROR: C is final, may not be subclassed.
\end{verbatim}
}
\comment{
\example The following example illustrates the difference between
virtual and non-virtual members with respect to overriding.
\begin{verbatim}
class C with {
virtual def f = "f in C"
def g = "g in C"
def both1 = this.f ++ ", " ++ this.g
def both2 = f ++ ", " ++ g
}
class D extends C with {
override def f = "f in D"
override def g = "redefined g in D"
new def g = "new g in D"
}
val d = D
println(d.f) \=// prints ``f in D''
println(d.g) \>// prints ``new g in D''
println(d.both1) \>// prints ``f in D, redefined g in D''
println(d.both2) \>// prints ``f in D, g in C''
val c: C = d
println(c.f) \=// prints ``f in D''
println(c.g) \>// prints ``redefined g in D''
println(c.both1) \>// prints ``f in D, redefined g in D''
println(c.both2) \>// prints ``f in D, g in C''
\end{verbatim}
}
\comment{
\section{The Self Type}
\label{sec:self-type}
\syntax\begin{verbatim}
SimpleType \=::= \= $\This$
\end{verbatim}
The self type \verb@this@ may be used in the statement part of a
template, where it refers to the type of the object being defined by
the template. It is the type of the self reference \verb@this@.
For every leaf class (\sref{sec:modifiers}) $C$, \verb@this@ is
treated as an alias for the class itself, as if it was declared such:
\begin{verbatim}
final class C ... with {
type this = C
...
}
\end{verbatim}
For non-leaf classes $C$, \verb@this@ is treated as an abstract type
bounded by the class itself, as if it was declared such:
\begin{verbatim}
abstract class C ... with {
type this extends C
...
}
\end{verbatim}
Analogously, for every compound type \verb@$T_1$ with ... with $T_n$@,
\verb@this@ is treated as an abstract type conforming to the whole compound
type, as if it was bound in the refinement
\begin{verbatim}
type this extends $T_1$ with ... with $T_n$ .
\end{verbatim}
Finally, for every declaration of a parameter or abstract type
\mbox{$a \extends T$}, \verb@this@ is treated as an an abstract type
conforming to $a$, as if the bound type $T$ was augmented to
\verb@$T$ with { abstract type this extends $a$ }@.
On the other hand, if the parameter or abstract type is declared
\verb@final@, as in $\FINAL;a \extends T$, then \verb@this@ is treated as an alias
for $a$, as if the bound type $T$ was augmented to
\verb@$T$ with { type this = $a$ }@.
\example
Consider the following classes for one- and two-dimensional
points with a \verb@distance@ method that computes the distance
between two points of the same type.
\begin{verbatim}
class Point1D(x: Float) with {
def xCoord = x
def distance (that: this) = abs(this.xCoord - that.xCoord)
def self: this = this
}
final class FinalPoint1D(x: Float) extends Point1D(x)
class Point2D(x: Float, y: Float) extends Point1D(x) with {
def yCoord = y
override def distance(that: this) =
sqrt (square(this.xCoord - that.xCoord) + square(this.yCoord - that.yCoord))
}
\end{verbatim}
Assume the following definitions:
\begin{verbatim}
val p1f: FinalPoint1D = FinalPoint1D(0.0)
val p1a: Point1D = p1f
val p1b: Point1D = Point2D(3.0, 4.0)
\end{verbatim}
Of the following expressions, three are well-formed, the other three
are ill-formed.
\begin{verbatim}
p1f distance p1f \=// OK, yields 0,0
p1f distance p1b \>// OK, yields 3.0
p1a distance p1a \>// OK, yields 0.0
p1a distance p1f \>// ERROR, required: p1a.this, found: FinalPoint1D
p1a distance p1b \>// ERROR, required: p1a.this, found: p1b.this
p1b distance p1a \>// ERROR, required: p1b.this, found: p1a.this
\end{verbatim}
The last of these expressions would cause an illegal access to a
non-existing class \verb@yCoord@ of an object of type \verb@Point1D@,
if it were permitted to execute in spite of being not well-typed.
}
\section{Class Definitions}
\label{sec:classes}
\syntax\begin{verbatim}
PureDef \=::= \= $\CLASS$ ClassDef {`,' ClassDef}
ClassDef \>::= \> Id ParamSig ClassTemplate
ClassTemplate \>::=\> extends Constr {with Constr} [with `{' {TemplateStat `;'} `}']
\> |\> with `{' {TemplateStat `;'} `}'
\end{verbatim}
The most general form of class definition is $\CLASS;c[tps](ps_1)
\ldots (ps_m);\EXTENDS;t$. Here,
\begin{itemize}
\item[]
$c$ is the name of the class to be defined.
\item[]
$tps$ is a non-empty list of type parameters of the class being
defined. The scope of a type parameter is the whole class definition,
including the type parameter section itself. It is illegal to define
two type parameters with the same name. The type parameter section
$[tps]$ may be omitted. A class with a type parameter section is
called {\em polymorphic}, otherwise it is called {\em monomorphic}.
\item[] $ps_1 \commadots ps_m$ are parameter clauses for the {\em primary
constructor} of the class. The scope of a formal parameter defined in
section $ps_i$ includes all parameter sections $ps_j$ for $j > i$ as
well as the statements $stats$. It is illegal to define two formal
parameters with the same name. The formal
parameter clauses are omitted for interface classes (\sref{sec:interfaces}).
\item[] $t$ is a
template (\sref{sec:templates}) of the form
$sc;\WITH;mc_1;\WITH;\ldots;\WITH;mc_n;\WITH;(stats)$
which defines the base classes, behavior and initial state of objects of
the class. The extends clause $\EXTENDS;sc$ can be omitted, in which case
\verb@extends scala.Object@ is assumed. The class body
$\WITH;(stats)$ may also be omitted, in which case the empty body
$\WITH;\{\}$ is assumed.
\end{itemize}
This definition is conceptually equivalent to
\begin{itemize}
\item[]
A definition of a new type $c[tps]$ which is a subtype of the types of
$sc, mc_1 \commadots mc_n$, which defines the
members of the template $t$ and which also carries the information
whether the class is \verb@final@, and whether it defines a case class
(\sref{sec:datadef}).
\item[]
A definition of a final constructor function with signature
\begin{verbatim}
def c[tps](ps$_1$)$\ldots$(ps$_n$):class c[tps] ,
\end{verbatim}
which when applied
initializes members of its result type by evaluating the template $t$.
\end{itemize}
Both the type and the constructor definition inherit any
\verb@private@ or \verb@protected@ modifiers present in the class
definition.
\section{Case Classes}
\label{sec:datadef}
\syntax\begin{verbatim}
PureDef \=::= \= $\CASE$ $\CLASS$ ClassDef {`,' ClassDef}
\end{verbatim}
If a class definition is prefixed with \verb@case@, the class is said
to be a {\em case class}. The primary constructor of a case class may
be used in a constructor pattern (\sref{sec:patterns}). Case classes
may not have abstract members, and none of the base classes of a case
class may be a case class. Furthermore, no type may have two different
case classes among its basetypes.
A case class definition of $c[tps](ps_1)\ldots(ps_n)$ with type
parameters $tps$ and value parameters $(ps_1)\ldots(ps_n)$ implicitly
generates the function definition
$$\DEF;c[tps](ps_1)\ldots(ps_n): c[tps] = \NEW;c[tps](ps_1)\ldots(ps_n)
$$
following the class definition itself. Also implicity defined are
accessor member definitions in the class that return its value
parameters. Every binding \verb@x: T@ in the parameter section leads
to a value definition of \verb@x@ that defines \verb@x@
to be an alias of the parameter. Every parameterless function binding
\verb@def x: T@ leads to a parameterless function definition of
\verb@x@ which returns the result of invoking the parameter function.
The case class may not contain a directly bound member with the same
simple name as one of its value parameters.
Every case class implicitly overrides some method definitions of class
\verb@Object@ (\sref{sec:cls-object}). In particular:
\begin{itemize}
\item[] Method \verb@==@ is structural equality, where two
instances are equal if they belong to the same class and
have equal (wrt \verb@==@) primary constructor arguments.
\item[] Method \verb@hashCode@ computes a hash-code
depending on the data structure in a way which maps equal (wrt
\verb@==@) values to equal hash-codes.
\item[] Method \verb@toString@ returns a string representation which
contains the name of the class and its primary constructor arguments.
\end{itemize}
\example Here is the definition of abstract syntax for lambda
calculus:
\begin{verbatim}
class Expr
case class
Var (x: String) extends Expr,
Apply (f: Expr, e: Expr) extends Expr,
Lambda (x: String, e: Expr) extends Expr;
\end{verbatim}
This defines a class \verb@Expr@ with case classes
\verb@Var@, \verb@Apply@ and \verb@Lambda@. A call-by-value evaluator for lambda
expressions could then be written as follows.
\begin{verbatim}
type Env = (String)Value;
case class Value(e: Expr, env: Env);
def eval(e: Expr, env: Env): Value = e match {
case Var (x) =>
env(x)
case Apply(f, g) => {
val Value(Lambda (x, e1), env1) = eval(f, env);
val v = eval(g, env);
eval (e1, (y => if (y == x) v else env1(y)))
}
case Lambda(_, _) =>
Value(e, env)
}
\end{verbatim}
It is possible to define further case classes that extend type
\verb@Expr@ in other parts of the program, for instance
\begin{verbatim}
case class Number(x: Int) extends Expr;
\end{verbatim}
\section{Interface Classes}
\label{sec:interfaces}
\syntax\begin{verbatim}
ClassDef \=::= \= Id [TypeParamClause] ClassTemplate
\end{verbatim}
A class definition whose constructor does not have value parameters
defines an {\em interface class}. The template of an interface classes
must satisfy the following two restrictions.
\begin{enumerate}
\item All base classes of the template are interface classes.
\item All non-empty statements are either declarations or method definitions.
\end{enumerate}
These restrictions ensure that the evaluation of the mixin constructor
of an interface type has no effect. Therefore, interface classes can be
used in two constellations where other classes cannot. Namely:
\begin{itemize}
\item The same interface class may appear several times in the base class
sequence of a template.
\item Packagings may add interface classes as new base classes to an
existing class or modulee.
\end{itemize}
\example\label{ex:comparable}
The following interface class defines the property of being
comparable to objects of some type. It contains an abstract method
\verb@<@ and default implementations of the other comparison operators
\verb@<=@, \verb@>@, and \verb@>=@.
\begin{verbatim}
abstract class Comparable[a] with {
def <(that: a)
def <= (that: a) = this < that || this == that
def > (that: a) = that < this
def >= (that: a) = that <= this
}
\end{verbatim}
\section{Modules}
\label{sec:modules}
\syntax\begin{verbatim}
ModuleDef \=::= \= Id [`:' Type] ClassTemplate
\end{verbatim}
A module definition is of the form $\MODULE;m;\EXTENDS;t$ where $t$ is
a template (\sref{sec:templates})
$sc;\WITH;mc_1;\WITH;\ldots;\WITH;mc_n;\WITH;(stats)$. The extends
clause $\EXTENDS;sc$ can be omitted, in which case
\verb@extends scala.Object@ is assumed.
The module body $\WITH;(stats)$ may also be omitted, in which case the
empty body $\WITH;\{\}$ is assumed.
The module definition defines a single object conforming to the
template $t$. It is almost equivalent to a triple of a class
definition,
a type definition and a value definition that creates an object of the class:
\begin{verbatim}
final class m$\Dollar$class extends t;
final type m = m$\Dollar$class;
final val m = new m$\Dollar$class;
\end{verbatim}
(The \verb@final@ modifiers are omitted if the definition occurs as
part of a block). The class name \verb@m$\Dollar$class@ is not
accessible for user programs.
However, unlike value definitions, modules are instantiated lazily.
The \verb@new m$\Dollar$class@ constructor is evaluated not at the
point of the let definition, but is instead evaluated the first time
$m$ is dereferenced during execution of the program (which might be
never at all). An attempt to dereference $m$ again in the course of
evaluation of the constructor leads to a run-time error. Other
threads trying to dereference $m$ while the constructor is being
evaluated block until evaluation is complete.
A module definition may also mention a type $T$ which represents the
externally visible interface of a module. The definition $\MODULE;m:
T;\EXTENDS;t$ then corresponds to:
\begin{verbatim}
final class m$\Dollar$class extends t;
final type m = m$\Dollar$class;
final val m: T = new m$\Dollar$class;
\end{verbatim}
\example
Classes in Scala do not have static members; however, an equivalent
effect can be achieved by defining a module:
E.g.
\begin{verbatim}
module Points with {
abstract class Point() with {
val x: Double;
val y: Double;
def isOrigin = x == 0,0 && y == 0.0;
}
val origin = new Point() with { val x = 0.0, y = 0.0 }
}
type Point = Points.Point
def Point(): class Point = Points.Point()
val Point = Points
\end{verbatim}
This defines a type \verb@Point@, a constructor \verb@Point@, and a
value \verb@Point@ which contains \verb@origin@ as a member. Hence,
Note that the double definition of \verb@Point@ in the term namespace
is a legal overloaded definition (\sref{sec:overloaded-defs}), since
\verb@Point@ exists both as a unary constructor function and as a
value. Therefore the name \verb@Point@ used in isolation identifies
the \verb@Point@ module, the expression \verb@Point.origin@ selects
its \verb@origin@ field, but \verb@new Point()@ is an invocation of
the \verb@Point@ constructor.
\comment{
\example Here's an outline of a module definition for a file system.
\begin{verbatim}
module FileSystem with {
private type FileDirectory;
private val dir: FileDirectory
interface File with {
def read(xs: Array[Byte])
def close: Unit
}
private class FileHandle extends File with { ... }
def open(name: String): File = ...
}
\end{verbatim}
}
\chapter{Expressions}
\label{sec:exprs}
\syntax\begin{verbatim}
Expr \=::=\= if `(' Expr `)' Expr [[`;'] else Expr]
\> |\> for `(' Enumerator `)' [do | yield] Expr
\> |\> Designator `=' Expr
\> |\> SimpleExpr ArgumentExpr `=' Expr
\> |\> Expr1
Expr1 \>::=\> Expr2 [`:' Type]
Expr2 \>::=\> Expr3 [Id]
Expr3 \>::=\> Expr4
\> |\> Expr3 Id Expr3
Expr4 \>::=\> SimpleExpr
\> |\> op Expr4
\> |\> new Template
SimpleExpr \>::=\> Designator
\> |\> literal
\> |\> null
\> |\> this
\> |\> super `.' Id
\> |\> outer `.' Id
\> |\> outer `.' this
\> |\> `[' [Exprs] `]'
\> |\> ArgumentExpr
\> |\> BlockExpr
\> |\> SimpleExpr ArgumentExpr
\> |\> SimpleExpr BlockExpr
\> |\> SimpleExpr TypeArgs
Exprs \>::= \> Expr {`,' Expr}
\end{verbatim}
Expressions are composed of operators and operands. Expression forms are
discussed subsequently in decreasing order of precedence.
\section{Designators}
\label{sec:designators}
\syntax\begin{verbatim}
Designator \=::= \= Id
\> | \> SimpleExpr `.' Id
\end{verbatim}
A designator refers to a named term. It can be a {\em simple name} or
a {\em selection}.
A {\em potential term binder} of an occurrence of simple name $x$ is:
\begin{enumerate}
\item A parameter named $x$ which has the identifer use in scope,
\item a term definition or declaration of $x$ in some enclosing block,
\item a term member of an enclosing module or class which is identified
by the simple name $x$ (\sref{sec:names}),
\item an import clause in an enclosing block or template that introduces
a term alias for $x$ and that textually precedes the identifier use.
\end{enumerate}
A simple name $x$ is {\em bound} by a potential term binder of $x$
which shadows (\sref{sec:names}) all other potential term binders of
$x$. It is an error if no such binder exists.
If $x$ is bound by an import clause whose right hand side is the
stable identifier (\sref{sec:stableids}) $r$, then the simple name $x$
refers to the same entity as $r.x$. If $x$ is bound by a declaration
or definition of a class member, then $x$ refers to the same entity as
\verb@this.x@. If $x$ is bound by some other term binder, then $x$
refers to the value, function, or class introduced by that binder.
Evaluation of $x$ is immediate.
\comment{
A simple name $x$ refers to one of the following:
\begin{itemize}
\item A parameter named $x$ which has the identifer use in scope.
\item A definition or declaration of $x$ in some enclosing block.
\item A term member of some enclosing module or class $M$ identified
by the simple name $x$ (\sref{sec:names}).
\end{itemize}
In each case, it is required that there is no other scope
which also defines an entity with simple name $x$
and which is nested between
the reference to $x$ and the scope defining $x$.
The type of $x$ is the declared type of the referenced
entity. Evaluation of $x$ is immediate.
}
If $r$ is a stable identifier of type $T$, the
selection $r.x$ refers to the term member of $r$ that is identified in
$T$ by the simple name $x$. For other expressions $e$, $e.x$ is typed
as if it was $(\VAL;x=e\semi x.a)$ for some fresh name $x$.
The selection $e.x$ is evaluated by first evaluating the qualifier
expression $e$. Then, if the value of $e$ is an as yet completely
unevaluated \verb@let@-bound object, the value's definition is
evaluated (\sref{sec:letdef}). The selection's result is the value to
which the selector identifier is bound in the selected object
designated by $e$.
\section{Stable Identifiers}
\label{sec:stableids}
\syntax\begin{verbatim}
StableId \=::= \= QualId
\end{verbatim}
A stable identifier is an expression that is known to evaluate to the
same object each time it is evaluated. Formally, a qualified
identifier $x_1.;\ldots;.x_n$ is a stable identifier if for each $i =
1 \commadots n$ the prefix $x_1.; \ldots ;.x_i$ identifies a value
(i.e.\ it does not have an overloaded type or method type).
\section{Literals}
\syntax\begin{verbatim}
SimpleExpr \=::= \= literal
\end{verbatim}
Typing and evaluation of literals are analogous to Java.
\section{The $\NULL$ Reference}
\syntax\begin{verbatim}
SimpleExpr \=::= \= null
\end{verbatim}
The reserved word \verb@null@ refers to a polymorphic parameterless
function of type \verb@[a extends scala.AnyRef]a@. Its result is the
special ``null'' object, which implements methods in class
\verb@scala.AnyRef@ as follows:
\begin{itemize}
\item[]
\verb@eq(x)@, \verb@==(x)@, \verb@equals(x)@ return \verb@True@ iff their
argument \verb@x@ is also the ``null'' object.
\item[]
\verb@is[T]@ always returns \verb@False@.
\item[]
\verb@as[T]@ always returns the ``null'' object itself.
\item[]
\verb@toString@ returns the string ``\verb@null@''.
\end{itemize}
A reference to any member of the ``null'' object which is not defined in class
\verb@Object@ causes a \verb@NullPointerException@ to be thrown.
\section{This and Super}
\label{sec:this-super}
\syntax\begin{verbatim}
SimpleExpr \=::= \= $\This$
\> | \> super `.' Id
\end{verbatim}
\ifqualified{
Super \>::= \> $\SUPER$
\> | \> `(' $\SUPER$ `:' Type `)'
}
The reserved name \verb@this@ may be used in the statement part of a
template, where it stands for the object of which the currently
evaluated expression forms part. The type of \verb@this@ is the self
type which is also written \verb@this@ (\sref{sec:self-type}).
A reference \verb@super.$m$@ in a template refers to one of the
following.
\begin{itemize}
\item
A binding of $m$ in a mixin base class (\sref{sec:base-classes}) $bc$
of the template, provided no mixin base class following $bc$ in the template's base class sequence also defines $m$, or
\item
The definition of $m$ in the actual superclass
(\sref{sec:base-classes}) of the template, provided no
mixin base class of the template also
defines $m$.
\end{itemize}
\comment{
\verb@super@ may be declared to be of a specific type, as in
\verb@(super:T).x@. The least proper supertype of the class or module containing
the reference must then conform to $T$. The meaning is the same as
$\SUPER.x$ except that the qualifier's static type is taken to be
$T$. The static type affects the definition of qualified expansion
(\sref{sec:names}) and with it the member resolution process
(\ref{ex:qualified-super} provides an illustration).
}
\example\label{ex:super}
Consider the following class definitions
\begin{verbatim}
class Root { val x = "Root" }
class A extends Root { override val x = "A" ; val superA = super.x }
class B extends Root { override val x = "B" ; val superB = super.x }
class C extends A with B with { override val x = "C" ; val superC = super.x }
class D extends A with { val superD = super.x }
class E extends C with D with { val superE = super.x }
\end{verbatim}
Then we have:
\begin{verbatim}
new A.superA = "Root", new B.superB = "Root"
new C.superA = "Root", new C.superB = "A", new C.superC = "A"
new D.superA = "Root", new D.superD = "A"
new E.superA = "Root", new E.superB = "A", new E.superC = "A",
new E.superD = "C", new E.superE = "C"
\end{verbatim}
Note that the \verb@superB@ function returns different results
depending on whether \verb@B@ is used as defining class or as a mixin class.
\ifqualified{
\example\label{ex:qualified-super}
Consider the class definitions
\begin{verbatim}
qualified class C with { def f: String = "C" }
qualified class D with { def f: String = "D" }
\end{verbatim}
Here is a subclass of \verb@C@ and \verb@D@ which overrides both
versions of \verb@f@ and invokes both previous definitions via \verb@super@:
\begin{verbatim}
class B extends C with D with {
override C def f = (super:C).f ++ "B"
override D def f = (super:D).f ++ "B"
}
\end{verbatim}
}
\section{Function Applications}
\label{sec:apply}
\syntax\begin{verbatim}
SimpleExpr \=::= \= SimpleExpr ArgumentExpr
\end{verbatim}
An application $f(e_1 \commadots e_n)$ applies the function $f$ to the
argument expressions $e_1 \commadots e_n$. If $f$ has some method type
$(x_1: T_1 \commadots x_n: T_n)U$, the type of each argument
expression $e_i$ must conform to the corresponding parameter type
$T_i$ of. if $f$ has some value type, the application is taken to be
equivalent to \verb@$f$.apply($e_1 \commadots e_n$)@, i.e.\ the
application of an \verb@apply@ function defined by $f$.
%Class constructor functions
%(\sref{sec:classes}) can only be applied in constructor invocations
%(\sref{sec:constr-invoke}), never in expressions.
Evaluation of $f(e_1 \commadots e_n)$ usually entails evaluation of
$f$ and $e_1 \commadots e_n$ in that order. Each argument expression
is converted to the type of its corresponding formal parameter. After
that, the application is rewritten to the function's right hand side,
with actual arguments substituted for formal parameters. The result
of evaluating the rewritten right-hand side is finally converted to
the function's declared result type, if one is given.
The case where a formal parameter has a parameterless method type
$[\,]T$ is treated specially. In this case, the corresponding
actual argument expression is not evaluated before the
application. Instead, every use of the formal parameter on the
right-hand side of the rewrite rule entails a re-evaluation of the
actual argument expression. In other words, the evaluation order for
$\DEF$-parameters is {\em call-by-name} whereas the evaluation order
for normal parameters is {\em call-by-value}.
\example The function \verb@while@ is defined as:
\begin{verbatim}
def while(def c: Boolean)(def s: Unit): Unit =
if (c) { s ; while(c)(s) } else {}
\end{verbatim}
Therefore the call
\begin{verbatim}
while (x != 0) { y = y + 1/x ; x = x - 1 }
\end{verbatim}
will never produce a division-by-zero error at run-time, since the
expression \verb@(y = 1/x)@ will be evaluated in the body of
\verb@while@ only if the condition parameter is false.
\subsection{References to Overloaded Bindings}
\label{sec:overloaded-refs}
If a name $f$ referenced in an identifier or selection is overloaded
(\sref{sec:overloaded-types}), the context of the reference has to
identify a unique alternative of the overloaded binding. This is done
as follows. Let $\AA$ be the set of all type alternatives of $f$. Let
$n \geq 0$ be maximal such that there is a method type of arity $\geq
n$ in $\AA$, and $f$ is a applied to at least $n$ argument lists,
e.g.\ it is used as in $f;(args_1) \ldots (args_n)$. Let $T_p$ be the
expected type of $f;(args_1) \ldots (args_n)$ (which may be partially
undefined). For $i \in 1 \commadots n$ let ${ts_i}$ be the list of
types of ${args_i}$ which are obtained by typing each argument in
${args_i}$ with a completely undefined prototype.
Among all {\em applicable} alternative types in $\AA$ the compiler
selects one which {\em specializes} all others.
A method type alternative of arity $m \geq n$ is {\em applicable} if a
non-overloaded function of that type could legally be applied to
stable identifier lists ${xs_1} \commadots xs_n$ of the argument types
${ts_1}
\commadots {ts_n}$, and the application's result type would match
$T_p$.
\comment{
Method types which do not have a class constructor
\verb@class T@ as their result type always specialize
method types which do. For other pairs of method types, the
following applies: }
A parameterized method type $(ps_1)
\ldots (ps_m) T$ where $m > 0$ {\em specializes} some other
type $U$ if $U$ is applicable to arguments $(ps_1)$ \ldots $(ps_m)$.
A polymorphic method type $[a_1
\extends S_1
\commadots a_k \extends S_k] (ps_1) \ldots (ps_m) T$ specializes
a type $U$ if $(ps_1) \ldots (ps_m) T$ is more
specific than $U$ under the assumption that for $i = 1 \commadots k$
each $a_i$ is an abstract type name bounded by $S_i$.
If there is no applicable signature which specializes all other
applicable signatures, or if there is more than one, the application
is rejected for being ambiguous.
\example Consider the following definitions:
\begin{verbatim}
class S extends B with {}
def f(x: S)(y: B) = ...
def f(x: B)(y: B) = ...
val s: S, b: B
\end{verbatim}
Then the application \verb@f(s)(s)@ refers to the first
definition of \verb@f@ whereas the application \verb@f(b)(b)@
refers to the second. Assume now we add a third overloaded definition
\begin{verbatim}
def f(x: B)(y: S) = ...
\end{verbatim}
Then the application \verb@f(s)(s)@ is rejected for being ambiguous, since
no most specific applicable signature exists.
\comment{
\example Consider the following definitions
\begin{verbatim}
class Point() with { ... }
module Point with { val origin = 0.0 }
\end{verbatim}
Then the term namespace contains the overloaded binding
\verb@Point: ()constr Point $\overload$ Point$\Dollar$class@
where $C_{Point}$ stands for the (invisible) type of the module
\verb@Point@. Therefore the name \verb@Point@ identifies the
\verb@Point@ module, the expression \verb@Point.origin@ selects its \verb@origin@
field, but \verb@Point()@ is an invocation of the \verb@Point@
constructor.
}
\section{Type Applications}
\label{sec:type-app}
\syntax\begin{verbatim}
SimpleExpr \=::= \= SimpleExpr `[' Types `]'
\end{verbatim}
A type application $f[T_1\commadots T_n]$ instantiates a polymorphic
value $f$ of type $[a_1 \extends B_1 \commadots a_n \extends B_n] U$ with
argument types $T_1 \commadots T_n$. Every argument type $T_i$ must
conform to the corresponding bound type $B_i$. That is, for each $i = 1
\commadots n$, we must have $T_i \conforms B_i\sigma$, where $\sigma$ is
the substitution $[a_1 := T_1, ..., a_n := T_n]$. The type of the
application is $U\sigma$. If the function part $f$ has an overloaded
type $T_1 \overload \ldots \overload T_n$ then excatly one alternative
$T_i$ must have an $n$-ary type parameter list, and this alternative
will be instantiated.
The function part $f$ may also have some value type. In this case the
type application is taken to be equivalent to
\verb@$f$.apply[$T_1\commadots T_n$]@,
i.e.\ the application of an \verb@apply@ function defined by $f$.
Type applications can be omitted if local type inference
(\sref{sec:local-type-inf}) can infer best type parameters for a
polymorphic functions from the types of the actual function arguments
and the expected result type.
\section{Instance Creation Expressions}
\label{sec:inst-creation}
\syntax\begin{verbatim}
Expr4 \=::= \= new Template
\end{verbatim}
A simple instance creation expression is $\NEW;c$ where $c$ is a
constructor invocation (\sref{sec:constr-invoke}). If $c$ has type
\verb@class T@, then \verb@new c@ has type \verb@T@.
This type must conform to
type \verb@scala.AnyRef@.
The expression
is evaluated by creating a fresh object of type \verb@T@, which is is
initialized by evaluating \verb@c@.
A general instance creation expression is
$$\NEW;sc;\WITH;mc_1;\WITH;\ldots;\WITH;mc_n;\WITH;(stats)$$ where $n \geq
0$, $sc$ as well as $mc_1 \commadots mc_n$ are constructor invocations
(of types $\CLASS;S, \CLASS;T_1 \commadots \CLASS;T_n$, say) and
$stats$ is a statement sequence containing initializer statements
and member definitions (\sref{sec:members}). The type of such an
instance creation expression is then the compound type
$S;\WITH;T_1;\WITH;\ldots;\WITH;T_n;\WITH;R$, where $R$ is a
refinement (\sref{sec:refinements}) which declares exactly those
members of $stats$ that override a member of $S$ or $T_1 \commadots
T_n$. This type must conform to
type \verb@scala.AnyRef@.
For this type to be well-formed, $R$ may not reference types
defined in $stats$ which do not themselves form part of $R$.
The instance creation expression is evaluated by creating a fresh
object, which is initialized by evaluating the expression template.
\example Consider the class
\begin{verbatim}
abstract class C with {
type T
val x: T
def f(x: T): Object
}
\end{verbatim}
and the instance creation expression
\begin{verbatim}
C with {
type T = Int
val x: T = 1
def f(x: T): T = y
val y: T = 2
}
\end{verbatim}
Then the created object's type is:
\begin{verbatim}
C with {
type T = Int
val x: T
def f(x: T): T
}
\end{verbatim}
The value \verb@y@ is missing from the type, since \verb@y@ does not
override a member of \verb@C@.
\section{Prefix, Infix, and Postfix Operations}
\label{sec:infix-operations}
\syntax\begin{verbatim}
Expr2 \=::= \= Expr3 [id]
Expr3 \>::= \> Expr4
\> | \> Expr3 Id Expr3
Expr4 \>::= \> SimpleExpr
\> |\> (`+' | `-' | `!') Expr4
\end{verbatim}
Expressions can be constructed from operands and operators. A prefix
operation $op;e$ consists of a prefix operator $op$, which must be one
of \verb@+@, \verb@-@, \verb@!@, and a simple expression $e$. The
expression is equivalent to the postfix method application $e.op$.
Prefix operators are different from normal function applications in
that their operand expression need not be atomic. For instance, the
input sequence \verb@-sin(x)@ is read as \verb@-(sin(x))@, whereas the
function application \verb@negate sin(x)@ would be parsed as the
application of the infix operator \verb@sin@ to the operands
\verb@negate@ and \verb@(x)@.
An infix or postfix operator can be an arbitrary identifier. Binary
operators have precedence and associativity defined as follows:
The {\em precedence} of an operator is determined by the operator's first
character. Characters are listed below in increasing order of
precedence, with characters on the same line having the same precedence.
\begin{verbatim}
(all letters)
|
^
&
< >
= !
:
+ -
* / %
(all other special characters)
\end{verbatim}
That is, operators starting with a letter have lowest precedence,
followed by operators starting with `\verb@|@', etc.
The {\em associativity} of an operator
is also determined by the operator's first character.
Operators starting with a colon
`\verb@:@' are right-associative. All other operators are left-associative.
Precedence and associativity of operators determine the grouping of
parts of an expression as follows.
\begin{itemize}
\item If there are several infix operations in an
expression, then operators with higher precedence bind more closely
than operators with lower precedence.
\item If there are consecutive infix
operations $e_0;op_1;e_1;op_2\ldots;op_n;e_n$ with operators $op_1
\commadots op_n$ of the same precedence, then all these operators must
have the same associativity. If all operators are left-associative,
the sequence is interpreted as $(\ldots(e_0;op_1;e_1);op_2;\ldots);
op_n;e_n$. Otherwise, if all operators are right-associative, the
sequence is interpreted as
$e_0;op_1;(e_1;op_2;(\ldots;op_n;e_n)\ldots)$.
\item
Postfix operators always have lower precedence than infix
operators. E.g.\ $e_1;op_1;e_2;op_2$ is always equivalent to
$(e_1;op_1;e_2);op_2$.
\end{itemize}
A postfix operation $e;op$ is interpreted as $e.op$. A
left-associative binary operation $e_1;op;e_2$ is interpreted as
$e_1.op(e_2)$. If $op$ is right-associative, the same operation is
interpreted as $(\VAL;x=e_1
\semi e_2.op(x))$, where $x$ is a fresh name.
\section{Typed Expressions}
\syntax\begin{verbatim}
Expr1 \=::= \= Expr2 [`:' Type]
\end{verbatim}
The typed expression $e: T$ has type $T$. The type of expression $e$
is required to conform to $T$. The result of the expression is the
value of $e$ converted to type $T$.
\example Here are examples of well-typed and illegal typed expressions.
\begin{verbatim}
1: Int \=// legal, of type Int
1: Long \>// legal, of type Long
// 1: String \>// illegal
\end{verbatim}
\section{Assignments}
\syntax\begin{verbatim}
Expr \=::= \= Designator `=' Expr
\> | \> SimpleExpr ArgumentExpr `=' Expr
\end{verbatim}
An assignment to a simple variable $x = e$ is interpreted as the invocation
\verb@$x$_=($e$)@ of the setter function for variable
$x$ (\sref{sec:vardef}).
Analogously, an assignment $f.a = e$ to a field $a$ is interpreted
as the invocation \verb@$f.a$_=($e$)@.
An assignment $f(is) = e$ with a function application to the
left of the ``$=$' operator is interpreted as \verb@$f$.update($is, e$)@, i.e.\
the invocation of an \verb@update@ function defined by $f$.
\section{Conditional Expressions}
\syntax\begin{verbatim}
Expr \=::= \= $\IF$ `(' Expr `)' Expr [$\ELSE$ Expr]
\end{verbatim}
The conditional expression \verb@if ($e_1$) $e_2$ else $e_3$@ is treated as
a shorthand for the expression
\begin{verbatim}
$e_1$.ifThenElse($e_2$)($e_3$) .
\end{verbatim}
The conditional expression \verb@if ($e_1$) $e_2$@ without an
else-part is treated as a shorthand for the expression
\begin{verbatim}
$e_1$.ifThen($e_2$) .
\end{verbatim}
The predefined type \verb@Boolean@ (\sref{sec:cls-Boolean})
contains implementations of
methods \verb@ifThen@ and \verb@ifThenElse@.
\section{Comprehensions}
\todo{change syntax; treat refulatble patterns as filters}
\syntax\begin{verbatim}
Expr \=::= \= for `(' Enumerator `)' [do | yield] Expr
Enumerator \>::=\> Generator {`;' Enumerator1}
Enumerator1 \>::=\> Generator
\> |\> Expr
\> |\>
Generator \>::=\> val Pattern `<-' Expr
\end{verbatim}
A comprehension \verb@for (g) e@ evaluates expression $e$ for each
binding generated by the enumerator $g$. An enumerator is a generator,
possibly followed by further generators or filters. A generator
\verb@val p <- e@ produces bindings from an expression $e$ which is
matched in some way against pattern $p$. Filters are expressions which
restrict enumerated bindings. The precise meaning of generators and
filters is defined by translation to invocations of four methods:
\verb@map@, \verb@filter@, \verb@flatMap@, and \verb@foreach@. These
methods can be implemented in different ways for different carrier
types. As an example, an implementation of these methods for lists is
given in (\sref{cls-list}).
The translation scheme is by repeated applications of the following
rules, until the comprehension has been eliminated.
\ifnewfor{
First, a definition: A pattern $P$ is a {\em binding} if $P$ is a
variable pattern or a tuple pattern consisting only of pattern
variables. In the following, we let $B$ range over bindings, $P$ over
patterns other than bindings, $E, F$ over expressions, and $G$ over
enumerators.
%\begin{itemize}
%\item
If
$x_1 \commadots x_n$ are the free variables of $p$, then
the generator \verb@p <- e@ is translated to:
\begin{verbatim}
$(x_1 \commadots x_n)$ <- e.filter(case p => True case _ => False).map(case p => $(x_1 \commadots x_n)$)
\end{verbatim}
%\item
A generator \verb@P <- E@ followed by a filter \verb@F@ is translated to
a single generator \verb@P <- E.filter(x_1 \commadots x_n => F)@.
%\item
The comprehension \verb@for (B <- E) E'@ is translated to
\verb@E.map(B => E')@.
%\item
The comprehension \verb@for (B <- E, G) E'@ is translated to
\begin{verbatim}
(val x$\Dollar$ = E ; x$\Dollar$.combine(for (B <- E) for (G) E'))
\end{verbatim}
%\end{itemize}
}
\begin{itemize}
\item
A for-comprehension
\verb@for (val p <- e) yield e'@
is translated to
\verb@e.map(x$_1$, ..., x$_n$ => e')@.
where x$_1$, ..., x$_n$ are the free variables of $p$.
A for-comprehension
\verb@for (val p <- e) do e'@
is translated to
\verb@e.foreach(x$_1$, ..., x$_n$ => e')@.
\item
A for-comprehension
\verb@for (val p <- e; f; s) yield e'@
where \verb@f@ is a filter expression and \verb@s@ is a (possibly empty)
sequence of generators or filters
is translated to
\verb@for (val p <- e.filter(x$_1$, ..., x$_n$ => f); s) yield e'@
where x$_1$, ..., x$_n$ are the free variables of $p$. The translation
of \verb@for@-\verb@do@ comprehensions is analogous for this case.
\item
A for-comprehension
\begin{verbatim}
for (val p <- e; val p' <- e'; s) yield e''
\end{verbatim}
where \verb@s@ is a (possibly empty)
sequence of generators or filters
is translated to
\begin{verbatim}
e.flatmap(x$_1$, ..., x$_n$ => for (val p' <- e'; s) yield e'') .
\end{verbatim}
A for-comprehension
\begin{verbatim}
for (val p <- e; val p' <- e'; s) do e'' .
\end{verbatim}
is translated to
\begin{verbatim}
e.foreach(x$_1$, ..., x$_n$ => for (val p' <- e'; s) do e'')
\end{verbatim}
\end{itemize}
\example
the following code produces all pairs of numbers
between \verb@1@ and \verb@n@ whose sums are prime.
\begin{verbatim}
for \= { \= val i <- range(1, n);
\> \> val j <- range(1, i-1);
\> \> isPrime(i+j)
} yield (i, j)
\end{verbatim}
The for-comprehension is translated to:
\begin{verbatim}
range(1, n)
.flatMap(
i => range(1, i-1)
.filter(j => isPrime(i+j))
.map(j => (i, j)))
\end{verbatim}
\comment{
\example
\begin{verbatim}
package class List[a] with {
def map[b](f: (a)b): List[b] = match {
case <> => <>
case x :: xs => f(x) :: xs.map(f)
}
def filter(p: (a)Boolean) = match {
case <> => <>
case x :: xs => if p(x) then x :: xs.filter(p) else xs.filter(p)
}
def flatMap[b](f: (a)List[b]): List[b] =
if (isEmpty) Nil
else f(head) ::: tail.flatMap(f);
}
def foreach(f: (a)Unit): Unit =
if (isEmpty) ()
else (f(head); tail.foreach(f));
}
\end{verbatim}
\example
\begin{verbatim}
abstract class Graph[Node] {
type Edge = (Node, Node)
val nodes: List[Node]
val edges: List[Edge]
def succs(n: Node) = for ((p, s) <- g.edges, p == n) s
def preds(n: Node) = for ((p, s) <- g.edges, s == n) p
}
def topsort[Node](g: Graph[Node]): List[Node] = {
val sources = for (n <- g.nodes, g.preds(n) == <>) n
if (g.nodes.isEmpty) <>
else if (sources.isEmpty) new Error(``topsort of cyclic graph'') throw
else sources :+: topsort(new Graph[Node] with {
val nodes = g.nodes diff sources
val edges = for ((p, s) <- g.edges, !(sources contains p)) (p, s)
})
}
\end{verbatim}
}
\section{Tuples}
\syntax\begin{verbatim}
ArgumentExpr \=::= \= `(' [Expr `,' Exprs] `)'
\end{verbatim}
An expression $(e_1 \commadots e_n)$ where $n \geq 2$
is a shorthand for the constructor invocation
\verb@Tuple$\,n$($e_1 \commadots e_n)$@.
The empty tuple $()$ is a shorthand for the constructor invocation
\verb@Unit@.
There are no tuples of length 1, since $(e)$ is seen as an expression
in parentheses, not as a tuple.
See \sref{sec:cls-tuple}
for a definition of the \verb@Unit@ and \verb@Tuple$\,n$@ classes.
\comment{
An $n$-tuple type implicitly defines parameterless functions $\_1 \commadots
\_n$ that select the tuple's components.
\example Here is an example of how tuples are formed and accessed.
\begin{verbatim}
def helloWorld = {
val pair = ("hello", "world")
println (pair._1 + " " + pair._2)
}
\end{verbatim}
}
\section{List Expressions}
\label{sec:list-exprs}
\syntax\begin{verbatim}
ListExpr \=::= \= `[' [Exprs] `]'
\end{verbatim}
The list expression $[ e_1 \commadots e_n ]$ with $n \geq 0$ is a
shorthand for
\begin{verbatim}
cons(e$_1$, ..., cons(e$_n$, nil) ... ) .
\end{verbatim}
\verb@cons@ and \verb@nil@ are defined in module \verb@Predef@ as:
\begin{verbatim}
def cons[a](x: a, xs: List[a]): List[a] = new ::_class(x)(xs);
def nil[a]: List[a] = Nil[a];
\end{verbatim}
Like all other members of module \verb@Predef@, these definitions
are implicitly imported in all programs.
\example Here is how the basic type of lists can be defined, so that
list expressions ``do the right thing''.
\begin{verbatim}
final class List[a] with {
def ::(x: a) = new ::_class(x)(this);
}
case class Nil[a] extends List[a];
case class ::_class[a](head: a)(tail: List[a]) extends List[a];
\end{verbatim}
Class \verb@List@ is declared \verb@final@ which has as
consequence that no further case classes for \verb@List@ can be
defined except for the two case classes \verb@Nil@ and \verb@::_class@ that are
defined together with the class.
Note the definition of ``\verb@::@'' as a method in class \verb@List@
and of \verb@::_class@ as a case class outside. This lets clients of
\verb@List@ compose and decompose lists with the infix operator
``\verb@::@''. E.g.\ \verb@x :: y :: zs@ is a valid list expression
because ``\verb@::@'' is a unary method of \verb@List@ and it is a
valid infix operation pattern (\sref{sec:patterns}) because
``\verb@::_class@'' is a case class with two parameter sections.
Note that list expressions are not argument expressions, hence it is
necessary to enclose them in parentheses when used as parameters.
This is necessary to distinguish list expression parameters from type arguments.
\example\
\begin{verbatim}
f([x, y]) \=// application of function `f' to the list `[x,y]'
g[x, y] \>// instantiation of polymorphic `g' with types `x, y'
\end{verbatim}
\section{Anonymous Functions}
\label{sec:closures}
\syntax\begin{verbatim}
ArgumentExpr \=::= \= `(' Closure `)'
Closure \>::= \> [Bindings] `=>' Closure
\> | \> Block
Bindings \>::= \> Binding {`,' Binding}
Binding \>::= \> Id [`:' Type]
\end{verbatim}
An anonymous function is a closure $x_1: T_1 \commadots x_n: T_n
\Arrow c$ in parentheses, where $n \geq 0$ and $c$ is a block or another closure.
The types of the parameters can be omitted if they can be inferred
from the context by local type inference. The scope of every
parameter name is the closure $c$. Let $T_1
\commadots T_n$ be the types of the parameters and let $U$ be the type
of $c$. The type $U$ may not depend on any of the parameter
names $x_1 \commadots x_n$. The type of the whole expression is then
$(T_1 \commadots T_n) U$. The expression is interpreted as
\begin{verbatim}
scala.Function$\,n$[$T_1 \commadots T_n, U$] with ( def apply($x_1 \commadots x_n$) = $c$ ) .
\end{verbatim}
\example Examples of anonymous functions:
\begin{verbatim}
(x => x) \=// The identity function
(f => g => x => f(g(x))) \>// Curried function composition
(x: Int,y: String => (y,x)) \>// A function which swaps its arguments
( => count = count + 1; count) \>// The function which takes an empty
\>// parameter list $()$, increments a global
\>// variable count and returns the new value.
\end{verbatim}
\section{Blocks}
\label{sec:blocks}
\syntax\begin{verbatim}
Block \=::= \= [{BlockStat `;'} Expr]
\end{verbatim}
A block $s_1 \semi\ldots\semi s_n \semi e$
is constructed from a sequence of block statements $s_1 \commadots s_n$
and a final expression $e$. The final expression can be omitted, in
which case the unit value $()$ is assumed.
Block statements may be definitions which bind local names in the
block. No modifiers are allowed in block-local definitions.
%Whether or not the scope includes the statement itself
%depends on the kind of definition.
The type of a block $s_1 \semi\ldots\semi s_n \semi e$ is the type of $e$. That
type must be equivalent to a type which does not refer to an entity
defined locally in the block.
Evaluation of the block entails
evaluation of its statement sequence, followed by an evaluation of the final expression
$e$, which defines the result of the block.
\section{Statements}
\label{sec:statements}
\syntax\begin{verbatim}
BlockStat \=::= \= Import
\> | \> Def
\> | \> $\VAL$ SimplePattern Id Expr
\> | \> [Expr]
TemplateStat \>::= \> Import
\> | \> {Modifier} Def
\> | \> {Modifier} Dcl
\> | \> [Expr]
PureStat \>::=\> Import
\> |\> {Modifier} PureDef
\> |\> `;'
\end{verbatim}
A statement can be a definition or an expression, or it can be empty.
Statements used in the template of a class definition can also be
declarations. An expression that is used as a statement can have an
arbitrary value type. An expression statement $e$ is evaluated by
evaluating $e$ and discarding the result of the evaluation.
With the exception of overloaded definitions
(\sref{sec:overloaded-defs}), a statement sequence making up a block
or template may not contain two definitions or declarations that bind
the same name in the same namespace. Evaluation of a statement
sequence entails evaluation of the statements in the order they are
written.
{\em Pure statements} are statements that are guaranteed to be
evaluated without side effect. A pure statement is either the empty
statement, or an import clause, or a pure definition (\sref{sec:defs}).
\chapter{Pattern Matching}
\section{Patterns}
\label{sec:patterns}
\syntax\begin{verbatim}
Pattern \=::= \= SimplePattern {Id SimplePattern}
\> | \> varid `:' Type
\> | \> `_' `:' Type
SimplePattern \>::= \> varid
\> | \> `_'
\> | \> literal
\> | \> StableId {`(' [Patterns] `)'}
\> | \> `(' [Patterns] `)'
\> | \> `[' [Patterns] `]'
Patterns \>::= \> Pattern {`,' Pattern}
\end{verbatim}
A pattern is built from constants, constructors, and
variables. Pattern matching tests whether a given value has the shape
defined by a pattern, and, if it does, binds the variables in the
pattern to the corresponding components of the value. The same
variable name may not be bound more than once in a pattern.
Pattern matching is always done in a context which supplies an
expected type of the pattern. We distinguish the following kinds of patterns.
A {\em variable pattern} $x$ is a simple identifier which starts with
a lower case letter. It matches any value, and binds the variable
name to that value. The type of $x$ is the expected type of the
pattern as given from outside. A special case is the wild-card
pattern $\_$ which is treated as if it was a fresh variable.
A {\em typed pattern} $x: T$ consists of a pattern variable $x$ and a
simple type $T$. The type $T$ may be a class type or a compound type;
it may not contain a refinement (\sref{sec:refinements}). This
pattern matches any value of type $T$ and binds the variable name to
that value. $T$ must conform to the pattern's expected type. The
type of $x$ is $T$.
A {\em pattern literal} $l$ matches any value that is equal (in terms
of $==$) to it. It's type must conform to the expected type of the
pattern.
A {\em named pattern constant} $r$ is a stable identifier
(\sref{sec:stableids}). To resolve the syntactic overlap with a
variable pattern, a named pattern constant may not be a simple name
starting with a lower-case letter. The type of $r$ must conform
to the expected type of the pattern. The pattern matches any value $v$
such that \verb@$r$ == $v$@ (\sref{sec:cls-object}).
A {\em constructor pattern} $c(p_1) \ldots (p_n)$ where $n \geq 0$
consists of an identifier $c$, followed by component patterns $p_1
\commadots p_n$. The constructor $c$ is either a simple name
or a qualified name $r.id$ where $r$ is a stable identifier. It refers
to a (possibly overloaded) function which has one alternative of
result type \verb@class C@, and which may not have other overloaded
alternatives with a class constructor type as result type.
Furthermore, the respective type parameters and value parameters of
(said alternative of) $c$ and of the primary constructor function of
class $C$ must be the same, after renaming corresponding type parameter
names. If $C$ is monomorphic, then
\verb@C@ must conform to the expected type of the pattern, and the
formal parameter types of $C$'s primary constructor are taken as the
expected types of the component patterns $p_1 \commadots p_n$. If $C$
is polymorphic, then there must be a unique type application instance
of it such that the instantiation of $C$ conforms to the expected type
of the pattern. The instantiated formal parameter types of $C$'s
primary constructor are then taken as the expected types of the
component patterns $p_1\commadots p_n$.
The pattern matches all objects created from
constructor invocations $c(v_1)\ldots(v_n)$ where each component
pattern $p_i$ matches the corresponding value $v_i$.
A {\em tuple pattern} $(p_1 \commadots p_n)$ with $n \geq 2$ matches
tuples which have components matching patterns $p_1 \commadots p_n$.
It is a shorthand for the constructor pattern
\verb@Tuple$\,n$($p_1 \commadots p_n$)@.
The empty tuple $()$ is a shorthand for the
constructor pattern \verb@Unit@. There are no tuple patterns of length
1. Instead, the pattern $(p)$ is regarded as equivalent to the
pattern $p$, except for grouping of operators.
A {\em list pattern} $[ p_1 \commadots p_n ]$ with $n \geq 0$
is a shorthand for \verb@::_class(p$_1$)(... ::_class(p$_n$, Nil)...)@.
An {\em infix operation pattern} \verb@p id p'@ is a shorthand for the
constructor pattern \verb@id_class(p)(p')@. The precedence and
associativity of operators in patterns is the same as in expressions
(\sref{sec:infix-operations}).
\example Some examples of patterns are:
\begin{enumerate}
\item
The pattern \verb@ex: IOException@ matches all instances of class
\verb@IOException@, binding variable \verb@ex@ to the instance.
\item
The pattern \verb@(x, _)@ matches pairs of values, binding \verb@x@ to
the first component of the pair. The second component is matched
with a wildcard pattern.
\item
The pattern \verb@x :: y :: xs@ matches lists of length $\geq 2$,
binding \verb@x@ to the lists's first element, \verb@y@ to the list's
second element, and \verb@xs@ to the remainder.
\end{enumerate}
\subsection{Pattern Matching Expressions}
\label{sec:pattern-match}
\syntax\begin{verbatim}
ArgumentExpr \=::= \= `(' Case {Case} `)'
Case \>::= \> $\CASE$ Patterns [$\IF$ Expr] `$=>$' Block
\end{verbatim}
A pattern matching expression $(\CASE;p_1 \Arrow b_1 ;\ldots; \CASE;p_n
\Arrow b_n)$ consists of a number $n \geq 1$ of cases. Each case
consists of a pattern $p_i$ and a block $b_i$. The scope
of the pattern variables in $p_i$ is the corresponding block
$b_i$.
The type of a pattern matching expression must in part be given from
the outside. It must be either \verb@Function[T$_p$, T$_r$]@ or
\verb@PartialFunction[T$_p$, T$_r$]@, where the argument type
\verb@T$_p$@ must be fully determined, but the result type \verb@T$_r$@
may be partially undetermined. All patterns are typed relative to the
expected type $T_p$ (\sref{sec:patterns}). Let $T_b$ be the least
type in the $(\conforms)$ ordering to which the types of all blocks
conform. The type of the pattern matching expression is then the
required type with \verb@T$_r$@ replaced by \verb@T$_b$@ (i.e. the
type is either \verb@Function[T$_p$, T$_b$]@ or
\verb@PartialFunction[T$_p$, T$_b$]@ -- see \sref{sec:cls-function} for
a definition of these classes).
When applying a pattern matching expression to a selector value,
patterns are tried in sequence until one is found which matches the
selector value (\sref{sec:patterns}). Say this case is $\CASE;p_i
\Arrow b_i$. The result of the whole expression is then the result of
evaluating $b_i$, where all pattern variables of $p_i$ are bound to
the corresponding parts of the selector value. If no matching pattern
is found, a \verb@MatchError@ exception is thrown.
The pattern in a case may also be followed by a guard suffix $\IF;e$
with a Boolean expression $e$. The guard expression is evaluated if
the preceding pattern in the case matches. If the guard expression
evaluates to \verb@True@, the pattern match succeeds as normal. If the
guard expression evaluates to \verb@False@, the patterns in the case
are considered not to match and the search for a matching pattern
continues.
A case with several patterns $\CASE;p_1 \commadots p_n ;\IF; e \Arrow b$ is a
shorthand for a sequence of single-pattern cases $\CASE;p_1;\IF;e \Arrow b
;\ldots; \CASE;p_n ;\IF;e\Arrow b$. In this case none of the patterns
$p_i$ may contain a named pattern variable (but the patterns may contain
wild-cards).
In the interest of efficiency the evaluation of a pattern matching
expression may try patterns in some other order than textual
sequence. This might affect evaluation through side effects in
let-bound (\sref{sec:letdef}) selector expressions or through side
effects in guards. However, it is guaranteed that a guard expression
is evaluated only if the pattern it guards matches.
\example
Often, pattern matching expressions are used as arguments
of the \verb@match@ method, which is predefined in class \verb@Any@
(\sref{sec:cls-object}) and is implemented there by postfix function
application. Here is an example:
\begin{verbatim}
def length [a] (xs: List[a]) = xs match {
case Nil => 0
case x :: xs1 => 1 + length (xs1)
}
\end{verbatim}
\chapter{Top-Level Definitions}
\label{sec:topdefs}
\syntax\begin{verbatim}
ClsDef \=::= \= Packaging
\> | \> ClassDef
\> | \> ModuleDef
Packaging \=::= \= package QualId with `(' {ClsDef `;'} `)'
\end{verbatim}
There are two kinds of compilation units: Main programs and library
units. A main program is a sequence of arbitrary definitions. A
library unit is a sequence of top-level definitions, i.e. class
definitions, module definitions, or packagings.
Implicitly imported into every compilation unit is the package
\verb@scala@ and the module \verb@scala.Predef@ (\sref{cls-predef}).
\section{Packagings}
\syntax\begin{verbatim}
Packaging \=::= \= package QualId with `(' {ClsDef `;'} `)'
\end{verbatim}
A packaging \verb@package P with ( D )@ declares all definitions in
\verb@D@ as members of the package whose qualified name is
\verb@P@. Packages are as in Java (this is likely to change in the
future).
\ifpackaging{
Packagings augment top-level modules and classes. A simple packaging
$$\PACKAGE;id;\WITH;mi_1;\ldots;\WITH;mi_n;\WITH;(stats)$$ augments the
template of the top-level module or class named $id$ with new mixin
classes and with new member definitions.
The static effect of such a packaging can be expressed as a
source-to-source tranformation which adds $mi_1 \commadots mi_n$ to
the mixin classes of $id$, and which adds the definitions in $stats$
to the statement part of $id$'s template. Each type $mi_j$ must refer
to an interface type and $stats$ must consists only of pure and local
definitions. The augmented template and any class that extends it
must be well-formed. The aditional definitions may not overwrite
definitions of the augmented template, and they may not access private
members of it.
Several packagings can be applied to the same top-level definition,
and those packagings may reside in different compilation units.
A qualified packaging $\PACKAGE;Q.id;\WITH;t$ is equivalent to the
nested packagings
\begin{verbatim}
package $Q$ with {
package $id$ with $t$
}
\end{verbatim}
A packaging with type parameters $\PACKAGE;c[tps];\WITH;...$ applies to
a parameterized class $c$. The number of type parameters must equal
the number of type parameters of $c$, and every bound in $tps$ must
conform to the corresponding bound in the original definition of $c$.
The augmented class has the type parameters given in its original
definition. If a parameter $a$ of an augmented class has a bound $T$
which is a strict subtype of the corresponding bound in the original
class, $a \conforms T$ is taken as an {\em application condition} for
the packaging. That is, every time a member defined in the packaging
is accessed or a conformance between class $c$ and a mixin base class
of the packaging needs to be established, an (instantiation of) the
application condition is checked. An unvalidated application
condition constitutes a type error. \todo{Need to specify more
precisely when application conditions are checked}
\example The following example will create a hello world program as
function \verb@main@ of module \verb@test.HelloWorld@.
\begin{verbatim}
package test with {
module HelloWord with {
def main(args: Array[String]) = out.println("hello world")
}
}
\end{verbatim}
This assumes there exists a top-level definition that defines a
\verb@test@ module, e.g.:
\begin{verbatim}
module test
\end{verbatim}
\example The following packaging adds class \verb@Comparable@
(\ref{ex:comparable}) as a mixin to class
\verb@scala.List@, provided the list elements are also comparable.
Every instance of \verb@List[$T$]@ will then implement
\verb@Comparable[List[$T$]]@ in the way it is defined in the
packaging. Each use of the added functionality for an instance type
\verb@List[$T$]@ requires that the application condition
\verb@T $<:$ Comparable@ is satisfied.
\begin{verbatim}
package scala.List[a extends Comparable[a]] with Comparable[List[a]] with {
def < (that: List[a]) = (this, that) match {
case (_, Nil) => False
case (Nil, _) => True
case (x :: xs, y :: ys) => (x < y) || (x == y && xs < ys)
}
}
\end{verbatim}
}
\chapter{Local Type Inference}
\label{sec:local-type-inf}
This needs to be specified in detail.
Essentially, similar to what is done for GJ.
\comment{
\section{Definitions}
For a possibly recursive definition such as $\LET;x_1 = e_1
;\ldots; \LET x_n = e_n$, local type inference proceeds as
follows.
A first phase assigns {\em a-priori types} to the $x_i$. The a-priori
type of $x$ is the declared type of $x$ if a declared type is
given. Otherwise, it is the inherited type, if one is
given. Otherwise, it is undefined.
A second phase assigns completely defined types to the $x_i$, in some
order. The type of $x$ is the a-priori type, if it is completely
defined. Otherwise, it is the a-priori type of $x$'s right hand side.
The a-priori type of an expression $e$ depends on the form of $e$.
\begin{enumerate}
\item
The a-priori type of a
typed expression $e:T$ is $T$.
\item
The a-priori type of a class instance
creation expression $c;\WITH;(b)$ is $C;\WITH;R$ where $C$ is the
type of the class given in $c$ and $R$ is the a-priori type of block
$b$.
\item
The a-priori type of a block is a record consisting the a-priori
types of each non-private identifier which is declared in the block
and which is visible at in last statement of the block. Here, it is
required that every import clause $\IMPORT;e_1 \commadots e_n$ refers
to expressions whose type can be computed with the type information
determined so far. Otherwise, a compile time error results.
\item
The a-priori type of any other expression is the expression's type, if
that type can be computed with the type information determined so far.
Otherwise, a compile time error results.
\end{enumerate}
The compiler will find an ordering in which types are assigned without
compiler errors to all variables $x_1 \commadots x_n$, if such an
ordering exists. This can be achieved by lazy evaluation.
}
\chapter{The Scala Standard Library}
The Scala standard library consists of the package \verb@scala@ with a
number of classes and modules.
\section{Root Classes}
\label{sec:cls-root}
\label{sec:cls-any}
\label{sec:cls-object}
The root of the Scala class hierarchy is formed by class \verb@Any@.
Every class in a Scala execution environment inherits directly or
indirectly from this class. Class \verb@Any@ has exactly two direct
subclasses: \verb@AnyRef@ and\verb@AnyVal@.
The subclass \verb@AnyRef@ represents all values which are represented
as objects in the underlying host system. The type of the \verb@null@
value copnforms to every subclass of \verb@AnyRef@. A direct subclass
of
\verb@AnyRef@ is class \verb@Object@. Every user-defined Scala
class inherits directly or indirectly from this class. Classes written
in other languages still inherit from \verb@scala.AnyRef@, but not
necessarily from \verb@scala.Object@.
The class \verb@AnyVal@ has a fixed number subclasses, which describe
values which are not implemented as objects in the underlying host
system.
Classes \verb@AnyRef@ and \verb@AnyVal@ are required to provide only
the members declared in class \verb@Any@, but implementations may add
host-specific methods to these classes (for instance, an
implementation may identify class \verb@AnyRef@ with its own root
class for objects).
The standard interfaces of these root classes is described by the
following definitions.
\begin{verbatim}
abstract class Any with {
/** Get runtime type descriptor */
def getType: Type = ...
/** Reference equality */
def eq (that: Any): Boolean = ...
/** Hash code */
def def hashCode: Int = ...
\end{verbatim}
\begin{verbatim}
/** Type test */
def is [a]: Boolean = ...
/** Type cast */
def as[a]: a = if (is[a]) ... else new CastException() throw
/** Semantic equality between values of same type */
def == (that: Any): Boolean = this equals that
/** Semantic inequality between values of same type */
def != (that: Any): Boolean = !(this == that)
/** Semantic equality between arbitrary values */
def equals (that: Any): Boolean = ...
/** Representation as string */
def toString: String = getType.toString ++ "@" ++ hashCode
/** Concatenation of string representations */
final def + (that: Any) = toString.concat(that)
/** Pattern matching application */
final def match [a] (f: (Any)a): a = f(this)
}
final class AnyVal extends Any
class AnyRef extends Any
class Object extends AnyRef
\end{verbatim}
\section{Value Classes}
\label{sec:cls-value}
Value classes are classes whose instances are not represented as
objects by the underlying host system. All value classes inherit from
class \verb@AnyVal@. Scala implementations need to provide the
following value classes (but are free to provide others as well).
\begin{verbatim}
final class Unit extends AnyVal with { ... }
final class Boolean extends AnyVal with { ... }
final class Double extends AnyVal with { ... }
final class Float extends Double with { ... }
final class Long extends Float with { ... }
final class Int extends Long with { ... }
final class Char extends Int with { ... }
final class Short extends Int with { ... }
final class Byte extends Short with { ... }
\end{verbatim}
These classes are defined in the following.
\subsection{Class \prog{Double}}
\begin{verbatim}
final class Double extends AnyVal with Ord with {
def asDouble: Double \=// convert to Double
def asFloat: Float \>// convert to Float
def asLong: Long \>// convert to Long
def asInt: Int \>// convert to Int
def asChar: Char \>// convert to Char
def asShort: Short \>// convert to Short
def asByte: Byte \>// convert to Byte
def + (that: Double): Double \>// double addition
def - (that: Double): Double \>// double subtraction
def * (that: Double): Double \>// double multiplication
def / (that: Double): Double \>// double division
def % (that: Double): Double \>// double remainder
def == (that: Double): Boolean \>// double equality
def != (that: Double): Boolean \>// double inequality
def < (that: Double): Boolean \>// double less
def > (that: Double): Boolean \>// double greater
def <= (that: Double): Boolean \>// double less or equals
def >= (that: Double): Boolean \>// double greater or equals
def - : Double = 0.0 - this \>// double negation
def + : Double = this
}
\end{verbatim}
\subsection{Class \prog{Float}}
\begin{verbatim}
final class Float extends Double with {
def asDouble: Double \=// convert to Double
def asFloat: Float \>// convert to Float
def asLong: Long \>// convert to Long
def asInt: Int \>// convert to Int
def asChar: Char \>// convert to Char
def asShort: Short \>// convert to Short
def asByte: Byte \>// convert to Byte
def + (that: Double): Double = asDouble + that
def + (that: Float): Double \>// float addition
/* analogous for -, *, /, % */
def == (that: Double): Boolean = asDouble == that
def == (that: Float): Boolean \>// float equality
/* analogous for !=, <, >, <=, >= */
def - : Float = 0.0f - this \>// float negation
def + : Float = this
}
\end{verbatim}
\subsection{Class \prog{Long}}
\begin{verbatim}
final class Long extends Float with {
def asDouble: Double \=// convert to Double
def asFloat: Float \>// convert to Float
def asLong: Long \>// convert to Long
def asInt: Int \>// convert to Int
def asChar: Char \>// convert to Char
def asShort: Short \>// convert to Short
def asByte: Byte \>// convert to Byte
def + (that: Double): Double = asDouble + that
def + (that: Float): Double = asFloat + that
def + (that: Long): Long = \>// long addition
/* analogous for -, *, /, % */
def << (cnt: Int): Long \>// long left shift
def >> (cnt: Int): Long \>// long signed right shift
def >>> (cnt: Int): Long \>// long unsigned right shift
def & (that: Long): Long \>// long bitwise and
def | (that: Long): Long \>// long bitwise or
def ^ (that: Long): Long \>// long bitwise exclusive or
def == (that: Double): Boolean = asDouble == that
def == (that: Float): Boolean = asFloat == that
def == (that: Long): Boolean \>// long equality
/* analogous for !=, <, >, <=, >= */
def - : Long = 0l - this \>// long negation
def + : Long = this
}
\end{verbatim}
\subsection{Class \prog{Int}}
\begin{verbatim}
class Int extends Long with {
def asDouble: Double \=// convert to Double
def asFloat: Float \>// convert to Float
def asLong: Long \>// convert to Long
def asInt: Int \>// convert to Int
def asChar: Char \>// convert to Char
def asShort: Short \>// convert to Short
def asByte: Byte \>// convert to Byte
def + (that: Double): Double = asDouble + that
def + (that: Float): Double = asFloat + that
def + (that: Long): Long = \>// long addition
def + (that: Int): Int = \>// long addition
/* analogous for -, *, /, % */
def << (cnt: Int): Int \>// long left shift
/* analogous for >>, >>> */
def & (that: Long): Long = asLong & that
def & (that: Int): Int \>// bitwise and
/* analogous for |, ^ */
def == (that: Double): Boolean = asDouble == that
def == (that: Float): Boolean = asFloat == that
def == (that: Long): Boolean \>// long equality
/* analogous for !=, <, >, <=, >= */
def - : Long = 0l - this \>// long negation
def + : Long = this
}
\end{verbatim}
\subsection{Class \prog{Boolean}}
\label{sec:cls-boolean}
\begin{verbatim}
abstract final class Boolean extends AnyVal with Ord with {
def ifThenElse[a](def t: a)(def e: a): a
def ifThen(def t: Unit): Unit = ifThenElse(t)()
def && (def x: Boolean): Boolean = ifThenElse(x)(False)
def || (def x: Boolean): Boolean = ifThenElse(True)(x)
def ! (def x: Boolean): Boolean = ifThenElse(False)(True)
def == (x: Boolean): Boolean = ifThenElse(x)(x.!)
def != (x: Boolean): Boolean = ifThenElse(x.!)(x)
def < (x: Boolean): Boolean = ifThenElse(False)(x)
def > (x: Boolean): Boolean = ifThenElse(x.!)(False)
def <= (x: Boolean): Boolean = ifThenElse(x)(True)
def >= (x: Boolean): Boolean = ifThenElse(True)(x.!)
}
case class True extends Boolean with { def ifThenElse(t)(e) = t }
case class False extends Boolean with { def ifThenElse(t)(e) = e }
\end{verbatim}
\comment{
\section{Reflection}
\subsection{Classes \prog{Type}, \prog{Class}, \prog{CompoundType}}
\begin{verbatim}
class Type[A] with {
def isSubType [B] (that: Type[B]): Boolean = ...
}
\end{verbatim}
\begin{verbatim}
class Class[A] extends Type[A] with {
...
}
\end{verbatim}
\begin{verbatim}
abstract class CompoundType[A] extends Type[A] with {
def components: List[Class[A]]
...
}
\end{verbatim}
}
\section{Other Standard Classes}
\subsection{Class \prog{Unit} and the \prog{Tuple} Classes}
\label{sec:cls-tuple}
\begin{verbatim}
case class Unit with {
def toString = "()"
}
case class Tuple$\,n$[a$_1$, ..., a$_n$](x$_1$: a$_1$, ..., x$_n$: a$_n$) with {
def $\_1$: a$_1$ = x$_1$
...
def $\_n$: a$_n$ = x$_n$
def toString = "(" ++ x$_1$ ++ "," ++ ... ++ x$_n$ ++ ")"
}
\end{verbatim}
\subsection{The \prog{Function} Classes}
\label{sec:cls-function}
\begin{verbatim}
class Function$\,n$[a$_1$, ..., a$_n$,b] with {
// some methods in Any are overwritten
def apply(x$_1$: a$_1$, ..., x$_n$: a$_n$): b
}
\end{verbatim}
Class \verb@Function1@ additionally defines the method
\begin{verbatim}
def o [c] (f: Function1[c,a$_1$]): Function1[c,b] = x: c => apply(f(x))
\end{verbatim}
There is also a module \verb@Function@, defined as follows.
\begin{verbatim}
module Function {
def compose[a](fs: List[(a)a]): (a)a = {
x => fs match {
case Nil => x
case f :: fs1 => compose(fs1)(f(x))
}
}
}
\end{verbatim}
A subclass of \verb@Function$\,n$@ describes partial functions, which
are undefined on some points in their domain.
\begin{verbatim}
class PartialFunction$\,n$[a$_1$, ..., a$_n$,b] extends Function$\,n$[a$_1$, ..., a$_n$,b] with {
def isDefined(x$_1$: a$_1$, ..., x$_n$: a$_n$): Boolean
}
\end{verbatim}
In addition to the \verb@apply@ method of functions, partial functions
also have a \verb@isDefined@ method, which tells whether the function
is defined at the given argument.
Classes \verb@Function@ and \verb@PartialFunction@ are defined to be aliases for
\verb@Function1@ and \verb@PartialFunction1@:
\begin{verbatim}
type Function[a,b] = Function1[a,b]
type PartialFunction[a,b] = PartialFunction1[a,b]
def Function[a,b]: class Function1[a,b] = Function1[a,b]
def PartialFunction[a,b]: class PartialFunction1[a,b] = PartialFunction1[a,b]
\end{verbatim}
\subsection{Class \prog{List}}\label{cls-list}
\begin{verbatim}
abstract class List[a] with {
abstract def isEmpty: Boolean;
abstract def head: a;
abstract def tail: List[a];
def ::(x: a): List[a] =
new ::_class(x)(this);
def :::(prefix: List[a]): List[a] =
if (prefix.isEmpty) this
else prefix.head :: (prefix.tail ::: this);
def length: Int = {
this match {
case [] => 0
case _ :: xs => xs.length + 1}
}
\end{verbatim}
\begin{verbatim}
def init: List[a] =
if (isEmpty) error("Nil.init")
else if (tail.isEmpty) Nil
else head :: tail.init;
def last: a =
if (isEmpty) error("Nil.last")
else if (tail.isEmpty) head
else tail.last;
def take(n: Int): List[a] =
if (n == 0) Nil
else head :: tail.take(n-1);
def drop(n: Int): List[a] =
if (n == 0) this
else tail.drop(n-1);
def takeWhile(p: (a)Boolean): List[a] =
if (isEmpty || !p(head)) Nil
else head :: tail.takeWhile(p);
def dropWhile(p: (a)Boolean): List[a] =
if (isEmpty || !p(head)) this
else tail.dropWhile(p);
def at(n: Int) = drop(n).head;
\end{verbatim}
\begin{verbatim}
def map[b](f: (a)b): List[b] =
if (isEmpty) Nil
else f(head) :: tail.map(f);
def foreach(f: (a)Unit): Unit =
if (isEmpty) ()
else (f(head); tail.foreach(f));
def filter(p: (a)Boolean): List[a] =
if (isEmpty) this
else if (p(head)) head :: tail.filter(p)
else tail.filter(p);
def forall(p: (a)Boolean): Boolean =
isEmpty || (p(head) && tail.forall(p));
def exists(p: (a)Boolean): Boolean =
!isEmpty && (p(head) || tail.exists(p));
\end{verbatim}
\begin{verbatim}
def :_foldl[b](z: b)(f: (b, a)b) = match {
case [] => z
case x :: xs => (f(z, x) :_foldl xs)(f)
}
def foldr[b](z: b)(f: (a, b)b) = match {
case [] => z
case x :: xs => f(x, (xs foldr z)(f))
}
def redl(f: (a, a)a) = match {
case [] => error("redl of empty list")
case x :: xs => (x :_foldl xs)(f)
}
def redr(f: (a, a)a): a = match {
case [] => error("redr of empty list")
case [x] => x
case x :: xs => f(x, xs redr f)
}
\end{verbatim}
\begin{verbatim}
def flatMap[b](f: (a)List[b]): List[b] =
if (isEmpty) Nil
else f(head) ::: tail.flatMap(f);
def reverse: List[a] = {
def snoc(xs: List[a], x: a): List[a] = x :: xs;
fold(snoc)(Nil)
}
def print: Unit =
if (isEmpty) System.out.println("[]")
else {
System.out.print(head.as[java.lang.Object]);
System.out.print(" :: ");
tail.print
}
def toArray: Array[a] = {
val xs = new Array[a](length);
copyToArray(xs, 0);
xs
}
def copyToArray(xs: Array[a], start: Int): Int = {
xs(start) = head;
tail.copyToArray(xs, start + 1)
}
\end{verbatim}
\begin{verbatim}
def mkString(start: String, sep: String, end: String): String =
start +
(if (isEmpty) end
else if (tail.isEmpty) head.toString() + end
else head.toString().concat(sep).concat(tail.mkString("", sep, end)));
def zip[b](that: List[b]): List[(a,b)] =
if (this.isEmpty || that.isEmpty) Nil
else (this.head, that.head) :: this.tail.zip(that.tail);
\end{verbatim}
\begin{verbatim}
def contains(elem: a) = exists(x => x == elem);
def union(that: List[a]): List[a] =
if (this.isEmpty) that
else {
val result = this.tail union that;
if (that contains this.head) result else this.head :: result;
}
def diff(that: List[a]): List[a] =
if (that.isEmpty) this
else {
val result = this.tail diff that;
if (that contains this.head) result else this.head :: result;
}
def intersect(that: List[a]): List[a] = filter(x => that contains x);
def removeDuplicates: List[a] =
if (isEmpty) this
else {
val rest = tail.removeDuplicates;
if (rest contains head) rest else head :: rest
}
}
\end{verbatim}
\begin{verbatim}
final case class ::_class[b](hd: b)(tl: List[b]) extends List[b] with {
def isEmpty = False;
def head = hd;
def tail = tl;
override def toString(): String = mkString("[", ",", "]");
}
\end{verbatim}
\begin{verbatim}
final case class Nil[c] extends List[c] with {
def isEmpty = True;
def head: c = error("head of empty list");
def tail: List[c] = error("tail of empty list");
override def toString(): String = "[]";
}
\end{verbatim}
\subsection{Class \prog{Array}}
The class of generic arrays is defined as follows.
\begin{verbatim}
class Array[a](l: int) extends Function[Int, a] with {
def length: int = l
def apply(i: Int): a = ...
def update(i: Int)(x: a): Unit = ...
}
\end{verbatim}
\comment{
\begin{verbatim}
module Array {
def create[a](i1: Int): Array[a] = Array[a](i1)
def create[a](i1: Int, i2: Int): Array[Array[a]] = {
val x: Array[Array[a]] = create(i1)
0 to (i1 - 1) do { i => x(i) = create(i2) }
x
}
...
def create[a](i1: Int, i2: Int, i3: Int, i4: Int, i5: Int,
i6: Int, i7: Int, i8: Int, i9: Int, i10: Int)
: Array[Array[Array[Array[Array[Array[Array[Array[Array[Array[a]]]]]]]]]] = {
val x: Array[Array[Array[Array[Array[Array[Array[Array[Array[a]]]]]]]]] = create(i1)
0 to (i1 - 1) do { i => x(i) = create(i2, i3, i4, i5, i6, i7, i8, i9, i10) }
x
}
}
\end{verbatim}
}
\section{Exceptions}
\label{sec:exceptions}
There is a predefined type \verb@Throwable@, as well as functions to
throw and handle values of type \verb@Throwable@. These are declared
as follows.
\begin{verbatim}
class Throwable with {
def throw[a]: a
}
class ExceptOrFinally[a] with {
def except (handler: PartialFunction[Throwable,a]): a
def finally (def handler: Unit): a
}
def try [a] (def body: a): ExceptOrFinally[a]
\end{verbatim}
The type \verb@Throwable@ represents exceptions and error objects; it
may be identified with an analogous type of the underlying
implementation such as \verb@java.lang.Throwable@. We will in the
following loosely call values of type \verb@Throwable@ exceptions.
The \verb@throw@ method in \verb@Throwable@ aborts execution of the
thread executing it and passes the thrown exception to the handler
that was most recently installed by a
\verb@try@ function in the current thread. If no \verb@try@ method is
active, the thread terminates.
The \verb@try@ function executes its body with the given exception
handler. A \verb@try@ expression comes in two forms. The first form is
\begin{verbatim}
try $body$ except $handler$ .
\end{verbatim}
If $body$ executes without an exception being thrown, then executing
the try expression is equivalent to just executing $body$. If some
exception is thrown from within $body$ for which \verb@handler@ is defined,
the handler is invoked with the thrown exception as argument.
The second form of a try expression is
\begin{verbatim}
try $body$ finally $handler$ .
\end{verbatim}
This expression will execute $body$. A normal execution of $body$ is
followed by an invocation of the $handler$ expression. The $handler$
expression does not take arguments and has \verb@Unit@ as result type.
If execution of the handler expression throws an exception, this
exception is propagated out of the \verb@try@ statement. Otherwise,
if an exception was thrown in $body$ prior to invocation of $handler$,
that exception is re-thrown after the invocation. Finally, if both
$body$ and $handler$ terminate normally, the original result of
$body$ is the result of the \verb@try@ expression.
\example An example of a try-except expression:
\begin{verbatim}
try {
System.in.readString()
} except {
case ex: EndOfFile => ""
}
\end{verbatim}
\example An example of a try-finally expression:
\begin{verbatim}
file = open (fileName)
if (file != null) {
try {
process (file)
} finally {
file.close
}
}
\end{verbatim}
\section{Concurrency}
\label{sec:concurrency}
\subsection{Basic Concurrency Constructs}
Scala programs may be executed by several threads that operate
concurrently. The thread model used is based on the model of the
underlying run-time system. We postulate a predefined
class \verb@Thread@ for run-time threads,
\verb@fork@ function to spawn off a new thread,
as well as \verb@Monitor@ and \verb@Signal@ classes. These are
specified as follows\nyi{Concurrentcy constructs are}.
\begin{verbatim}
class Thread with { ... }
def fork (def p: Unit): Thread
\end{verbatim}
The \verb@fork@ function runs its argument computation \verb@p@ in a
separate thread. It returns the thread object immediately to its
caller. Unhandled exceptions (\sref{sec:exceptions}) thrown during
evaluation of \verb@p@ abort execution of the forked thread and are
otherwise ignored.
\begin{verbatim}
class Monitor with {
def synchronized [a] (def e: a): a
}
\end{verbatim}
Monitors define a \verb@synchronized@ method which provides mutual
exclusion between threads. It executes its argument computation
\verb@e@ while asserting exclusive ownership of the monitor
object whose method is invoked. If some other thread has ownership of
the same monitor object, the computation is delayed until the other
process has relinquished its ownership. Ownership of a monitor is
relinquished at the end of the argument computation, and while the
computation is waiting for a signal.
\begin{verbatim}
class Signal with {
def wait: Unit
def wait(msec: Long): Unit
def notify: Unit
def notifyAll: Unit
}
\end{verbatim}
The \verb@Signal@ class provides the basic means for process
synchronization. The \verb@wait@ method of a signal suspends the
calling thread until it is woken up by some future invocation of the
signal's \verb@notify@ or \verb@notifyAll@ method. The \verb@notify@
method wakes up one thread that is waiting for the signal. The
\verb@notifyAll@ method wakes up all threads that are waiting for the
signal. A second version of the \verb@wait@ method takes a time-out
parameter (given in milliseconds). A thread calling \verb@wait(msec)@
will suspend until unblocked by a \verb@notify@ or \verb@notifyAll@
method, or until the \verb@msec@ millseconds have passed.
\subsection{Channels}
\begin{verbatim}
class Channel[a] with {
def write(x: a): Unit
def read: a
}
\end{verbatim}
An object of type \verb@Channel[a]@ Channels offer a write-operation
which writes data of type \verb@a@ to the channel, and a read
operation, which returns written data as a result. The write operation
is non-blocking; that is it returns immediately without waiting for
the written data to be read.
\subsection{Message Spaces}
The Scala library also provides message spaces as a higher-level,
flexible construct for process synchronization and communication. A
{\em message} is an arbitrary object that inherits from the
\verb@Message@ class.
There is a special message \verb@TIMEOUT@ which is used to signal a time-out.
\begin{verbatim}
class Message
case class TIMEOUT extends Message
\end{verbatim}
Message spaces implement the following class.
\begin{verbatim}
class MessageSpace with {
def send(msg: Message): Unit
def receive[a](f: PartialFunction1[Message, a]): a
def receiveWithin[a](msec: Long)(f: PartialFunction1[Message, a]): a
}
\end{verbatim}
The state of a message space consists of a multi-set of messages.
Messages are added to the space using the \verb@send@ method. Messages
are removed using the \verb@receive@ method, which is passed a message
processor \verb@f@ as argument, which is a partial function from
messages to some arbitrary result type. Typically, this function is
implemented as a pattern matching expression. The \verb@receive@
method blocks until there is a message in the space for which its
message processor is defined. The matching message is then removed
from the space and the blocked thread is restarted by applying the
message processor to the message. Both sent messages and receivers are
ordered in time. A receiver $r$ is applied to a matching message $m$
only if there is no other (message, receiver) pair which precedes $(m,
r)$ in the partial ordering on pairs that orders each component in
time.
The message space class also offers a method \verb@receiveWithin@
which blocks for only a specified maximal amount of time. If no
message is received within the specified time interval (given in
milliseconds), the message processor argument $f$ will be unblocked
with the special \verb@TIMEOUT@ message.
\appendix
\chapter{Scala Syntax Summary}
The lexical syntax of Scala is given by the following grammar in EBNF
form.
\begin{verbatim}
upper \=::= \=`A' | ... | `Z' | `$\Dollar$' | `_'
lower \>::= \>`a' | ... | `z'
letter \>::= \>upper | lower
digit \>::= \>`0' | ... | `9'
special \>::= \>``everything else except parentheses ([{}]) and period''
op \>::= \>special {special} [`_' [id]]
varid \>::= \>lower {letter | digit} [`_' [id]]
id \>::= \>upper {letter | digit} [`_' [id]]
\> |\>varid
\> |\>op
intLit \>::= \>``as in Java''
floatLit \>::= \>``as in Java''
charLit \>::= \>``as in Java''
stringLit \>::= \>``as in Java''
comment \>::= \>`/*' ``any sequence of characters'' `*/'
\> |\>`//' `any sequence of characters up to end of line''
\end{verbatim}
The context-free syntax of Scala is given by the following EBNF
grammar.
\begin{verbatim}
literal \=::= \= intLit
\> |\> floatLit
\> |\> charLit
\> |\> stringLit
\> |\> symbolLit
\> |\> true
\> |\> false
\> |\> null
Id \>::=\> id | `+' | `-' | `!'
QualId \>::=\> Id {`.' Id}
Ids \>::=\> Id {`,' Id}
\end{verbatim}
\begin{verbatim}
StableId \=::= \= Id
\> |\> Path `.' Id
\> |\> [Ident '.'] super `.' Id
Path \>::=\> StableId
\> |\> [Ident `.'] this
Type \>::= \> Type1 `=>' Type
\> |\> `(' [Types] `)' `=>' Type
\> |\> Type1
Type1 \>::= \> SimpleType {with SimpleType} [Refinement]
SimpleType \>::= \> SimpleType TypeArgs
\> |\> SimpleType `#' Id
\> |\> StableId
\> |\> Path `.' type
\> |\> `(' Type ')'
TypeArgs \>::= \> `[' Types `]'
Types \>::= \> Type {`,' Type}
Refinement \>::=\> `{' [RefineStat {`;' RefineStat}] `}'
RefineStat \>::=\> Dcl
\> |\> type TypeDef {`,' TypeDef}
\> |\>
Exprs \>::=\> Expr {`,' Expr}
Expr \>::=\> [Bindings `=>'] Expr
\> |\> if `(' Expr `)' Expr [[`;'] else Expr]
\> |\> try Expr [`;'] (except Expr | finally Expr)
\> |\> while '(' Expr ')' Expr
\> |\> do Expr [`;'] while `(' Expr ')'
\> |\> for `(' Enumerators `)' (do | yield) Expr
\> |\> [SimpleExpr `.'] Id `=' Expr
\> |\> SimpleExpr ArgumentExpr `=' Expr
\> |\> PostfixExpr [`:' Type1 | as Type1 | is Type1]
PostfixExpr \>::=\> InfixExpr [Id]
InfixExpr \>::=\> PrefixExpr
\> |\> InfixExpr Id InfixExpr
PrefixExpr \>::=\> [`-' | `+' | `~' | `!'] SimpleExpr
SimpleExpr \>::=\> literal
\> |\> Path
\> |\> `(' [Expr] `)'
\> |\> BlockExpr
\> |\> new Template
\> |\> SimpleExpr `.' Id
\> |\> SimpleExpr TypeArgs
\> |\> SimpleExpr ArgumentExpr
ArgumentExpr \>::=\> `(' Expr ')'
\> |\> BlockExpr
BlockExpr \>::=\> `{' CaseClause {CaseClause} `}'
\> |\> `{' Block `}'
Block \>::=\> {BlockStat `;'} [Expr]
\end{verbatim}
\begin{verbatim}
Enumerators \=::= \= Generator {`;' Enumerator}
Enumerator \>::=\> Generator
\> |\> Expr
Generator \>::=\> val Pattern `<-' Expr
Block \>::=\> {BlockStat `;'} [Expr]
BlockStat \>::=\> Import
\> |\> Def
\> |\> {LocalModifier} ClsDef
\> |\> Expr
\> |\>
CaseClause \>::=\> case Pattern [`if' PostfixExpr] `=>' Block
Constr \>::=\> StableId [TypeArgs] [`(' [Exprs] `)']
ConstrExpr \>::=\> Constr
\> |\> `{' {BlockStat `;'} Constr `}'
Pattern \>::=\> varid `:' Type1
\> |\> `_' `:' Type1
\> |\> SimplePattern {Id SimplePattern}
SimplePattern \>::=\> varid
\> |\> `_'
\> |\> literal
\> |\> StableId [`(' [Patterns] `)']
\> |\> `(' [Pattern] `)'
Patterns \>::=\> Pattern {`,' Pattern}
TypeParamClause \>::=\> `[' TypeParam {`,' TypeParam} `]'
FunTypeParamClause \>::=\> `[' TypeDcl {`,' TypeDcl} `]'
TypeParam \>::=\> [`+' | `-'] TypeDcl
ParamClause \>::=\> `(' [Param {`,' Param}] `)'
Param \>::=\> [def] Id `:' Type [`*']
Bindings \>::=\> Id [`:' Type1]
\> |\> `(' Binding {`,' Binding `)'
\> |\>
Binding \>::=\> Id [`:' Type]
Modifier \>::=\> abstract
\> |\> final
\> |\> private
\> |\> protected
\> |\> override
LocalModifier \>::=\> abstract
\> |\> final
Template \>::=\> Constr {`with' Constr} [TemplateBody]
TemplateBody \>::=\> `{' [TemplateStat {`;' TemplateStat}] `}'
\end{verbatim}
\begin{verbatim}
TemplateStat \=::= \= Import
\> |\> {Modifier} Def
\> |\> {Modifier} Dcl
\> |\> Expr
\> |\>
Import \>::=\> import ImportExpr {`,' ImportExpr}
ImportExpr \>::=\> StableId `.' (Id | `_' | ImportSelectors)
ImportSelectors \>::=\> `{' {ImportSelector `,'} (ImportSelector | `_') `}'
ImportSelector \>::=\> Id [`=>' Id | `=>' `_']
Dcl \>::=\> val ValDcl {`,' ValDcl}
\> |\> var VarDcl {`,' VarDcl}
\> |\> def FunDcl {`,' FunDcl}
\> |\> constr ConstrDcl {`,' ConstrDcl}
\> |\> type TypeDcl {`,' TypeDcl}
ValDcl \>::=\> Id `:' Type
VarDcl \>::=\> Id `:' Type
FunDcl \>::=\> Id [FunTypeParamClause] {ParamClause} `:' Type
ConstrDcl \>::=\> Id [FunTypeParamClause] [ParamClause] `:' Type
TypeDcl \>::=\> Id [`>:' Type] [`<:' Type]
Def \>::=\> val PatDef {`,' PatDef}
\> |\> var VarDef {`,' VarDef}
\> |\> def FunDef {`,' FunDef}
\> |\> constr ConstrDef {`,' ConstrDef}
\> |\> type TypeDef {`,' TypeDef}
\> |\> ClsDef
PatDef \>::=\> Pattern `=' Expr
VarDef \>::=\> Id [`:' Type] `=' Expr
\> |\> Id `:' Type `=' `_'
FunDef \>::=\> Id [FunTypeParamClause] {ParamClause} [`:' Type] `=' Expr
ConstrDef \>::=\> Id [FunTypeParamClause] [ParamClause] [`:' Type] `=' ConstrExpr
TypeDef \>::=\> Id `=' Type
ClsDef \>::=\> ([case] class | trait) ClassDef {`,' ClassDef}
\> |\> [case] object ObjectDef {`,' ObjectDef}
ClassDef \>::=\> Id [TypeParamClause] [ParamClause] [`:' SimpleType] ClassTemplate
ObjectDef \>::=\> Id [`:' SimpleType] ClassTemplate
ClassTemplate \>::=\> extends Template
\> |\> TemplateBody
\> |\>
CompilationUnit \>::=\> [package QualId `;'] [{TopStat `;'} TopStat]
TopStat \>::=\> {Modifier} ClsDef
\> |\> Packaging
\> |\> Import
\> |\>
Packaging \>::=\> package QualId `{' [{TopStat `;'} TopStat] `}'
\end{verbatim}
case class extends { ... }
trait List { }
class Nil
class Cons
\comment{changes:
Type \=::= \= SimpleType {with SimpleType} [with Refinement]
\> |\> class SimpleType
SimpleType \>::=\> SimpleType [TypeArgs]
\> |\> `(' [Types] `)'
\> |\>
\> |\> this
}
\end{document}
\comment{changes:
Type \=::= \= SimpleType {with SimpleType} [with Refinement]
\> |\> class SimpleType
SimpleType \>::=\> TypeDesignator [TypeArgs]
\> |\> `(' Type `,' Types `)'
\> |\> `(' [Types] `)' Type
\> |\> this
PureDef \>::=\> module ModuleDef {`,' ModuleDef}
\>::=\> def FunDef {`,' FunDef}
\> |\> type TypeDef {`,' TypeDef}
\> |\> [case] class ClassDef {`,' ClassDef}
\> |\> case CaseDef {`,' CaseDef}
CaseDef \>::=\> Ids ClassTemplate
Modifier \>::=\> final
\> |\> private
\> |\> protected
\> |\> override [QualId]
\> |\> qualified
\> |\> abstract
\section{Class Aliases}
\label{sec:class-alias}
\syntax\begin{verbatim}
ClassDef \=::= \= ClassAlias
InterfaceDef \>::= \> ClassAlias
ClassAlias \>::= \> Id [TypeParamClause] `=' SimpleType
\end{verbatim}
Classes may also be defined to be aliases for other classes. A class
alias is of the form $\CLASS;c[tps] = d[targs]$ where $d[targs]$ is a
class type. Both $tps$ and $targs$ may be empty.
This introduces the type $c[tps]$ as an alias for type
$d[targs]$, in the same way the following type alias definition would:
\begin{verbatim}
type c[tps] = d[targs]
\end{verbatim}
The class alias definition is legal if the type alias definition would be legal.
Assuming $d$ defines a class with type parameters $tps'$ and
parameters $(ps_1) \ldots (ps_n)$, the newly defined type is also
introduced as a class with a constructor which takes type parameters
$[tps]$, and which takes value parameters
$([targs/tps']ps_1)\ldots([targs/tps']ps_n)$.
The modifiers \verb@private@ and
\verb@protected@ apply to a class alias independently of the class it represents.
The class $c$ is regarded as final if $d$ is final, or if a
\verb@final@ modifier is given for the alias definition.
$c$ is regarded as a case class iff $d$ is one. In this
case,
\begin{itemize}
\item the alias definition may also be prefixed with \verb@case@, and
\item the case constructor is also aliased, as if it was
defined such:
\begin{verbatim}
def c[tps](ps$_1$)\ldots(ps$_n$):D = d[targs]$([targs/tps']ps$_1$)\ldots([targs/tps']ps$_n$)$ .
\end{verbatim}
The new function $c$ is again classified as a case constructor, so
it may appear in constructor patterns (\sref{sec:patterns}).
\end{itemize}
Aliases for interfaces follow the same rules as class aliases, but
start with \verb@interface@ instead of \verb@class@.
}
type T extends { ... }
class C extends { ... }
new C { ... }
type C
class C < { ... }
A & B & C &
\ifqualified{
Parameter clauses (\sref{sec:funsigs}),
definitions that are local to a block (\sref{sec:blocks}), and import
clauses always introduce {\em simple names} $x$, which consist of a
single identifier. On the other hand, definitions and declarations
that form part of a module (\sref{sec:modules}) or a class
(\sref{sec:classes}) conceptually always introduce {\em qualified
names}\nyi{Qualified names are}
$Q\qex x$ where a simple name $x$ comes with a qualified
identifier $Q$. $Q$ is either the fully qualified name of a module or
class which is labelled
\verb@qualified@, or it is the empty name $\epsilon$.
The {\em fully qualified name} of a module or class $M[targs]$ with
simple name $M$ and type arguments $[targs]$ is
\begin{itemize}
\item $Q.M$, if the definition of $M$ appears in the template defining
a module or class with fully qualified name $Q$.
\item
$M$ if the definition of $M$ appears on the top-level or as a definition
in a block.
\end{itemize}
}
\ifqualified{
It is possible that a definition in some class or module $M$
introduces several qualified names $Q_1\qex x \commadots Q_n\qex x$ in a name
space that have the same simple name suffix but different qualifiers
$Q_1 \commadots Q_n$. This happens for instance if a module \verb@M@
implements two qualified classes \verb@C@, \verb@D@ that each define a
function \verb@f@:
\begin{verbatim}
qualified abstract class B { def f: Unit = ""}
qualified abstract class C extends B { def f: Unit }
qualified abstract class D extends B { def f: Unit }
module M extends C with D with {
override C def f = println("C::f")
override D def f = println("D::f")
\=
// f \>// error: ambiguous
(this:D).f \>// prints ``D::f''
}
def main() = (M:C).f \>// prints ``C::f''
\end{verbatim}
Members of modules or classes are accessed using simple names,
not qualified names.
The {\em qualified expansion} of a simple name $x$ in some type $T$ is
determined as follows: Let $Q_1\qex x \commadots Q_n\qex x$ be all the
qualified names of members of $T$ that have a simple name suffix $x$.
If one of the qualifiers $Q_i$ is the empty name $\epsilon$, then the
qualified expansion of $x$ in $T$ is $\epsilon\qex x$. Otherwise, let
$C_1
\commadots C_n$ be the base classes (\sref{sec:base-classes})
of $T$ that have fully qualified
names $Q_1
\commadots Q_n$, respectively. If there exists a least class $C_j$
among the $C_i$ in the subclass ordering, then the qualified expansion
of $x$ in $T$ is $Q_j\qex x$. Otherwise the qualified expansion does not
exist.
Conversely, if $Q\qex x$ is the qualified expansion of some simple
name $x$ in $M$, we say that the entity named $Q\qex x$ in $M$ is {\em
identified in $M$ by the simple name} $x$. We leave out the
qualification ``in $M$'' if it is clear from the context.
In the example above, the qualified expansion of \verb@f@ in \verb@C@
is \verb@C::f@, because \verb@C@ is a subclass of \verb@B@. On the
other hand, the qualified expansion of \verb@f@ in \verb@M@ does not
exist, since among the two choices \verb@C::f@ and \verb@D::f@ neither
class is a subclass of the other.
A member access $e.x$ of some type term $e$ of type $T$ references the
member identified in $T$ by the simple name $x$ (i.e.\ the member
which is named by the qualified expansion of $x$ in $T$).
In the example above, the simple name \verb@f@ in \verb@M@ would be
ambiguous since the qualified expansion of \verb@f@ in \verb@M@ does
not exist. To reference one of the two functions with simple name
\verb@f@, one can use an explicit typing. For instance, the name
\verb@(this:D).f@ references the implementation of \verb@D::f@ in
\verb@M@.
}
|