summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/typechecker/Typers.scala
blob: dec6d58b455ba75767a23e7980248e8083e95f2c (plain) (blame)
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
/* NSC -- new Scala compiler
 * Copyright 2005-2009 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$

//todo: rewrite or disllow new T where T is a mixin (currently: <init> not a member of T)
//todo: use inherited type info also for vars and values
//todo: disallow C#D in superclass
//todo: treat :::= correctly
package scala.tools.nsc.typechecker

import scala.collection.mutable.{HashMap, ListBuffer}
import scala.compat.Platform.currentTime
import scala.tools.nsc.util.{HashSet, Position, Set, NoPosition, SourceFile}
import symtab.Flags._
import util.HashSet

// Suggestion check whether we can do without priming scopes with symbols of outer scopes,
// like the IDE does.
/** This trait provides methods to assign types to trees.
 *
 *  @author  Martin Odersky
 *  @version 1.0
 */
trait Typers { self: Analyzer =>
  import global._
  import definitions._
  import posAssigner.atPos

  private final val printTypings = false

  var appcnt = 0
  var idcnt = 0
  var selcnt = 0
  var implcnt = 0
  var impltime = 0l

  private val transformed = new HashMap[Tree, Tree]

  private val superDefs = new HashMap[Symbol, ListBuffer[Tree]]

  def resetTyper() {
    resetContexts
    resetNamer()
    transformed.clear
    superDefs.clear
  }

  object UnTyper extends Traverser {
    override def traverse(tree: Tree) = {
      if (tree != EmptyTree) tree.tpe = null
      if (tree.hasSymbol) tree.symbol = NoSymbol
      super.traverse(tree)
    }
  }
/* needed for experimental version where eraly types can be type arguments
  class EarlyMap(clazz: Symbol) extends TypeMap {
    def apply(tp: Type): Type = tp match {
      case TypeRef(NoPrefix, sym, List()) if (sym hasFlag PRESUPER) =>
        TypeRef(ThisType(clazz), sym, List())
      case _ =>
        mapOver(tp)
    }
  }
*/
  // IDE hooks
  def newTyper(context: Context): Typer = new NormalTyper(context)
  private class NormalTyper(context : Context) extends Typer(context)
  // hooks for auto completion

  /** when in 1.4 mode the compiler accepts and ignores useless
   *  type parameters of Java generics
   */
  def onePointFourMode = true // todo changeto: settings.target.value == "jvm-1.4"

  // Mode constants

  /** The three mode <code>NOmode</code>, <code>EXPRmode</code>
   *  and <code>PATTERNmode</code> are mutually exclusive.
   */
  val NOmode        = 0x000
  val EXPRmode      = 0x001
  val PATTERNmode   = 0x002
  val TYPEmode      = 0x004

  /** The mode <code>SCCmode</code> is orthogonal to above. When set we are
   *  in the this or super constructor call of a constructor.
   */
  val SCCmode       = 0x008

  /** The mode <code>FUNmode</code> is orthogonal to above.
   *  When set we are looking for a method or constructor.
   */
  val FUNmode       = 0x010

  /** The mode <code>POLYmode</code> is orthogonal to above.
   *  When set expression types can be polymorphic.
   */
  val POLYmode      = 0x020

  /** The mode <code>QUALmode</code> is orthogonal to above. When set
   *  expressions may be packages and Java statics modules.
   */
  val QUALmode      = 0x040

  /** The mode <code>TAPPmode</code> is set for the function/type constructor
   *  part of a type application. When set we do not decompose PolyTypes.
   */
  val TAPPmode      = 0x080

  /** The mode <code>SUPERCONSTRmode</code> is set for the <code>super</code>
   *  in a superclass constructor call <code>super.&lt;init&gt;</code>.
   */
  val SUPERCONSTRmode = 0x100

  /** The mode <code>SNDTRYmode</code> indicates that an application is typed
   *  for the 2nd time. In that case functions may no longer be coerced with
   *  implicit views.
   */
  val SNDTRYmode    = 0x200

  /** The mode <code>LHSmode</code> is set for the left-hand side of an
   *  assignment.
   */
  val LHSmode       = 0x400

  /** The mode <code>REGPATmode</code> is set when regular expression patterns
   *  are allowed.
   */
  val REGPATmode    = 0x1000

  /** The mode <code>ALTmode</code> is set when we are under a pattern alternative */
  val ALTmode       = 0x2000

  /** The mode <code>HKmode</code> is set when we are typing a higher-kinded type
   * adapt should then check kind-arity based on the prototypical type's kind arity
   * type arguments should not be inferred
   */
  val HKmode        = 0x4000 // @M: could also use POLYmode | TAPPmode

  /** The mode <code>JAVACALLmode</code> is set when we are typing a call to a Java method
   *  needed temporarily for vararg conversions
   *  !!!VARARG-CONVERSION!!!
   */
  val JAVACALLmode  = 0x8000

  /** The mode <code>TYPEPATmode</code> is set when we are typing a type in a pattern
   */
  val TYPEPATmode   = 0x10000

  private val stickyModes: Int  = EXPRmode | PATTERNmode | TYPEmode | ALTmode

  private def funMode(mode: Int) = mode & (stickyModes | SCCmode) | FUNmode | POLYmode

  private def typeMode(mode: Int) =
    if ((mode & (PATTERNmode | TYPEPATmode)) != 0) TYPEmode | TYPEPATmode
    else TYPEmode

  private def argMode(fun: Tree, mode: Int) =
    if (treeInfo.isSelfOrSuperConstrCall(fun)) mode | SCCmode
    else if (fun.symbol hasFlag JAVA) mode | JAVACALLmode // !!!VARARG-CONVERSION!!!
    else mode

  abstract class Typer(context0: Context) {
    import context0.unit

    val infer = new Inferencer(context0) {
      override def isCoercible(tp: Type, pt: Type): Boolean =
        tp.isError || pt.isError ||
        context0.implicitsEnabled && // this condition prevents chains of views
        inferView(EmptyTree, tp, pt, false) != EmptyTree
    }

    /** Find implicit arguments and pass them to given tree.
     */
    def applyImplicitArgs(tree: Tree): Tree = tree.tpe match {
      case MethodType(formals, _) =>
        def implicitArg(pt: Type): SearchResult = {
          val result = inferImplicit(tree, pt, true, context)
          if (result == SearchFailure)
            context.error(tree.pos, "no implicit argument matching parameter type "+pt+" was found.")
          result
        }
        val argResults = formals map implicitArg
        val args = argResults map (_.tree)
        for (s <- argResults map (_.subst)) {
          s traverse tree
          for (arg <- args) s traverse arg
        }
        Apply(tree, args) setPos tree.pos
      case ErrorType =>
        tree
    }

    /** Infer an implicit conversion (``view'') between two types.
     *  @param tree             The tree which needs to be converted.
     *  @param from             The source type of the conversion
     *  @param to               The target type of the conversion
     *  @param reportAmbiguous  Should ambiguous implicit errors be reported?
     *                          False iff we search for a view to find out
     *                          whether one type is coercible to another.
     */
    def inferView(tree: Tree, from: Type, to: Type, reportAmbiguous: Boolean): Tree = {
      if (settings.debug.value) log("infer view from "+from+" to "+to)//debug
      if (phase.id > currentRun.typerPhase.id) EmptyTree
      else from match {
        case MethodType(_, _) => EmptyTree
        case OverloadedType(_, _) => EmptyTree
        case PolyType(_, _) => EmptyTree
        case _ =>
          def wrapImplicit(from: Type): Tree = {
            val result = inferImplicit(tree, MethodType(List(from), to), reportAmbiguous, context)
            if (result.subst != EmptyTreeTypeSubstituter) result.subst traverse tree
            result.tree
          }
          val result = wrapImplicit(from)
          if (result != EmptyTree) result
          else wrapImplicit(appliedType(ByNameParamClass.typeConstructor, List(from)))
      }
    }

    /** Infer an implicit conversion (``view'') that makes a member available.
     *  @param tree             The tree which needs to be converted.
     *  @param from             The source type of the conversion
     *  @param name             The name of the member that needs to be available
     *  @param tp               The expected type of the member that needs to be available
     */
    def inferView(tree: Tree, from: Type, name: Name, tp: Type): Tree = {
      val to = refinedType(List(WildcardType), NoSymbol)
      var psym = if (name.isTypeName) to.typeSymbol.newAbstractType(tree.pos, name)
                 else to.typeSymbol.newValue(tree.pos, name)
      psym = to.decls enter psym
      psym setInfo tp
      inferView(tree, from, to, true)
    }

    import infer._

    private var namerCache: Namer = null
    def namer = {
      if ((namerCache eq null) || namerCache.context != context)
        namerCache = newNamer(context)
      namerCache
    }

    private[typechecker] var context = context0
    def context1 = context

    /** Report a type error.
     *
     *  @param pos0   The position where to report the error
     *  @param ex     The exception that caused the error
     */
    def reportTypeError(pos0: Position, ex: TypeError) {
      if (settings.debug.value) ex.printStackTrace()
      val pos = if (ex.pos == NoPosition) pos0 else ex.pos
      ex match {
        case CyclicReference(sym, info: TypeCompleter) =>
          val msg =
            info.tree match {
              case ValDef(_, _, tpt, _) if (tpt.tpe eq null) =>
                "recursive "+sym+" needs type"
              case DefDef(_, _, _, _, tpt, _) if (tpt.tpe eq null) =>
                (if (sym.owner.isClass && sym.owner.info.member(sym.name).hasFlag(OVERLOADED)) "overloaded "
                 else "recursive ")+sym+" needs result type"
              case _ =>
                ex.getMessage()
            }
          if (context.retyping) context.error(pos, msg)
          else context.unit.error(pos, msg)
          if (sym == ObjectClass)
            throw new FatalError("cannot redefine root "+sym)
        case _ =>
          context.error(pos, ex)
      }
    }

    /** Check that <code>tree</code> is a stable expression.
     *
     *  @param tree ...
     *  @return     ...
     */
    def checkStable(tree: Tree): Tree =
      if (treeInfo.isPureExpr(tree)) tree
      else errorTree(
        tree,
        "stable identifier required, but "+tree+" found."+
        (if (isStableExceptVolatile(tree)) {
          val tpe = tree.symbol.tpe match {
            case PolyType(_, rtpe) => rtpe
            case t => t
          }
          "\n Note that "+tree.symbol+" is not stable because its type, "+tree.tpe+", is volatile."
         } else ""))

    /** Would tree be a stable (i.e. a pure expression) if the type
     *  of its symbol was not volatile?
     */
    private def isStableExceptVolatile(tree: Tree) = {
      tree.hasSymbol && tree.symbol != NoSymbol && tree.tpe.isVolatile &&
      { val savedTpe = tree.symbol.info
        val savedSTABLE = tree.symbol getFlag STABLE
        tree.symbol setInfo AnyRefClass.tpe
        tree.symbol setFlag STABLE
       val result = treeInfo.isPureExpr(tree)
        tree.symbol setInfo savedTpe
        tree.symbol setFlag savedSTABLE
        result
      }
    }

    /** Check that `tpt' refers to a non-refinement class type */
    def checkClassType(tpt: Tree, existentialOK: Boolean) {
      def check(tpe: Type): Unit = tpe.normalize match {
        case TypeRef(_, sym, _) if sym.isClass && !sym.isRefinementClass => ;
        case ErrorType => ;
        case PolyType(_, restpe) => check(restpe)
        case ExistentialType(_, restpe) if existentialOK => check(restpe)
        case AnnotatedType(_, underlying, _) => check(underlying)
        case t => error(tpt.pos, "class type required but "+t+" found")
      }
      check(tpt.tpe)
    }

    /** Check that type <code>tp</code> is not a subtype of itself.
     *
     *  @param pos ...
     *  @param tp  ...
     *  @return    <code>true</code> if <code>tp</code> is not a subtype of itself.
     */
    def checkNonCyclic(pos: Position, tp: Type): Boolean = {
      def checkNotLocked(sym: Symbol): Boolean = {
        sym.initialize
	sym.lockOK || {error(pos, "cyclic aliasing or subtyping involving "+sym); false}
      }
      tp match {
        case TypeRef(pre, sym, args) =>
          (checkNotLocked(sym)) && (
            !sym.isTypeMember ||
            checkNonCyclic(pos, appliedType(pre.memberInfo(sym), args), sym)   // @M! info for a type ref to a type parameter now returns a polytype
            // @M was: checkNonCyclic(pos, pre.memberInfo(sym).subst(sym.typeParams, args), sym)
          )
        case SingleType(pre, sym) =>
          checkNotLocked(sym)
/*
        case TypeBounds(lo, hi) =>
          var ok = true
          for (t <- lo) ok = ok & checkNonCyclic(pos, t)
          ok
*/
        case st: SubType =>
          checkNonCyclic(pos, st.supertype)
        case ct: CompoundType =>
          var p = ct.parents
          while (!p.isEmpty && checkNonCyclic(pos, p.head)) p = p.tail
          p.isEmpty
        case _ =>
          true
      }
    }

    def checkNonCyclic(pos: Position, tp: Type, lockedSym: Symbol): Boolean = {
      lockedSym.lock {
        throw new TypeError("illegal cyclic reference involving " + lockedSym)
      }
      val result = checkNonCyclic(pos, tp)
      lockedSym.unlock()
      result
    }

    def checkNonCyclic(sym: Symbol) {
      if (!checkNonCyclic(sym.pos, sym.tpe)) sym.setInfo(ErrorType)
    }

    def checkNonCyclic(defn: Tree, tpt: Tree) {
      if (!checkNonCyclic(defn.pos, tpt.tpe, defn.symbol)) {
        tpt.tpe = ErrorType
        defn.symbol.setInfo(ErrorType)
      }
    }

    def checkParamsConvertible(pos: Position, tpe: Type) {
      tpe match {
        case MethodType(formals, restpe) =>
          /*
          if (formals.exists(_.typeSymbol == ByNameParamClass) && formals.length != 1)
            error(pos, "methods with `=>'-parameter can be converted to function values only if they take no other parameters")
          if (formals exists (_.typeSymbol == RepeatedParamClass))
            error(pos, "methods with `*'-parameters cannot be converted to function values");
          */
          if (restpe.isDependent)
            error(pos, "method with dependent type "+tpe+" cannot be converted to function value");
          checkParamsConvertible(pos, restpe)
        case _ =>
      }
    }

    def checkRegPatOK(pos: Position, mode: Int) =
      if ((mode & REGPATmode) == 0 &&
          phase.id <= currentRun.typerPhase.id) // fixes t1059
        error(pos, "no regular expression pattern allowed here\n"+
              "(regular expression patterns are only allowed in arguments to *-parameters)")

    /** Check that type of given tree does not contain local or private
     *  components.
     */
    object checkNoEscaping extends TypeMap {
      private var owner: Symbol = _
      private var scope: Scope = _
      private var hiddenSymbols: List[Symbol] = _

      /** Check that type <code>tree</code> does not refer to private
       *  components unless itself is wrapped in something private
       *  (<code>owner</code> tells where the type occurs).
       *
       *  @param owner ...
       *  @param tree  ...
       *  @return      ...
       */
      def privates[T <: Tree](owner: Symbol, tree: T): T =
        check(owner, EmptyScope, WildcardType, tree)

      /** Check that type <code>tree</code> does not refer to entities
       *  defined in scope <code>scope</code>.
       *
       *  @param scope ...
       *  @param pt    ...
       *  @param tree  ...
       *  @return      ...
       */
      def locals[T <: Tree](scope: Scope, pt: Type, tree: T): T =
        check(NoSymbol, scope, pt, tree)

      def check[T <: Tree](owner: Symbol, scope: Scope, pt: Type, tree: T): T = {
        this.owner = owner
        this.scope = scope
        hiddenSymbols = List()
        val tp1 = apply(tree.tpe)
        if (hiddenSymbols.isEmpty || inIDE) tree setType tp1 // @S: because arguments of classes are owned by the classes' owner
        else if (hiddenSymbols exists (_.isErroneous)) setError(tree)
        else if (isFullyDefined(pt)) tree setType pt //todo: eliminate
        else if (tp1.typeSymbol.isAnonymousClass) // todo: eliminate
          check(owner, scope, pt, tree setType tp1.typeSymbol.classBound)
        else if (owner == NoSymbol)
          tree setType packSymbols(hiddenSymbols.reverse, tp1)
        else { // privates
          val badSymbol = hiddenSymbols.head
          error(tree.pos,
                (if (badSymbol hasFlag PRIVATE) "private " else "") + badSymbol +
                " escapes its defining scope as part of type "+tree.tpe)
          setError(tree)
        }
      }

      def addHidden(sym: Symbol) =
        if (!(hiddenSymbols contains sym)) hiddenSymbols = sym :: hiddenSymbols

      override def apply(t: Type): Type = {
        def checkNoEscape(sym: Symbol) {
          if (sym.hasFlag(PRIVATE)) {
            var o = owner
            while (o != NoSymbol && o != sym.owner &&
                   !o.isLocal && !o.hasFlag(PRIVATE) &&
                   !o.privateWithin.hasTransOwner(sym.owner))
              o = o.owner
            if (o == sym.owner) addHidden(sym)
          } else if (sym.owner.isTerm && !sym.isTypeParameterOrSkolem) {
            var e = scope.lookupEntryWithContext(sym.name)(context.owner)
            var found = false
            while (!found && (e ne null) && e.owner == scope) {
              if (e.sym == sym) {
                found = true
                addHidden(sym)
              } else {
                e = scope.lookupNextEntry(e)
              }
            }
          }
        }
        mapOver(
          t match {
            case TypeRef(_, sym, args) =>
              checkNoEscape(sym)
              if (!hiddenSymbols.isEmpty && hiddenSymbols.head == sym &&
                  sym.isAliasType && sym.typeParams.length == args.length) {
                hiddenSymbols = hiddenSymbols.tail
                t.normalize
              } else t
            case SingleType(_, sym) =>
              checkNoEscape(sym)
              t
            case _ =>
              t
          })
      }
    }

    def reenterValueParams(vparamss: List[List[ValDef]]) {
      for (vparams <- vparamss)
        for (vparam <- vparams)
          vparam.symbol = context.scope enter vparam.symbol
    }

    def reenterTypeParams(tparams: List[TypeDef]): List[Symbol] =
      for (tparam <- tparams) yield {
        tparam.symbol = context.scope enter tparam.symbol
        tparam.symbol.deSkolemize
      }

    /** The qualifying class of a this or super with prefix <code>qual</code>.
     *
     *  @param tree ...
     *  @param qual ...
     *  @return     ...
     */
    def qualifyingClassContext(tree: Tree, qual: Name, packageOK: Boolean): Context = {
      var c = context.enclClass
      if (!qual.isEmpty) {
        while (c != NoContext && c.owner.name != qual) c = c.outer.enclClass
      }
      if (c == NoContext || !(packageOK || c.enclClass.tree.isInstanceOf[Template]))
	  error(
	    tree.pos,
	    if (qual.isEmpty) tree+" can be used only in a class, object, or template"
	    else qual+" is not an enclosing class")
      c
    }

    /** The typer for an expression, depending on where we are. If we are before a superclass
     *  call, this is a typer over a constructor context; otherwise it is the current typer.
     */
    def constrTyperIf(inConstr: Boolean): Typer =
      if (inConstr) {
        assert(context.undetparams.isEmpty)
        newTyper(context.makeConstructorContext)
      } else this

