Welcome to mirror list, hosted at ThFree Co, Russian Federation.

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

using System;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Diagnostics;
using Mono.CompilerServices.SymbolWriter;

#if NET_2_1
using XmlElement = System.Object;
#endif

#if STATIC
using SecurityType = System.Collections.Generic.List<IKVM.Reflection.Emit.CustomAttributeBuilder>;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using SecurityType = System.Collections.Generic.Dictionary<System.Security.Permissions.SecurityAction, System.Security.PermissionSet>;
using System.Reflection;
using System.Reflection.Emit;
#endif

namespace ICSharpCode.NRefactory.MonoCSharp
{
	//
	// General types container, used as a base class for all constructs which can hold types
	//
	public abstract class TypeContainer : MemberCore
	{
		public readonly MemberKind Kind;

		protected List<TypeContainer> containers;

		TypeDefinition main_container;

		protected Dictionary<string, MemberCore> defined_names;

		protected bool is_defined;

		public int CounterAnonymousMethods { get; set; }
		public int CounterAnonymousContainers { get; set; }
		public int CounterSwitchTypes { get; set; }

		protected TypeContainer (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
			: base (parent, name, attrs)
		{
			this.Kind = kind;
			defined_names = new Dictionary<string, MemberCore> ();
		}

		public override TypeSpec CurrentType {
			get {
				return null;
			}
		}

		public Dictionary<string, MemberCore> DefinedNames {
			get {
				return defined_names;
			}
		}

		public TypeDefinition PartialContainer {
			get {
				return main_container;
			}
			protected set {
				main_container = value;
			}
		}

		public IList<TypeContainer> Containers {
			get {
				return containers;
			}
		}

		//
		// Any unattached attributes during parsing get added here. User
		// by FULL_AST mode
		//
		public Attributes UnattachedAttributes {
			get; set;
		}

		public void AddCompilerGeneratedClass (CompilerGeneratedContainer c)
		{
			AddTypeContainerMember (c);
		}

		public virtual void AddPartial (TypeDefinition next_part)
		{
			MemberCore mc;
			(PartialContainer ?? this).defined_names.TryGetValue (next_part.MemberName.Basename, out mc);

			AddPartial (next_part, mc as TypeDefinition);
		}

		protected void AddPartial (TypeDefinition next_part, TypeDefinition existing)
		{
			next_part.ModFlags |= Modifiers.PARTIAL;

			if (existing == null) {
				AddTypeContainer (next_part);
				return;
			}

			if ((existing.ModFlags & Modifiers.PARTIAL) == 0) {
				if (existing.Kind != next_part.Kind) {
					AddTypeContainer (next_part);
				} else {
					Report.SymbolRelatedToPreviousError (next_part);
					Error_MissingPartialModifier (existing);
				}

				return;
			}

			if (existing.Kind != next_part.Kind) {
				Report.SymbolRelatedToPreviousError (existing);
				Report.Error (261, next_part.Location,
					"Partial declarations of `{0}' must be all classes, all structs or all interfaces",
					next_part.GetSignatureForError ());
			}

			if ((existing.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
				((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0 &&
				 (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) == 0)) {
					 Report.SymbolRelatedToPreviousError (existing);
				Report.Error (262, next_part.Location,
					"Partial declarations of `{0}' have conflicting accessibility modifiers",
					next_part.GetSignatureForError ());
			}

			var tc_names = existing.CurrentTypeParameters;
			if (tc_names != null) {
				for (int i = 0; i < tc_names.Count; ++i) {
					var tp = next_part.MemberName.TypeParameters[i];
					if (tc_names[i].MemberName.Name != tp.MemberName.Name) {
						Report.SymbolRelatedToPreviousError (existing.Location, "");
						Report.Error (264, next_part.Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
							next_part.GetSignatureForError ());
						break;
					}

					if (tc_names[i].Variance != tp.Variance) {
						Report.SymbolRelatedToPreviousError (existing.Location, "");
						Report.Error (1067, next_part.Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
							next_part.GetSignatureForError ());
						break;
					}
				}
			}

			if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
				existing.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
			} else if ((existing.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFIER) != 0) {
				existing.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFIER | Modifiers.AccessibilityMask);
				existing.ModFlags |= next_part.ModFlags;
			} else {
				existing.ModFlags |= next_part.ModFlags;
			}

			existing.Definition.Modifiers = existing.ModFlags;

			if (next_part.attributes != null) {
				if (existing.attributes == null)
					existing.attributes = next_part.attributes;
				else
					existing.attributes.AddAttributes (next_part.attributes.Attrs);
			}

			next_part.PartialContainer = existing;

			existing.AddPartialPart (next_part);

			AddTypeContainerMember (next_part);
		}

		public virtual void AddTypeContainer (TypeContainer tc)
		{
			AddTypeContainerMember (tc);

			var tparams = tc.MemberName.TypeParameters;
			if (tparams != null && tc.PartialContainer != null) {
				var td = (TypeDefinition) tc;
				for (int i = 0; i < tparams.Count; ++i) {
					var tp = tparams[i];
					if (tp.MemberName == null)
						continue;

					td.AddNameToContainer (tp, tp.Name);
				}
			}
		}

		protected virtual void AddTypeContainerMember (TypeContainer tc)
		{
			containers.Add (tc);
		}

		public virtual void CloseContainer ()
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					tc.CloseContainer ();
				}
			}
		}

		public virtual void CreateMetadataName (StringBuilder sb)
		{
			if (Parent != null && Parent.MemberName != null)
				Parent.CreateMetadataName (sb);

			MemberName.CreateMetadataName (sb);
		}

		public virtual bool CreateContainer ()
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					tc.CreateContainer ();
				}
			}

			return true;
		}

		public override bool Define ()
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					tc.Define ();
				}
			}

			// Release cache used by parser only
			if (Module.Evaluator == null) {
				defined_names = null;
			} else {
				defined_names.Clear ();
			}

			return true;
		}

		public virtual void PrepareEmit ()
		{
			if (containers != null) {
				foreach (var t in containers) {
					try {
						t.PrepareEmit ();
					} catch (Exception e) {
						if (MemberName == MemberName.Null)
							throw;

						throw new InternalErrorException (t, e);
					}
				}
			}
		}

		public virtual bool DefineContainer ()
		{
			if (is_defined)
				return true;

			is_defined = true;

			DoDefineContainer ();

			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					try {
						tc.DefineContainer ();
					} catch (Exception e) {
						if (MemberName == MemberName.Null)
							throw;

						throw new InternalErrorException (tc, e);
					}
				}
			}

			return true;
		}

		public virtual void ExpandBaseInterfaces ()
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					tc.ExpandBaseInterfaces ();
				}
			}
		}

		protected virtual void DefineNamespace ()
		{
			if (containers != null) {
				foreach (var tc in containers) {
					try {
						tc.DefineNamespace ();
					} catch (Exception e) {
						throw new InternalErrorException (tc, e);
					}
				}
			}
		}

		protected virtual void DoDefineContainer ()
		{
		}

		public virtual void EmitContainer ()
		{
			if (containers != null) {
				for (int i = 0; i < containers.Count; ++i)
					containers[i].EmitContainer ();
			}
		}

		protected void Error_MissingPartialModifier (MemberCore type)
		{
			Report.Error (260, type.Location,
				"Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
				type.GetSignatureForError ());
		}

		public override string GetSignatureForDocumentation ()
		{
			if (Parent != null && Parent.MemberName != null)
				return Parent.GetSignatureForDocumentation () + "." + MemberName.GetSignatureForDocumentation ();

			return MemberName.GetSignatureForDocumentation ();
		}

		public override string GetSignatureForError ()
		{
			if (Parent != null && Parent.MemberName != null) 
				return Parent.GetSignatureForError () + "." + MemberName.GetSignatureForError ();

			return MemberName.GetSignatureForError ();
		}

		public virtual string GetSignatureForMetadata ()
		{
			var sb = new StringBuilder ();
			CreateMetadataName (sb);
			return sb.ToString ();
		}

		public virtual void RemoveContainer (TypeContainer cont)
		{
			if (containers != null)
				containers.Remove (cont);

			var tc = Parent == Module ? Module : this;
			tc.defined_names.Remove (cont.MemberName.Basename);
		}

		public virtual void VerifyMembers ()
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers)
					tc.VerifyMembers ();
			}
		}

		public override void WriteDebugSymbol (MonoSymbolFile file)
		{
			if (containers != null) {
				foreach (TypeContainer tc in containers) {
					tc.WriteDebugSymbol (file);
				}
			}
		}
	}

	public abstract class TypeDefinition : TypeContainer, ITypeDefinition
	{
		//
		// Different context is needed when resolving type container base
		// types. Type names come from the parent scope but type parameter
		// names from the container scope.
		//
		public struct BaseContext : IMemberContext
		{
			TypeContainer tc;

			public BaseContext (TypeContainer tc)
			{
				this.tc = tc;
			}

			#region IMemberContext Members

			public CompilerContext Compiler {
				get { return tc.Compiler; }
			}

			public TypeSpec CurrentType {
				get { return tc.PartialContainer.CurrentType; }
			}

			public TypeParameters CurrentTypeParameters {
				get { return tc.PartialContainer.CurrentTypeParameters; }
			}

			public MemberCore CurrentMemberDefinition {
				get { return tc; }
			}

			public bool IsObsolete {
				get { return tc.IsObsolete; }
			}

			public bool IsUnsafe {
				get { return tc.IsUnsafe; }
			}

			public bool IsStatic {
				get { return tc.IsStatic; }
			}

			public ModuleContainer Module {
				get { return tc.Module; }
			}

			public string GetSignatureForError ()
			{
				return tc.GetSignatureForError ();
			}

			public ExtensionMethodCandidates LookupExtensionMethod (string name, int arity)
			{
				return null;
			}

			public FullNamedExpression LookupNamespaceAlias (string name)
			{
				return tc.Parent.LookupNamespaceAlias (name);
			}

			public FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
			{
				if (arity == 0) {
					var tp = CurrentTypeParameters;
					if (tp != null) {
						TypeParameter t = tp.Find (name);
						if (t != null)
							return new TypeParameterExpr (t, loc);
					}
				}

				return tc.Parent.LookupNamespaceOrType (name, arity, mode, loc);
			}

			#endregion
		}

		[Flags]
		enum CachedMethods
		{
			Equals				= 1,
			GetHashCode			= 1 << 1,
			HasStaticFieldInitializer	= 1 << 2
		}

		readonly List<MemberCore> members;

		// Holds a list of fields that have initializers
		protected List<FieldInitializer> initialized_fields;

		// Holds a list of static fields that have initializers
		protected List<FieldInitializer> initialized_static_fields;

		Dictionary<MethodSpec, Method> hoisted_base_call_proxies;

		Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();

		//
		// Points to the first non-static field added to the container.
		//
		// This is an arbitrary choice.  We are interested in looking at _some_ non-static field,
		// and the first one's as good as any.
		//
		protected FieldBase first_nonstatic_field;

		//
		// This one is computed after we can distinguish interfaces
		// from classes from the arraylist `type_bases' 
		//
		protected TypeSpec base_type;
		FullNamedExpression base_type_expr;	// TODO: It's temporary variable
		protected TypeSpec[] iface_exprs;

		protected List<FullNamedExpression> type_bases;

		// Partial parts for classes only
		List<TypeDefinition> class_partial_parts;

		TypeDefinition InTransit;

		public TypeBuilder TypeBuilder;
		GenericTypeParameterBuilder[] all_tp_builders;
		//
		// All recursive type parameters put together sharing same
		// TypeParameter instances
		//
		TypeParameters all_type_parameters;

		public const string DefaultIndexerName = "Item";

		bool has_normal_indexers;
		string indexer_name;
		protected bool requires_delayed_unmanagedtype_check;
		bool error;
		bool members_defined;
		bool members_defined_ok;
		protected bool has_static_constructor;

		private CachedMethods cached_method;

		protected TypeSpec spec;
		TypeSpec current_type;

		public int DynamicSitesCounter;
		public int AnonymousMethodsCounter;
		public int MethodGroupsCounter;

		static readonly string[] attribute_targets = new [] { "type" };
		static readonly string[] attribute_targets_primary = new [] { "type", "method" };

		/// <remarks>
		///  The pending methods that need to be implemented
		//   (interfaces or abstract methods)
		/// </remarks>
		PendingImplementation pending;

		protected TypeDefinition (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
			: base (parent, name, attrs, kind)
		{
			PartialContainer = this;
			members = new List<MemberCore> ();
		}

		#region Properties

		public List<FullNamedExpression> BaseTypeExpressions {
			get {
				return type_bases;
			}
		}

		public override TypeSpec CurrentType {
			get {
				if (current_type == null) {
					if (IsGenericOrParentIsGeneric) {
						//
						// Switch to inflated version as it's used by all expressions
						//
						var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Types;
						current_type = spec.MakeGenericType (this, targs);
					} else {
						current_type = spec;
					}
				}

				return current_type;
			}
		}

		public override TypeParameters CurrentTypeParameters {
			get {
				return PartialContainer.MemberName.TypeParameters;
			}
		}

		int CurrentTypeParametersStartIndex {
			get {
				int total = all_tp_builders.Length;
				if (CurrentTypeParameters != null) {
					return total - CurrentTypeParameters.Count;
				}
				return total;
			}
		}

		public virtual AssemblyDefinition DeclaringAssembly {
			get {
				return Module.DeclaringAssembly;
			}
		}

		IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
			get {
				return Module.DeclaringAssembly;
			}
		}

		public TypeSpec Definition {
			get {
				return spec;
			}
		}

		public bool HasMembersDefined {
			get {
				return members_defined;
			}
		}
		
		public List<FullNamedExpression> TypeBaseExpressions {
			get {
				return type_bases;
			}
		}

		public bool HasInstanceConstructor {
			get {
				return (caching_flags & Flags.HasInstanceConstructor) != 0;
			}
			set {
				caching_flags |= Flags.HasInstanceConstructor;
			}
		}

		// Indicated whether container has StructLayout attribute set Explicit
		public bool HasExplicitLayout {
			get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
			set { caching_flags |= Flags.HasExplicitLayout; }
		}

		public bool HasOperators {
			get {
				return (caching_flags & Flags.HasUserOperators) != 0;
			}
			set {
				caching_flags |= Flags.HasUserOperators;
			}
		}

		public bool HasStructLayout {
			get { return (caching_flags & Flags.HasStructLayout) != 0; }
			set { caching_flags |= Flags.HasStructLayout; }
		}

		public TypeSpec[] Interfaces {
			get {
				return iface_exprs;
			}
		}

		public bool IsGenericOrParentIsGeneric {
			get {
				return all_type_parameters != null;
			}
		}

		public bool IsTopLevel {
			get {
				return !(Parent is TypeDefinition);
			}
		}

		public bool IsPartial {
			get {
				return (ModFlags & Modifiers.PARTIAL) != 0;
			}
		}

		bool ITypeDefinition.IsTypeForwarder {
			get {
				return false;
			}
		}

		bool ITypeDefinition.IsCyclicTypeForwarder {
			get {
				return false;
			}
		}

		//
		// Returns true for secondary partial containers
		//
		bool IsPartialPart {
			get {
				return PartialContainer != this;
			}
		}

		public MemberCache MemberCache {
			get {
				return spec.MemberCache;
			}
		}

		public List<MemberCore> Members {
			get {
				return members;
			}
		}

		string ITypeDefinition.Namespace {
			get {
				var p = Parent;
				while (p.Kind != MemberKind.Namespace)
					p = p.Parent;

				return p.MemberName == null ? null : p.GetSignatureForError ();
			}
		}

		public ParametersCompiled PrimaryConstructorParameters { get; set; }

		public Arguments PrimaryConstructorBaseArguments { get; set; }

		public Location PrimaryConstructorBaseArgumentsStart { get; set; }

		public TypeParameters TypeParametersAll {
			get {
				return all_type_parameters;
			}
		}

		public override string[] ValidAttributeTargets {
			get {
				return PrimaryConstructorParameters != null ? attribute_targets_primary : attribute_targets;
			}
		}

#if FULL_AST
		public bool HasOptionalSemicolon {
			get;
			private set;
		}
		Location optionalSemicolon;
		public Location OptionalSemicolon {
			get {
				return optionalSemicolon;
			}
			set {
				optionalSemicolon = value;
				HasOptionalSemicolon = true;
			}
		}
#endif

		#endregion

		public override void Accept (StructuralVisitor visitor)
		{
			visitor.Visit (this);
		}

		public void AddMember (MemberCore symbol)
		{
			if (symbol.MemberName.ExplicitInterface != null) {
				if (!(Kind == MemberKind.Class || Kind == MemberKind.Struct)) {
					Report.Error (541, symbol.Location,
						"`{0}': explicit interface declaration can only be declared in a class or struct",
						symbol.GetSignatureForError ());
				}
			}

			AddNameToContainer (symbol, symbol.MemberName.Name);
			members.Add (symbol);
		}

		public override void AddTypeContainer (TypeContainer tc)
		{
			AddNameToContainer (tc, tc.MemberName.Basename);

			base.AddTypeContainer (tc);
		}

		protected override void AddTypeContainerMember (TypeContainer tc)
		{
			members.Add (tc);

			if (containers == null)
				containers = new List<TypeContainer> ();

			base.AddTypeContainerMember (tc);
		}

		//
		// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
		//
		public virtual void AddNameToContainer (MemberCore symbol, string name)
		{
			if (((ModFlags | symbol.ModFlags) & Modifiers.COMPILER_GENERATED) != 0)
				return;

			MemberCore mc;
			if (!PartialContainer.defined_names.TryGetValue (name, out mc)) {
				PartialContainer.defined_names.Add (name, symbol);
				return;
			}

			if (symbol.EnableOverloadChecks (mc))
				return;

			InterfaceMemberBase im = mc as InterfaceMemberBase;
			if (im != null && im.IsExplicitImpl)
				return;

			Report.SymbolRelatedToPreviousError (mc);
			if ((mc.ModFlags & Modifiers.PARTIAL) != 0 && (symbol is ClassOrStruct || symbol is Interface)) {
				Error_MissingPartialModifier (symbol);
				return;
			}

			if (symbol is TypeParameter) {
				Report.Error (692, symbol.Location,
					"Duplicate type parameter `{0}'", symbol.GetSignatureForError ());
			} else {
				Report.Error (102, symbol.Location,
					"The type `{0}' already contains a definition for `{1}'",
					GetSignatureForError (), name);
			}

			return;
		}

		public void AddConstructor (Constructor c)
		{
			AddConstructor (c, false);
		}

		public void AddConstructor (Constructor c, bool isDefault)
		{
			bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
			if (!isDefault)
				AddNameToContainer (c, is_static ? Constructor.TypeConstructorName : Constructor.ConstructorName);

			if (is_static && c.ParameterInfo.IsEmpty) {
				PartialContainer.has_static_constructor = true;
			} else {
				PartialContainer.HasInstanceConstructor = true;
			}

			members.Add (c);
		}

		public bool AddField (FieldBase field)
		{
			AddMember (field);

			if ((field.ModFlags & Modifiers.STATIC) != 0)
				return true;

			var first_field = PartialContainer.first_nonstatic_field;
			if (first_field == null) {
				PartialContainer.first_nonstatic_field = field;
				return true;
			}

			if (Kind == MemberKind.Struct && first_field.Parent != field.Parent) {
				Report.SymbolRelatedToPreviousError (first_field.Parent);
				Report.Warning (282, 3, field.Location,
					"struct instance field `{0}' found in different declaration from instance field `{1}'",
					field.GetSignatureForError (), first_field.GetSignatureForError ());
			}
			return true;
		}

		/// <summary>
		/// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
		/// </summary>
		public void AddIndexer (Indexer i)
		{
			members.Add (i);
		}

		public void AddOperator (Operator op)
		{
			PartialContainer.HasOperators = true;
			AddMember (op);
		}

		public void AddPartialPart (TypeDefinition part)
		{
			if (Kind != MemberKind.Class)
				return;

			if (class_partial_parts == null)
				class_partial_parts = new List<TypeDefinition> ();

			class_partial_parts.Add (part);
		}

		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
		{
			if (a.Target == AttributeTargets.Method) {
				foreach (var m in members) {
					var c = m as Constructor;
					if (c == null)
						continue;

					if (c.IsPrimaryConstructor) {
						c.ApplyAttributeBuilder (a, ctor, cdata, pa);
						return;
					}
				}

				throw new InternalErrorException ();
			}

			if (has_normal_indexers && a.Type == pa.DefaultMember) {
				Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
				return;
			}

			if (a.Type == pa.Required) {
				Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
				return;
			}

			TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
		} 

		public override AttributeTargets AttributeTargets {
			get {
				throw new NotSupportedException ();
			}
		}

		public TypeSpec BaseType {
			get {
				return spec.BaseType;
			}
		}

		protected virtual TypeAttributes TypeAttr {
			get {
				return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel);
			}
		}

		public int TypeParametersCount {
			get {
				return MemberName.Arity;
			}
		}

		TypeParameterSpec[] ITypeDefinition.TypeParameters {
			get {
				return PartialContainer.CurrentTypeParameters.Types;
			}
		}

		public string GetAttributeDefaultMember ()
		{
			return indexer_name ?? DefaultIndexerName;
		}

		public bool IsComImport {
			get {
				if (OptAttributes == null)
					return false;

				return OptAttributes.Contains (Module.PredefinedAttributes.ComImport);
			}
		}

		public void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
		{
			if (IsPartialPart)
				PartialContainer.RegisterFieldForInitialization (field, expression);

			if ((field.ModFlags & Modifiers.STATIC) != 0){
				if (initialized_static_fields == null) {
					HasStaticFieldInitializer = true;
					initialized_static_fields = new List<FieldInitializer> (4);
				}

				initialized_static_fields.Add (expression);
			} else {
				if (Kind == MemberKind.Struct) {
					if (Compiler.Settings.Version != LanguageVersion.Experimental) {
						Report.Error (573, expression.Location, "'{0}': Structs cannot have instance property or field initializers",
							GetSignatureForError ());
					}
				}

				if (initialized_fields == null)
					initialized_fields = new List<FieldInitializer> (4);

				initialized_fields.Add (expression);
			}
		}

		public void ResolveFieldInitializers (BlockContext ec)
		{
			Debug.Assert (!IsPartialPart);

			if (ec.IsStatic) {
				if (initialized_static_fields == null)
					return;

				bool has_complex_initializer = !ec.Module.Compiler.Settings.Optimize;
				int i;
				ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
				for (i = 0; i < initialized_static_fields.Count; ++i) {
					FieldInitializer fi = initialized_static_fields [i];
					ExpressionStatement s = fi.ResolveStatement (ec);
					if (s == null) {
						s = EmptyExpressionStatement.Instance;
					} else if (!fi.IsSideEffectFree) {
						has_complex_initializer = true;
					}

					init [i] = s;
				}

				for (i = 0; i < initialized_static_fields.Count; ++i) {
					FieldInitializer fi = initialized_static_fields [i];
					//
					// Need special check to not optimize code like this
					// static int a = b = 5;
					// static int b = 0;
					//
					if (!has_complex_initializer && fi.IsDefaultInitializer)
						continue;

					ec.AssignmentInfoOffset += fi.AssignmentOffset;
					ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
				}

				return;
			}

			if (initialized_fields == null)
				return;

			for (int i = 0; i < initialized_fields.Count; ++i) {
				FieldInitializer fi = initialized_fields [i];

				//
				// Clone before resolving otherwise when field initializer is needed
				// in more than 1 constructor any resolve after the initial one would
				// only took the resolved expression which is problem for expressions
				// that generate extra expressions or code during Resolve phase
				//
				var cloned = fi.Clone (new CloneContext ());

				ExpressionStatement s = fi.ResolveStatement (ec);
				if (s == null) {
					initialized_fields [i] = new FieldInitializer (fi.Field, ErrorExpression.Instance, Location.Null);
					continue;
				}

				//
				// Field is re-initialized to its default value => removed
				//
				if (fi.IsDefaultInitializer && Kind != MemberKind.Struct && ec.Module.Compiler.Settings.Optimize)
					continue;

				ec.AssignmentInfoOffset += fi.AssignmentOffset;
				ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
				initialized_fields [i] = (FieldInitializer) cloned;
			}
		}

		public override string DocComment {
			get {
				return comment;
			}
			set {
				if (value == null)
					return;

				comment += value;
			}
		}

		public PendingImplementation PendingImplementations {
			get { return pending; }
		}

		internal override void GenerateDocComment (DocumentationBuilder builder)
		{
			if (IsPartialPart)
				return;

			base.GenerateDocComment (builder);

			foreach (var member in members)
				member.GenerateDocComment (builder);
		}

		public TypeSpec GetAttributeCoClass ()
		{
			if (OptAttributes == null)
				return null;

			Attribute a = OptAttributes.Search (Module.PredefinedAttributes.CoClass);
			if (a == null)
				return null;

			return a.GetCoClassAttributeValue ();
		}

		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
		{
			Attribute a = null;
			if (OptAttributes != null) {
				a = OptAttributes.Search (pa);
			}

			if (a == null)
				return null;

			return a.GetAttributeUsageAttribute ();
		}

		public virtual CompilationSourceFile GetCompilationSourceFile ()
		{
			TypeContainer ns = Parent;
			while (true) {
				var sf = ns as CompilationSourceFile;
				if (sf != null)
					return sf;

				ns = ns.Parent;
			}
		}

		public override string GetSignatureForMetadata ()
		{
			if (Parent is TypeDefinition) {
				return Parent.GetSignatureForMetadata () + "+" + TypeNameParser.Escape (FilterNestedName (MemberName.Basename));
			}

			return base.GetSignatureForMetadata ();
		}

		public virtual void SetBaseTypes (List<FullNamedExpression> baseTypes)
		{
			type_bases = baseTypes;
		}

		/// <summary>
		///   This function computes the Base class and also the
		///   list of interfaces that the class or struct @c implements.
		///   
		///   The return value is an array (might be null) of
		///   interfaces implemented (as Types).
		///   
		///   The @base_class argument is set to the base object or null
		///   if this is `System.Object'. 
		/// </summary>
		protected virtual TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
		{
			base_class = null;
			if (type_bases == null)
				return null;

			int count = type_bases.Count;
			TypeSpec[] ifaces = null;
			var base_context = new BaseContext (this);
			for (int i = 0, j = 0; i < count; i++){
				FullNamedExpression fne = type_bases [i];

				var fne_resolved = fne.ResolveAsType (base_context);
				if (fne_resolved == null)
					continue;

				if (i == 0 && Kind == MemberKind.Class && !fne_resolved.IsInterface) {
					if (fne_resolved.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
						Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
							GetSignatureForError ());

						continue;
					}
					
					base_type = fne_resolved;
					base_class = fne;
					continue;
				}

				if (ifaces == null)
					ifaces = new TypeSpec [count - i];

				if (fne_resolved.IsInterface) {
					for (int ii = 0; ii < j; ++ii) {
						if (fne_resolved == ifaces [ii]) {
							Report.Error (528, Location, "`{0}' is already listed in interface list",
								fne_resolved.GetSignatureForError ());
							break;
						}
					}

					if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved)) {
						Report.Error (61, fne.Location,
							"Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
							fne_resolved.GetSignatureForError (), GetSignatureForError ());
					}
				} else {
					Report.SymbolRelatedToPreviousError (fne_resolved);
					if (Kind != MemberKind.Class) {
						Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
					} else if (base_class != null)
						Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
							GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
					else {
						Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
							GetSignatureForError (), fne_resolved.GetSignatureForError ());
					}
				}

				ifaces [j++] = fne_resolved;
			}

			return ifaces;
		}

		//
		// Checks that some operators come in pairs:
		//  == and !=
		// > and <
		// >= and <=
		// true and false
		//
		// They are matched based on the return type and the argument types
		//
		void CheckPairedOperators ()
		{
			bool has_equality_or_inequality = false;
			List<Operator.OpType> found_matched = new List<Operator.OpType> ();

			for (int i = 0; i < members.Count; ++i) {
				var o_a = members[i] as Operator;
				if (o_a == null)
					continue;

				var o_type = o_a.OperatorType;
				if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
					has_equality_or_inequality = true;

				if (found_matched.Contains (o_type))
					continue;

				var matching_type = o_a.GetMatchingOperator ();
				if (matching_type == Operator.OpType.TOP) {
					continue;
				}

				bool pair_found = false;
				for (int ii = 0; ii < members.Count; ++ii) {
					var o_b = members[ii] as Operator;
					if (o_b == null || o_b.OperatorType != matching_type)
						continue;

					if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
						continue;

					if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
						continue;

					found_matched.Add (matching_type);
					pair_found = true;
					break;
				}

				if (!pair_found) {
					Report.Error (216, o_a.Location,
						"The operator `{0}' requires a matching operator `{1}' to also be defined",
						o_a.GetSignatureForError (), Operator.GetName (matching_type));
				}
			}

			if (has_equality_or_inequality) {
				if (!HasEquals)
					Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
						GetSignatureForError ());

				if (!HasGetHashCode)
					Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
						GetSignatureForError ());
			}
		}

		public override void CreateMetadataName (StringBuilder sb)
		{
			if (Parent.MemberName != null) {
				Parent.CreateMetadataName (sb);

				if (sb.Length != 0) {
					sb.Append (".");
				}
			}

			sb.Append (MemberName.Basename);
		}
	
		bool CreateTypeBuilder ()
		{
			//
			// Sets .size to 1 for structs with no instance fields
			//
			int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null && !(this is StateMachine) ? 1 : 0;

			var parent_def = Parent as TypeDefinition;
			if (parent_def == null) {
				var sb = new StringBuilder ();
				CreateMetadataName (sb);
				TypeBuilder = Module.CreateBuilder (sb.ToString (), TypeAttr, type_size);
			} else {
				TypeBuilder = parent_def.TypeBuilder.DefineNestedType (FilterNestedName (MemberName.Basename), TypeAttr, null, type_size);
			}

			if (DeclaringAssembly.Importer != null)
				DeclaringAssembly.Importer.AddCompiledType (TypeBuilder, spec);

			spec.SetMetaInfo (TypeBuilder);
			spec.MemberCache = new MemberCache (this);

			TypeParameters parentAllTypeParameters = null;
			if (parent_def != null) {
				spec.DeclaringType = Parent.CurrentType;
				parent_def.MemberCache.AddMember (spec);
				parentAllTypeParameters = parent_def.all_type_parameters;
			}

			if (MemberName.TypeParameters != null || parentAllTypeParameters != null) {
				var tparam_names = CreateTypeParameters (parentAllTypeParameters);

				all_tp_builders = TypeBuilder.DefineGenericParameters (tparam_names);

				if (CurrentTypeParameters != null) {
					CurrentTypeParameters.Create (spec, CurrentTypeParametersStartIndex, this);
					CurrentTypeParameters.Define (all_tp_builders);
				}
			}

			return true;
		}

		public static string FilterNestedName (string name)
		{
			//
			// SRE API does not handle namespaces and types separately but
			// determine that from '.' in name. That's problematic because 
			// dot is valid character for type name. By replacing any '.'
			// in name we avoid any ambiguities and never emit metadata
			// namespace for nested types
			//
			return name.Replace ('.', '_');
		}

		string[] CreateTypeParameters (TypeParameters parentAllTypeParameters)
		{
			string[] names;
			int parent_offset = 0;
			if (parentAllTypeParameters != null) {
				if (CurrentTypeParameters == null) {
					all_type_parameters = parentAllTypeParameters;
					return parentAllTypeParameters.GetAllNames ();
				}

				names = new string[parentAllTypeParameters.Count + CurrentTypeParameters.Count];
				all_type_parameters = new TypeParameters (names.Length);
				all_type_parameters.Add (parentAllTypeParameters);

				parent_offset = all_type_parameters.Count;
				for (int i = 0; i < parent_offset; ++i)
					names[i] = all_type_parameters[i].MemberName.Name;

			} else {
				names = new string[CurrentTypeParameters.Count];
			}

			for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
				if (all_type_parameters != null)
					all_type_parameters.Add (MemberName.TypeParameters[i]);

				var name = CurrentTypeParameters[i].MemberName.Name;
				names[parent_offset + i] = name;
				for (int ii = 0; ii < parent_offset + i; ++ii) {
					if (names[ii] != name)
						continue;

					var tp = CurrentTypeParameters[i];
					var conflict = all_type_parameters[ii];

					tp.WarningParentNameConflict (conflict);
				}
			}

			if (all_type_parameters == null)
				all_type_parameters = CurrentTypeParameters;

			return names;
		}


		public SourceMethodBuilder CreateMethodSymbolEntry ()
		{
			if (Module.DeclaringAssembly.SymbolWriter == null || (ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
				return null;

			var source_file = GetCompilationSourceFile ();
			if (source_file == null)
				return null;

			return new SourceMethodBuilder (source_file.SymbolUnitEntry);
		}

		//
		// Creates a proxy base method call inside this container for hoisted base member calls
		//
		public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
		{
			Method proxy_method;

			//
			// One proxy per base method is enough
			//
			if (hoisted_base_call_proxies == null) {
				hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
				proxy_method = null;
			} else {
				hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
			}

			if (proxy_method == null) {
				string name = CompilerGeneratedContainer.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);

				MemberName member_name;
				TypeArguments targs = null;
				TypeSpec return_type = method.ReturnType;
				var local_param_types = method.Parameters.Types;

				if (method.IsGeneric) {
					//
					// Copy all base generic method type parameters info
					//
					var hoisted_tparams = method.GenericDefinition.TypeParameters;
					var tparams = new TypeParameters ();

					targs = new TypeArguments ();
					targs.Arguments = new TypeSpec[hoisted_tparams.Length];
					for (int i = 0; i < hoisted_tparams.Length; ++i) {
						var tp = hoisted_tparams[i];
						var local_tp = new TypeParameter (tp, null, new MemberName (tp.Name, Location), null);
						tparams.Add (local_tp);

						targs.Add (new SimpleName (tp.Name, Location));
						targs.Arguments[i] = local_tp.Type;
					}

					member_name = new MemberName (name, tparams, Location);

					//
					// Mutate any method type parameters from original
					// to newly created hoisted version
					//
					var mutator = new TypeParameterMutator (hoisted_tparams, tparams);
					return_type = mutator.Mutate (return_type);
					local_param_types = mutator.Mutate (local_param_types);
				} else {
					member_name = new MemberName (name);
				}

				var base_parameters = new Parameter[method.Parameters.Count];
				for (int i = 0; i < base_parameters.Length; ++i) {
					var base_param = method.Parameters.FixedParameters[i];
					base_parameters[i] = new Parameter (new TypeExpression (local_param_types [i], Location),
						base_param.Name, base_param.ModFlags, null, Location);
					base_parameters[i].Resolve (this, i);
				}

				var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
				if (method.Parameters.HasArglist) {
					cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
					cloned_params.Types[0] = Module.PredefinedTypes.RuntimeArgumentHandle.Resolve ();
				}

				// Compiler generated proxy
				proxy_method = new Method (this, new TypeExpression (return_type, Location),
					Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
					member_name, cloned_params, null);

				var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location) {
					IsCompilerGenerated = true
				};

				var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
				mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
				if (targs != null)
					mg.SetTypeArguments (rc, targs);

				// Get all the method parameters and pass them as arguments
				var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
				Statement statement;
				if (method.ReturnType.Kind == MemberKind.Void)
					statement = new StatementExpression (real_base_call);
				else
					statement = new Return (real_base_call, Location);

				block.AddStatement (statement);
				proxy_method.Block = block;

				members.Add (proxy_method);
				proxy_method.Define ();
				proxy_method.PrepareEmit ();

				hoisted_base_call_proxies.Add (method, proxy_method);
			}

			return proxy_method.Spec;
		}

		protected bool DefineBaseTypes ()
		{
			if (IsPartialPart && Kind == MemberKind.Class)
				return true;

			return DoDefineBaseType ();
		}

		bool DoDefineBaseType ()
		{
			iface_exprs = ResolveBaseTypes (out base_type_expr);
			bool set_base_type;

			if (IsPartialPart) {
				set_base_type = false;

				if (base_type_expr != null) {
					if (PartialContainer.base_type_expr != null && PartialContainer.base_type != base_type) {
						Report.SymbolRelatedToPreviousError (base_type_expr.Location, "");
						Report.Error (263, Location,
							"Partial declarations of `{0}' must not specify different base classes",
							GetSignatureForError ());
					} else {
						PartialContainer.base_type_expr = base_type_expr;
						PartialContainer.base_type = base_type;
						set_base_type = true;
					}
				}

				if (iface_exprs != null) {
					if (PartialContainer.iface_exprs == null)
						PartialContainer.iface_exprs = iface_exprs;
					else {
						var ifaces = new List<TypeSpec> (PartialContainer.iface_exprs);
						foreach (var iface_partial in iface_exprs) {
							if (ifaces.Contains (iface_partial))
								continue;

							ifaces.Add (iface_partial);
						}

						PartialContainer.iface_exprs = ifaces.ToArray ();
					}
				}

				PartialContainer.members.AddRange (members);
				if (containers != null) {
					if (PartialContainer.containers == null)
						PartialContainer.containers = new List<TypeContainer> ();

					PartialContainer.containers.AddRange (containers);
				}

				if (PrimaryConstructorParameters != null) {
					if (PartialContainer.PrimaryConstructorParameters != null) {
						Report.Error (8036, Location, "Only one part of a partial type can declare primary constructor parameters");
					} else {
						PartialContainer.PrimaryConstructorParameters = PrimaryConstructorParameters;
					}
				}

				members_defined = members_defined_ok = true;
				caching_flags |= Flags.CloseTypeCreated;
			} else {
				set_base_type = true;
			}

			var cycle = CheckRecursiveDefinition (this);
			if (cycle != null) {
				Report.SymbolRelatedToPreviousError (cycle);
				if (this is Interface) {
					Report.Error (529, Location,
						"Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
					    GetSignatureForError (), cycle.GetSignatureForError ());

					iface_exprs = null;
					PartialContainer.iface_exprs = null;
				} else {
					Report.Error (146, Location,
						"Circular base class dependency involving `{0}' and `{1}'",
						GetSignatureForError (), cycle.GetSignatureForError ());

					base_type = null;
					PartialContainer.base_type = null;
				}
			}

			if (iface_exprs != null) {
				if (!PrimaryConstructorBaseArgumentsStart.IsNull) {
					Report.Error (8049, PrimaryConstructorBaseArgumentsStart, "Implemented interfaces cannot have arguments");
				}

				foreach (var iface_type in iface_exprs) {
					// Prevents a crash, the interface might not have been resolved: 442144
					if (iface_type == null)
						continue;
					
					if (!spec.AddInterfaceDefined (iface_type))
						continue;

					TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
				}
			}

			if (Kind == MemberKind.Interface) {
				spec.BaseType = Compiler.BuiltinTypes.Object;
				return true;
			}

			if (set_base_type) {
				SetBaseType ();
			}

			//
			// Base type of partial container has to be resolved before we
			// resolve any nested types of the container. We need to know
			// partial parts because the base type can be specified in file
			// defined after current container
			//
			if (class_partial_parts != null) {
				foreach (var pp in class_partial_parts) {
					if (pp.PrimaryConstructorBaseArguments != null)
						PrimaryConstructorBaseArguments = pp.PrimaryConstructorBaseArguments;

					pp.DoDefineBaseType ();
				}

			}

			return true;
		}

		void SetBaseType ()
		{
			if (base_type == null) {
				TypeBuilder.SetParent (null);
				return;
			}

			if (spec.BaseType == base_type)
				return;

			spec.BaseType = base_type;

			if (IsPartialPart)
				spec.UpdateInflatedInstancesBaseType ();

			// Set base type after type creation
			TypeBuilder.SetParent (base_type.GetMetaInfo ());
		}

		public override void ExpandBaseInterfaces ()
		{
			if (!IsPartialPart)
				DoExpandBaseInterfaces ();

			base.ExpandBaseInterfaces ();
		}

		public void DoExpandBaseInterfaces ()
		{
			if ((caching_flags & Flags.InterfacesExpanded) != 0)
				return;

			caching_flags |= Flags.InterfacesExpanded;

			//
			// Expand base interfaces. It cannot be done earlier because all partial
			// interface parts need to be defined before the type they are used from
			//
			if (iface_exprs != null) {
				foreach (var iface in iface_exprs) {
					if (iface == null)
						continue;

					var td = iface.MemberDefinition as TypeDefinition;
					if (td != null)
						td.DoExpandBaseInterfaces ();

					if (iface.Interfaces == null)
						continue;

					foreach (var biface in iface.Interfaces) {
						if (spec.AddInterfaceDefined (biface)) {
							TypeBuilder.AddInterfaceImplementation (biface.GetMetaInfo ());
						}
					}
				}
			}

			//
			// Include all base type interfaces too, see ImportTypeBase for details
			//
			if (base_type != null) {
				var td = base_type.MemberDefinition as TypeDefinition;
				if (td != null)
					td.DoExpandBaseInterfaces ();

				//
				// Simply use base interfaces only, they are all expanded which makes
				// it easy to handle generic type argument propagation with single
				// inflator only.
				//
				// interface IA<T> : IB<T>
				// interface IB<U> : IC<U>
				// interface IC<V>
				//
				if (base_type.Interfaces != null) {
					foreach (var iface in base_type.Interfaces) {
						spec.AddInterfaceDefined (iface);
					}
				}
			}
		}

		public override void PrepareEmit ()
		{
			if ((caching_flags & Flags.CloseTypeCreated) != 0)
				return;

			foreach (var member in members) {
				var pbm = member as PropertyBasedMember;
				if (pbm != null)
					pbm.PrepareEmit ();

				var pm = member as IParametersMember;
				if (pm != null) {
					var mc = member as MethodOrOperator;
					if (mc != null) {
						mc.PrepareEmit ();
					}

					var p = pm.Parameters;
					if (p.IsEmpty)
						continue;

					((ParametersCompiled) p).ResolveDefaultValues (member);
					continue;
				}

				var c = member as Const;
				if (c != null)
					c.DefineValue ();
			}

			base.PrepareEmit ();
		}

		//
		// Defines the type in the appropriate ModuleBuilder or TypeBuilder.
		//
		public override bool CreateContainer ()
		{
			if (TypeBuilder != null)
				return !error;

			if (error)
				return false;

			if (IsPartialPart) {
				spec = PartialContainer.spec;
				TypeBuilder = PartialContainer.TypeBuilder;
				all_tp_builders = PartialContainer.all_tp_builders;
				all_type_parameters = PartialContainer.all_type_parameters;
			} else {
				if (!CreateTypeBuilder ()) {
					error = true;
					return false;
				}
			}

			return base.CreateContainer ();
		}

		protected override void DoDefineContainer ()
		{
			DefineBaseTypes ();

			DoResolveTypeParameters ();
		}

		//
		// Replaces normal spec with predefined one when compiling corlib
		// and this type container defines predefined type
		//
		public void SetPredefinedSpec (BuiltinTypeSpec spec)
		{
			// When compiling build-in types we start with two
			// version of same type. One is of BuiltinTypeSpec and
			// second one is ordinary TypeSpec. The unification
			// happens at later stage when we know which type
			// really matches the builtin type signature. However
			// that means TypeSpec create during CreateType of this
			// type has to be replaced with builtin one
			// 
			spec.SetMetaInfo (TypeBuilder);
			spec.MemberCache = this.spec.MemberCache;
			spec.DeclaringType = this.spec.DeclaringType;

			this.spec = spec;
			current_type = null;
		}

		public override void RemoveContainer (TypeContainer cont)
		{
			base.RemoveContainer (cont);
			Members.Remove (cont);
			Cache.Remove (cont.MemberName.Basename);
		}

		protected virtual bool DoResolveTypeParameters ()
		{
			var tparams = MemberName.TypeParameters;
			if (tparams == null)
				return true;

			var base_context = new BaseContext (this);
			for (int i = 0; i < tparams.Count; ++i) {
				var tp = tparams[i];

				if (!tp.ResolveConstraints (base_context)) {
					error = true;
					return false;
				}

				if (IsPartialPart) {
					var pc_tp = PartialContainer.CurrentTypeParameters [i];

					tp.Create (spec, this);
					tp.Define (pc_tp);

					if (tp.OptAttributes != null) {
						if (pc_tp.OptAttributes == null)
							pc_tp.OptAttributes = tp.OptAttributes;
						else
							pc_tp.OptAttributes.Attrs.AddRange (tp.OptAttributes.Attrs);
					}
				}
			}

			if (IsPartialPart) {
				PartialContainer.CurrentTypeParameters.UpdateConstraints (this);
			}

			return true;
		}

		TypeSpec CheckRecursiveDefinition (TypeDefinition tc)
		{
			if (InTransit != null)
				return spec;

			InTransit = tc;

			if (base_type != null) {
				var ptc = base_type.MemberDefinition as TypeDefinition;
				if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
					return base_type;
			}

			if (iface_exprs != null) {
				foreach (var iface in iface_exprs) {
					// the interface might not have been resolved, prevents a crash, see #442144
					if (iface == null)
						continue;
					var ptc = iface.MemberDefinition as Interface;
					if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
						return iface;
				}
			}

			if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
				return spec;

			InTransit = null;
			return null;
		}

		/// <summary>
		///   Populates our TypeBuilder with fields and methods
		/// </summary>
		public sealed override bool Define ()
		{
			if (members_defined)
				return members_defined_ok;

			members_defined_ok = DoDefineMembers ();
			members_defined = true;

			base.Define ();

			return members_defined_ok;
		}

		protected virtual bool DoDefineMembers ()
		{
			Debug.Assert (!IsPartialPart);

			if (iface_exprs != null) {
				foreach (var iface_type in iface_exprs) {
					if (iface_type == null)
						continue;

					// Ensure the base is always setup
					var compiled_iface = iface_type.MemberDefinition as Interface;
					if (compiled_iface != null)
						compiled_iface.Define ();

					ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
					if (oa != null && !IsObsolete)
						AttributeTester.Report_ObsoleteMessage (oa, iface_type.GetSignatureForError (), Location, Report);

					if (iface_type.Arity > 0) {
						// TODO: passing `this' is wrong, should be base type iface instead
						VarianceDecl.CheckTypeVariance (iface_type, Variance.Covariant, this);

						if (((InflatedTypeSpec) iface_type).HasDynamicArgument () && !IsCompilerGenerated) {
							Report.Error (1966, Location,
								"`{0}': cannot implement a dynamic interface `{1}'",
								GetSignatureForError (), iface_type.GetSignatureForError ());
							return false;
						}
					}

					if (iface_type.IsGenericOrParentIsGeneric) {
						foreach (var prev_iface in iface_exprs) {
							if (prev_iface == iface_type || prev_iface == null)
								break;

							if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface))
								continue;

							Report.Error (695, Location,
								"`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
								GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
						}
					}
				}

				if (Kind == MemberKind.Interface) {
					foreach (var iface in spec.Interfaces) {
						MemberCache.AddInterface (iface);
					}
				}
			}

			if (base_type != null) {
				//
				// Run checks skipped during DefineType (e.g FullNamedExpression::ResolveAsType)
				//
				if (base_type_expr != null) {
					ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
					if (obsolete_attr != null && !IsObsolete)
						AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), base_type_expr.Location, Report);

					if (IsGenericOrParentIsGeneric && base_type.IsAttribute) {
						Report.Error (698, base_type_expr.Location,
							"A generic type cannot derive from `{0}' because it is an attribute class",
							base_type.GetSignatureForError ());
					}
				}

				var baseContainer = base_type.MemberDefinition as ClassOrStruct;
				if (baseContainer != null) {
					baseContainer.Define ();

					//
					// It can trigger define of this type (for generic types only)
					//
					if (HasMembersDefined)
						return true;
				}
			}

			if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
				pending = PendingImplementation.GetPendingImplementations (this);
			}

			var count = members.Count;		
			for (int i = 0; i < count; ++i) {
				var mc = members[i] as InterfaceMemberBase;
				if (mc == null || !mc.IsExplicitImpl)
					continue;

				try {
					mc.Define ();
				} catch (Exception e) {
					throw new InternalErrorException (mc, e);
				}
			}

			for (int i = 0; i < count; ++i) {
				var mc = members[i] as InterfaceMemberBase;
				if (mc != null && mc.IsExplicitImpl)
					continue;

				if (members[i] is TypeContainer)
					continue;

				try {
					members[i].Define ();
				} catch (Exception e) {
					throw new InternalErrorException (members[i], e);
				}
			}

			if (HasOperators) {
				CheckPairedOperators ();
			}

			if (requires_delayed_unmanagedtype_check) {
				requires_delayed_unmanagedtype_check = false;
				foreach (var member in members) {
					var f = member as Field;
					if (f != null && f.MemberType != null && f.MemberType.IsPointer)
						TypeManager.VerifyUnmanaged (Module, f.MemberType, f.Location);
				}
			}

			ComputeIndexerName();

			if (HasEquals && !HasGetHashCode) {
				Report.Warning (659, 3, Location,
					"`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", GetSignatureForError ());
			}

			if (Kind == MemberKind.Interface && iface_exprs != null) {
				MemberCache.RemoveHiddenMembers (spec);
			}

			return true;
		}

		void ComputeIndexerName ()
		{
			var indexers = MemberCache.FindMembers (spec, MemberCache.IndexerNameAlias, true);
			if (indexers == null)
				return;

			string class_indexer_name = null;

			//
			// Check normal indexers for consistent name, explicit interface implementation
			// indexers are ignored
			//
			foreach (var indexer in indexers) {
				//
				// FindMembers can return unfiltered full hierarchy names
				//
				if (indexer.DeclaringType != spec)
					continue;

				has_normal_indexers = true;

				if (class_indexer_name == null) {
					indexer_name = class_indexer_name = indexer.Name;
					continue;
				}

				if (indexer.Name != class_indexer_name)
					Report.Error (668, ((Indexer)indexer.MemberDefinition).Location,
						"Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
			}
		}

		void EmitIndexerName ()
		{
			if (!has_normal_indexers)
				return;

			var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get ();
			if (ctor == null)
				return;

			var encoder = new AttributeEncoder ();
			encoder.Encode (GetAttributeDefaultMember ());
			encoder.EncodeEmptyNamedArguments ();

			TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
		}

		public override void VerifyMembers ()
		{
			//
			// Check for internal or private fields that were never assigned
			//
			if (!IsCompilerGenerated && Compiler.Settings.WarningLevel >= 3 && this == PartialContainer) {
				bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
				foreach (var member in members) {
					if (member is Event) {
						//
						// An event can be assigned from same class only, report
						// this warning for all accessibility modes
						//
						if (!member.IsUsed && !PartialContainer.HasStructLayout)
							Report.Warning (67, 3, member.Location, "The event `{0}' is never used", member.GetSignatureForError ());

						continue;
					}

					if ((member.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
						if (is_type_exposed)
							continue;

						member.SetIsUsed ();
					}

					var f = member as Field;
					if (f == null)
						continue;

					if (!member.IsUsed) {
						if (!PartialContainer.HasStructLayout) {
							if ((member.caching_flags & Flags.IsAssigned) == 0) {
								Report.Warning (169, 3, member.Location, "The private field `{0}' is never used", member.GetSignatureForError ());
							} else {
								Report.Warning (414, 3, member.Location, "The private field `{0}' is assigned but its value is never used",
									member.GetSignatureForError ());
							}
						}

						continue;
					}

					if ((f.caching_flags & Flags.IsAssigned) != 0)
						continue;

					//
					// Only report 649 on level 4
					//
					if (Compiler.Settings.WarningLevel < 4)
						continue;

					//
					// Don't be pedantic when type requires specific layout
					//
					if (f.OptAttributes != null || PartialContainer.HasStructLayout)
						continue;

					Constant c = New.Constantify (f.MemberType, f.Location);
					string value;
					if (c != null) {
						value = c.GetValueAsLiteral ();
					} else if (TypeSpec.IsReferenceType (f.MemberType)) {
						value = "null";
					} else {
						value = null;
					}

					if (value != null)
						value = " `" + value + "'";

					Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value{1}",
						f.GetSignatureForError (), value);
				}
			}

			base.VerifyMembers ();
		}

		public override void Emit ()
		{
			if (OptAttributes != null)
				OptAttributes.Emit ();

			if (!IsCompilerGenerated) {
				if (!IsTopLevel) {
					MemberSpec candidate;
					bool overrides = false;
					var conflict_symbol = MemberCache.FindBaseMember (this, out candidate, ref overrides);
					if (conflict_symbol == null && candidate == null) {
						if ((ModFlags & Modifiers.NEW) != 0)
							Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
								GetSignatureForError ());
					} else {
						if ((ModFlags & Modifiers.NEW) == 0) {
							if (candidate == null)
								candidate = conflict_symbol;

							Report.SymbolRelatedToPreviousError (candidate);
							Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
								GetSignatureForError (), candidate.GetSignatureForError ());
						}
					}
				}

				// Run constraints check on all possible generic types
				if (base_type != null && base_type_expr != null) {
					ConstraintChecker.Check (this, base_type, base_type_expr.Location);
				}

				if (iface_exprs != null) {
					foreach (var iface_type in iface_exprs) {
						if (iface_type == null)
							continue;

						ConstraintChecker.Check (this, iface_type, Location);	// TODO: Location is wrong
					}
				}
			}

			if (all_tp_builders != null) {
				int current_starts_index = CurrentTypeParametersStartIndex;
				for (int i = 0; i < all_tp_builders.Length; i++) {
					if (i < current_starts_index) {
						all_type_parameters[i].EmitConstraints (all_tp_builders [i]);
					} else {
						var tp = CurrentTypeParameters [i - current_starts_index];
						tp.CheckGenericConstraints (!IsObsolete);
						tp.Emit ();
					}
				}
			}

			if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
				Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);