    /** The typer for a label definition. If this is part of a template we
     *  first have to enter the label definition.
     */
    def labelTyper(ldef: LabelDef): Typer =
      if (ldef.symbol == NoSymbol) { // labeldef is part of template
        val typer1 = newTyper(context.makeNewScope(ldef, context.owner)(LabelScopeKind))
        typer1.enterLabelDef(ldef)
        typer1
      } else this

    final val xtypes = false

    /** Does the context of tree <code>tree</code> require a stable type?
     */
    private def isStableContext(tree: Tree, mode: Int, pt: Type) =
      isNarrowable(tree.tpe) && ((mode & (EXPRmode | LHSmode)) == EXPRmode) &&
      (xtypes ||
      (pt.isStable ||
       (mode & QUALmode) != 0 && !tree.symbol.isConstant ||
       pt.typeSymbol.isAbstractType && pt.bounds.lo.isStable && !(tree.tpe <:< pt)) ||
       pt.typeSymbol.isRefinementClass && !(tree.tpe <:< pt))

    /** Make symbol accessible. This means:
     *  If symbol refers to package object, insert `.package` as second to last selector.
     *  Call checkAccessible, which sets symbol's attributes.
     */
    private def makeAccessible(tree: Tree, sym: Symbol, pre: Type, site: Tree): Tree =
      if (isInPackageObject(sym, pre.typeSymbol)) {
        val qual = typedQualifier {
          tree match {
            case Ident(_) => Ident(nme.PACKAGEkw)
            case Select(qual, _) => Select(qual, nme.PACKAGEkw)
            case SelectFromTypeTree(qual, _) => Select(qual, nme.PACKAGEkw)
          }
        }
        val tree1 = tree match {
          case Ident(name) => Select(qual, name)
          case Select(_, name) => Select(qual, name)
          case SelectFromTypeTree(_, name) => SelectFromTypeTree(qual, name)
        }
        val tree2 = checkAccessible(tree1, sym, qual.tpe, qual)
        tree2
      } else {
        checkAccessible(tree, sym, pre, site)
      }

    private def isInPackageObject(sym: Symbol, pkg: Symbol) =
      pkg.isPackageClass &&
      sym.owner.isModuleClass &&
      sym.owner.name.toTermName == nme.PACKAGEkw &&
      sym.owner.owner == pkg

    /** Post-process an identifier or selection node, performing the following:
     *  1. Check that non-function pattern expressions are stable
     *  2. Check that packages and static modules are not used as values
     *  3. Turn tree type into stable type if possible and required by context.
     *  </ol>
     */
    private def stabilize(tree: Tree, pre: Type, mode: Int, pt: Type): Tree = {
      def isNotAValue(sym: Symbol) =    // bug #1392
        !sym.isValue || (sym.isModule && isValueClass(sym.linkedClassOfModule))

      if (tree.symbol.hasFlag(OVERLOADED) && (mode & FUNmode) == 0)
        inferExprAlternative(tree, pt)
      val sym = tree.symbol
      if (tree.tpe.isError) tree
      else if ((mode & (PATTERNmode | FUNmode)) == PATTERNmode && tree.isTerm) { // (1)
        checkStable(tree)
      } else if ((mode & (EXPRmode | QUALmode)) == EXPRmode && isNotAValue(sym) && !phase.erasedTypes) { // (2)
        errorTree(tree, sym+" is not a value")
      } else {
        if (sym.isStable && pre.isStable && tree.tpe.typeSymbol != ByNameParamClass &&
            (isStableContext(tree, mode, pt) || sym.isModule && !sym.isMethod))
          tree.setType(singleType(pre, sym))
        else tree
      }
    }

    private def isNarrowable(tpe: Type): Boolean = tpe match {
      case TypeRef(_, _, _) | RefinedType(_, _) => true
      case ExistentialType(_, tpe1) => isNarrowable(tpe1)
      case AnnotatedType(_, tpe1, _) => isNarrowable(tpe1)
      case PolyType(_, tpe1) => isNarrowable(tpe1)
      case _ => !phase.erasedTypes
    }

    private def stabilizedType(tree: Tree): Type = tree.tpe
/*{
      val sym = tree.symbol
      val res = tree match {
        case Ident(_) if (sym.isStable) =>
          val pre = if (sym.owner.isClass) sym.owner.thisType else NoPrefix
          singleType(pre, sym)
        case Select(qual, _) if (qual.tpe.isStable && sym.isStable) =>
          singleType(qual.tpe, sym)
        case _ =>
          tree.tpe
      }
      res
    }
*/
    /**
     *  @param tree ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    def stabilizeFun(tree: Tree, mode: Int, pt: Type): Tree = {
      val sym = tree.symbol
      val pre = tree match {
        case Select(qual, _) => qual.tpe
        case _ => NoPrefix
      }
      if (tree.tpe.isInstanceOf[MethodType] && pre.isStable && sym.tpe.paramTypes.isEmpty &&
          (isStableContext(tree, mode, pt) || sym.isModule))
        tree.setType(MethodType(List(), singleType(pre, sym)))
      else tree
    }

    /** The member with given name of given qualifier tree */
    def member(qual: Tree, name: Name)(from : Symbol) = qual.tpe match {
      case ThisType(clazz) if (context.enclClass.owner.hasTransOwner(clazz)) =>
        qual.tpe.member(name)
      case _  =>
        if (phase.next.erasedTypes) qual.tpe.member(name)
        else qual.tpe.nonLocalMember(name)(from)
    }

    def silent(op: Typer => Tree): AnyRef /* in fact, TypeError or Tree */ = try {
      if (context.reportGeneralErrors) {
        val context1 = context.makeSilent(context.reportAmbiguousErrors)
        context1.undetparams = context.undetparams
        context1.savedTypeBounds = context.savedTypeBounds
        val typer1 = newTyper(context1)
        val result = op(typer1)
        context.undetparams = context1.undetparams
        context.savedTypeBounds = context1.savedTypeBounds
        result
      } else {
        op(this)
      }
    } catch {
      case ex: CyclicReference => throw ex
      case ex: TypeError => ex
    }

    /** Perform the following adaptations of expression, pattern or type `tree' wrt to
     *  given mode `mode' and given prototype `pt':
     *  (-1) For expressions with annotated types, let AnnotationCheckers decide what to do
     *  (0) Convert expressions with constant types to literals
     *  (1) Resolve overloading, unless mode contains FUNmode
     *  (2) Apply parameterless functions
     *  (3) Apply polymorphic types to fresh instances of their type parameters and
     *      store these instances in context.undetparams,
     *      unless followed by explicit type application.
     *  (4) Do the following to unapplied methods used as values:
     *  (4.1) If the method has only implicit parameters pass implicit arguments
     *  (4.2) otherwise, if `pt' is a function type and method is not a constructor,
     *        convert to function by eta-expansion,
     *  (4.3) otherwise, if the method is nullary with a result type compatible to `pt'
     *        and it is not a constructor, apply it to ()
     *  otherwise issue an error
     *  (5) Convert constructors in a pattern as follows:
     *  (5.1) If constructor refers to a case class factory, set tree's type to the unique
     *        instance of its primary constructor that is a subtype of the expected type.
     *  (5.2) If constructor refers to an exractor, convert to application of
     *        unapply or unapplySeq method.
     *
     *  (6) Convert all other types to TypeTree nodes.
     *  (7) When in TYPEmode but not FUNmode or HKmode, check that types are fully parameterized
     *      (7.1) In HKmode, higher-kinded types are allowed, but they must have the expected kind-arity
     *  (8) When in both EXPRmode and FUNmode, add apply method calls to values of object type.
     *  (9) If there are undetermined type variables and not POLYmode, infer expression instance
     *  Then, if tree's type is not a subtype of expected type, try the following adaptations:
     *  (10) If the expected type is Byte, Short or Char, and the expression
     *      is an integer fitting in the range of that type, convert it to that type.
     *  (11) Widen numeric literals to their expected type, if necessary
     *  (12) When in mode EXPRmode, convert E to { E; () } if expected type is scala.Unit.
     *  (13) When in mode EXPRmode, apply a view
     *  If all this fails, error
     */
    protected def adapt(tree: Tree, mode: Int, pt: Type): Tree = tree.tpe match {
      case atp @ AnnotatedType(_, _, _) if canAdaptAnnotations(tree, mode, pt) => // (-1)
        adaptAnnotations(tree, mode, pt)
      case ct @ ConstantType(value) if ((mode & (TYPEmode | FUNmode)) == 0 && (ct <:< pt) && !inIDE) => // (0)
        copy.Literal(tree, value)
      case OverloadedType(pre, alts) if ((mode & FUNmode) == 0) => // (1)
        inferExprAlternative(tree, pt)
        adapt(tree, mode, pt)
      case PolyType(List(), restpe) => // (2)
        adapt(tree setType restpe, mode, pt)
      case TypeRef(_, sym, List(arg))
      if ((mode & EXPRmode) != 0 && sym == ByNameParamClass) => // (2)
        adapt(tree setType arg, mode, pt)
      case tr @ TypeRef(_, sym, _)
      if sym.isAliasType && tr.normalize.isInstanceOf[ExistentialType] &&
        ((mode & (EXPRmode | LHSmode)) == EXPRmode) =>
        adapt(tree setType tr.normalize.skolemizeExistential(context.owner, tree), mode, pt)
      case et @ ExistentialType(_, _) if ((mode & (EXPRmode | LHSmode)) == EXPRmode) =>
        adapt(tree setType et.skolemizeExistential(context.owner, tree), mode, pt)
      case PolyType(tparams, restpe) if ((mode & (TAPPmode | PATTERNmode)) == 0) => // (3)
        assert((mode & HKmode) == 0) //@M
        val tparams1 = cloneSymbols(tparams)
        val tree1 = if (tree.isType) tree
                    else TypeApply(tree, tparams1 map (tparam =>
                      TypeTree(tparam.tpe) setOriginal tree)) setPos tree.pos
        context.undetparams = context.undetparams ::: tparams1
        adapt(tree1 setType restpe.substSym(tparams, tparams1), mode, pt)
      case mt: ImplicitMethodType if ((mode & (EXPRmode | FUNmode | LHSmode)) == EXPRmode) => // (4.1)
        if (!context.undetparams.isEmpty && (mode & POLYmode) == 0) { // (9)
          context.undetparams = inferExprInstance(
            tree, context.extractUndetparams(), pt, mt.paramTypes exists isManifest)
              // if we are looking for a manifest, instantiate type to Nothing anyway,
              // as we would get amnbiguity errors otherwise. Example
              // Looking for a manifest of Nil: This mas many potential types,
              // so we need to instantiate to minimal type List[Nothing].
        }
        val typer1 = constrTyperIf(treeInfo.isSelfOrSuperConstrCall(tree))
        typer1.typed(typer1.applyImplicitArgs(tree), mode, pt)
      case mt: MethodType
      if (((mode & (EXPRmode | FUNmode | LHSmode)) == EXPRmode) &&
          (context.undetparams.isEmpty || (mode & POLYmode) != 0)) =>
        val meth = tree.symbol
        if (!meth.isConstructor &&
            //isCompatible(tparamsToWildcards(mt, context.undetparams), pt) &&
            isFunctionType(pt))/* &&
            (pt <:< functionType(mt.paramTypes map (t => WildcardType), WildcardType)))*/ { // (4.2)
          if (settings.debug.value) log("eta-expanding "+tree+":"+tree.tpe+" to "+pt)
          checkParamsConvertible(tree.pos, tree.tpe)
          val tree1 = etaExpand(context.unit, tree)
//          println("eta "+tree+" ---> "+tree1+":"+tree1.tpe)
          typed(tree1, mode, pt)
        } else if (!meth.isConstructor && mt.paramTypes.isEmpty) { // (4.3)
          adapt(typed(Apply(tree, List()) setPos tree.pos), mode, pt)
        } else if (context.implicitsEnabled) {
          errorTree(tree, "missing arguments for "+meth+meth.locationString+
                    (if (meth.isConstructor) ""
                     else ";\nfollow this method with `_' if you want to treat it as a partially applied function"))
        } else {
          setError(tree)
        }
      case _ =>
        def applyPossible = {
          def applyMeth = member(adaptToName(tree, nme.apply), nme.apply)(context.owner)
          if ((mode & TAPPmode) != 0)
            tree.tpe.typeParams.isEmpty && applyMeth.filter(! _.tpe.typeParams.isEmpty) != NoSymbol
          else
            applyMeth.filter(_.tpe.paramSectionCount > 0) != NoSymbol
        }
        if (tree.isType) {
          if ((mode & FUNmode) != 0) {
            tree
          } else if (tree.hasSymbol && !tree.symbol.typeParams.isEmpty && (mode & HKmode) == 0 &&
                     !(tree.symbol.hasFlag(JAVA) && context.unit.isJava)) { // (7)
            // @M When not typing a higher-kinded type ((mode & HKmode) == 0)
            // or raw type (tree.symbol.hasFlag(JAVA) && context.unit.isJava), types must be of kind *,
            // and thus parameterised types must be applied to their type arguments
            // @M TODO: why do kind-* tree's have symbols, while higher-kinded ones don't?
            errorTree(tree, tree.symbol+" takes type parameters")
            tree setType tree.tpe
          } else if ( // (7.1) @M: check kind-arity
                    // @M: removed check for tree.hasSymbol and replace tree.symbol by tree.tpe.symbol (TypeTree's must also be checked here, and they don't directly have a symbol)
                     ((mode & HKmode) != 0) &&
                    // @M: don't check tree.tpe.symbol.typeParams. check tree.tpe.typeParams!!!
                    // (e.g., m[Int] --> tree.tpe.symbol.typeParams.length == 1, tree.tpe.typeParams.length == 0!)
                     tree.tpe.typeParams.length != pt.typeParams.length &&
                     !(tree.tpe.typeSymbol==AnyClass ||
                       tree.tpe.typeSymbol==NothingClass ||
                       pt == WildcardType )) {
              // Check that the actual kind arity (tree.symbol.typeParams.length) conforms to the expected
              // kind-arity (pt.typeParams.length). Full checks are done in checkKindBounds in Infer.
              // Note that we treat Any and Nothing as kind-polymorphic.
              // We can't perform this check when typing type arguments to an overloaded method before the overload is resolved
              // (or in the case of an error type) -- this is indicated by pt == WildcardType (see case TypeApply in typed1).
              errorTree(tree, tree.tpe+" takes "+reporter.countElementsAsString(tree.tpe.typeParams.length, "type parameter")+
                              ", expected: "+reporter.countAsString(pt.typeParams.length))
              tree setType tree.tpe
          } else tree match { // (6)
            case TypeTree() => tree
            case _ => TypeTree(tree.tpe) setOriginal(tree)
          }
        } else if ((mode & (PATTERNmode | FUNmode)) == (PATTERNmode | FUNmode)) { // (5)
          val extractor = tree.symbol.filter(sym => unapplyMember(sym.tpe).exists)
          if (extractor != NoSymbol) {
            tree setSymbol extractor
            val unapply = unapplyMember(extractor.tpe)
            val clazz = if (unapply.tpe.paramTypes.length == 1) unapply.tpe.paramTypes.head.typeSymbol
                        else NoSymbol
            if ((unapply hasFlag CASE) && (clazz hasFlag CASE) &&
                !(clazz.info.baseClasses.tail exists (_ hasFlag CASE))) {
              if (!phase.erasedTypes) checkStable(tree) //todo: do we need to demand this?
              // convert synthetic unapply of case class to case class constructor
              val prefix = tree.tpe.prefix
              val tree1 = TypeTree(clazz.primaryConstructor.tpe.asSeenFrom(prefix, clazz.owner))
                  .setOriginal(tree)
              try {
                inferConstructorInstance(tree1, clazz.typeParams, pt)
              } catch {
                case tpe : TypeError => throw tpe
                case t : Exception =>
                  logError("CONTEXT: " + (tree.pos).dbgString, t)
                  throw t
              }
              tree1
            } else {
              tree
            }
          } else {
            errorTree(tree, tree.symbol + " is not a case class constructor, nor does it have an unapply/unapplySeq method")
          }
        } else if ((mode & (EXPRmode | FUNmode)) == (EXPRmode | FUNmode) &&
                   !tree.tpe.isInstanceOf[MethodType] &&
                   !tree.tpe.isInstanceOf[OverloadedType] &&
                   applyPossible) {
          assert((mode & HKmode) == 0) //@M
          val qual = adaptToName(tree, nme.apply) match {
            case id @ Ident(_) =>
              val pre = if (id.symbol.owner.isPackageClass) id.symbol.owner.thisType
                        else if (id.symbol.owner.isClass)
                          context.enclosingSubClassContext(id.symbol.owner).prefix
                        else NoPrefix
              stabilize(id, pre, EXPRmode | QUALmode, WildcardType)
            case sel @ Select(qualqual, _) =>
              stabilize(sel, qualqual.tpe, EXPRmode | QUALmode, WildcardType)
            case other =>
              other
          }
          typed(atPos(tree.pos)(Select(qual, nme.apply)), mode, pt)
        } else if (!context.undetparams.isEmpty && (mode & POLYmode) == 0) { // (9)
          assert((mode & HKmode) == 0) //@M
          instantiate(tree, mode, pt)
        } else if (tree.tpe <:< pt) {
          def isStructuralType(tpe: Type): Boolean = tpe match {
            case RefinedType(ps, decls) =>
              decls.toList exists (x => x.isTerm && x.allOverriddenSymbols.isEmpty)
            case _ =>
              false
          }
          if (isStructuralType(pt) && tree.tpe.typeSymbol == ArrayClass) {
            // all Arrays used as structural refinement typed values must be boxed
            // this does not solve the case where the type to be adapted to comes
            // from a type variable that was bound by a strctural but is instantiated
            typed(Apply(Select(gen.mkAttributedRef(ScalaRunTimeModule), nme.forceBoxedArray), List(tree)))
          }
          else
            tree
        } else {
          if ((mode & PATTERNmode) != 0) {
            if ((tree.symbol ne null) && tree.symbol.isModule)
              inferModulePattern(tree, pt)
            if (isPopulated(tree.tpe, approximateAbstracts(pt)))
              return tree
          }
          val tree1 = constfold(tree, pt) // (10) (11)
          if (tree1.tpe <:< pt) adapt(tree1, mode, pt)
          else {
            if ((mode & (EXPRmode | FUNmode)) == EXPRmode) {
              pt.normalize match {
                case TypeRef(_, sym, _) =>
                  // note: was if (pt.typeSymbol == UnitClass) but this leads to a potentially
                  // infinite expansion if pt is constant type ()
                  if (sym == UnitClass && tree.tpe <:< AnyClass.tpe) // (12)
                    return typed(atPos(tree.pos)(Block(List(tree), Literal(()))), mode, pt)
                case _ =>
              }
              if (!context.undetparams.isEmpty) {
                return instantiate(tree, mode, pt)
              }
              if (context.implicitsEnabled && !tree.tpe.isError && !pt.isError) {
                // (13); the condition prevents chains of views
                if (settings.debug.value) log("inferring view from "+tree.tpe+" to "+pt)
                val coercion = inferView(tree, tree.tpe, pt, true)
                // convert forward views of delegate types into closures wrapped around
                // the delegate's apply method (the "Invoke" method, which was translated into apply)
                if (forMSIL && coercion != null && isCorrespondingDelegate(tree.tpe, pt)) {
                  val meth: Symbol = tree.tpe.member(nme.apply)
                  if(settings.debug.value)
                    log("replacing forward delegate view with: " + meth + ":" + meth.tpe)
                  return typed(Select(tree, meth), mode, pt)
                }
                if (coercion != EmptyTree) {
                  if (settings.debug.value) log("inferred view from "+tree.tpe+" to "+pt+" = "+coercion+":"+coercion.tpe)
                  return newTyper(context.makeImplicit(context.reportAmbiguousErrors)).typed(
                      Apply(coercion, List(tree)) setPos tree.pos, mode, pt)
                }
              }
            }
            if (settings.debug.value) {
              log("error tree = "+tree)
              if (settings.explaintypes.value) explainTypes(tree.tpe, pt)
            }
            typeErrorTree(tree, tree.tpe, pt)
          }
        }
    }

    /**
     *  @param tree ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    def instantiate(tree: Tree, mode: Int, pt: Type): Tree = {
      inferExprInstance(tree, context.extractUndetparams(), pt, true)
      adapt(tree, mode, pt)
    }

    /**
     *  @param qual ...
     *  @param name ...
     *  @param tp   ...
     *  @return     ...
     */
    def adaptToMember(qual: Tree, name: Name, tp: Type): Tree = {
      val qtpe = qual.tpe.widen
      if (qual.isTerm &&
          ((qual.symbol eq null) || !qual.symbol.isTerm || qual.symbol.isValue) &&
          phase.id <= currentRun.typerPhase.id && !qtpe.isError && !tp.isError &&
          qtpe.typeSymbol != NullClass && qtpe.typeSymbol != NothingClass && qtpe != WildcardType) {
        val coercion = inferView(qual, qtpe, name, tp)
        if (coercion != EmptyTree)
          typedQualifier(atPos(qual.pos)(Apply(coercion, List(qual))))
        else qual
      } else qual
    }

    def adaptToName(qual: Tree, name: Name) =
      if (member(qual, name)(context.owner) != NoSymbol) qual
      else adaptToMember(qual, name, WildcardType)

    private def typePrimaryConstrBody(clazz : Symbol, cbody: Tree, tparams: List[Symbol], enclTparams: List[Symbol], vparamss: List[List[ValDef]]): Tree = {
      // XXX: see about using the class's symbol....
      enclTparams foreach (sym => context.scope.enter(sym))
      namer.enterValueParams(context.owner, vparamss)
      typed(cbody)
    }

    def parentTypes(templ: Template): List[Tree] =
      if (templ.parents.isEmpty) List()
      else try {
        val clazz = context.owner

        // Normalize supertype and mixins so that supertype is always a class, not a trait.
        var supertpt = typedTypeConstructor(templ.parents.head)
        val firstParent = supertpt.tpe.typeSymbol
        var mixins = templ.parents.tail map typedType
        // If first parent is a trait, make it first mixin and add its superclass as first parent
        while ((supertpt.tpe.typeSymbol ne null) && supertpt.tpe.typeSymbol.initialize.isTrait) {
          val supertpt1 = typedType(supertpt)
          if (!supertpt1.tpe.isError) {
            mixins = supertpt1 :: mixins
            supertpt = TypeTree(supertpt1.tpe.parents.head) setOriginal supertpt /* setPos supertpt.pos */
          }
        }

        // Determine
        //  - supertparams: Missing type parameters from supertype
        //  - supertpe: Given supertype, polymorphic in supertparams
        val supertparams = if (supertpt.hasSymbol) supertpt.symbol.typeParams else List()
        var supertpe = supertpt.tpe
        if (!supertparams.isEmpty)
          supertpe = PolyType(supertparams, appliedType(supertpe, supertparams map (_.tpe)))

        // A method to replace a super reference by a New in a supercall
        def transformSuperCall(scall: Tree): Tree = (scall: @unchecked) match {
          case Apply(fn, args) =>
            copy.Apply(scall, transformSuperCall(fn), args map (_.duplicate))
          case Select(Super(_, _), nme.CONSTRUCTOR) =>
            copy.Select(
              scall,
              New(TypeTree(supertpe) setOriginal supertpt) setType supertpe setPos supertpt.pos,
              nme.CONSTRUCTOR)
        }

        treeInfo.firstConstructor(templ.body) match {
          case constr @ DefDef(_, _, _, vparamss, _, cbody @ Block(cstats, cunit)) =>
            // Convert constructor body to block in environment and typecheck it
            val cstats1: List[Tree] = cstats map (_.duplicate)
            val scall = if (cstats.isEmpty) EmptyTree else cstats.last
            val cbody1 = scall match {
              case Apply(_, _) =>
                copy.Block(cbody, cstats1.init,
                           if (supertparams.isEmpty) cunit.duplicate
                           else transformSuperCall(scall))
              case _ =>
                copy.Block(cbody, cstats1, cunit.duplicate)
            }

            val outercontext = context.outer
            assert(clazz != NoSymbol)
            val cscope = outercontext.makeNewScope(constr, outercontext.owner)(ParentTypesScopeKind(clazz))
            val cbody2 = newTyper(cscope) // called both during completion AND typing.
                .typePrimaryConstrBody(clazz,
                  cbody1, supertparams, clazz.unsafeTypeParams, vparamss map (_.map(_.duplicate)))

            scall match {
              case Apply(_, _) =>
                val sarg = treeInfo.firstArgument(scall)
                if (sarg != EmptyTree && supertpe.typeSymbol != firstParent)
                  error(sarg.pos, firstParent+" is a trait; does not take constructor arguments")
                if (!supertparams.isEmpty) supertpt = TypeTree(cbody2.tpe) setPos supertpt.pos
              case _ =>
                if (!supertparams.isEmpty) error(supertpt.pos, "missing type arguments")
            }

            List.map2(cstats1, treeInfo.preSuperFields(templ.body)) {
              (ldef, gdef) => gdef.tpt.tpe = ldef.symbol.tpe
            }
          case _ =>
            if (!supertparams.isEmpty) error(supertpt.pos, "missing type arguments")
        }
/* experimental: early types as type arguments
        val hasEarlyTypes = templ.body exists (treeInfo.isEarlyTypeDef)
        val earlyMap = new EarlyMap(clazz)
        List.mapConserve(supertpt :: mixins){ tpt =>
          val tpt1 = checkNoEscaping.privates(clazz, tpt)
          if (hasEarlyTypes) tpt1 else tpt1 setType earlyMap(tpt1.tpe)
        }
*/

        //Console.println("parents("+clazz") = "+supertpt :: mixins);//DEBUG
        List.mapConserve(supertpt :: mixins)(tpt => checkNoEscaping.privates(clazz, tpt))
      } catch {
        case ex: TypeError =>
          templ.tpe = null
          reportTypeError(templ.pos, ex)
          List(TypeTree(AnyRefClass.tpe))
      }

    /** <p>Check that</p>
     *  <ul>
     *    <li>all parents are class types,</li>
     *    <li>first parent class is not a mixin; following classes are mixins,</li>
     *    <li>final classes are not inherited,</li>
     *    <li>
     *      sealed classes are only inherited by classes which are
     *      nested within definition of base class, or that occur within same
     *      statement sequence,
     *    </li>
     *    <li>self-type of current class is a subtype of self-type of each parent class.</li>
     *    <li>no two parents define same symbol.</li>
     *  </ul>
     */
    def validateParentClasses(parents: List[Tree], selfType: Type) {

      def validateParentClass(parent: Tree, superclazz: Symbol) {
        if (!parent.tpe.isError) {
          val psym = parent.tpe.typeSymbol.initialize
          checkClassType(parent, false)
          if (psym != superclazz) {
            if (psym.isTrait) {
              val ps = psym.info.parents
              if (!ps.isEmpty && !superclazz.isSubClass(ps.head.typeSymbol))
                error(parent.pos, "illegal inheritance; super"+superclazz+
                      "\n is not a subclass of the super"+ps.head.typeSymbol+
                      "\n of the mixin " + psym);
            } else {
              error(parent.pos, psym+" needs to be a trait be mixed in")
            }
          }
          if (psym hasFlag FINAL) {
            error(parent.pos, "illegal inheritance from final "+psym)
          }
          if (psym.isSealed && !phase.erasedTypes) {
            if (context.unit.source.file != psym.sourceFile)
              error(parent.pos, "illegal inheritance from sealed "+psym)
            else
              psym addChild context.owner
          }
          if (!(selfType <:< parent.tpe.typeOfThis) &&
              !phase.erasedTypes &&
              !(context.owner hasFlag SYNTHETIC) && // don't do this check for synthetic concrete classes for virtuals (part of DEVIRTUALIZE)
	      !(settings.suppressVTWarn.value))
          {
            //Console.println(context.owner);//DEBUG
            //Console.println(context.owner.unsafeTypeParams);//DEBUG
            //Console.println(List.fromArray(context.owner.info.closure));//DEBUG
            // disable in IDE, don't know how else to avoid it on refresh
            if (!inIDE) error(parent.pos, "illegal inheritance;\n self-type "+
                  selfType+" does not conform to "+parent +
                  "'s selftype "+parent.tpe.typeOfThis)
            if (settings.explaintypes.value) explainTypes(selfType, parent.tpe.typeOfThis)
          }
          if (parents exists (p => p != parent && p.tpe.typeSymbol == psym && !psym.isError))
            error(parent.pos, psym+" is inherited twice")
        }
      }

      if (!parents.isEmpty && !parents.head.tpe.isError)
        for (p <- parents) validateParentClass(p, parents.head.tpe.typeSymbol)

/*
      if (settings.Xshowcls.value != "" &&
          settings.Xshowcls.value == context.owner.fullNameString)
        println("INFO "+context.owner+
                ", baseclasses = "+(context.owner.info.baseClasses map (_.fullNameString))+
                ", lin = "+(context.owner.info.baseClasses map (context.owner.thisType.baseType)))
*/
    }

    def checkFinitary(classinfo: ClassInfoType) {
      val clazz = classinfo.typeSymbol
      for (tparam <- clazz.typeParams) {
        if (classinfo.expansiveRefs(tparam) contains tparam) {
          error(tparam.pos, "class graph is not finitary because type parameter "+tparam.name+" is expansively recursive")
          val newinfo = ClassInfoType(
            classinfo.parents map (_.instantiateTypeParams(List(tparam), List(AnyRefClass.tpe))),
            classinfo.decls,
            clazz)
          clazz.setInfo {
            clazz.info match {
              case PolyType(tparams, _) => PolyType(tparams, newinfo)
              case _ => newinfo
            }
          }
        }
      }
    }

    /**
     *  @param cdef ...
     *  @return     ...
     */
    def typedClassDef(cdef: ClassDef): Tree = {
//      attributes(cdef)
      val typedMods = typedModifiers(cdef.mods)
      val clazz = cdef.symbol;
      if (inIDE && clazz == NoSymbol) {
        throw new TypeError("type signature typing failed")
      }
      assert(clazz != NoSymbol)
      reenterTypeParams(cdef.tparams)
      val tparams1 = List.mapConserve(cdef.tparams)(typedTypeDef)
      val impl1 = newTyper(context.make(cdef.impl, clazz, scopeFor(cdef.impl, TypedDefScopeKind)))
        .typedTemplate(cdef.impl, parentTypes(cdef.impl))
      val impl2 = addSyntheticMethods(impl1, clazz, context)
      if ((clazz != ClassfileAnnotationClass) &&
	  (clazz isNonBottomSubClass ClassfileAnnotationClass))
	unit.warning (cdef.pos,
          "implementation restriction: subclassing Classfile does not\n"+
          "make your annotation visible at runtime.  If that is what\n"+
	  "you want, you must write the annotation class in Java.")
      copy.ClassDef(cdef, typedMods, cdef.name, tparams1, impl2)
        .setType(NoType)
    }

    /**
     *  @param mdef ...
     *  @return     ...
     */
    def typedModuleDef(mdef: ModuleDef): Tree = {
      //Console.println("sourcefile of " + mdef.symbol + "=" + mdef.symbol.sourceFile)
//      attributes(mdef)
      val typedMods = typedModifiers(mdef.mods)
      val clazz = mdef.symbol.moduleClass
      if (inIDE && clazz == NoSymbol) throw new TypeError("bad signature")
      assert(clazz != NoSymbol)
      val impl1 = newTyper(context.make(mdef.impl, clazz, scopeFor(mdef.impl, TypedDefScopeKind)))
        .typedTemplate(mdef.impl, parentTypes(mdef.impl))
      val impl2 = addSyntheticMethods(impl1, clazz, context)

      copy.ModuleDef(mdef, typedMods, mdef.name, impl2) setType NoType
    }

    /**
     *  @param stat ...
     *  @return     ...
     */
    def addGetterSetter(stat: Tree): List[Tree] = stat match {
      case ValDef(mods, name, tpt, rhs)
        if (mods.flags & (PRIVATE | LOCAL)) != (PRIVATE | LOCAL)
          && !stat.symbol.isModuleVar
          && !stat.symbol.hasFlag(LAZY) =>
        val vdef = copy.ValDef(stat, mods | PRIVATE | LOCAL, nme.getterToLocal(name), tpt, rhs)
        val value = vdef.symbol
        val getter = if ((mods hasFlag DEFERRED)) value else value.getter(value.owner)
        // XXX:
        if (inIDE && getter == NoSymbol)
          return Nil
        assert(getter != NoSymbol, stat)
        if (getter hasFlag OVERLOADED)
          error(getter.pos, getter+" is defined twice")
        val getterDef: DefDef = {
          getter.attributes = value.initialize.attributes
          val result = DefDef(getter, vparamss =>
              if (mods hasFlag DEFERRED) EmptyTree
              else typed(
                atPos(vdef.pos) { gen.mkCheckInit(Select(This(value.owner), value)) },
                EXPRmode, value.tpe))
          result.tpt.asInstanceOf[TypeTree] setOriginal tpt /* setPos tpt.pos */
          checkNoEscaping.privates(getter, result.tpt)
          copy.DefDef(result, result.mods withAnnotations mods.annotations, result.name,
                      result.tparams, result.vparamss, result.tpt, result.rhs)
          //todo: withAnnotations is probably unnecessary
        }
        def setterDef: DefDef = {
          val setr = getter.setter(value.owner)
          setr.attributes = value.attributes
          val result = atPos(vdef.pos)(
            DefDef(setr, vparamss =>
              if ((mods hasFlag DEFERRED) || (setr hasFlag OVERLOADED))
                EmptyTree
              else
                typed(Assign(Select(This(value.owner), value),
                             Ident(vparamss.head.head)))))
          copy.DefDef(result, result.mods withAnnotations mods.annotations, result.name,
                      result.tparams, result.vparamss, result.tpt, result.rhs)
        }
        val gs = if (mods hasFlag MUTABLE) List(getterDef, setterDef)
                 else List(getterDef)
        if (mods hasFlag DEFERRED) gs else vdef :: gs

      case DocDef(comment, defn) =>
        addGetterSetter(defn) map (stat => DocDef(comment, stat))

      case Annotated(annot, defn) =>
        addGetterSetter(defn) map (stat => Annotated(annot, stat))

      case _ =>
        List(stat)
    }

    protected def enterSyms(txt: Context, trees: List[Tree]) = {
      var txt0 = txt
      for (tree <- trees) txt0 = enterSym(txt0, tree)
    }

    protected def enterSym(txt: Context, tree: Tree): Context =
      if (txt eq context) namer.enterSym(tree)
      else newNamer(txt).enterSym(tree)

    /**
     *  @param templ    ...
     *  @param parents1 ...
     *    <li> <!-- 2 -->
     *      Check that inner classes do not inherit from Annotation
     *    </li>
     *  @return         ...
     */
    def typedTemplate(templ: Template, parents1: List[Tree]): Template = {
      val clazz = context.owner
      if (templ.symbol == NoSymbol)
        templ setSymbol newLocalDummy(clazz, templ.pos)
      val self1 = templ.self match {
        case vd @ ValDef(mods, name, tpt, EmptyTree) =>
          val tpt1 = checkNoEscaping.privates(clazz.thisSym, typedType(tpt))
          copy.ValDef(vd, mods, name, tpt1, EmptyTree) setType NoType
      }
      if (self1.name != nme.WILDCARD) context.scope enter self1.symbol
      val selfType =
        if (clazz.isAnonymousClass && !phase.erasedTypes)
          intersectionType(clazz.info.parents, clazz.owner)
        else clazz.typeOfThis
      // the following is necessary for templates generated later
      assert(clazz.info.decls != EmptyScope)
      enterSyms(context.outer.make(templ, clazz, clazz.info.decls), templ.body)
      validateParentClasses(parents1, selfType)
      if ((clazz isSubClass ClassfileAnnotationClass) && !clazz.owner.isPackageClass)
        unit.error(clazz.pos, "inner classes cannot be classfile annotations")
      if (!phase.erasedTypes && !clazz.info.resultType.isError) // @S: prevent crash for duplicated type members
        checkFinitary(clazz.info.resultType.asInstanceOf[ClassInfoType])
      val body =
        if (phase.id <= currentRun.typerPhase.id && !reporter.hasErrors)
          templ.body flatMap addGetterSetter
        else templ.body
      val body1 = typedStats(body, templ.symbol)
      copy.Template(templ, parents1, self1, body1) setType clazz.tpe
    }

    /** Type check the annotations within a set of modifiers.  */
    def typedModifiers(mods: Modifiers): Modifiers = {
      val Modifiers(flags, privateWithin, annotations) = mods
      val typedAnnots = annotations.map(typed(_).asInstanceOf[Annotation])
      Modifiers(flags, privateWithin, typedAnnots)
    }

    /**
     *  @param vdef ...
     *  @return     ...
     */
    def typedValDef(vdef: ValDef): ValDef = {
//      attributes(vdef)
      val sym = vdef.symbol
      val typer1 = constrTyperIf(sym.hasFlag(PARAM) && sym.owner.isConstructor)
      val typedMods = typedModifiers(vdef.mods)

      var tpt1 = checkNoEscaping.privates(sym, typer1.typedType(
        if (inIDE) vdef.tpt.duplicate // avoids wrong context sticking
        else vdef.tpt))
      checkNonCyclic(vdef, tpt1)
      val rhs1 =
        if (vdef.rhs.isEmpty) {
          if (sym.isVariable && sym.owner.isTerm && phase.id <= currentRun.typerPhase.id)
            error(vdef.pos, "local variables must be initialized")
          vdef.rhs
        } else {
          //assert(vdef.rhs.tpe == null)
          val rhs = if (inIDE && vdef.rhs.tpe != null) vdef.rhs.duplicate else vdef.rhs
          newTyper(typer1.context.make(vdef, sym)).transformedOrTyped(rhs, tpt1.tpe)
        }
      copy.ValDef(vdef, typedMods, vdef.name, tpt1, checkDead(rhs1)) setType NoType
    }