#if STATIC
			if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
				TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
#endif

			base.Emit ();

			for (int i = 0; i < members.Count; i++) {
				var m = members[i];
				if ((m.caching_flags & Flags.CloseTypeCreated) != 0)
					continue;

				m.Emit ();
			}

			EmitIndexerName ();
			CheckAttributeClsCompliance ();

			if (pending != null)
				pending.VerifyPendingMethods ();
		}


		void CheckAttributeClsCompliance ()
		{
			if (!spec.IsAttribute || !IsExposedFromAssembly () || !Compiler.Settings.VerifyClsCompliance || !IsClsComplianceRequired ())
				return;

			foreach (var m in members) {
				var c = m as Constructor;
				if (c == null)
					continue;

				if (c.HasCompliantArgs)
					return;
			}

			Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
		}

		public sealed override void EmitContainer ()
		{
			if ((caching_flags & Flags.CloseTypeCreated) != 0)
				return;

			Emit ();
		}

		public override void CloseContainer ()
		{
			if ((caching_flags & Flags.CloseTypeCreated) != 0)
				return;

			// Close base type container first to avoid TypeLoadException
			if (spec.BaseType != null) {
				var btype = spec.BaseType.MemberDefinition as TypeContainer;
				if (btype != null) {
					btype.CloseContainer ();

					if ((caching_flags & Flags.CloseTypeCreated) != 0)
						return;
				}
			}

			try {
				caching_flags |= Flags.CloseTypeCreated;
				TypeBuilder.CreateType ();
			} catch (TypeLoadException) {
				//
				// This is fine, the code still created the type
				//
			} catch (Exception e) {
				throw new InternalErrorException (this, e);
			}

			base.CloseContainer ();
			
			containers = null;
			initialized_fields = null;
			initialized_static_fields = null;
			type_bases = null;
			OptAttributes = null;
		}

		//
		// Performs the validation on a Method's modifiers (properties have
		// the same properties).
		//
		// TODO: Why is it not done at parse stage, move to Modifiers::Check
		//
		public bool MethodModifiersValid (MemberCore mc)
		{
			const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
			const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
			bool ok = true;
			var flags = mc.ModFlags;
			
			//
			// At most one of static, virtual or override
			//
			if ((flags & Modifiers.STATIC) != 0){
				if ((flags & vao) != 0){
					Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
						mc.GetSignatureForError ());
					ok = false;
				}
			}

			if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
				Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
					mc.GetSignatureForError ());
				ok = false;
			}

			//
			// If the declaration includes the abstract modifier, then the
			// declaration does not include static, virtual or extern
			//
			if ((flags & Modifiers.ABSTRACT) != 0){
				if ((flags & Modifiers.EXTERN) != 0){
					Report.Error (
						180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
					ok = false;
				}

				if ((flags & Modifiers.SEALED) != 0) {
					Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
					ok = false;
				}

				if ((flags & Modifiers.VIRTUAL) != 0){
					Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
					ok = false;
				}

				if ((ModFlags & Modifiers.ABSTRACT) == 0){
					Report.SymbolRelatedToPreviousError (this);
					Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
						mc.GetSignatureForError (), GetSignatureForError ());
					ok = false;
				}
			}

			if ((flags & Modifiers.PRIVATE) != 0){
				if ((flags & vao) != 0){
					Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
					ok = false;
				}
			}

			if ((flags & Modifiers.SEALED) != 0){
				if ((flags & Modifiers.OVERRIDE) == 0){
					Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
					ok = false;
				}
			}

			return ok;
		}

		protected override bool VerifyClsCompliance ()
		{
			if (!base.VerifyClsCompliance ())
				return false;

			// Check all container names for user classes
			if (Kind != MemberKind.Delegate)
				MemberCache.VerifyClsCompliance (Definition, Report);

			if (BaseType != null && !BaseType.IsCLSCompliant ()) {
				Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
					GetSignatureForError (), BaseType.GetSignatureForError ());
			}
			return true;
		}

		/// <summary>
		///   Performs checks for an explicit interface implementation.  First it
		///   checks whether the `interface_type' is a base inteface implementation.
		///   Then it checks whether `name' exists in the interface type.
		/// </summary>
		public bool VerifyImplements (InterfaceMemberBase mb)
		{
			var ifaces = PartialContainer.Interfaces;
			if (ifaces != null) {
				foreach (TypeSpec t in ifaces){
					if (t == mb.InterfaceType)
						return true;

					var expanded_base = t.Interfaces;
					if (expanded_base == null)
						continue;

					foreach (var bt in expanded_base) {
						if (bt == mb.InterfaceType)
							return true;
					}
				}
			}
			
			Report.SymbolRelatedToPreviousError (mb.InterfaceType);
			Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
				mb.GetSignatureForError (), mb.InterfaceType.GetSignatureForError ());
			return false;
		}

		//
		// Used for visiblity checks to tests whether this definition shares
		// base type baseType, it does member-definition search
		//
		public bool IsBaseTypeDefinition (TypeSpec baseType)
		{
			// RootContext check
			if (TypeBuilder == null)
				return false;

			var type = spec;
			do {
				if (type.MemberDefinition == baseType.MemberDefinition)
					return true;

				type = type.BaseType;
			} while (type != null);

			return false;
		}

		public override bool IsClsComplianceRequired ()
		{
			if (IsPartialPart)
				return PartialContainer.IsClsComplianceRequired ();

			return base.IsClsComplianceRequired ();
		}

		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
		{
			return Module.DeclaringAssembly == assembly;
		}

		public virtual bool IsUnmanagedType ()
		{
			return false;
		}

		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
		{
			throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
		}

		//
		// Public function used to locate types.
		//
		// Returns: Type or null if they type can not be found.
		//
		public override FullNamedExpression LookupNamespaceOrType (string name, int arity, LookupMode mode, Location loc)
		{
			FullNamedExpression e;
			if (arity == 0 && Cache.TryGetValue (name, out e) && mode != LookupMode.IgnoreAccessibility)
				return e;

			e = null;

			if (arity == 0) {
				var tp = CurrentTypeParameters;
				if (tp != null) {
					TypeParameter tparam = tp.Find (name);
					if (tparam != null)
						e = new TypeParameterExpr (tparam, Location.Null);
				}
			}

			if (e == null) {
				TypeSpec t = LookupNestedTypeInHierarchy (name, arity);

				if (t != null && (t.IsAccessible (this) || mode == LookupMode.IgnoreAccessibility))
					e = new TypeExpression (t, Location.Null);
				else {
					var errors = Compiler.Report.Errors;
					e = Parent.LookupNamespaceOrType (name, arity, mode, loc);

					// TODO: LookupNamespaceOrType does more than just lookup. The result
					// cannot be cached or the error reporting won't happen
					if (errors != Compiler.Report.Errors)
						return e;
				}
			}

			// TODO MemberCache: How to cache arity stuff ?
			if (arity == 0 && mode == LookupMode.Normal)
				Cache[name] = e;

			return e;
		}

		TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
		{
			// Has any nested type
			// Does not work, because base type can have
			//if (PartialContainer.Types == null)
			//	return null;

			var container = PartialContainer.CurrentType;
			return MemberCache.FindNestedType (container, name, arity);
		}

		public void Mark_HasEquals ()
		{
			cached_method |= CachedMethods.Equals;
		}

		public void Mark_HasGetHashCode ()
		{
			cached_method |= CachedMethods.GetHashCode;
		}

		public override void WriteDebugSymbol (MonoSymbolFile file)
		{
			if (IsPartialPart)
				return;

			foreach (var m in members) {
				m.WriteDebugSymbol (file);
			}
		}

		/// <summary>
		/// Method container contains Equals method
		/// </summary>
		public bool HasEquals {
			get {
				return (cached_method & CachedMethods.Equals) != 0;
			}
		}
 
		/// <summary>
		/// Method container contains GetHashCode method
		/// </summary>
		public bool HasGetHashCode {
			get {
				return (cached_method & CachedMethods.GetHashCode) != 0;
			}
		}

		public bool HasStaticFieldInitializer {
			get {
				return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
			}
			set {
				if (value)
					cached_method |= CachedMethods.HasStaticFieldInitializer;
				else
					cached_method &= ~CachedMethods.HasStaticFieldInitializer;
			}
		}

		public override string DocCommentHeader {
			get { return "T:"; }
		}
	}

	public abstract class ClassOrStruct : TypeDefinition
	{
		public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;

		SecurityType declarative_security;
		protected Constructor generated_primary_constructor;

		protected ClassOrStruct (TypeContainer parent, MemberName name, Attributes attrs, MemberKind kind)
			: base (parent, name, attrs, kind)
		{
		}

		public ToplevelBlock PrimaryConstructorBlock { get; set; }

		protected override TypeAttributes TypeAttr {
			get {
				TypeAttributes ta = base.TypeAttr;
				if (!has_static_constructor)
					ta |= TypeAttributes.BeforeFieldInit;

				if (Kind == MemberKind.Class) {
					ta |= TypeAttributes.AutoLayout | TypeAttributes.Class;
					if (IsStatic)
						ta |= StaticClassAttribute;
				} else {
					ta |= TypeAttributes.SequentialLayout;
				}

				return ta;
			}
		}

		public override void AddNameToContainer (MemberCore symbol, string name)
		{
			if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
				if (symbol is TypeParameter) {
					Report.Error (694, symbol.Location,
						"Type parameter `{0}' has same name as containing type, or method",
						symbol.GetSignatureForError ());
					return;
				}

				InterfaceMemberBase imb = symbol as InterfaceMemberBase;
				if (imb == null || !imb.IsExplicitImpl) {
					Report.SymbolRelatedToPreviousError (this);
					Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
						symbol.GetSignatureForError ());
					return;
				}
			}

			base.AddNameToContainer (symbol, name);
		}

		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
		{
			if (a.IsValidSecurityAttribute ()) {
				a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
				return;
			}

			if (a.Type == pa.StructLayout) {
				PartialContainer.HasStructLayout = true;
				if (a.IsExplicitLayoutKind ())
					PartialContainer.HasExplicitLayout = true;
			}

			if (a.Type == pa.Dynamic) {
				a.Error_MisusedDynamicAttribute ();
				return;
			}

			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
		}

		/// <summary>
		/// Defines the default constructors 
		/// </summary>
		protected virtual Constructor DefineDefaultConstructor (bool is_static)
		{
			// The default instance constructor is public
			// If the class is abstract, the default constructor is protected
			// The default static constructor is private

			Modifiers mods;
			ParametersCompiled parameters = null;
			if (is_static) {
				mods = Modifiers.STATIC | Modifiers.PRIVATE;
				parameters = ParametersCompiled.EmptyReadOnlyParameters;
			} else {
				mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
				parameters = PrimaryConstructorParameters ?? ParametersCompiled.EmptyReadOnlyParameters;
			}

			var c = new Constructor (this, MemberName.Name, mods, null, parameters, Location);
			if (Kind == MemberKind.Class)
				c.Initializer = new GeneratedBaseInitializer (Location, PrimaryConstructorBaseArguments);

			if (PrimaryConstructorParameters != null && !is_static) {
				c.IsPrimaryConstructor = true;
				c.caching_flags |= Flags.MethodOverloadsExist;
			}
			
			AddConstructor (c, true);
			if (PrimaryConstructorBlock == null) {
				c.Block = new ToplevelBlock (Compiler, parameters, Location) {
					IsCompilerGenerated = true
				};
			} else {
				c.Block = PrimaryConstructorBlock;
			}

			return c;
		}

		protected override bool DoDefineMembers ()
		{
			CheckProtectedModifier ();

			if (PrimaryConstructorParameters != null) {

				foreach (Parameter p in PrimaryConstructorParameters.FixedParameters) {
					if (p.Name == MemberName.Name) {
						Report.Error (8039, p.Location, "Primary constructor of type `{0}' has parameter of same name as containing type",
							GetSignatureForError ());
					}

					if (CurrentTypeParameters != null) {
						for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
							var tp = CurrentTypeParameters [i];
							if (p.Name == tp.Name) {
								Report.Error (8038, p.Location, "Primary constructor of type `{0}' has parameter of same name as type parameter `{1}'",
									GetSignatureForError (), p.GetSignatureForError ());
							}
						}
					}
				}
			}

			base.DoDefineMembers ();

			return true;
		}

		public override void Emit ()
		{
			if (!has_static_constructor && HasStaticFieldInitializer) {
				var c = DefineDefaultConstructor (true);
				c.Define ();
			}

			base.Emit ();

			if (declarative_security != null) {
				foreach (var de in declarative_security) {
#if STATIC
					TypeBuilder.__AddDeclarativeSecurity (de);
#elif !NET6_0
					TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
#endif
				}
			}
		}
	}


	public sealed class Class : ClassOrStruct
	{
		const Modifiers AllowedModifiers =
			Modifiers.NEW |
			Modifiers.PUBLIC |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL |
			Modifiers.PRIVATE |
			Modifiers.ABSTRACT |
			Modifiers.SEALED |
			Modifiers.STATIC |
			Modifiers.UNSAFE;
			
		public Class (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
			: base (parent, name, attrs, MemberKind.Class)
		{
			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;
			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
			spec = new TypeSpec (Kind, null, this, null, ModFlags);
		}

		public override void Accept (StructuralVisitor visitor)
		{
			visitor.Visit (this);
		}

		public override void SetBaseTypes (List<FullNamedExpression> baseTypes)
		{
			var pmn = MemberName;
			if (pmn.Name == "Object" && !pmn.IsGeneric && Parent.MemberName.Name == "System" && Parent.MemberName.Left == null)
				Report.Error (537, Location,
					"The class System.Object cannot have a base class or implement an interface.");

			base.SetBaseTypes (baseTypes);
		}

		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
		{
			if (a.Type == pa.AttributeUsage) {
				if (!BaseType.IsAttribute && spec.BuiltinType != BuiltinTypeSpec.Type.Attribute) {
					Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
				}
			}

			if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
				Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
				return;
			}

			if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
				a.Error_MissingGuidAttribute ();
				return;
			}

			if (a.Type == pa.Extension) {
				a.Error_MisusedExtensionAttribute ();
				return;
			}

			if (a.Type.IsConditionallyExcluded (this))
				return;

			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
		}

		public override AttributeTargets AttributeTargets {
			get {
				return AttributeTargets.Class;
			}
		}

		protected override bool DoDefineMembers ()
		{
			if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
				Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
			}

			if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
				Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
			}

			if (IsStatic) {
				if (PrimaryConstructorParameters != null) {
					Report.Error (-800, Location, "`{0}': Static classes cannot have primary constructor", GetSignatureForError ());
					PrimaryConstructorParameters = null;
				}

				foreach (var m in Members) {
					if (m is Operator) {
						Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
						continue;
					}

					if (m is Destructor) {
						Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
						continue;
					}

					if (m is Indexer) {
						Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
						continue;
					}

					if ((m.ModFlags & Modifiers.STATIC) != 0 || m is TypeContainer)
						continue;

					if (m is Constructor) {
						Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
						continue;
					}

					Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
				}
			} else {
				if (!PartialContainer.HasInstanceConstructor || PrimaryConstructorParameters != null)
					generated_primary_constructor = DefineDefaultConstructor (false);
			}

			return base.DoDefineMembers ();
		}

		public override void Emit ()
		{
			base.Emit ();

			if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
				Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);

			if (base_type != null && base_type.HasDynamicElement) {
				Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
			}
		}

		public override void GetCompletionStartingWith (string prefix, List<string> results)
		{
			base.GetCompletionStartingWith (prefix, results);

			var bt = base_type;
			while (bt != null) {
				results.AddRange (MemberCache.GetCompletitionMembers (this, bt, prefix).Where (l => l.IsStatic).Select (l => l.Name));
				bt = bt.BaseType;
			}
		}

		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
		{
			var ifaces = base.ResolveBaseTypes (out base_class);

			if (base_class == null) {
				if (spec.BuiltinType != BuiltinTypeSpec.Type.Object)
					base_type = Compiler.BuiltinTypes.Object;
			} else {
				if (base_type.IsGenericParameter){
					Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
						GetSignatureForError (), base_type.GetSignatureForError ());
				} else if (base_type.IsStatic) {
					Report.SymbolRelatedToPreviousError (base_type);
					Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
						GetSignatureForError (), base_type.GetSignatureForError ());
				} else if (base_type.IsSealed) {
					Report.SymbolRelatedToPreviousError (base_type);
					Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
						GetSignatureForError (), base_type.GetSignatureForError ());
				} else if (PartialContainer.IsStatic && base_type.BuiltinType != BuiltinTypeSpec.Type.Object) {
					Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
						GetSignatureForError (), base_type.GetSignatureForError ());
				}

				switch (base_type.BuiltinType) {
				case BuiltinTypeSpec.Type.Enum:
				case BuiltinTypeSpec.Type.ValueType:
				case BuiltinTypeSpec.Type.MulticastDelegate:
				case BuiltinTypeSpec.Type.Delegate:
				case BuiltinTypeSpec.Type.Array:
					if (!(spec is BuiltinTypeSpec)) {
						Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
							GetSignatureForError (), base_type.GetSignatureForError ());

						base_type = Compiler.BuiltinTypes.Object;
					}
					break;
				}

				if (!IsAccessibleAs (base_type)) {
					Report.SymbolRelatedToPreviousError (base_type);
					Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
						base_type.GetSignatureForError (), GetSignatureForError ());
				}
			}

			if (PartialContainer.IsStatic && ifaces != null) {
				foreach (var t in ifaces)
					Report.SymbolRelatedToPreviousError (t);
				Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
			}

			return ifaces;
		}

		/// Search for at least one defined condition in ConditionalAttribute of attribute class
		/// Valid only for attribute classes.
		public override string[] ConditionalConditions ()
		{
			if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
				return null;

			caching_flags &= ~Flags.Excluded_Undetected;

			if (OptAttributes == null)
				return null;

			Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
			if (attrs == null)
				return null;

			string[] conditions = new string[attrs.Length];
			for (int i = 0; i < conditions.Length; ++i)
				conditions[i] = attrs[i].GetConditionalAttributeValue ();

			caching_flags |= Flags.Excluded;
			return conditions;
		}
	}

	public sealed class Struct : ClassOrStruct
	{
		bool is_unmanaged, has_unmanaged_check_done;
		bool InTransit;

		// <summary>
		//   Modifiers allowed in a struct declaration
		// </summary>
		const Modifiers AllowedModifiers =
			Modifiers.NEW       |
			Modifiers.PUBLIC    |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL  |
			Modifiers.UNSAFE    |
			Modifiers.PRIVATE;

		public Struct (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
			: base (parent, name, attrs, MemberKind.Struct)
		{
			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;			
			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
			spec = new TypeSpec (Kind, null, this, null, ModFlags);
		}

		public override AttributeTargets AttributeTargets {
			get {
				return AttributeTargets.Struct;
			}
		}

		public override void Accept (StructuralVisitor visitor)
		{
			visitor.Visit (this);
		}

		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
		{
			base.ApplyAttributeBuilder (a, ctor, cdata, pa);

			//
			// When struct constains fixed fixed and struct layout has explicitly
			// set CharSet, its value has to be propagated to compiler generated
			// fixed types
			//
			if (a.Type == pa.StructLayout) {
				var value = a.GetNamedValue ("CharSet");
				if (value == null)
					return;

				for (int i = 0; i < Members.Count; ++i) {
					FixedField ff = Members [i] as FixedField;
					if (ff == null)
						continue;

					ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
				}
			}
		}

		bool CheckStructCycles ()
		{
			if (InTransit)
				return false;

			InTransit = true;
			foreach (var member in Members) {
				var field = member as Field;
				if (field == null)
					continue;

				TypeSpec ftype = field.Spec.MemberType;
				if (!ftype.IsStruct)
					continue;

				if (ftype is BuiltinTypeSpec)
					continue;

				foreach (var targ in ftype.TypeArguments) {
					if (!CheckFieldTypeCycle (targ)) {
						Report.Error (523, field.Location,
							"Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
							field.GetSignatureForError (), ftype.GetSignatureForError ());
						break;
					}
				}

				//
				// Static fields of exactly same type are allowed
				//
				if (field.IsStatic && ftype == CurrentType)
					continue;

				if (!CheckFieldTypeCycle (ftype)) {
					Report.Error (523, field.Location,
						"Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
						field.GetSignatureForError (), ftype.GetSignatureForError ());
					break;
				}
			}

			InTransit = false;
			return true;
		}

		static bool CheckFieldTypeCycle (TypeSpec ts)
		{
			var fts = ts.MemberDefinition as Struct;
			if (fts == null)
				return true;

			return fts.CheckStructCycles ();
		}

		protected override bool DoDefineMembers ()
		{
			var res = base.DoDefineMembers ();

			if (PrimaryConstructorParameters != null || (initialized_fields != null && !HasUserDefaultConstructor ())) {
				generated_primary_constructor = DefineDefaultConstructor (false);
				generated_primary_constructor.Define ();
			}

			return res;
		}

		public override void Emit ()
		{
			CheckStructCycles ();

			base.Emit ();
		}

		bool HasUserDefaultConstructor ()
		{
			foreach (var m in PartialContainer.Members) {
				var c = m as Constructor;
				if (c == null)
					continue;

				if (!c.IsStatic && c.ParameterInfo.IsEmpty)
					return true;
			}

			return false;
		}

		public override bool IsUnmanagedType ()
		{
			if (has_unmanaged_check_done)
				return is_unmanaged;

			if (requires_delayed_unmanagedtype_check)
				return true;

			var parent_def = Parent.PartialContainer;
			if (parent_def != null && parent_def.IsGenericOrParentIsGeneric) {
				has_unmanaged_check_done = true;
				return false;
			}

			if (first_nonstatic_field != null) {
				requires_delayed_unmanagedtype_check = true;

				foreach (var member in Members) {
					var f = member as Field;
					if (f == null)
						continue;

					if (f.IsStatic)
						continue;

					// It can happen when recursive unmanaged types are defined
					// struct S { S* s; }
					TypeSpec mt = f.MemberType;
					if (mt == null) {
						return true;
					}

					if (mt.IsUnmanaged)
						continue;

					has_unmanaged_check_done = true;
					return false;
				}

				has_unmanaged_check_done = true;
			}

			is_unmanaged = true;
			return true;
		}

		protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
		{
			var ifaces = base.ResolveBaseTypes (out base_class);
			base_type = Compiler.BuiltinTypes.ValueType;
			return ifaces;
		}
	}

	/// <summary>
	///   Interfaces
	/// </summary>
	public sealed class Interface : TypeDefinition {

		/// <summary>
		///   Modifiers allowed in a class declaration
		/// </summary>
		const Modifiers AllowedModifiers =
			Modifiers.NEW       |
			Modifiers.PUBLIC    |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL  |
		 	Modifiers.UNSAFE    |
			Modifiers.PRIVATE;

		public Interface (TypeContainer parent, MemberName name, Modifiers mod, Attributes attrs)
			: base (parent, name, attrs, MemberKind.Interface)
		{
			var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE;

			this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
			spec = new TypeSpec (Kind, null, this, null, ModFlags);
		}

		#region Properties

		public override AttributeTargets AttributeTargets {
			get {
				return AttributeTargets.Interface;
			}
		}

		protected override TypeAttributes TypeAttr {
			get {
				const TypeAttributes DefaultTypeAttributes =
					TypeAttributes.AutoLayout |
					TypeAttributes.Abstract |
					TypeAttributes.Interface;

				return base.TypeAttr | DefaultTypeAttributes;
			}
		}

		#endregion

		public override void Accept (StructuralVisitor visitor)
		{
			visitor.Visit (this);
		}

		public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
		{
			if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
				a.Error_MissingGuidAttribute ();
				return;
			}

			base.ApplyAttributeBuilder (a, ctor, cdata, pa);
		}

		protected override bool VerifyClsCompliance ()
		{
			if (!base.VerifyClsCompliance ())
				return false;

			if (iface_exprs != null) {
				foreach (var iface in iface_exprs) {
					if (iface.IsCLSCompliant ())
						continue;

					Report.SymbolRelatedToPreviousError (iface);
					Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
						GetSignatureForError (), iface.GetSignatureForError ());
				}
			}

			return true;
		}
	}

	public abstract class InterfaceMemberBase : MemberBase
	{
		//
		// Common modifiers allowed in a class declaration
		//
		protected const Modifiers AllowedModifiersClass =
			Modifiers.NEW |
			Modifiers.PUBLIC |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL |
			Modifiers.PRIVATE |
			Modifiers.STATIC |
			Modifiers.VIRTUAL |
			Modifiers.SEALED |
			Modifiers.OVERRIDE |
			Modifiers.ABSTRACT |
			Modifiers.UNSAFE |
			Modifiers.EXTERN;

		//
		// Common modifiers allowed in a struct declaration
		//
		protected const Modifiers AllowedModifiersStruct =
			Modifiers.NEW |
			Modifiers.PUBLIC |
			Modifiers.PROTECTED |
			Modifiers.INTERNAL |
			Modifiers.PRIVATE |
			Modifiers.STATIC |
			Modifiers.OVERRIDE |
			Modifiers.UNSAFE |
			Modifiers.EXTERN;

		//
		// Common modifiers allowed in a interface declaration
		//
		protected const Modifiers AllowedModifiersInterface =
			Modifiers.NEW |
			Modifiers.UNSAFE;

		//
		// Whether this is an interface member.
		//
		public bool IsInterface;

		//
		// If true, this is an explicit interface implementation
		//
		public readonly bool IsExplicitImpl;

		protected bool is_external_implementation;

		//
		// The interface type we are explicitly implementing
		//
		public TypeSpec InterfaceType;

		//
		// The method we're overriding if this is an override method.
		//
		protected MethodSpec base_method;

		readonly Modifiers explicit_mod_flags;
		public MethodAttributes flags;

		protected InterfaceMemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, MemberName name, Attributes attrs)
			: base (parent, type, mod, allowed_mod, Modifiers.PRIVATE, name, attrs)
		{
			IsInterface = parent.Kind == MemberKind.Interface;
			IsExplicitImpl = (MemberName.ExplicitInterface != null);
			explicit_mod_flags = mod;
		}

		public abstract Variance ExpectedMemberTypeVariance { get; }
		
		protected override bool CheckBase ()
		{
			if (!base.CheckBase ())
				return false;

			if ((caching_flags & Flags.MethodOverloadsExist) != 0)
				CheckForDuplications ();
			
			if (IsExplicitImpl)
				return true;

			// For System.Object only
			if (Parent.BaseType == null)
				return true;

			MemberSpec candidate;
			bool overrides = false;
			var base_member = FindBaseMember (out candidate, ref overrides);

			if ((ModFlags & Modifiers.OVERRIDE) != 0) {
				if (base_member == null) {
					if (candidate == null) {
						if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
							Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
								"object.Finalize()");
						} else {
							Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
								GetSignatureForError (), SimpleName.GetMemberType (this));
						}
					} else {
						Report.SymbolRelatedToPreviousError (candidate);
						if (this is Event)
							Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
						else if (this is PropertyBase)
							Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
						else
							Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
								GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
					}

					return false;
				}

				//
				// Handles ambiguous overrides
				//
				if (candidate != null) {
					Report.SymbolRelatedToPreviousError (candidate);
					Report.SymbolRelatedToPreviousError (base_member);

					// Get member definition for error reporting
					var m1 = MemberCache.GetMember (base_member.DeclaringType.GetDefinition (), base_member);
					var m2 = MemberCache.GetMember (candidate.DeclaringType.GetDefinition (), candidate);

					Report.Error (462, Location,
						"`{0}' cannot override inherited members `{1}' and `{2}' because they have the same signature when used in type `{3}'",
						GetSignatureForError (), m1.GetSignatureForError (), m2.GetSignatureForError (), Parent.GetSignatureForError ());
				}

				if (!CheckOverrideAgainstBase (base_member))
					return false;

				ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
				if (oa != null) {
					if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
						Report.SymbolRelatedToPreviousError (base_member);
						Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
							GetSignatureForError (), base_member.GetSignatureForError ());
					}
				} else {
					if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
						Report.SymbolRelatedToPreviousError (base_member);
						Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
							GetSignatureForError (), base_member.GetSignatureForError ());
					}
				}

				base_method = base_member as MethodSpec;
				return true;
			}

			if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
				base_member = candidate;

			if (base_member == null) {
				if ((ModFlags & Modifiers.NEW) != 0) {
					if (base_member == null) {
						Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
							GetSignatureForError ());
					}
				}
			} else {
				if ((ModFlags & Modifiers.NEW) == 0) {
					ModFlags |= Modifiers.NEW;
					if (!IsCompilerGenerated) {
						Report.SymbolRelatedToPreviousError (base_member);
						if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
							Report.Warning (114, 2, Location, "`{0}' hides inherited member `{1}'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword",
								GetSignatureForError (), base_member.GetSignatureForError ());
						} else {
							Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
								GetSignatureForError (), base_member.GetSignatureForError ());
						}
					}
				}

				if (!IsInterface && base_member.IsAbstract && !overrides && !IsStatic) {
					Report.SymbolRelatedToPreviousError (base_member);
					Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
						GetSignatureForError (), base_member.GetSignatureForError ());
				}
			}

			return true;
		}

		protected virtual bool CheckForDuplications ()
		{
			return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
		}

		//
		// Performs various checks on the MethodInfo `mb' regarding the modifier flags
		// that have been defined.
		//
		protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
		{
			bool ok = true;

			if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
				Report.SymbolRelatedToPreviousError (base_member);
				Report.Error (506, Location,
					"`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
					 GetSignatureForError (), TypeManager.CSharpSignature (base_member));
				ok = false;
			}

			// Now we check that the overriden method is not final	
			if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
				Report.SymbolRelatedToPreviousError (base_member);
				Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
							  GetSignatureForError (), TypeManager.CSharpSignature (base_member));
				ok = false;
			}

			var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
			if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
				Report.SymbolRelatedToPreviousError (base_member);
				if (this is PropertyBasedMember) {
					Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
						GetSignatureForError (), base_member_type.GetSignatureForError (), base_member.GetSignatureForError ());
				} else {
					Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
						GetSignatureForError (), base_member_type.GetSignatureForError (), base_member.GetSignatureForError ());
				}
				ok = false;
			}

			return ok;
		}

		protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
		{
			var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
			var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;

			if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
				//
				// It must be at least "protected"
				//
				if ((thisp & Modifiers.PROTECTED) == 0) {
					return false;
				}

				//
				// when overriding protected internal, the method can be declared
				// protected internal only within the same assembly or assembly
				// which has InternalsVisibleTo
				//
				if ((thisp & Modifiers.INTERNAL) != 0) {
					return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
				}

				//
				// protected overriding protected internal inside same assembly
				// requires internal modifier as well
				//
				if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
					return false;
				}

				return true;
			}

			return thisp == base_classp;
		}

		public override bool Define ()
		{
			if (IsInterface) {
				ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
					Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));

				flags = MethodAttributes.Public |
					MethodAttributes.Abstract |
					MethodAttributes.HideBySig |
					MethodAttributes.NewSlot |
					MethodAttributes.Virtual;
			} else {
				Parent.PartialContainer.MethodModifiersValid (this);

				flags = ModifiersExtensions.MethodAttr (ModFlags);
			}

			if (IsExplicitImpl) {
				InterfaceType = MemberName.ExplicitInterface.ResolveAsType (Parent);
				if (InterfaceType == null)
					return false;

				if ((ModFlags & Modifiers.PARTIAL) != 0) {
					Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
						GetSignatureForError ());
				}

				if (!InterfaceType.IsInterface) {
					Report.SymbolRelatedToPreviousError (InterfaceType);
					Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
						InterfaceType.GetSignatureForError ());
				} else {
					Parent.PartialContainer.VerifyImplements (this);
				}

				Modifiers allowed_explicit = Modifiers.AllowedExplicitImplFlags;
				if (this is Method)
					allowed_explicit |= Modifiers.ASYNC;

				ModifiersExtensions.Check (allowed_explicit, explicit_mod_flags, 0, Location, Report);
			}

			return base.Define ();
		}

		protected bool DefineParameters (ParametersCompiled parameters)
		{
			if (!parameters.Resolve (this))
				return false;

			bool error = false;
			for (int i = 0; i < parameters.Count; ++i) {
				Parameter p = parameters [i];

				if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
					p.Warning_UselessOptionalParameter (Report);

				if (p.CheckAccessibility (this))
					continue;

				TypeSpec t = parameters.Types [i];
				Report.SymbolRelatedToPreviousError (t);
				if (this is Indexer)
					Report.Error (55, Location,
						      "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
						      t.GetSignatureForError (), GetSignatureForError ());
				else if (this is Operator)
					Report.Error (57, Location,
						      "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
						      t.GetSignatureForError (), GetSignatureForError ());
				else
					Report.Error (51, Location,
						"Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
						t.GetSignatureForError (), GetSignatureForError ());
				error = true;
			}
			return !error;
		}

		protected override void DoMemberTypeDependentChecks ()
		{
			base.DoMemberTypeDependentChecks ();

			VarianceDecl.CheckTypeVariance (MemberType, ExpectedMemberTypeVariance, this);
		}

		public override void Emit()
		{
			// for extern static method must be specified either DllImport attribute or MethodImplAttribute.
			// We are more strict than csc and report this as an error because SRE does not allow emit that
			if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation && (OptAttributes == null || !OptAttributes.HasResolveError ())) {
				if (this is Constructor) {
					Report.Warning (824, 1, Location,
						"Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
				} else {
					Report.Warning (626, 1, Location,
						"`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
						GetSignatureForError ());
				}
			}

			base.Emit ();
		}

		public override bool EnableOverloadChecks (MemberCore overload)
		{
			//
			// Two members can differ in their explicit interface
			// type parameter only
			//
			InterfaceMemberBase imb = overload as InterfaceMemberBase;
			if (imb != null && imb.IsExplicitImpl) {
				if (IsExplicitImpl) {
					caching_flags |= Flags.MethodOverloadsExist;
				}
				return true;
			}

			return IsExplicitImpl;
		}

		protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
		{
			var base_modifiers = base_member.Modifiers;

			// Remove internal modifier from types which are not internally accessible
			if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
				!base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
				base_modifiers = Modifiers.PROTECTED;

			Report.SymbolRelatedToPreviousError (base_member);
			Report.Error (507, member.Location,
				"`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
				member.GetSignatureForError (),
				ModifiersExtensions.AccessibilityName (base_modifiers),
				base_member.GetSignatureForError ());
		}

		protected void Error_StaticReturnType ()
		{
			Report.Error (722, Location,
				"`{0}': static types cannot be used as return types",
				MemberType.GetSignatureForError ());
		}

		/// <summary>
		/// Gets base method and its return type
		/// </summary>
		protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate, ref bool overrides)
		{
			return MemberCache.FindBaseMember (this, out bestCandidate, ref overrides);
		}

		//
		// The "short" name of this property / indexer / event.  This is the
		// name without the explicit interface.
		//
		public string ShortName {
			get { return MemberName.Name; }
		}
		
		//
		// Returns full metadata method name
		//
		public string GetFullName (MemberName name)
		{
			return GetFullName (name.Name);
		}

		public string GetFullName (string name)
		{
			if (!IsExplicitImpl)
				return name;

			//
			// When dealing with explicit members a full interface type
			// name is added to member name to avoid possible name conflicts
			//
			// We use CSharpName which gets us full name with benefit of
			// replacing predefined names which saves some space and name
			// is still unique
			//
			return InterfaceType.GetSignatureForError () + "." + name;
		}

		public override string GetSignatureForDocumentation ()
		{
			if (IsExplicitImpl)
				return Parent.GetSignatureForDocumentation () + "." + InterfaceType.GetSignatureForDocumentation (true) + "#" + ShortName;

			return Parent.GetSignatureForDocumentation () + "." + ShortName;
		}

		public override bool IsUsed 
		{
			get { return IsExplicitImpl || base.IsUsed; }
		}

		public override void SetConstraints (List<Constraints> constraints_list)
		{
			if (((ModFlags & Modifiers.OVERRIDE) != 0 || IsExplicitImpl)) {
				Report.Error (460, Location,
					"`{0}': Cannot specify constraints for overrides and explicit interface implementation methods",
					GetSignatureForError ());
			}

			base.SetConstraints (constraints_list);
		}
	}

	public abstract class MemberBase : MemberCore
	{
		protected FullNamedExpression type_expr;
		protected TypeSpec member_type;
		public new TypeDefinition Parent;

		protected MemberBase (TypeDefinition parent, FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod, MemberName name, Attributes attrs)
			: base (parent, name, attrs)
		{
			this.Parent = parent;
			this.type_expr = type;

			if (name != MemberName.Null)
				ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
		}

		#region Properties

		public TypeSpec MemberType {
			get {
				return member_type;
			}
		}

		public FullNamedExpression TypeExpression {
			get {
				return type_expr;
			}
		}

		#endregion

		//
		// Main member define entry
		//
		public override bool Define ()
		{
			DoMemberTypeIndependentChecks ();

			//
			// Returns false only when type resolution failed
			//
			if (!ResolveMemberType ())
				return false;

			DoMemberTypeDependentChecks ();
			return true;
		}

		//
		// Any type_name independent checks
		//
		protected virtual void DoMemberTypeIndependentChecks ()
		{
			if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
				(ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
				Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
					GetSignatureForError (), Parent.GetSignatureForError ());
			}
		}

		//
		// Any type_name dependent checks
		//
		protected virtual void DoMemberTypeDependentChecks ()
		{
			// verify accessibility
			if (!IsAccessibleAs (MemberType)) {
				Report.SymbolRelatedToPreviousError (MemberType);
				if (this is Property)
					Report.Error (53, Location,
						"Inconsistent accessibility: property type `" +
						MemberType.GetSignatureForError () + "' is less " +
						"accessible than property `" + GetSignatureForError () + "'");
				else if (this is Indexer)
					Report.Error (54, Location,
						"Inconsistent accessibility: indexer return type `" +
						MemberType.GetSignatureForError () + "' is less " +
						"accessible than indexer `" + GetSignatureForError () + "'");
				else if (this is MethodCore) {
					if (this is Operator)
						Report.Error (56, Location,
							"Inconsistent accessibility: return type `" +
							MemberType.GetSignatureForError () + "' is less " +
							"accessible than operator `" + GetSignatureForError () + "'");
					else
						Report.Error (50, Location,
							"Inconsistent accessibility: return type `" +
							MemberType.GetSignatureForError () + "' is less " +
							"accessible than method `" + GetSignatureForError () + "'");
				} else if (this is Event) {
					Report.Error (7025, Location,
						"Inconsistent accessibility: event type `{0}' is less accessible than event `{1}'",
						MemberType.GetSignatureForError (), GetSignatureForError ());
				} else {
					Report.Error (52, Location,
						      "Inconsistent accessibility: field type `" +
						      MemberType.GetSignatureForError () + "' is less " +
						      "accessible than field `" + GetSignatureForError () + "'");
				}
			}
		}

		protected void IsTypePermitted ()
		{
			if (MemberType.IsSpecialRuntimeType) {
				if (Parent is StateMachine) {
					Report.Error (4012, Location,
						"Parameters or local variables of type `{0}' cannot be declared in async methods or iterators",
						MemberType.GetSignatureForError ());
				} else if (Parent is HoistedStoreyClass) {
					Report.Error (4013, Location,
						"Local variables of type `{0}' cannot be used inside anonymous methods, lambda expressions or query expressions",
						MemberType.GetSignatureForError ());
				} else {
					Report.Error (610, Location, 
						"Field or property cannot be of type `{0}'", MemberType.GetSignatureForError ());
				}
			}
		}

		protected virtual bool CheckBase ()
		{
			CheckProtectedModifier ();

			return true;
		}

		public override string GetSignatureForDocumentation ()
		{
			return Parent.GetSignatureForDocumentation () + "." + MemberName.Basename;
		}

		protected virtual bool ResolveMemberType ()
		{
			if (member_type != null)
				throw new InternalErrorException ("Multi-resolve");

			member_type = type_expr.ResolveAsType (this);
			return member_type != null;
		}
	}
}