    /** Enter all aliases of local parameter accessors.
     *
     *  @param clazz    ...
     *  @param vparamss ...
     *  @param rhs      ...
     */
    def computeParamAliases(clazz: Symbol, vparamss: List[List[ValDef]], rhs: Tree) {
      if (settings.debug.value) log("computing param aliases for "+clazz+":"+clazz.primaryConstructor.tpe+":"+rhs);//debug
      def decompose(call: Tree): (Tree, List[Tree]) = call match {
        case Apply(fn, args) =>
          val (superConstr, args1) = decompose(fn)
          val formals = (if (fn.tpe == null && inIDE) ErrorType else fn.tpe).paramTypes
          val args2 = if (formals.isEmpty || formals.last.typeSymbol != RepeatedParamClass) args
                      else args.take(formals.length - 1) ::: List(EmptyTree)
          if (args2.length != formals.length) {
            if (!inIDE)
              assert(false, "mismatch " + clazz + " " + formals + " " + args2);//debug
            else error(call.pos, "XXX: mismatch " + clazz + " " + formals + " " + args2)
          }
          (superConstr, args1 ::: args2)
        case Block(stats, expr) if !stats.isEmpty =>
          decompose(stats.last)
        case _ =>
          (call, List())
      }
      val (superConstr, superArgs) = decompose(rhs)
      assert(superConstr.symbol ne null)//debug

      // an object cannot be allowed to pass a reference to itself to a superconstructor
      // because of initialization issues; bug #473
      for {
        arg <- superArgs
        val sym = arg.symbol
        if sym != null && sym.isModule && (sym.info.baseClasses contains clazz)
      } error(rhs.pos, "super constructor cannot be passed a self reference unless parameter is declared by-name")

      if (superConstr.symbol.isPrimaryConstructor) {
        val superClazz = superConstr.symbol.owner
        if (!superClazz.hasFlag(JAVA)) {
          val superParamAccessors = superClazz.constrParamAccessors
          if (superParamAccessors.length == superArgs.length) {
            List.map2(superParamAccessors, superArgs) { (superAcc, superArg) =>
              superArg match {
                case Ident(name) =>
                  if (vparamss.exists(_.exists(_.symbol == superArg.symbol))) {
                    var alias = superAcc.initialize.alias
                    if (alias == NoSymbol)
                      alias = superAcc.getter(superAcc.owner)
                    if (alias != NoSymbol &&
                        superClazz.info.nonPrivateMember(alias.name) != alias)
                      alias = NoSymbol
                    if (alias != NoSymbol) {
                      var ownAcc = clazz.info.decl(name).suchThat(_.hasFlag(PARAMACCESSOR))
                      if ((ownAcc hasFlag ACCESSOR) && !ownAcc.isDeferred)
                        ownAcc = ownAcc.accessed
                      if (!ownAcc.isVariable && !alias.accessed.isVariable) {
                        if (settings.debug.value)
                          log("" + ownAcc + " has alias "+alias + alias.locationString);//debug
                        ownAcc.asInstanceOf[TermSymbol].setAlias(alias)
                      }
                    }
                  }
                case _ =>
              }
              ()
            }
          } else if (inIDE) { // XXX: maybe add later
            Console.println("" + superClazz + ":" +
              superClazz.info.decls.toList.filter(_.hasFlag(PARAMACCESSOR)))
            error(rhs.pos, "mismatch: " + superParamAccessors +
              ";" + rhs + ";" + superClazz.info.decls)//debug
            return
          }
        }
      }
    }

    private def checkStructuralCondition(refinement: Symbol, vparam: ValDef) {
      val tp = vparam.symbol.tpe
      if (tp.typeSymbol.isAbstractType && !(tp.typeSymbol.hasTransOwner(refinement)))
        error(vparam.tpt.pos,"Parameter type in structural refinement may not refer to abstract type defined outside that same refinement")
    }

    /**
     *  @param ddef ...
     *  @return     ...
     */
    def typedDefDef(ddef: DefDef): DefDef = {
      val meth = ddef.symbol
      if (inIDE && meth == NoSymbol) throw new TypeError("bad signature")
      reenterTypeParams(ddef.tparams)
      reenterValueParams(ddef.vparamss)
      val tparams1 = List.mapConserve(ddef.tparams)(typedTypeDef)
      val vparamss1 = List.mapConserve(ddef.vparamss)(vparams1 =>
        List.mapConserve(vparams1)(typedValDef))
      for (vparams1 <- vparamss1; if !vparams1.isEmpty; vparam1 <- vparams1.init) {
        if (vparam1.symbol.tpe.typeSymbol == RepeatedParamClass)
          error(vparam1.pos, "*-parameter must come last")
      }
      var tpt1 = checkNoEscaping.privates(meth, typedType(ddef.tpt))
      if (!settings.Xexperimental.value) {
        for (vparams <- vparamss1; vparam <- vparams) {
          checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); ()
        }
        checkNoEscaping.locals(context.scope, WildcardType, tpt1)
      }
      checkNonCyclic(ddef, tpt1)
      ddef.tpt.setType(tpt1.tpe)
      val typedMods = typedModifiers(ddef.mods)
      var rhs1 =
        if (ddef.name == nme.CONSTRUCTOR) {
          if (!meth.isPrimaryConstructor &&
              (!meth.owner.isClass ||
               meth.owner.isModuleClass ||
               meth.owner.isAnonymousClass ||
               meth.owner.isRefinementClass))
            error(ddef.pos, "constructor definition not allowed here")
          typed(ddef.rhs)
        } else {
          if (inIDE && ddef.rhs == EmptyTree) EmptyTree
          else transformedOrTyped(ddef.rhs, tpt1.tpe)
        }
      if (meth.isPrimaryConstructor && meth.isClassConstructor &&
          phase.id <= currentRun.typerPhase.id && !reporter.hasErrors)
        computeParamAliases(meth.owner, vparamss1, rhs1)
      if (tpt1.tpe.typeSymbol != NothingClass && !context.returnsSeen) rhs1 = checkDead(rhs1)

      if (meth.owner.isRefinementClass && meth.allOverriddenSymbols.isEmpty)
        for (vparams <- ddef.vparamss; vparam <- vparams)
          checkStructuralCondition(meth.owner, vparam)

      copy.DefDef(ddef, typedMods, ddef.name, tparams1, vparamss1, tpt1, rhs1) setType NoType
    }

    def typedTypeDef(tdef: TypeDef): TypeDef = {
      reenterTypeParams(tdef.tparams) // @M!
      val tparams1 = List.mapConserve(tdef.tparams)(typedTypeDef) // @M!
      val typedMods = typedModifiers(tdef.mods)
      val rhs1 = checkNoEscaping.privates(tdef.symbol, typedType(tdef.rhs))
      checkNonCyclic(tdef.symbol)
      rhs1.tpe match {
        case TypeBounds(lo1, hi1) =>
          if (!(lo1 <:< hi1))
            error(tdef.pos, "lower bound "+lo1+" does not conform to upper bound "+hi1)
        case _ =>
      }
      copy.TypeDef(tdef, typedMods, tdef.name, tparams1, rhs1) setType NoType
    }

    private def enterLabelDef(stat: Tree) {
      stat match {
        case ldef @ LabelDef(_, _, _) =>
          if (ldef.symbol == NoSymbol)
            ldef.symbol = namer.enterInScope(
              context.owner.newLabel(ldef.pos, ldef.name) setInfo MethodType(List(), UnitClass.tpe))
        case _ =>
      }
    }

    def typedLabelDef(ldef: LabelDef): LabelDef = {
      val restpe = ldef.symbol.tpe.resultType
      val rhs1 = typed(ldef.rhs, restpe)
      ldef.params foreach (param => param.tpe = param.symbol.tpe)
      copy.LabelDef(ldef, ldef.name, ldef.params, rhs1) setType restpe
    }

    protected def typedFunctionIDE(fun : Function, txt : Context) = {}

    /**
     *  @param block ...
     *  @param mode  ...
     *  @param pt    ...
     *  @return      ...
     */
    def typedBlock(block: Block, mode: Int, pt: Type): Block = {
      if (context.retyping) {
        for (stat <- block.stats) {
          if (stat.isDef) context.scope.enter(stat.symbol)
        }
      }
      namer.enterSyms(block.stats)
      block.stats foreach enterLabelDef
      val stats1 = typedStats(block.stats, context.owner)
      val expr1 = typed(block.expr, mode & ~(FUNmode | QUALmode), pt)
      val block1 = copy.Block(block, stats1, expr1)
        .setType(if (treeInfo.isPureExpr(block)) expr1.tpe else expr1.tpe.deconst)
      //checkNoEscaping.locals(context.scope, pt, block1)
      block1
    }

    /**
     *  @param cdef   ...
     *  @param pattpe ...
     *  @param pt     ...
     *  @return       ...
     */
    def typedCase(cdef: CaseDef, pattpe: Type, pt: Type): CaseDef = {
      val pat1: Tree = typedPattern(cdef.pat, pattpe)
      val guard1: Tree = if (cdef.guard == EmptyTree) EmptyTree
                         else typed(cdef.guard, BooleanClass.tpe)
      var body1: Tree = typed(cdef.body, pt)
      if (!context.savedTypeBounds.isEmpty) {
        body1.tpe = context.restoreTypeBounds(body1.tpe)
        if (isFullyDefined(pt) && !(body1.tpe <:< pt)) {
          body1 =
            typed {
              atPos(body1.pos) {
                TypeApply(Select(body1, Any_asInstanceOf), List(TypeTree(pt))) // @M no need for pt.normalize here, is done in erasure
              }
            }
        }
      }
//    body1 = checkNoEscaping.locals(context.scope, pt, body1)
      copy.CaseDef(cdef, pat1, guard1, body1) setType body1.tpe
    }

    def typedCases(tree: Tree, cases: List[CaseDef], pattp0: Type, pt: Type): List[CaseDef] = {
      var pattp = pattp0
      List.mapConserve(cases) ( cdef =>
        newTyper(context.makeNewScope(cdef, context.owner)(TypedCasesScopeKind))
          .typedCase(cdef, pattp, pt))
/* not yet!
        cdef.pat match {
          case Literal(Constant(null)) =>
            if (!(pattp <:< NonNullClass.tpe))
              pattp = intersectionType(List(pattp, NonNullClass.tpe), context.owner)
          case _ =>
        }
        result
*/
    }

    /**
     *  @param fun  ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    def typedFunction(fun: Function, mode: Int, pt: Type): Tree = {
      val codeExpected = !forCLDC && !forMSIL && (pt.typeSymbol isNonBottomSubClass CodeClass)

      if (fun.vparams.length > definitions.MaxFunctionArity)
        return errorTree(fun, "implementation restricts functions to " + definitions.MaxFunctionArity + " parameters")

      def decompose(pt: Type): (Symbol, List[Type], Type) =
        if ((isFunctionType(pt)
             ||
             pt.typeSymbol == PartialFunctionClass &&
             fun.vparams.length == 1 && fun.body.isInstanceOf[Match])
             && // see bug901 for a reason why next conditions are neeed
            (pt.normalize.typeArgs.length - 1 == fun.vparams.length
             ||
             fun.vparams.exists(_.tpt.isEmpty)))
          (pt.typeSymbol, pt.normalize.typeArgs.init, pt.normalize.typeArgs.last)
        else
          (FunctionClass(fun.vparams.length), fun.vparams map (x => NoType), WildcardType)

      val (clazz, argpts, respt) = decompose(if (codeExpected) pt.normalize.typeArgs.head else pt)

      if (fun.vparams.length != argpts.length)
        errorTree(fun, "wrong number of parameters; expected = " + argpts.length)
      else {
        val vparamSyms = List.map2(fun.vparams, argpts) { (vparam, argpt) =>
          if (vparam.tpt.isEmpty) {
            vparam.tpt.tpe =
              if (isFullyDefined(argpt)) argpt
              else {
                fun match {
                  case etaExpansion(vparams, fn, args) if !codeExpected =>
                    silent(_.typed(fn, funMode(mode), pt)) match {
                      case fn1: Tree if context.undetparams.isEmpty =>
                        // if context,undetparams is not empty, the function was polymorphic,
                        // so we need the missing arguments to infer its type. See #871
                        //println("typing eta "+fun+":"+fn1.tpe+"/"+context.undetparams)
                        val ftpe = normalize(fn1.tpe) baseType FunctionClass(fun.vparams.length)
                        if (isFunctionType(ftpe) && isFullyDefined(ftpe))
                          return typedFunction(fun, mode, ftpe)
                      case _ =>
                    }
                  case _ =>
                }
                error(
                  vparam.pos,
                  "missing parameter type"+
                  (if (vparam.mods.hasFlag(SYNTHETIC)) " for expanded function "+fun
                   else ""))
                ErrorType
              }
          }
          enterSym(context, vparam)
          if (context.retyping) context.scope enter vparam.symbol
          vparam.symbol
        }

        val vparams = List.mapConserve(fun.vparams)(typedValDef)
//        for (vparam <- vparams) {
//          checkNoEscaping.locals(context.scope, WildcardType, vparam.tpt); ()
//        }
        var body = typed(fun.body, respt)
        val formals = vparamSyms map (_.tpe)
        val restpe = packedType(body, fun.symbol).deconst
        val funtpe = typeRef(clazz.tpe.prefix, clazz, formals ::: List(restpe))
//        body = checkNoEscaping.locals(context.scope, restpe, body)
        val fun1 = copy.Function(fun, vparams, body).setType(funtpe)
        if (codeExpected) {
          val liftPoint = Apply(Select(Ident(CodeModule), nme.lift_), List(fun1))
          typed(atPos(fun.pos)(liftPoint))
        } else fun1
      }
    }

    def typedRefinement(stats: List[Tree]) {
      namer.enterSyms(stats)
      // need to delay rest of typedRefinement to avoid cyclic reference errors
      unit.toCheck += { () =>
        val stats1 = typedStats(stats, NoSymbol)
        for (stat <- stats1 if stat.isDef) {
          val member = stat.symbol
          if (!(context.owner.info.baseClasses.tail forall
                (bc => member.matchingSymbol(bc, context.owner.thisType) == NoSymbol))) {
                  member setFlag OVERRIDE
                }
        }
      }
    }

    def typedImport(imp : Import) : Import = imp

    def typedStats(stats: List[Tree], exprOwner: Symbol): List[Tree] = {

      val inBlock = exprOwner == context.owner

      def typedStat(stat: Tree): Tree = {
        if (context.owner.isRefinementClass && !treeInfo.isDeclaration(stat))
          errorTree(stat, "only declarations allowed here")
        stat match {
          case imp @ Import(_, _) =>
            val imp0 = typedImport(imp)
            if (imp0 ne null) {
              context = context.makeNewImport(imp0)
              imp0.symbol.initialize
            }
            if ((imp0 ne null) && inIDE) {
              imp0.symbol.info match {
              case ImportType(exr) =>
                imp0.expr.tpe = exr.tpe
              case _ =>
              }
              imp0
            } else EmptyTree
          case _ =>
            val localTyper = if (inBlock || (stat.isDef && !stat.isInstanceOf[LabelDef])) this
                             else newTyper(context.make(stat, exprOwner))
            val result = checkDead(localTyper.typed(stat))
            if (treeInfo.isSelfOrSuperConstrCall(result)) {
              context.inConstructorSuffix = true
              if (!inIDE && treeInfo.isSelfConstrCall(result) && result.symbol.pos.offset.getOrElse(0) >= exprOwner.enclMethod.pos.offset.getOrElse(0))
                error(stat.pos, "called constructor's definition must precede calling constructor's definition")
            }
            result
        }
      }

      def accesses(accessor: Symbol, accessed: Symbol) =
        (accessed hasFlag LOCAL) && (accessed hasFlag PARAMACCESSOR) ||
        (accessor hasFlag ACCESSOR) &&
        !(accessed hasFlag ACCESSOR) && accessed.isPrivateLocal

      def checkNoDoubleDefsAndAddSynthetics(stats: List[Tree]): List[Tree] = {
        val scope = if (inBlock) context.scope else context.owner.info.decls;
        val newStats = new ListBuffer[Tree]
        var e = scope.elems;
        while ((e ne null) && e.owner == scope) {

          // check no double def
          var e1 = scope.lookupNextEntry(e);
          while ((e1 ne null) && e1.owner == scope) {
            if (!accesses(e.sym, e1.sym) && !accesses(e1.sym, e.sym) &&
                (e.sym.isType || inBlock || (e.sym.tpe matches e1.sym.tpe)))
              if (!e.sym.isErroneous && !e1.sym.isErroneous && !inIDE)
                error(e.sym.pos, e1.sym+" is defined twice"+
                      {if(!settings.debug.value) "" else " in "+unit.toString})
            e1 = scope.lookupNextEntry(e1);
          }

          // add synthetics
          context.unit.synthetics get e.sym match {
            case Some(tree) =>
              newStats += tree
              context.unit.synthetics -= e.sym
            case _ =>
          }

          e = e.next
        }
        if (newStats.isEmpty) stats
        else stats ::: (newStats.toList map typedStat)
      }
      val result = List.mapConserve(stats)(typedStat)
      if (phase.erasedTypes) result
      else checkNoDoubleDefsAndAddSynthetics(result)
    }

    def typedArg(arg: Tree, mode: Int, newmode: Int, pt: Type): Tree =
      checkDead(constrTyperIf((mode & SCCmode) != 0).typed(arg, mode & stickyModes | newmode, pt))

    def typedArgs(args: List[Tree], mode: Int) =
      List.mapConserve(args)(arg => typedArg(arg, mode, 0, WildcardType))

    def typedArgs(args: List[Tree], mode: Int, originalFormals: List[Type], adaptedFormals: List[Type]) = {
      if (isVarArgs(originalFormals)) {
        val nonVarCount = originalFormals.length - 1
        val prefix =
          List.map2(args take nonVarCount, adaptedFormals take nonVarCount) ((arg, formal) =>
            typedArg(arg, mode, 0, formal))

        // if array is passed into java vararg and formal's element is not an array,
        // convert it to vararg by adding : _*
        // this is a gross hack to enable vararg transition; remove it as soon as possible.
        // !!!VARARG-CONVERSION!!!
        def hasArrayElement(tpe: Type) =
          tpe.typeArgs.length == 1 && tpe.typeArgs.head.typeSymbol == ArrayClass
        var args0 = args
        if ((mode & JAVACALLmode) != 0 &&
            (args.length == originalFormals.length) &&
            !hasArrayElement(adaptedFormals(nonVarCount)) &&
            !settings.XnoVarargsConversion.value) {
              val lastarg = typedArg(args(nonVarCount), mode, REGPATmode, WildcardType)
              if ((lastarg.tpe.typeSymbol == ArrayClass || lastarg.tpe.typeSymbol == NullClass) &&
                  !treeInfo.isWildcardStarArg(lastarg)) {
                if (lastarg.tpe.typeSymbol == ArrayClass)
                  unit.warning(
                    lastarg.pos,
                    "I'm seeing an array passed into a Java vararg.\n"+
                    "I assume that the elements of this array should be passed as individual arguments to the vararg.\n"+
                    "Therefore I follow the array with a `: _*', to mark it as a vararg argument.\n"+
                    "If that's not what you want, compile this file with option -Xno-varargs-conversion.")
                args0 = args.init ::: List(gen.wildcardStar(args.last))
              }
            }
        val suffix =
          List.map2(args0 drop nonVarCount, adaptedFormals drop nonVarCount) ((arg, formal) =>
            typedArg(arg, mode, REGPATmode, formal))
        prefix ::: suffix
      } else {
        List.map2(args, adaptedFormals)((arg, formal) => typedArg(arg, mode, 0, formal))
      }
    }

    /** Does function need to be instantiated, because a missing parameter
     *  in an argument closure overlaps with an uninstantiated formal?
     */
    def needsInstantiation(tparams: List[Symbol], formals: List[Type], args: List[Tree]) = {
      def isLowerBounded(tparam: Symbol) = {
        val losym = tparam.info.bounds.lo.typeSymbol
        losym != NothingClass && losym != NullClass
      }
      List.exists2(formals, args) {
        case (formal, Function(vparams, _)) =>
          (vparams exists (_.tpt.isEmpty)) &&
          vparams.length <= MaxFunctionArity &&
          (formal baseType FunctionClass(vparams.length) match {
            case TypeRef(_, _, formalargs) =>
              List.exists2(formalargs, vparams) ((formalarg, vparam) =>
                vparam.tpt.isEmpty && (tparams exists (formalarg contains))) &&
              (tparams forall isLowerBounded)
            case _ =>
              false
          })
        case _ =>
          false
      }
    }

    /**
     *  @param tree ...
     *  @param fun0 ...
     *  @param args ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    def doTypedApply(tree: Tree, fun0: Tree, args: List[Tree], mode: Int, pt: Type): Tree = {
      var fun = fun0
      if (fun.hasSymbol && (fun.symbol hasFlag OVERLOADED)) {
        // preadapt symbol to number and shape of arguments given
        def shapeType(arg: Tree): Type = arg match {
          case Function(vparams, body) =>
            functionType(vparams map (vparam => AnyClass.tpe), shapeType(body))
          case _ =>
            NothingClass.tpe
        }
        val argtypes = args map shapeType
        val pre = fun.symbol.tpe.prefix
        var sym = fun.symbol filter { alt =>
          isApplicableSafe(context.undetparams, followApply(pre.memberType(alt)), argtypes, pt)
        }
        //println("narrowed to "+sym+":"+sym.info+"/"+argtypes)
        if (sym hasFlag OVERLOADED) {
          // eliminate functions that would result from tupling transforms
          val sym1 = sym filter (alt => hasExactlyNumParams(followApply(alt.tpe), argtypes.length))
          if (sym1 != NoSymbol) sym = sym1
        }
        if (sym != NoSymbol)
          fun = adapt(fun setSymbol sym setType pre.memberType(sym), funMode(mode), WildcardType)
      }
      fun.tpe match {
        case OverloadedType(pre, alts) =>
          val undetparams = context.extractUndetparams()
          val args1 = typedArgs(args, argMode(fun, mode))
          context.undetparams = undetparams
          inferMethodAlternative(fun, undetparams, args1 map (_.tpe.deconst), pt)
          doTypedApply(tree, adapt(fun, funMode(mode), WildcardType), args1, mode, pt)
        case mt @ MethodType(formals0, _) =>
          val formals = formalTypes(formals0, args.length)
          var args1 = actualArgs(tree.pos, args, formals.length)
          if (args1.length != args.length) {
            silent(_.doTypedApply(tree, fun, args1, mode, pt)) match {
              case t: Tree => t
              case ex => errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
            }
          } else if (formals.length != args1.length) {
            if (mt.isErroneous) setError(tree)
            else errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
          } else {
            val tparams = context.extractUndetparams()
            if (tparams.isEmpty) {
              val args2 = typedArgs(args1, argMode(fun, mode), formals0, formals)
              val restpe = mt.resultType(args2 map (_.tpe))
              def ifPatternSkipFormals(tp: Type) = tp match {
                case MethodType(_, rtp) if ((mode & PATTERNmode) != 0) => rtp
                case _ => tp
              }

              // Replace the Delegate-Chainer methods += and -= with corresponding
              // + and - calls, which are translated in the code generator into
              // Combine and Remove
              if (forMSIL) {
                fun match {
                  case Select(qual, name) =>
                   if (isSubType(qual.tpe, DelegateClass.tpe)
                      && (name == encode("+=") || name == encode("-=")))
                     {
                       val n = if (name == encode("+=")) nme.PLUS else nme.MINUS
                       val f = Select(qual, n)
                       // the compiler thinks, the PLUS method takes only one argument,
                       // but he thinks it's an instance method -> still two ref's on the stack
                       //  -> translated by backend
                       val rhs = copy.Apply(tree, f, args1)
                       return typed(Assign(qual, rhs))
                     }
                  case _ => ()
                }
              }

              if (!inIDE && fun.symbol == List_apply && args.isEmpty) {
                atPos(tree.pos) { gen.mkNil setType restpe }
              } else {
                constfold(copy.Apply(tree, fun, args2).setType(ifPatternSkipFormals(restpe)))
              }
              /* Would like to do the following instead, but curiously this fails; todo: investigate
              if (!inIDE && fun.symbol.name == nme.apply && fun.symbol.owner == ListClass && args.isEmpty) {
                atPos(tree.pos) { gen.mkNil setType restpe }
              } else {
                constfold(copy.Apply(tree, fun, args2).setType(ifPatternSkipFormals(restpe)))
              }
              */

            } else if (needsInstantiation(tparams, formals, args1)) {
              //println("needs inst "+fun+" "+tparams+"/"+(tparams map (_.info)))
              inferExprInstance(fun, tparams, WildcardType, true)
              doTypedApply(tree, fun, args1, mode, pt)
            } else {
              assert((mode & PATTERNmode) == 0); // this case cannot arise for patterns
              val lenientTargs = protoTypeArgs(tparams, formals, mt.resultApprox, pt)
              val strictTargs = List.map2(lenientTargs, tparams)((targ, tparam) =>
                if (targ == WildcardType) tparam.tpe else targ)
              def typedArgToPoly(arg: Tree, formal: Type): Tree = {
                val lenientPt = formal.instantiateTypeParams(tparams, lenientTargs)
                val arg1 = typedArg(arg, argMode(fun, mode), POLYmode, lenientPt)
                val argtparams = context.extractUndetparams()
                if (!argtparams.isEmpty) {
                  val strictPt = formal.instantiateTypeParams(tparams, strictTargs)
                  inferArgumentInstance(arg1, argtparams, strictPt, lenientPt)
                }
                arg1
              }
              val args2 = List.map2(args1, formals)(typedArgToPoly)
              if (args2 exists (_.tpe.isError)) setError(tree)
              else {
                if (settings.debug.value) log("infer method inst "+fun+", tparams = "+tparams+", args = "+args2.map(_.tpe)+", pt = "+pt+", lobounds = "+tparams.map(_.tpe.bounds.lo)+", parambounds = "+tparams.map(_.info));//debug
                val undetparams = inferMethodInstance(fun, tparams, args2, pt)
                val result = doTypedApply(tree, fun, args2, mode, pt)
                context.undetparams = undetparams
                result
              }
            }
          }

        case SingleType(_, _) =>
          doTypedApply(tree, fun setType fun.tpe.widen, args, mode, pt)

        case ErrorType =>
          setError(copy.Apply(tree, fun, args))
        /* --- begin unapply  --- */

        case otpe if (mode & PATTERNmode) != 0 && unapplyMember(otpe).exists =>
          val unapp = unapplyMember(otpe)
          assert(unapp.exists, tree)
          val unappType = otpe.memberType(unapp)
          val argDummyType = pt // was unappArg
         // @S: do we need to memoize this?
          val argDummy =  context.owner.newValue(fun.pos, nme.SELECTOR_DUMMY)
            .setFlag(SYNTHETIC)
            .setInfo(argDummyType)
          if (args.length > MaxTupleArity)
            error(fun.pos, "too many arguments for unapply pattern, maximum = "+MaxTupleArity)
          val arg = Ident(argDummy) setType argDummyType
          val oldArgType = arg.tpe
          if (!isApplicableSafe(List(), unappType, List(arg.tpe), WildcardType)) {
            //Console.println("UNAPP: need to typetest, arg.tpe = "+arg.tpe+", unappType = "+unappType)
            def freshArgType(tp: Type): (Type, List[Symbol]) = tp match {
              case MethodType(formals, _) =>
                (formals(0), List())
              case PolyType(tparams, restype) =>
                val tparams1 = cloneSymbols(tparams)
                (freshArgType(restype)._1.substSym(tparams, tparams1), tparams1)
              case OverloadedType(_, _) =>
                error(fun.pos, "cannot resolve overloaded unapply")
                (ErrorType, List())
            }
            val (unappFormal, freeVars) = freshArgType(unappType)
            val context1 = context.makeNewScope(context.tree, context.owner)(FreshArgScopeKind)
            freeVars foreach(sym => context1.scope.enter(sym))
            val typer1 = newTyper(context1)
            arg.tpe = typer1.infer.inferTypedPattern(tree.pos, unappFormal, arg.tpe)
            //todo: replace arg with arg.asInstanceOf[inferTypedPattern(unappFormal, arg.tpe)] instead.
            argDummy.setInfo(arg.tpe) // bq: this line fixed #1281. w.r.t. comment ^^^, maybe good enough?
          }
/*
          val funPrefix = fun.tpe.prefix match {
            case tt @ ThisType(sym) =>
              //Console.println(" sym="+sym+" "+" .isPackageClass="+sym.isPackageClass+" .isModuleClass="+sym.isModuleClass);
              //Console.println(" funsymown="+fun.symbol.owner+" .isClass+"+fun.symbol.owner.isClass);
              //Console.println(" contains?"+sym.tpe.decls.lookup(fun.symbol.name));
              if(sym != fun.symbol.owner && (sym.isPackageClass||sym.isModuleClass) /*(1)*/ ) { // (1) see 'files/pos/unapplyVal.scala'
                if(fun.symbol.owner.isClass) {
                  mkThisType(fun.symbol.owner)
                } else {
                //Console.println("2 ThisType("+fun.symbol.owner+")")
                  NoPrefix                                                 // see 'files/run/unapplyComplex.scala'
                }
              } else tt
            case st @ SingleType(pre, sym) => st
              st
            case xx                        => xx // cannot happen?
          }
          val fun1untyped = fun
            Apply(
              Select(
                gen.mkAttributedRef(funPrefix, fun.symbol) setType null,
                // setType null is necessary so that ref will be stabilized; see bug 881
                unapp),
              List(arg))
          }
*/
          val fun1untyped = atPos(fun.pos) {
            Apply(
              Select(
                fun setType null, // setType null is necessary so that ref will be stabilized; see bug 881
                unapp),
              List(arg))
          }

          val fun1 = typed(fun1untyped)
          if (fun1.tpe.isErroneous) setError(tree)
          else {
            val formals0 = unapplyTypeList(fun1.symbol, fun1.tpe)
            val formals1 = formalTypes(formals0, args.length)
            if (formals1.length == args.length) {
              val args1 = typedArgs(args, mode, formals0, formals1)
              if (!isFullyDefined(pt)) assert(false, tree+" ==> "+UnApply(fun1, args1)+", pt = "+pt)
              // <pending-change>
              //   this would be a better choice (from #1196), but fails due to (broken?) refinements
              val itype =  glb(List(pt, arg.tpe))
              // </pending-change>
              // restore old type (arg is a dummy tree, just needs to pass typechecking)
              arg.tpe = oldArgType
              UnApply(fun1, args1) setPos tree.pos setType itype //pt
              //
              // if you use the better itype, then the following happens.
              // the required type looks wrong...
              //
              ///files/pos/bug0646.scala                                [FAILED]
              //
              //failed with type mismatch;
              // found   : scala.xml.NodeSeq{ ... }
              // required: scala.xml.NodeSeq{ ... } with scala.xml.NodeSeq{ ... } with scala.xml.Node on: temp3._data().==("Blabla").&&({
              //  exit(temp0);
              //  true
              //})
            } else {
              errorTree(tree, "wrong number of arguments for "+treeSymTypeMsg(fun))
            }
          }

/* --- end unapply  --- */
        case _ =>
          errorTree(tree, fun+" of type "+fun.tpe+" does not take parameters")
      }
    }

    def typedAnnotation(annot: Annotation, owner: Symbol): AnnotationInfo =
      typedAnnotation(annot, owner, EXPRmode)

    def typedAnnotation(annot: Annotation, owner: Symbol, mode: Int): AnnotationInfo =
      typedAnnotation(annot, owner, mode, NoSymbol)

    def typedAnnotation(annot: Annotation, owner: Symbol, mode: Int, selfsym: Symbol): AnnotationInfo = {
      var attrError: Boolean = false
      def error(pos: Position, msg: String): Null = {
        context.error(pos, msg)
        attrError = true
        null
      }
      def needConst(tr: Tree) {
        error(tr.pos, "attribute argument needs to be a constant; found: "+tr)
      }

      val typedConstr =
        if (selfsym == NoSymbol) {
          // why a new typer: definitions inside the annotation's constructor argument
          // should not have the annotated's owner as owner.
          val typer1 = newTyper(context.makeNewScope(annot.constr, owner)(TypedScopeKind))
          typer1.typed(annot.constr, mode, AnnotationClass.tpe)
        } else {
          // Since a selfsym is supplied, the annotation should have
          // an extra "self" identifier in scope for type checking.
          // This is implemented by wrapping the rhs
          // in a function like "self => rhs" during type checking,
          // and then stripping the "self =>" and substituting
          // in the supplied selfsym.
          val funcparm = ValDef(NoMods, nme.self, TypeTree(selfsym.info), EmptyTree)
          val func = Function(List(funcparm), annot.constr.duplicate)
                                         // The .duplicate of annot.constr
                                         // deals with problems that
                                         // accur if this annotation is
                                         // later typed again, which
                                         // the compiler sometimes does.
                                         // The problem is that "self"
                                         // ident's within annot.constr
                                         // will retain the old symbol
                                         // from the previous typing.
          val fun1clazz = FunctionClass(1)
          val funcType = typeRef(fun1clazz.tpe.prefix,
                                 fun1clazz,
                                 List(selfsym.info, AnnotationClass.tpe))

          typed(func, mode, funcType) match {
            case t @ Function(List(arg), rhs) =>
              val subs =
                new TreeSymSubstituter(List(arg.symbol),List(selfsym))
              subs(rhs)
          }
        }

      lazy val annotationError = AnnotationInfo(ErrorType, Nil, Nil)
      typedConstr match {
        case t @ Apply(Select(New(tpt), nme.CONSTRUCTOR), args) =>
          if ((t.tpe==null) || t.tpe.isErroneous) annotationError
          else {
            val annType = tpt.tpe

            val needsConstant =
              (annType.typeSymbol isNonBottomSubClass ClassfileAnnotationClass)

            def annotArg(tree: Tree): AnnotationArgument = {
              val arg = new AnnotationArgument(tree)
              if(needsConstant && !arg.isConstant && !inIDE)
                needConst(tree)
              arg
            }
            val constrArgs = args map annotArg

            val attrScope = annType.decls
              .filter(sym => sym.isMethod && !sym.isConstructor && sym.hasFlag(JAVA))
            val names = new collection.mutable.HashSet[Symbol]
            names ++= attrScope.elements.filter(_.isMethod)
            if (args.length == 1) {
              names.retain(sym => sym.name != nme.value)
            }
            val nvPairs = annot.elements map {
              case vd @ ValDef(_, name, _, rhs) => {
                val sym = attrScope.lookupWithContext(name)(context.owner);
                if (sym == NoSymbol) {
                  error(vd.pos, "unknown attribute element name: " + name)
                } else if (!names.contains(sym)) {
                  error(vd.pos, "duplicate value for element " + name)
                } else {
                  names -= sym
                  val annArg =
                    annotArg(
                      typed(rhs, EXPRmode, sym.tpe.resultType))
                  (sym.name, annArg)
                }
              }
            }
            for (name <- names) {
              if (!name.attributes.contains(AnnotationInfo(AnnotationDefaultAttr.tpe, List(), List()))) {
                error(annot.constr.pos, "attribute " + annType.typeSymbol.fullNameString + " is missing element " + name.name)
              }
            }
            if (annType.typeSymbol.hasFlag(JAVA) && settings.target.value == "jvm-1.4") {
              context.warning (annot.constr.pos, "Java annotation will not be emitted in classfile unless you use the '-target:jvm-1.5' option")
            }
            if (attrError) annotationError
            else AnnotationInfo(annType, constrArgs, nvPairs)
          }
        // XXX what should the default case be doing here?
        // see bug #1837 for code which induced a MatchError
        case _  => annotationError
      }
    }

    def isRawParameter(sym: Symbol) = // is it a type parameter leaked by a raw type?
      sym.isTypeParameter && sym.owner.hasFlag(JAVA)

    /** Given a set `rawSyms' of term- and type-symbols, and a type `tp'.
     *  produce a set of fresh type parameters and a type so that it can be
     *  abstracted to an existential type.
     *  Every type symbol `T' in `rawSyms' is mapped to a clone.
     *  Every term symbol `x' of type `T' in `rawSyms' is given an
     *  associated type symbol of the following form:
     *
     *    type x.type <: T with <singleton>
     *
     *  The name of the type parameter is `x.type', to produce nice diagnostics.
     *  The <singleton> parent ensures that the type parameter is still seen as a stable type.
     *  Type symbols in rawSyms are fully replaced by the new symbols.
     *  Term symbols are also replaced, except when they are the term
     *  symbol of an Ident tree, in which case only the type of the
     *  Ident is changed.
     */
    protected def existentialTransform(rawSyms: List[Symbol], tp: Type) = {
      val typeParams: List[Symbol] = rawSyms map { sym =>
        val name = if (sym.isType) sym.name else newTypeName(sym.name+".type")
        val bound = sym.existentialBound
        val sowner = if (isRawParameter(sym)) context.owner else sym.owner
        val quantified: Symbol = recycle(sowner.newAbstractType(sym.pos, name))
        trackSetInfo(quantified setFlag EXISTENTIAL)(bound.cloneInfo(quantified))
      }
      val typeParamTypes = typeParams map (_.tpe) // don't trackSetInfo here, since type already set!
      //println("ex trans "+rawSyms+" . "+tp+" "+typeParamTypes+" "+(typeParams map (_.info)))//DEBUG
      for (tparam <- typeParams) tparam.setInfo(tparam.info.subst(rawSyms, typeParamTypes))
      (typeParams, tp.subst(rawSyms, typeParamTypes))
    }

    /** Compute an existential type from raw hidden symbols `syms' and type `tp'
     */
    def packSymbols(hidden: List[Symbol], tp: Type): Type =
      if (hidden.isEmpty) tp
      else {
//          Console.println("original type: "+tp)
//          Console.println("hidden symbols: "+hidden)
        val (tparams, tp1) = existentialTransform(hidden, tp)
//          Console.println("tparams: "+tparams+", result: "+tp1)
        val res = existentialAbstraction(tparams, tp1)
//          Console.println("final result: "+res)
        res
      }

    class SymInstance(val sym: Symbol, val tp: Type) {
      override def equals(other: Any): Boolean = other match {
        case that: SymInstance =>
          this.sym == that.sym && this.tp =:= that.tp
        case _ =>
          false
      }
      override def hashCode: Int = sym.hashCode * 41 + tp.hashCode
    }

    /** convert skolems to existentials */
    def packedType(tree: Tree, owner: Symbol): Type = {
      def defines(tree: Tree, sym: Symbol) =
        sym.isExistentialSkolem && sym.unpackLocation == tree ||
        tree.isDef && tree.symbol == sym
      def isVisibleParameter(sym: Symbol) =
        (sym hasFlag PARAM) && (sym.owner == owner) && (sym.isType || !owner.isAnonymousFunction)
      def containsDef(owner: Symbol, sym: Symbol): Boolean =
        (!(sym hasFlag PACKAGE)) && {
          var o = sym.owner
          while (o != owner && o != NoSymbol && !(o hasFlag PACKAGE)) o = o.owner
          o == owner && !isVisibleParameter(sym)
        }
      var localSyms = collection.immutable.Set[Symbol]()
      var boundSyms = collection.immutable.Set[Symbol]()
      var localInstances = collection.immutable.Map[SymInstance, Symbol]()
      def isLocal(sym: Symbol): Boolean =
        if (sym == NoSymbol) false
        else if (owner == NoSymbol) tree exists (defines(_, sym))
        else containsDef(owner, sym) || isRawParameter(sym)
      def containsLocal(tp: Type): Boolean =
        tp exists (t => isLocal(t.typeSymbol) || isLocal(t.termSymbol))
      val normalizeLocals = new TypeMap {
        def apply(tp: Type): Type = tp match {
          case TypeRef(pre, sym, args) =>
            if (sym.isAliasType && containsLocal(tp)) apply(tp.normalize)
            else {
              if (pre.isVolatile)
                context.error(tree.pos, "Inferred type "+tree.tpe+" contains type selection from volatile type "+pre)
              mapOver(tp)
            }
          case _ =>
            mapOver(tp)
        }
      }
      // add all local symbols of `tp' to `localSyms'
      // expanding higher-kinded types into individual copies for each instance.
      def addLocals(tp: Type) {
        def addIfLocal(sym: Symbol, tp: Type) {
          if (sym != NoSymbol && !sym.isRefinementClass && isLocal(sym) &&
              !(localSyms contains sym) && !(boundSyms contains sym) ) {
            if (sym.typeParams.isEmpty) {
              localSyms += sym
              addLocals(sym.existentialBound)
            } else if (tp.typeArgs.isEmpty) {
              unit.error(tree.pos,
                "implementation restriction: can't existentially abstract over higher-kinded type" + tp)
            } else {
              val inst = new SymInstance(sym, tp)
              if (!(localInstances contains inst)) {
                val bound = sym.existentialBound match {
                  case PolyType(tparams, restpe) =>
                    restpe.subst(tparams, tp.typeArgs)
                  case t =>
                    t
                }
                val local = trackSetInfo(recycle(sym.owner.newAbstractType(
                  sym.pos, unit.fresh.newName(sym.pos, sym.name.toString))
                    .setFlag(sym.flags)))(bound)
                localInstances += (inst -> local)
                addLocals(bound)
              }
            }
          }
        }
        for (t <- tp) {
          t match {
            case ExistentialType(tparams, _) =>
              boundSyms ++= tparams
	    case AnnotatedType(annots, _, _) =>
	      for (annot <- annots; arg <- annot.args; t <- arg.intTree) {
		t match {
		  case Ident(_) =>
		    // Check the symbol of an Ident, unless the
		    // Ident's type is already over an existential.
		    // (If the type is already over an existential,
                    // then remap the type, not the core symbol.)
		    if (!t.tpe.typeSymbol.hasFlag(EXISTENTIAL))
		      addIfLocal(t.symbol, t.tpe)
		  case _ => ()
		}
	      }
            case _ =>
          }
          addIfLocal(t.termSymbol, t)
          addIfLocal(t.typeSymbol, t)
        }
      }

      object substLocals extends TypeMap {
	    override val dropNonConstraintAnnotations = true

        def apply(t: Type): Type = t match {
          case TypeRef(_, sym, args) if (sym.isLocal && args.length > 0) =>
            localInstances.get(new SymInstance(sym, t)) match {
              case Some(local) => typeRef(NoPrefix, local, List())
              case None => mapOver(t)
            }
          case _ => mapOver(t)
        }

	override def mapOver(arg: Tree, giveup: ()=>Nothing) = {
	  object substLocalTrees extends TypeMapTransformer {
	    override def transform(tr: Tree) = {
              localInstances.get(new SymInstance(tr.symbol, tr.tpe)) match {
		case Some(local) =>
		  Ident(local.existentialToString)
		    .setSymbol(tr.symbol).copyAttrs(tr).setType(
		      typeRef(NoPrefix, local, List()))

		case None => super.transform(tr)
	      }
	    }
	  }

	  substLocalTrees.transform(arg)
	}
      }

      val normalizedTpe = normalizeLocals(tree.tpe)
      addLocals(normalizedTpe)

      packSymbols(localSyms.toList ::: localInstances.values.toList, substLocals(normalizedTpe))
    }

    protected def typedExistentialTypeTree(tree: ExistentialTypeTree, mode: Int): Tree = {
      for (wc <- tree.whereClauses)
        if (wc.symbol == NoSymbol) { namer.enterSym(wc); wc.symbol setFlag EXISTENTIAL }
        else context.scope enter wc.symbol
      val whereClauses1 = typedStats(tree.whereClauses, context.owner)
      for (vd @ ValDef(_, _, _, _) <- tree.whereClauses)
        if (vd.symbol.tpe.isVolatile)
          error(vd.pos, "illegal abstraction from value with volatile type "+vd.symbol.tpe)
      val tpt1 = typedType(tree.tpt, mode)
      val (typeParams, tpe) = existentialTransform(tree.whereClauses map (_.symbol), tpt1.tpe)
      //println(tpe + ": " + tpe.getClass )
      TypeTree(ExistentialType(typeParams, tpe)) setOriginal tree
    }

    /**
     *  @param tree ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    protected def typed1(tree: Tree, mode: Int, pt: Type): Tree = {
      //Console.println("typed1("+tree.getClass()+","+Integer.toHexString(mode)+","+pt+")")
      def ptOrLub(tps: List[Type]) = if (isFullyDefined(pt)) pt else lub(tps map (_.deconst))

      //@M! get the type of the qualifier in a Select tree, otherwise: NoType
      def prefixType(fun: Tree): Type = fun match {
        case Select(qualifier, _) => qualifier.tpe
//        case Ident(name) => ??
        case _ => NoType
      }

      def typedAnnotated(annot: Annotation, arg1: Tree): Tree = {
        /** mode for typing the annotation itself */
        val annotMode = mode & ~TYPEmode | EXPRmode

        if (arg1.isType) {
          val selfsym =
            if (!settings.selfInAnnots.value)
              NoSymbol
            else
              arg1.tpe.selfsym match {
                case NoSymbol =>
                  /* Implementation limitation: Currently this
                   * can cause cyclical reference errors even
                   * when the self symbol is not referenced at all.
                   * Surely at least some of these cases can be
                   * fixed by proper use of LazyType's.  Lex tinkered
                   * on this but did not succeed, so is leaving
                   * it alone for now. Example code with the problem:
                   *  class peer extends Annotation
                   *  class NPE[T <: NPE[T] @peer]
                   *
                   * (Note: -Yself-in-annots must be on to see the problem)
                   **/
                  val sym =
                    newLocalDummy(context.owner, annot.pos)
                      .newValue(annot.pos, nme.self)
                  sym.setInfo(arg1.tpe.withoutAttributes)
                  sym
                case sym => sym
              }

          // use the annotation context's owner as parent for symbols defined
          // inside a type annotation
          val ainfo = typedAnnotation(annot, context.owner, annotMode, selfsym)
          val atype0 = arg1.tpe.withAttribute(ainfo)
          val atype =
            if ((selfsym != NoSymbol) && (ainfo.refsSymbol(selfsym)))
              atype0.withSelfsym(selfsym)
            else
              atype0 // do not record selfsym if
                     // this annotation did not need it

          if (ainfo.isErroneous)
            arg1  // simply drop erroneous annotations
          else
            TypeTree(atype) setOriginal tree
        } else {
          def annotTypeTree(ainfo: AnnotationInfo): Tree =
            TypeTree(arg1.tpe.withAttribute(ainfo)) setOriginal tree

          val annotInfo = typedAnnotation(annot, context.owner, annotMode)

          arg1 match {
            case _: DefTree =>
              if (!annotInfo.atp.isError) {
                val attributed =
                  if (arg1.symbol.isModule) arg1.symbol.moduleClass else arg1.symbol
                attributed.attributes = annotInfo :: attributed.attributes
              }
              arg1
            case _ =>
              val atpt = annotTypeTree(annotInfo)
              Typed(arg1, atpt) setPos tree.pos setType atpt.tpe
          }
        }
      }

      def typedBind(name: Name, body: Tree) = {
        var vble = tree.symbol
        if (name.isTypeName) {
          assert(body == EmptyTree)
          if (vble == NoSymbol)
            vble =
              if (isFullyDefined(pt))
                context.owner.newAliasType(tree.pos, name) setInfo pt
              else
                context.owner.newAbstractType(tree.pos, name) setInfo
                  mkTypeBounds(NothingClass.tpe, AnyClass.tpe)
          val rawInfo = vble.rawInfo
          vble = if (vble.name == nme.WILDCARD.toTypeName) context.scope.enter(vble)
                 else namer.enterInScope(vble)
          trackSetInfo(vble)(rawInfo) // vble could have been recycled, detect changes in type
          tree setSymbol vble setType vble.tpe
        } else {
          if (vble == NoSymbol)
            vble = context.owner.newValue(tree.pos, name)
          if (vble.name.toTermName != nme.WILDCARD) {
/*
          if (namesSomeIdent(vble.name))
            context.warning(tree.pos,
              "pattern variable"+vble.name+" shadows a value visible in the environment;\n"+
              "use backquotes `"+vble.name+"` if you mean to match against that value;\n" +
              "or rename the variable or use an explicit bind "+vble.name+"@_ to avoid this warning.")
*/
            if ((mode & ALTmode) != 0)
              error(tree.pos, "illegal variable in pattern alternative")
            vble = namer.enterInScope(vble)
          }
          val body1 = typed(body, mode, pt)
          trackSetInfo(vble)(
            if (treeInfo.isSequenceValued(body)) seqType(body1.tpe)
            else body1.tpe)
          copy.Bind(tree, name, body1) setSymbol vble setType body1.tpe   // buraq, was: pt
        }
      }

      def typedArrayValue(elemtpt: Tree, elems: List[Tree]) = {
        val elemtpt1 = typedType(elemtpt, mode)
        val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, elemtpt1.tpe))
        copy.ArrayValue(tree, elemtpt1, elems1)
          .setType(
            (if (isFullyDefined(pt) && !phase.erasedTypes) pt
             else appliedType(ArrayClass.typeConstructor, List(elemtpt1.tpe))).notNull)
      }

      def typedAssign(lhs: Tree, rhs: Tree): Tree = {
        def mayBeVarGetter(sym: Symbol) = sym.info match {
          case PolyType(List(), _) => sym.owner.isClass && !sym.isStable
          case _: ImplicitMethodType => sym.owner.isClass && !sym.isStable
          case _ => false
        }
        val lhs1 = typed(lhs, EXPRmode | LHSmode, WildcardType)
        val varsym = lhs1.symbol
        if ((varsym ne null) && mayBeVarGetter(varsym))
          lhs1 match {
            case Select(qual, name) =>
              return typed(
                Apply(
                  Select(qual, nme.getterToSetter(name)) setPos lhs.pos,
                  List(rhs)) setPos tree.pos,
                mode, pt)

            case _ =>

          }
        if ((varsym ne null) && (varsym.isVariable || varsym.isValue && phase.erasedTypes)) {
          val rhs1 = typed(rhs, lhs1.tpe)
          copy.Assign(tree, lhs1, checkDead(rhs1)) setType UnitClass.tpe
        } else {
          if (!lhs1.tpe.isError) {
            //println(lhs1+" = "+rhs)//DEBUG
            error(tree.pos,
                  if ((varsym ne null) && varsym.isValue) "reassignment to val"
                  else "assignment to non variable")
          }
          setError(tree)
        }
      }

      def typedIf(cond: Tree, thenp: Tree, elsep: Tree) = {
        val cond1 = checkDead(typed(cond, BooleanClass.tpe))
        if (elsep.isEmpty) { // in the future, should be unecessary
          val thenp1 = typed(thenp, UnitClass.tpe)
          copy.If(tree, cond1, thenp1, elsep) setType thenp1.tpe
        } else {
          val thenp1 = typed(thenp, pt)
          val elsep1 = typed(elsep, pt)
          copy.If(tree, cond1, thenp1, elsep1) setType ptOrLub(List(thenp1.tpe, elsep1.tpe))
        }
      }

      def typedReturn(expr: Tree) = {
        val enclMethod = context.enclMethod
        if (enclMethod == NoContext ||
            enclMethod.owner.isConstructor ||
            context.enclClass.enclMethod == enclMethod // i.e., we are in a constructor of a local class
            ) {
          errorTree(tree, "return outside method definition")
        } else {
          val DefDef(_, _, _, _, restpt, _) = enclMethod.tree
          var restpt0 = restpt
          if (inIDE && (restpt0.tpe eq null)) {
            restpt0 = typed(restpt0, TYPEmode, WildcardType)
          }
          if (restpt0.tpe eq null) {
            errorTree(tree, "" + enclMethod.owner +
                      " has return statement; needs result type")
          } else {
            context.enclMethod.returnsSeen = true
            val expr1: Tree = typed(expr, restpt0.tpe)
            copy.Return(tree, checkDead(expr1)) setSymbol enclMethod.owner setType NothingClass.tpe
          }
        }
      }

      def typedNew(tpt: Tree) = {
        var tpt1 = typedTypeConstructor(tpt)
        checkClassType(tpt1, false)
        if (tpt1.hasSymbol && !tpt1.symbol.typeParams.isEmpty) {
          context.undetparams = cloneSymbols(tpt1.symbol.typeParams)
          tpt1 = TypeTree()
            .setOriginal(tpt1) /* .setPos(tpt1.pos) */
            .setType(appliedType(tpt1.tpe, context.undetparams map (_.tpe)))
        }
        /** If current tree <tree> appears in <val x(: T)? = <tree>>
         *  return `tp with x.type' else return `tp'.
         */
        def narrowRhs(tp: Type) = {
          var sym = context.tree.symbol
          if (sym != null && sym != NoSymbol && sym.owner.isClass && sym.getter(sym.owner) != NoSymbol)
            sym = sym.getter(sym.owner)
          context.tree match {
            case ValDef(mods, _, _, Apply(Select(`tree`, _), _)) if !(mods hasFlag MUTABLE) =>
              val pre = if (sym.owner.isClass) sym.owner.thisType else NoPrefix
              intersectionType(List(tp, singleType(pre, sym)))
            case _ =>
              tp
          }
        }
        if (tpt1.tpe.typeSymbol.isAbstractType || (tpt1.tpe.typeSymbol hasFlag ABSTRACT))
          error(tree.pos, tpt1.tpe.typeSymbol + " is abstract; cannot be instantiated")
        else if (tpt1.tpe.typeSymbol.initialize.thisSym != tpt1.tpe.typeSymbol &&
                 !(narrowRhs(tpt1.tpe) <:< tpt1.tpe.typeOfThis) &&
                 !phase.erasedTypes) {
          error(tree.pos, tpt1.tpe.typeSymbol +
                " cannot be instantiated because it does not conform to its self-type "+
                tpt1.tpe.typeOfThis)
        }
        copy.New(tree, tpt1).setType(tpt1.tpe)
      }

      def typedEta(expr1: Tree): Tree = expr1.tpe match {
        case TypeRef(_, sym, _) if (sym == ByNameParamClass) =>
          val expr2 = Function(List(), expr1) setPos expr1.pos
          new ChangeOwnerTraverser(context.owner, expr2.symbol).traverse(expr2)
          typed1(expr2, mode, pt)
        case PolyType(List(), restpe) =>
          val expr2 = Function(List(), expr1) setPos expr1.pos
          new ChangeOwnerTraverser(context.owner, expr2.symbol).traverse(expr2)
          typed1(expr2, mode, pt)
        case PolyType(_, MethodType(formals, _)) =>
          if (isFunctionType(pt)) expr1
          else adapt(expr1, mode, functionType(formals map (t => WildcardType), WildcardType))
        case MethodType(formals, _) =>
          if (isFunctionType(pt)) expr1
          else expr1 match {
            case Select(qual, name) if (forMSIL &&
                                        pt != WildcardType &&
                                        pt != ErrorType &&
                                        isSubType(pt, DelegateClass.tpe)) =>
              val scalaCaller = newScalaCaller(pt);
              addScalaCallerInfo(scalaCaller, expr1.symbol)
              val n: Name = scalaCaller.name
              val del = Ident(DelegateClass) setType DelegateClass.tpe
              val f = Select(del, n)
              //val f1 = TypeApply(f, List(Ident(pt.symbol) setType pt))
              val args: List[Tree] = if(expr1.symbol.isStatic) List(Literal(Constant(null)))
                                     else List(qual) // where the scala-method is located
              val rhs = Apply(f, args);
              typed(rhs)
            case _ =>
              adapt(expr1, mode, functionType(formals map (t => WildcardType), WildcardType))
          }
        case ErrorType =>
          expr1
        case _ =>
          errorTree(expr1, "_ must follow method; cannot follow " + expr1.tpe)
      }

      def typedTypeApply(fun: Tree, args: List[Tree]): Tree = fun.tpe match {
        case OverloadedType(pre, alts) =>
          inferPolyAlternatives(fun, args map (_.tpe))
          val tparams = fun.symbol.typeParams //@M TODO: fun.symbol.info.typeParams ? (as in typedAppliedTypeTree)
          val args1 = if(args.length == tparams.length) {
            //@M: in case TypeApply we can't check the kind-arities of the type arguments,
            // as we don't know which alternative to choose... here we do
            map2Conserve(args, tparams) {
              //@M! the polytype denotes the expected kind
              (arg, tparam) => typedHigherKindedType(arg, mode, polyType(tparam.typeParams, AnyClass.tpe))
            }
          } else // @M: there's probably something wrong when args.length != tparams.length... (triggered by bug #320)
           // Martin, I'm using fake trees, because, if you use args or arg.map(typedType),
           // inferPolyAlternatives loops...  -- I have no idea why :-(
           // ...actually this was looping anyway, see bug #278.
            return errorTree(fun, "wrong number of type parameters for "+treeSymTypeMsg(fun))

          typedTypeApply(fun, args1)
        case SingleType(_, _) =>
          typedTypeApply(fun setType fun.tpe.widen, args)
        case PolyType(tparams, restpe) if (tparams.length != 0) =>
          if (tparams.length == args.length) {
            val targs = args map (_.tpe)
            checkBounds(tree.pos, NoPrefix, NoSymbol, tparams, targs, "")
            if (fun.symbol == Predef_classOf) {
              checkClassType(args.head, true)
              atPos(tree.pos) { gen.mkClassOf(targs.head) }
            } else {
              if (phase.id <= currentRun.typerPhase.id &&
                  fun.symbol == Any_isInstanceOf && !targs.isEmpty)
                checkCheckable(tree.pos, targs.head, "")
              val resultpe = restpe.instantiateTypeParams(tparams, targs)
              //@M substitution in instantiateParams needs to be careful!
              //@M example: class Foo[a] { def foo[m[x]]: m[a] = error("") } (new Foo[Int]).foo[List] : List[Int]
              //@M    --> first, m[a] gets changed to m[Int], then m gets substituted for List,
              //          this must preserve m's type argument, so that we end up with List[Int], and not List[a]
              //@M related bug: #1438
              //println("instantiating type params "+restpe+" "+tparams+" "+targs+" = "+resultpe)
              copy.TypeApply(tree, fun, args) setType resultpe
            }
          } else {
            errorTree(tree, "wrong number of type parameters for "+treeSymTypeMsg(fun))
          }
        case ErrorType =>
          setError(tree)
        case _ =>
          errorTree(tree, treeSymTypeMsg(fun)+" does not take type parameters.")
        }

      /**
       *  @param args ...
       *  @return     ...
       */
      def tryTypedArgs(args: List[Tree], mode: Int, other: TypeError): List[Tree] = {
        val c = context.makeSilent(false)
        c.retyping = true
        try {
          newTyper(c).typedArgs(args, mode)
        } catch {
          case ex: TypeError =>
            null
        }
      }

      /** Try to apply function to arguments; if it does not work try to
       *  insert an implicit conversion.
       *
       *  @param fun  ...
       *  @param args ...
       *  @return     ...
       */
      def tryTypedApply(fun: Tree, args: List[Tree]): Tree =
        silent(_.doTypedApply(tree, fun, args, mode, pt)) match {
          case t: Tree =>
            t
          case ex: TypeError =>
            def errorInResult(tree: Tree): Boolean = tree.pos == ex.pos || {
              tree match {
                case Block(_, r) => errorInResult(r)
                case Match(_, cases) => cases exists errorInResult
                case CaseDef(_, _, r) => errorInResult(r)
                case Annotated(_, r) => errorInResult(r)
                case If(_, t, e) => errorInResult(t) || errorInResult(e)
                case Try(b, catches, _) => errorInResult(b) || (catches exists errorInResult)
                case Typed(r, Function(List(), EmptyTree)) => errorInResult(r)
                case _ => false
              }
            }
            if (errorInResult(fun) || (args exists errorInResult)) {
              val Select(qual, name) = fun
              val args1 = tryTypedArgs(args, argMode(fun, mode), ex)
              val qual1 =
                if ((args1 ne null) && !pt.isError) {
                  def templateArgType(arg: Tree) =
                    new BoundedWildcardType(mkTypeBounds(arg.tpe, AnyClass.tpe))
                  adaptToMember(qual, name, MethodType(args1 map templateArgType, pt))
                } else qual
              if (qual1 ne qual) {
                val tree1 = Apply(Select(qual1, name) setPos fun.pos, args1) setPos tree.pos
                return typed1(tree1, mode | SNDTRYmode, pt)
              }
            }
            reportTypeError(tree.pos, ex)
            setError(tree)
        }

      def typedApply(fun: Tree, args: List[Tree]) = {
        val stableApplication = (fun.symbol ne null) && fun.symbol.isMethod && fun.symbol.isStable
        if (stableApplication && (mode & PATTERNmode) != 0) {
          // treat stable function applications f() as expressions.
          typed1(tree, mode & ~PATTERNmode | EXPRmode, pt)
        } else {
          val funpt = if ((mode & PATTERNmode) != 0) pt else WildcardType
          silent(_.typed(fun, funMode(mode), funpt)) match {
            case fun1: Tree =>
              val fun2 = if (stableApplication) stabilizeFun(fun1, mode, pt) else fun1
              if (util.Statistics.enabled) appcnt += 1
              val res =
                if (phase.id <= currentRun.typerPhase.id &&
                    fun2.isInstanceOf[Select] &&
                    !fun2.tpe.isInstanceOf[ImplicitMethodType] &&
                    ((fun2.symbol eq null) || !fun2.symbol.isConstructor) &&
                    (mode & (EXPRmode | SNDTRYmode)) == EXPRmode) {
                      tryTypedApply(fun2, args)
                    } else {
                      doTypedApply(tree, fun2, args, mode, pt)
                    }
            /*
              if (fun2.hasSymbol && fun2.symbol.isConstructor && (mode & EXPRmode) != 0) {
                res.tpe = res.tpe.notNull
              }
              */
              if (fun2.symbol == Array_apply) typed { atPos(tree.pos) { gen.mkCheckInit(res) } }
              else res
              /* Would like to do the following instead, but curiously this fails; todo: investigate
              if (fun2.symbol.name == nme.apply && fun2.symbol.owner == ArrayClass)
                typed { atPos(tree.pos) { gen.mkCheckInit(res) } }
              else res
              */
            case ex: TypeError =>
              fun match {
                case Select(qual, name)
                if (mode & PATTERNmode) == 0 && nme.isOpAssignmentName(name.decode) =>
                  val qual1 = typedQualifier(qual)
                  if (treeInfo.isVariableOrGetter(qual1)) {
                    convertToAssignment(fun, qual1, name, args, ex)
                  } else {
		    if ((qual1.symbol ne null) && qual1.symbol.isValue)
		      error(tree.pos, "reassignment to val")
		    else
                      reportTypeError(fun.pos, ex)
                    setError(tree)
                  }
                case _ =>
                  reportTypeError(fun.pos, ex)
                  setError(tree)
              }
          }
        }
      }

      def convertToAssignment(fun: Tree, qual: Tree, name: Name, args: List[Tree], ex: TypeError): Tree = {
        val prefix = name.subName(0, name.length - nme.EQL.length)
        def mkAssign(vble: Tree): Tree =
          Assign(
            vble,
              Apply(Select(vble.duplicate, prefix) setPos fun.pos, args) setPos tree.pos
          ) setPos tree.pos
        val tree1 = qual match {
          case Select(qualqual, vname) =>
            gen.evalOnce(qualqual, context.owner, context.unit) { qq =>
              mkAssign(Select(qq(), vname) setPos qual.pos)
            }
          case Apply(Select(table, nme.apply), indices) =>
            gen.evalOnceAll(table :: indices, context.owner, context.unit) { ts =>
              val tab = ts.head
              val is = ts.tail
              Apply(
                 Select(tab(), nme.update) setPos table.pos,
                 ((is map (i => i())) ::: List(
                   Apply(
                     Select(
                       Apply(
                         Select(tab(), nme.apply) setPos table.pos,
                         is map (i => i())) setPos qual.pos,
                       prefix) setPos fun.pos,
                     args) setPos tree.pos)
                 )
               ) setPos tree.pos
             }
           case Ident(_) =>
             mkAssign(qual)
        }
        typed1(tree1, mode, pt)
/*
        if (settings.debug.value) log("retry assign: "+tree1)
        silent(_.typed1(tree1, mode, pt)) match {
          case t: Tree =>
            t
          case _ =>
            reportTypeError(tree.pos, ex)
            setError(tree)
        }
*/
      }

      def typedSuper(qual: Name, mix: Name) = {
        val (clazz, selftype) =
          if (tree.symbol != NoSymbol) {
            (tree.symbol, tree.symbol.thisType)
          } else {
            val clazzContext = qualifyingClassContext(tree, qual, false)
            (clazzContext.owner, clazzContext.prefix)
          }
        if (clazz == NoSymbol) setError(tree)
        else {
          def findMixinSuper(site: Type): Type = {
            val ps = site.parents filter (p => compare(p.typeSymbol, mix))
            if (ps.isEmpty) {
              if (settings.debug.value)
                Console.println(site.parents map (_.typeSymbol.name))//debug
              if (phase.erasedTypes && context.enclClass.owner.isImplClass) {
                // the reference to super class got lost during erasure
                unit.error(tree.pos, "implementation restriction: traits may not select fields or methods from to super[C] where C is a class")
              } else {
                error(tree.pos, mix+" does not name a parent class of "+clazz)
              }
              ErrorType
            } else if (!ps.tail.isEmpty) {
              error(tree.pos, "ambiguous parent class qualifier")
              ErrorType
            } else {
              ps.head
            }
          }
          val owntype =
            if (mix.isEmpty) {
              if ((mode & SUPERCONSTRmode) != 0)
                if (clazz.info.parents.isEmpty) AnyRefClass.tpe // can happen due to cyclic references ==> #1036
                else clazz.info.parents.head
              else intersectionType(clazz.info.parents)
            } else {
              findMixinSuper(clazz.info)
            }
          tree setSymbol clazz setType mkSuperType(selftype, owntype)
        }
      }

      def typedThis(qual: Name) = {
        val (clazz, selftype) =
          if (tree.symbol != NoSymbol) {
            (tree.symbol, tree.symbol.thisType)
          } else {
            val clazzContext = qualifyingClassContext(tree, qual, false)
            (clazzContext.owner, clazzContext.prefix)
          }
        if (clazz == NoSymbol) setError(tree)
        else {
          tree setSymbol clazz setType selftype.underlying
          if (isStableContext(tree, mode, pt)) tree setType selftype
          tree
        }
      }


      /** Attribute a selection where <code>tree</code> is <code>qual.name</code>.
       *  <code>qual</code> is already attributed.
       *
       *  @param qual ...
       *  @param name ...
       *  @return     ...
       */
      def typedSelect(qual: Tree, name: Name): Tree = {
        val sym =
          if (tree.symbol != NoSymbol) {
            if (phase.erasedTypes && qual.isInstanceOf[Super])
              qual.tpe = tree.symbol.owner.tpe
            if (false && settings.debug.value) { // todo: replace by settings.check.value?
              val alts = qual.tpe.member(tree.symbol.name).alternatives
              if (!(alts exists (alt =>
                alt == tree.symbol || alt.isTerm && (alt.tpe matches tree.symbol.tpe))))
                assert(false, "symbol "+tree.symbol+tree.symbol.locationString+" not in "+alts+" of "+qual.tpe+
                       "\n members = "+qual.tpe.members+
                       "\n type history = "+qual.tpe.termSymbol.infosString+
                       "\n phase = "+phase)
            }
            tree.symbol
          } else {
            if (!inIDE) member(qual, name)(context.owner)
            else verifyAndPrioritize(_ filter (alt => context.isAccessible(alt, qual.tpe, qual.isInstanceOf[Super])))(pt)(member(qual,name)(context.owner))
          }
        if (sym == NoSymbol && name != nme.CONSTRUCTOR && (mode & EXPRmode) != 0) {
          val qual1 = adaptToName(qual, name)
          if (qual1 ne qual) return typed(copy.Select(tree, qual1, name), mode, pt)
        }
        if (!sym.exists) {
          if (settings.debug.value) Console.err.println("qual = "+qual+":"+qual.tpe+"\nSymbol="+qual.tpe.termSymbol+"\nsymbol-info = "+qual.tpe.termSymbol.info+"\nscope-id = "+qual.tpe.termSymbol.info.decls.hashCode()+"\nmembers = "+qual.tpe.members+"\nname = "+name+"\nfound = "+sym+"\nowner = "+context.enclClass.owner)
          if (!qual.tpe.widen.isErroneous) {
            error(tree.pos,
              if (name == nme.CONSTRUCTOR)
                qual.tpe.widen+" does not have a constructor"
              else
                decode(name)+" is not a member of "+qual.tpe.widen +
                (if (!inIDE && (context.unit ne null) &&
                    ((for(a <- qual.pos.line; b <- tree.pos.line) yield a < b).getOrElse(false)))
                  "\npossible cause: maybe a semicolon is missing before `"+decode(name)+"'?"
                 else ""))
          }
          setError(tree)
        } else {
          val tree1 = tree match {
            case Select(_, _) => copy.Select(tree, qual, name)
            case SelectFromTypeTree(_, _) => copy.SelectFromTypeTree(tree, qual, name)
          }
          //if (name.toString == "Elem") println("typedSelect "+qual+":"+qual.tpe+" "+sym+"/"+tree1+":"+tree1.tpe)
          val result = stabilize(makeAccessible(tree1, sym, qual.tpe, qual), qual.tpe, mode, pt)
          def isPotentialNullDeference() = {
            phase.id <= currentRun.typerPhase.id &&
            !sym.isConstructor &&
            !(qual.tpe <:< NotNullClass.tpe) && !qual.tpe.isNotNull &&
            (result.symbol != Any_isInstanceOf)  // null.isInstanceOf[T] is not a dereference; bug #1356
          }
          if (settings.Xchecknull.value && isPotentialNullDeference)
            unit.warning(tree.pos, "potential null pointer dereference: "+tree)

          result
        }
      }

      /** does given name name an identifier visible at this point?
       *
       *  @param name the given name
       *  @return     <code>true</code> if an identifier with the given name is visible.
       */
      def namesSomeIdent(name: Name): Boolean = {
        var cx = context
        while (cx != NoContext) {
          val pre = cx.enclClass.prefix
          val defEntry = cx.scope.lookupEntryWithContext(name)(context.owner)
          if ((defEntry ne null) && defEntry.sym.exists) return true
          cx = cx.enclClass
          if ((pre.member(name) filter (
            sym => sym.exists && context.isAccessible(sym, pre, false))) != NoSymbol) return true
          cx = cx.outer
        }
        var imports = context.imports      // impSym != NoSymbol => it is imported from imports.head
        while (!imports.isEmpty) {
          if (imports.head.importedSymbol(name) != NoSymbol) return true
          imports = imports.tail
        }
        false
      }

      /** Attribute an identifier consisting of a simple name or an outer reference.
       *
       *  @param tree      The tree representing the identifier.
       *  @param name      The name of the identifier.
       *  Transformations: (1) Prefix class members with this.
       *                   (2) Change imported symbols to selections
       */
      def typedIdent(name: Name): Tree = {
        def ambiguousError(msg: String) =
          error(tree.pos, "reference to " + name + " is ambiguous;\n" + msg)

        var defSym: Symbol = tree.symbol // the directly found symbol
        var pre: Type = NoPrefix         // the prefix type of defSym, if a class member
        var qual: Tree = EmptyTree       // the qualififier tree if transformed tree is a select

        // if we are in a constructor of a pattern, ignore all definitions
        // which are methods (note: if we don't do that
        // case x :: xs in class List would return the :: method).
        def qualifies(sym: Symbol): Boolean =
          sym.exists &&
          ((mode & PATTERNmode | FUNmode) != (PATTERNmode | FUNmode) || !sym.isSourceMethod)

        if (defSym == NoSymbol) {
          var defEntry: ScopeEntry = null // the scope entry of defSym, if defined in a local scope

          var cx = context
          if ((mode & (PATTERNmode | TYPEPATmode)) != 0) {
            // println("ignoring scope: "+name+" "+cx.scope+" "+cx.outer.scope)
            // ignore current variable scope in patterns to enforce linearity
            cx = cx.outer
          }

          while (defSym == NoSymbol && cx != NoContext) {
            pre = cx.enclClass.prefix
            defEntry = if (!inIDE) cx.scope.lookupEntryWithContext(name)(context.owner)
                       else verifyAndPrioritize(sym => sym)(pt)(cx.scope.lookupEntryWithContext(name)(context.owner))
            if ((defEntry ne null) && qualifies(defEntry.sym)) {
              defSym = defEntry.sym
            } else if (inIDE) { // IDE: cannot rely on linked scopes.
              if (cx.outer.owner eq cx.enclClass.owner) {
                //cx = cx.outer
                defSym =
                  verifyAndPrioritize{ // enables filtering of auto completion
                  _ filter (sym => qualifies(sym) && context.isAccessible(sym, pre, false))
                }(pt)(pre.member(name) filter (
                    sym => qualifies(sym) && context.isAccessible(sym, pre, false)))
              }
              val oldScope = cx.scope
              cx = cx.outer
              while (cx.scope == oldScope && !(cx.outer.owner eq cx.enclClass.owner)) // can't skip
                cx = cx.outer
            } else {
              cx = cx.enclClass
              defSym = pre.member(name) filter (
                sym => qualifies(sym) && context.isAccessible(sym, pre, false))
              if (defSym == NoSymbol) cx = cx.outer
            }
          }

          val symDepth = if (defEntry eq null) cx.depth
                         else cx.depth - (cx.scope.nestingLevel - defEntry.owner.nestingLevel)
          var impSym: Symbol = NoSymbol;      // the imported symbol
          var imports = context.imports;      // impSym != NoSymbol => it is imported from imports.head
          while (!impSym.exists && !imports.isEmpty && imports.head.depth > symDepth) {
            impSym = imports.head.importedSymbol(name)
            if (!impSym.exists) imports = imports.tail
          }

          // detect ambiguous definition/import,
          // update `defSym' to be the final resolved symbol,
          // update `pre' to be `sym's prefix type in case it is an imported member,
          // and compute value of:

          if (defSym.exists && impSym.exists) {
            // imported symbols take precedence over package-owned symbols in different
            // compilation units. Defined symbols take precedence over errenous imports.
            if (defSym.owner.isPackageClass &&
                ((!inIDE && !currentRun.compiles(defSym)) ||
                 (context.unit ne null) && defSym.sourceFile != context.unit.source.file))
              defSym = NoSymbol
            else if (impSym.isError)
              impSym = NoSymbol
          }
          if (defSym.exists) {
            if (impSym.exists)
              ambiguousError(
                "it is both defined in "+defSym.owner +
                " and imported subsequently by \n"+imports.head)
            else if (!defSym.owner.isClass || defSym.owner.isPackageClass || defSym.isTypeParameterOrSkolem)
              pre = NoPrefix
            else
              qual = atPos(tree.pos)(gen.mkAttributedQualifier(pre))
          } else {
            if (impSym.exists) {
              var impSym1 = NoSymbol
              var imports1 = imports.tail
              def ambiguousImport() = {
                if (!(imports.head.qual.tpe =:= imports1.head.qual.tpe))
                  ambiguousError(
                    "it is imported twice in the same scope by\n"+imports.head +  "\nand "+imports1.head)
              }
              while (!imports1.isEmpty &&
                     (!imports.head.isExplicitImport(name) ||
                      imports1.head.depth == imports.head.depth)) {
                var impSym1 = imports1.head.importedSymbol(name)
                if (impSym1.exists) {
                  if (imports1.head.isExplicitImport(name)) {
                    if (imports.head.isExplicitImport(name) ||
                        imports1.head.depth != imports.head.depth) ambiguousImport()
                    impSym = impSym1
                    imports = imports1
                  } else if (!imports.head.isExplicitImport(name) &&
                             imports1.head.depth == imports.head.depth) ambiguousImport()
                }
                imports1 = imports1.tail
              }
              defSym = impSym
              qual = atPos(tree.pos)(resetPos(imports.head.qual.duplicate))
              pre = qual.tpe
            } else {
              if (settings.debug.value) {
                log(context.imports)//debug
              }
              error(tree.pos, "not found: "+decode(name))
              defSym = context.owner.newErrorSymbol(name)
            }
          }
        }
        if (defSym.owner.isPackageClass) pre = defSym.owner.thisType
        if (defSym.isThisSym) {
          val tree1 = typed1(This(defSym.owner) setPos tree.pos, mode, pt)
          if (inIDE) {
            Ident(defSym.name) setType tree1.tpe setSymbol defSym setPos tree.pos
          } else tree1
        } else {
          val tree1 = if (qual == EmptyTree) tree
                      else atPos(tree.pos)(Select(qual, name))
                    // atPos necessary because qualifier might come from startContext
          stabilize(makeAccessible(tree1, defSym, pre, qual), pre, mode, pt)
        }
      }

      def typedCompoundTypeTree(templ: Template) = {
        val parents1 = List.mapConserve(templ.parents)(typedType(_, mode))
        if (parents1 exists (_.tpe.isError)) tree setType ErrorType
        else {
          val decls = scopeFor(tree, CompoundTreeScopeKind)
          //Console.println("Owner: " + context.enclClass.owner + " " + context.enclClass.owner.id)
          val self = refinedType(parents1 map (_.tpe), context.enclClass.owner, decls, templ.pos)
          newTyper(context.make(templ, self.typeSymbol, decls)).typedRefinement(templ.body)
          tree setType self
        }
      }

      def typedAppliedTypeTree(tpt: Tree, args: List[Tree]) = {
        val tpt1 = typed1(tpt, mode | FUNmode | TAPPmode, WildcardType)
        if (tpt1.tpe.isError) {
          setError(tree)
        } else if (!tpt1.hasSymbol) {
          errorTree(tree, tpt1.tpe+" does not take type parameters")
        } else {
          val tparams = tpt1.symbol.typeParams
          if (tparams.length == args.length) {
          // @M: kind-arity checking is done here and in adapt, full kind-checking is in checkKindBounds (in Infer)
            val args1 =
              if(!tpt1.symbol.rawInfo.isComplete)
                List.mapConserve(args){(x: Tree) => typedHigherKindedType(x, mode)}
                // if symbol hasn't been fully loaded, can't check kind-arity
              else map2Conserve(args, tparams) {
                (arg, tparam) =>
                  typedHigherKindedType(arg, mode, polyType(tparam.typeParams, AnyClass.tpe))
                  //@M! the polytype denotes the expected kind
              }
            val argtypes = args1 map (_.tpe)
            val owntype = if (tpt1.symbol.isClass || tpt1.symbol.isTypeMember)
                             // @M! added the latter condition
                             appliedType(tpt1.tpe, argtypes)
                          else tpt1.tpe.instantiateTypeParams(tparams, argtypes)
            List.map2(args, tparams) { (arg, tparam) => arg match {
              // note: can't use args1 in selector, because Bind's got replaced
              case Bind(_, _) =>
                if (arg.symbol.isAbstractType)
                  arg.symbol setInfo // XXX, feedback. don't trackSymInfo here!
                    TypeBounds(
                      lub(List(arg.symbol.info.bounds.lo, tparam.info.bounds.lo.subst(tparams, argtypes))),
                      glb(List(arg.symbol.info.bounds.hi, tparam.info.bounds.hi.subst(tparams, argtypes))))
              case _ =>
            }}
            TypeTree(owntype) setOriginal(tree) // setPos tree.pos
          } else if (tparams.length == 0) {
            if (onePointFourMode && (tpt1.symbol hasFlag JAVA)) tpt1
            else errorTree(tree, tpt1.tpe+" does not take type parameters")
          } else {
            //Console.println("\{tpt1}:\{tpt1.symbol}:\{tpt1.symbol.info}")
            if (settings.debug.value) Console.println(tpt1+":"+tpt1.symbol+":"+tpt1.symbol.info);//debug
            errorTree(tree, "wrong number of type arguments for "+tpt1.tpe+", should be "+tparams.length)
          }
        }
      }

      // begin typed1
      implicit val scopeKind = TypedScopeKind
      val sym: Symbol = tree.symbol
      if ((sym ne null) && (sym ne NoSymbol)) sym.initialize
      //if (settings.debug.value && tree.isDef) log("typing definition of "+sym);//DEBUG
      tree match {
        case PackageDef(name, stats) =>
          assert(sym.moduleClass ne NoSymbol)
          val stats1 = newTyper(context.make(tree, sym.moduleClass, sym.info.decls))
            .typedStats(stats, NoSymbol)
          copy.PackageDef(tree, name, stats1) setType NoType

        case tree @ ClassDef(_, _, _, _) =>
          newTyper(context.makeNewScope(tree, sym)).typedClassDef(tree)

        case tree @ ModuleDef(_, _, _) =>
          newTyper(context.makeNewScope(tree, sym.moduleClass)).typedModuleDef(tree)

        case vdef @ ValDef(_, _, _, _) =>
          typedValDef(vdef)

        case ddef @ DefDef(_, _, _, _, _, _) =>
          newTyper(context.makeNewScope(tree, sym)).typedDefDef(ddef)

        case tdef @ TypeDef(_, _, _, _) =>
          newTyper(context.makeNewScope(tree, sym)).typedTypeDef(tdef)

        case ldef @ LabelDef(_, _, _) =>
          labelTyper(ldef).typedLabelDef(ldef)

        case DocDef(comment, defn) =>
          val ret = typed(defn, mode, pt)
          if ((comments ne null) && (defn.symbol ne null) && (defn.symbol ne NoSymbol)) comments(defn.symbol) = comment
          ret

	case Annotation(constr, elements) =>
	  val typedConstr = typed(constr, mode, WildcardType)
	  val typedElems = elements.map(typed(_, mode, WildcardType))
          (copy.Annotation(tree, typedConstr, typedElems)
	    setType typedConstr.tpe)

        case Annotated(annot, arg) =>
          typedAnnotated(annot, typed(arg, mode, pt))

        case tree @ Block(_, _) =>
          newTyper(context.makeNewScope(tree, context.owner)(BlockScopeKind(context.depth)))
            .typedBlock(tree, mode, pt)

        case Sequence(elems) =>
          checkRegPatOK(tree.pos, mode)
          val elems1 = List.mapConserve(elems)(elem => typed(elem, mode, pt))
          copy.Sequence(tree, elems1) setType pt

        case Alternative(alts) =>
          val alts1 = List.mapConserve(alts)(alt => typed(alt, mode | ALTmode, pt))
          copy.Alternative(tree, alts1) setType pt

        case Star(elem) =>
          checkRegPatOK(tree.pos, mode)
          val elem1 = typed(elem, mode, pt)
          copy.Star(tree, elem1) setType pt

        case Bind(name, body) =>
          typedBind(name, body)

        case UnApply(fun, args) =>
          val fun1 = typed(fun)
          val tpes = formalTypes(unapplyTypeList(fun.symbol, fun1.tpe), args.length)
          val args1 = List.map2(args, tpes)(typedPattern(_, _))
          copy.UnApply(tree, fun1, args1) setType pt

        case ArrayValue(elemtpt, elems) =>
          typedArrayValue(elemtpt, elems)

        case tree @ Function(_, _) =>
          if (tree.symbol == NoSymbol)
            tree.symbol = recycle(context.owner.newValue(tree.pos, nme.ANON_FUN_NAME)
              .setFlag(SYNTHETIC).setInfo(NoType))
          newTyper(context.makeNewScope(tree, tree.symbol)).typedFunction(tree, mode, pt)

        case Assign(lhs, rhs) =>
          typedAssign(lhs, rhs)

        case If(cond, thenp, elsep) =>
          typedIf(cond, thenp, elsep)

        case tree @ Match(selector, cases) =>
          if (selector == EmptyTree) {
            val arity = if (isFunctionType(pt)) pt.normalize.typeArgs.length - 1 else 1
            val params = for (i <- List.range(0, arity)) yield
              ValDef(Modifiers(PARAM | SYNTHETIC),
                  unit.fresh.newName(tree.pos, "x" + i + "$"), TypeTree(), EmptyTree)
            val ids = for (p <- params) yield Ident(p.name)
            val selector1 = atPos(tree.pos) { if (arity == 1) ids.head else gen.mkTuple(ids) }
            val body = copy.Match(tree, selector1, cases)
            typed1(atPos(tree.pos) { Function(params, body) }, mode, pt)
          } else {
            val selector1 = checkDead(typed(selector))
            val cases1 = typedCases(tree, cases, selector1.tpe.widen, pt)
            copy.Match(tree, selector1, cases1) setType ptOrLub(cases1 map (_.tpe))
          }

        case Return(expr) =>
          typedReturn(expr)

        case Try(block, catches, finalizer) =>
          val block1 = typed(block, pt)
          val catches1 = typedCases(tree, catches, ThrowableClass.tpe, pt)
          val finalizer1 = if (finalizer.isEmpty) finalizer
                           else typed(finalizer, UnitClass.tpe)
          copy.Try(tree, block1, catches1, finalizer1)
            .setType(ptOrLub(block1.tpe :: (catches1 map (_.tpe))))

        case Throw(expr) =>
          val expr1 = typed(expr, ThrowableClass.tpe)
          copy.Throw(tree, expr1) setType NothingClass.tpe

        case New(tpt: Tree) =>
          typedNew(tpt)

        case Typed(expr, Function(List(), EmptyTree)) =>
          typedEta(checkDead(typed1(expr, mode, pt)))

        case Typed(expr, tpt) =>
          if (treeInfo.isWildcardStarArg(tree)) {
            val expr1 = typed(expr, mode & stickyModes, seqType(pt))
            expr1.tpe.baseType(SeqClass) match {
              case TypeRef(_, _, List(elemtp)) =>
                copy.Typed(tree, expr1, tpt setType elemtp) setType elemtp
              case _ =>
                setError(tree)
            }
          } else {
            val tpt1 = typedType(tpt, mode)
            val expr1 = typed(expr, mode & stickyModes, tpt1.tpe.deconst)
            val owntype =
              if ((mode & PATTERNmode) != 0) inferTypedPattern(tpt1.pos, tpt1.tpe, pt)
              else tpt1.tpe
            //Console.println(typed pattern: "+tree+":"+", tp = "+tpt1.tpe+", pt = "+pt+" ==> "+owntype)//DEBUG
            copy.Typed(tree, expr1, tpt1) setType owntype
          }

        case TypeApply(fun, args) =>
          // @M: kind-arity checking is done here and in adapt, full kind-checking is in checkKindBounds (in Infer)
          //@M! we must type fun in order to type the args, as that requires the kinds of fun's type parameters.
          // However, args should apparently be done first, to save context.undetparams. Unfortunately, the args
          // *really* have to be typed *after* fun. We escape from this classic Catch-22 by simply saving&restoring undetparams.

          // @M TODO: the compiler still bootstraps&all tests pass when this is commented out..
          //val undets = context.undetparams

          // @M: fun is typed in TAPPmode because it is being applied to its actual type parameters
          val fun1 = typed(fun, funMode(mode) | TAPPmode, WildcardType)
          val tparams = fun1.symbol.typeParams

          //@M TODO: val undets_fun = context.undetparams  ?
          // "do args first" (by restoring the context.undetparams) in order to maintain context.undetparams on the function side.

          // @M TODO: the compiler still bootstraps when this is commented out.. TODO: run tests
          //context.undetparams = undets

          // @M maybe the well-kindedness check should be done when checking the type arguments conform to the type parameters' bounds?
          val args1 = if(args.length == tparams.length) map2Conserve(args, tparams) {
                        //@M! the polytype denotes the expected kind
                        (arg, tparam) => typedHigherKindedType(arg, mode, polyType(tparam.typeParams, AnyClass.tpe))
                      } else {
                      //@M  this branch is correctly hit for an overloaded polymorphic type. It also has to handle erroneous cases.
                      // Until the right alternative for an overloaded method is known, be very liberal,
                      // typedTypeApply will find the right alternative and then do the same check as
                      // in the then-branch above. (see pos/tcpoly_overloaded.scala)
                      // this assert is too strict: be tolerant for errors like trait A { def foo[m[x], g]=error(""); def x[g] = foo[g/*ERR: missing argument type*/] }
                      //assert(fun1.symbol.info.isInstanceOf[OverloadedType] || fun1.symbol.isError) //, (fun1.symbol,fun1.symbol.info,fun1.symbol.info.getClass,args,tparams))
                        List.mapConserve(args)(typedHigherKindedType(_, mode))
                      }

          //@M TODO: context.undetparams = undets_fun ?
          typedTypeApply(fun1, args1)

        case Apply(Block(stats, expr), args) =>
          typed1(atPos(tree.pos)(Block(stats, Apply(expr, args))), mode, pt)

        case Apply(fun, args) =>
          typedApply(fun, args)

        case ApplyDynamic(qual, args) =>
          val reflectiveCalls = !(settings.refinementMethodDispatch.value == "invoke-dynamic")
          val qual1 = typed(qual, AnyRefClass.tpe)
          val args1 = List.mapConserve(args)(arg => if (reflectiveCalls) typed(arg, AnyRefClass.tpe) else typed(arg))
          copy.ApplyDynamic(tree, qual1, args1) setType (if (reflectiveCalls) AnyRefClass.tpe else tree.symbol.info.resultType)

        case Super(qual, mix) =>
          typedSuper(qual, mix)

        case This(qual) =>
          typedThis(qual)

        case Select(qual @ Super(_, _), nme.CONSTRUCTOR) =>
          val qual1 =
            typed(qual, EXPRmode | QUALmode | POLYmode | SUPERCONSTRmode, WildcardType)
          // the qualifier type of a supercall constructor is its first parent class
          typedSelect(qual1, nme.CONSTRUCTOR)

        case Select(qual, name) =>
          if (util.Statistics.enabled) selcnt += 1
          var qual1 = checkDead(typedQualifier(qual, mode))
          if (name.isTypeName) qual1 = checkStable(qual1)
          val tree1 = typedSelect(qual1, name)
          if (qual1.symbol == RootPackage) copy.Ident(tree1, name)
          else tree1

        case Ident(name) =>
          if (util.Statistics.enabled) idcnt += 1
          if ((name == nme.WILDCARD && (mode & (PATTERNmode | FUNmode)) == PATTERNmode) ||
              (name == nme.WILDCARD.toTypeName && (mode & TYPEmode) != 0))
            tree setType pt
          else
            typedIdent(name)

        case Literal(value) =>
          tree setType (
            if (value.tag == UnitTag) UnitClass.tpe
            else mkConstantType(value))

        case SingletonTypeTree(ref) =>
          val ref1 = checkStable(
            typed(ref, EXPRmode | QUALmode | (mode & TYPEPATmode), AnyRefClass.tpe))
          tree setType ref1.tpe.resultType

        case SelectFromTypeTree(qual, selector) =>
          val qual1 = typedType(qual, mode)
          if (qual1.tpe.isVolatile) error(tree.pos, "illegal type selection from volatile type "+qual.tpe)
          typedSelect(typedType(qual, mode), selector)

        case CompoundTypeTree(templ) =>
          typedCompoundTypeTree(templ)

        case AppliedTypeTree(tpt, args) =>
          typedAppliedTypeTree(tpt, args)

        case TypeBoundsTree(lo, hi) =>
          val lo1 = typedType(lo, mode)
          val hi1 = typedType(hi, mode)
          copy.TypeBoundsTree(tree, lo1, hi1) setType mkTypeBounds(lo1.tpe, hi1.tpe)

        case etpt @ ExistentialTypeTree(_, _) =>
          newTyper(context.makeNewScope(tree, context.owner)).typedExistentialTypeTree(etpt, mode)

        case TypeTree() =>
          // we should get here only when something before failed
          // and we try again (@see tryTypedApply). In that case we can assign
          // whatever type to tree; we just have to survive until a real error message is issued.
          tree setType AnyClass.tpe
        case EmptyTree if inIDE => EmptyTree // just tolerate it in the IDE.
        case _ =>
          throw new Error("unexpected tree: " + tree.getClass + "\n" + tree)//debug
      }
    }

    /**
     *  @param tree ...
     *  @param mode ...
     *  @param pt   ...
     *  @return     ...
     */
    def typed(tree: Tree, mode: Int, pt: Type): Tree = {

      def dropExistential(tp: Type): Type = tp match {
        case ExistentialType(tparams, tpe) =>
          if (settings.debug.value) println("drop ex "+tree+" "+tp)
          new SubstWildcardMap(tparams).apply(tp)
        case TypeRef(_, sym, _) if sym.isAliasType =>
          val tp0 = tp.normalize
          val tp1 = dropExistential(tp0)
          if (tp1 eq tp0) tp else tp1
        case _ => tp
      }

      try {
        if (settings.debug.value)
          assert(pt ne null, tree)//debug
        if (context.retyping &&
            (tree.tpe ne null) && (tree.tpe.isErroneous || !(tree.tpe <:< pt))) {
          tree.tpe = null
          if (tree.hasSymbol) tree.symbol = NoSymbol
        }
        if (printTypings) println("typing "+tree+", "+context.undetparams+(mode & TYPEPATmode)); //DEBUG

        var tree1 = if (tree.tpe ne null) tree else typed1(tree, mode, dropExistential(pt))
        if (printTypings) println("typed "+tree1+":"+tree1.tpe+", "+context.undetparams+", pt = "+pt); //DEBUG

        tree1.tpe = addAnnotations(tree1, tree1.tpe)

        val result = if (tree1.isEmpty || (inIDE && tree1.tpe == null)) tree1 else adapt(tree1, mode, pt)
        if (printTypings) println("adapted "+tree1+":"+tree1.tpe+" to "+pt+", "+context.undetparams); //DEBUG
//      if ((mode & TYPEmode) != 0) println("type: "+tree1+" has type "+tree1.tpe)
        result
      } catch {
        case ex: TypeError =>
          if (inIDE) throw ex
          tree.tpe = null
          //Console.println("caught "+ex+" in typed");//DEBUG
          reportTypeError(tree.pos, ex)
          setError(tree)
        case ex: Exception =>
          if (settings.debug.value) // @M causes cyclic reference error
            Console.println("exception when typing "+tree+", pt = "+pt)
          if ((context ne null) && (context.unit ne null) &&
              (context.unit.source ne null) && (tree ne null))
            logError("AT: " + (tree.pos).dbgString, ex);
          throw(ex)
        case ex: java.lang.Error =>
          Console.println("exception when typing "+tree+", pt = "+pt)
          throw ex
      }
    }

    def atOwner(owner: Symbol): Typer =
      newTyper(context.make(context.tree, owner))

    def atOwner(tree: Tree, owner: Symbol): Typer =
      newTyper(context.make(tree, owner))

    /** Types expression or definition <code>tree</code>.
     *
     *  @param tree ...
     *  @return     ...
     */
    def typed(tree: Tree): Tree = {
      val ret = typed(tree, EXPRmode, WildcardType)
      ret
    }

    /** Types expression <code>tree</code> with given prototype <code>pt</code>.
     *
     *  @param tree ...
     *  @param pt   ...
     *  @return     ...
     */
    def typed(tree: Tree, pt: Type): Tree =
      typed(tree, EXPRmode, pt)

    /** Types qualifier <code>tree</code> of a select node.
     *  E.g. is tree occurs in a context like <code>tree.m</code>.
     *
     *  @param tree ...
     *  @return     ...
     */
    def typedQualifier(tree: Tree, mode: Int): Tree =
      typed(tree, EXPRmode | QUALmode | POLYmode | mode & TYPEPATmode, WildcardType)

    def typedQualifier(tree: Tree): Tree = typedQualifier(tree, NOmode)

    /** Types function part of an application */
    def typedOperator(tree: Tree): Tree =
      typed(tree, EXPRmode | FUNmode | POLYmode | TAPPmode, WildcardType)

    /** Types a pattern with prototype <code>pt</code> */
    def typedPattern(tree: Tree, pt: Type): Tree =
      typed(tree, PATTERNmode, pt)

    /** Types a (fully parameterized) type tree */
    def typedType(tree: Tree, mode: Int): Tree =
      typed(tree, typeMode(mode), WildcardType)

    /** Types a (fully parameterized) type tree */
    def typedType(tree: Tree): Tree = typedType(tree, NOmode)

    /** Types a higher-kinded type tree -- pt denotes the expected kind*/
    def typedHigherKindedType(tree: Tree, mode: Int, pt: Type): Tree =
      if (pt.typeParams.isEmpty) typedType(tree, mode) // kind is known and it's *
      else typed(tree, HKmode, pt)

    def typedHigherKindedType(tree: Tree, mode: Int): Tree =
      typed(tree, HKmode, WildcardType)

    def typedHigherKindedType(tree: Tree): Tree = typedHigherKindedType(tree, NOmode)

    /** Types a type constructor tree used in a new or supertype */
    def typedTypeConstructor(tree: Tree, mode: Int): Tree = {
      val result = typed(tree, typeMode(mode) | FUNmode, WildcardType)
      val restpe = result.tpe.normalize
      if (!phase.erasedTypes && restpe.isInstanceOf[TypeRef] && !restpe.prefix.isStable) {
        error(tree.pos, restpe.prefix+" is not a legal prefix for a constructor")
      }
      result setType restpe // @M: normalization is done during erasure
    }

    def typedTypeConstructor(tree: Tree): Tree = typedTypeConstructor(tree, NOmode)

    def computeType(tree: Tree, pt: Type): Type = {
      val tree1 = typed(tree, pt)
      transformed(tree) = tree1
      packedType(tree1, context.owner)
    }

    def transformedOrTyped(tree: Tree, pt: Type): Tree = transformed.get(tree) match {
      case Some(tree1) => transformed -= tree; tree1
      case None => typed(tree, pt)
    }
/*
    def convertToTypeTree(tree: Tree): Tree = tree match {
      case TypeTree() => tree
      case _ => TypeTree(tree.tpe)
    }
*/
  }
}