Merge branch 'cecil-light'
[mono.git] / mcs / mcs / class.cs
1 //
2 // class.cs: Class and Struct handlers
3 //
4 // Authors: Miguel de Icaza (miguel@gnu.org)
5 //          Martin Baulig (martin@ximian.com)
6 //          Marek Safar (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2004-2008 Novell, Inc
12 //
13
14 using System;
15 using System.Collections.Generic;
16 using System.Reflection;
17 using System.Reflection.Emit;
18 using System.Runtime.CompilerServices;
19 using System.Runtime.InteropServices;
20 using System.Security;
21 using System.Security.Permissions;
22 using System.Text;
23 using System.Linq;
24
25 #if NET_2_1
26 using XmlElement = System.Object;
27 #else
28 using System.Xml;
29 #endif
30
31 using Mono.CompilerServices.SymbolWriter;
32
33 namespace Mono.CSharp {
34
35         /// <summary>
36         ///   This is the base class for structs and classes.  
37         /// </summary>
38         public abstract class TypeContainer : DeclSpace, ITypeDefinition
39         {
40                 //
41                 // Different context is needed when resolving type container base
42                 // types. Type names come from the parent scope but type parameter
43                 // names from the container scope.
44                 //
45                 public struct BaseContext : IMemberContext
46                 {
47                         TypeContainer tc;
48
49                         public BaseContext (TypeContainer tc)
50                         {
51                                 this.tc = tc;
52                         }
53
54                         #region IMemberContext Members
55
56                         public CompilerContext Compiler {
57                                 get { return tc.Compiler; }
58                         }
59
60                         public TypeSpec CurrentType {
61                                 get { return tc.Parent.CurrentType; }
62                         }
63
64                         public TypeParameter[] CurrentTypeParameters {
65                                 get { return tc.PartialContainer.CurrentTypeParameters; }
66                         }
67
68                         public MemberCore CurrentMemberDefinition {
69                                 get { return tc; }
70                         }
71
72                         public bool HasUnresolvedConstraints {
73                                 get { return true; }
74                         }
75
76                         public bool IsObsolete {
77                                 get { return tc.IsObsolete; }
78                         }
79
80                         public bool IsUnsafe {
81                                 get { return tc.IsUnsafe; }
82                         }
83
84                         public bool IsStatic {
85                                 get { return tc.IsStatic; }
86                         }
87
88                         public string GetSignatureForError ()
89                         {
90                                 return tc.GetSignatureForError ();
91                         }
92
93                         public IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
94                         {
95                                 return null;
96                         }
97
98                         public FullNamedExpression LookupNamespaceAlias (string name)
99                         {
100                                 return tc.Parent.LookupNamespaceAlias (name);
101                         }
102
103                         public FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
104                         {
105                                 if (arity == 0) {
106                                         TypeParameter[] tp = CurrentTypeParameters;
107                                         if (tp != null) {
108                                                 TypeParameter t = TypeParameter.FindTypeParameter (tp, name);
109                                                 if (t != null)
110                                                         return new TypeParameterExpr (t, loc);
111                                         }
112                                 }
113
114                                 return tc.Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
115                         }
116
117                         #endregion
118                 }
119
120                 [Flags]
121                 enum CachedMethods
122                 {
123                         Equals                          = 1,
124                         GetHashCode                     = 1 << 1,
125                         HasStaticFieldInitializer       = 1 << 2
126                 }
127
128
129                 // Whether this is a struct, class or interface
130                 public readonly MemberKind Kind;
131
132                 // Holds a list of classes and structures
133                 protected List<TypeContainer> types;
134
135                 List<MemberCore> ordered_explicit_member_list;
136                 List<MemberCore> ordered_member_list;
137
138                 // Holds the list of properties
139                 List<MemberCore> properties;
140
141                 // Holds the list of constructors
142                 protected List<Constructor> instance_constructors;
143
144                 // Holds the list of fields
145                 protected List<FieldBase> fields;
146
147                 // Holds a list of fields that have initializers
148                 protected List<FieldInitializer> initialized_fields;
149
150                 // Holds a list of static fields that have initializers
151                 protected List<FieldInitializer> initialized_static_fields;
152
153                 // Holds the list of constants
154                 protected List<MemberCore> constants;
155
156                 // Holds the methods.
157                 List<MemberCore> methods;
158
159                 // Holds the events
160                 protected List<MemberCore> events;
161
162                 // Holds the indexers
163                 List<MemberCore> indexers;
164
165                 // Holds the operators
166                 List<MemberCore> operators;
167
168                 // Holds the compiler generated classes
169                 protected List<CompilerGeneratedClass> compiler_generated;
170
171                 Dictionary<MethodSpec, Method> hoisted_base_call_proxies;
172
173                 Dictionary<string, FullNamedExpression> Cache = new Dictionary<string, FullNamedExpression> ();
174
175                 //
176                 // Pointers to the default constructor and the default static constructor
177                 //
178                 protected Constructor default_constructor;
179                 protected Constructor default_static_constructor;
180
181                 //
182                 // Points to the first non-static field added to the container.
183                 //
184                 // This is an arbitrary choice.  We are interested in looking at _some_ non-static field,
185                 // and the first one's as good as any.
186                 //
187                 FieldBase first_nonstatic_field;
188
189                 //
190                 // This one is computed after we can distinguish interfaces
191                 // from classes from the arraylist `type_bases' 
192                 //
193                 protected TypeSpec base_type;
194                 protected TypeExpr base_type_expr;
195                 protected TypeExpr[] iface_exprs;
196
197                 protected List<FullNamedExpression> type_bases;
198
199                 bool members_defined;
200                 bool members_defined_ok;
201                 bool type_defined;
202
203                 TypeContainer InTransit;
204
205                 GenericTypeParameterBuilder[] all_tp_builders;
206
207                 public const string DefaultIndexerName = "Item";
208
209                 private bool seen_normal_indexers = false;
210                 private string indexer_name = DefaultIndexerName;
211                 protected bool requires_delayed_unmanagedtype_check;
212                 bool error;
213
214                 private CachedMethods cached_method;
215
216                 protected TypeSpec spec;
217                 TypeSpec current_type;
218
219                 List<TypeContainer> partial_parts;
220
221                 public int DynamicSitesCounter;
222
223                 /// <remarks>
224                 ///  The pending methods that need to be implemented
225                 //   (interfaces or abstract methods)
226                 /// </remarks>
227                 PendingImplementation pending;
228
229                 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
230                                       Attributes attrs, MemberKind kind)
231                         : base (ns, parent, name, attrs)
232                 {
233                         if (parent != null && parent.NamespaceEntry != ns)
234                                 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
235
236                         this.Kind = kind;
237                         this.PartialContainer = this;
238                 }
239
240                 #region Properties
241
242                 public override TypeSpec CurrentType {
243                         get {
244                                 if (current_type == null) {
245                                         if (IsGeneric) {
246                                                 //
247                                                 // Switch to inflated version as it's used by all expressions
248                                                 //
249                                                 var targs = CurrentTypeParameters == null ? TypeSpec.EmptyTypes : CurrentTypeParameters.Select (l => l.Type).ToArray ();
250                                                 current_type = spec.MakeGenericType (targs);
251                                         } else {
252                                                 current_type = spec;
253                                         }
254                                 }
255
256                                 return current_type;
257                         }
258                 }
259
260                 public override TypeParameter[] CurrentTypeParameters {
261                         get {
262                                 return PartialContainer.type_params;
263                         }
264                 }
265
266                 int CurrentTypeParametersStartIndex {
267                         get {
268                                 int total = all_tp_builders.Length;
269                                 if (CurrentTypeParameters != null) {
270                                         return total - CurrentTypeParameters.Length;
271                                 }
272                                 return total;
273                         }
274                 }
275
276                 public virtual AssemblyDefinition DeclaringAssembly {
277                         get {
278                                 return Module.DeclaringAssembly;
279                         }
280                 }
281
282                 IAssemblyDefinition ITypeDefinition.DeclaringAssembly {
283                         get {
284                                 return Module.DeclaringAssembly;
285                         }
286                 }
287
288                 public TypeSpec Definition {
289                         get {
290                                 return spec;
291                         }
292                 }
293
294                 public bool HasMembersDefined {
295                         get {
296                                 return members_defined;
297                         }
298                 }
299
300                 #endregion
301
302                 public bool AddMember (MemberCore symbol)
303                 {
304                         return AddToContainer (symbol, symbol.MemberName.Basename);
305                 }
306
307                 public bool AddMember (MemberCore symbol, string name)
308                 {
309                         return AddToContainer (symbol, name);
310                 }
311
312                 protected virtual bool AddMemberType (TypeContainer ds)
313                 {
314                         return AddToContainer (ds, ds.Basename);
315                 }
316
317                 protected virtual void RemoveMemberType (DeclSpace ds)
318                 {
319                         RemoveFromContainer (ds.Basename);
320                 }
321
322                 public void AddConstant (Const constant)
323                 {
324                         if (!AddMember (constant))
325                                 return;
326
327                         if (constants == null)
328                                 constants = new List<MemberCore> ();
329                         
330                         constants.Add (constant);
331                 }
332
333                 public TypeContainer AddTypeContainer (TypeContainer tc)
334                 {
335                         if (!AddMemberType (tc))
336                                 return tc;
337
338                         if (types == null)
339                                 types = new List<TypeContainer> ();
340
341                         types.Add (tc);
342                         return tc;
343                 }
344
345                 public virtual TypeContainer AddPartial (TypeContainer next_part)
346                 {
347                         return AddPartial (next_part, next_part.Basename);
348                 }
349
350                 protected TypeContainer AddPartial (TypeContainer next_part, string name)
351                 {
352                         next_part.ModFlags |= Modifiers.PARTIAL;
353                         TypeContainer tc = GetDefinition (name) as TypeContainer;
354                         if (tc == null)
355                                 return AddTypeContainer (next_part);
356
357                         if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
358                                 Report.SymbolRelatedToPreviousError (next_part);
359                                 Error_MissingPartialModifier (tc);
360                         }
361
362                         if (tc.Kind != next_part.Kind) {
363                                 Report.SymbolRelatedToPreviousError (tc);
364                                 Report.Error (261, next_part.Location,
365                                         "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
366                                         next_part.GetSignatureForError ());
367                         }
368
369                         if ((tc.ModFlags & Modifiers.AccessibilityMask) != (next_part.ModFlags & Modifiers.AccessibilityMask) &&
370                                 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
371                                  (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
372                                 Report.SymbolRelatedToPreviousError (tc);
373                                 Report.Error (262, next_part.Location,
374                                         "Partial declarations of `{0}' have conflicting accessibility modifiers",
375                                         next_part.GetSignatureForError ());
376                         }
377
378                         if (tc.partial_parts == null)
379                                 tc.partial_parts = new List<TypeContainer> (1);
380
381                         if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
382                                 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
383                         } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
384                                 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.AccessibilityMask);
385                                 tc.ModFlags |= next_part.ModFlags;
386                         } else {
387                                 tc.ModFlags |= next_part.ModFlags;
388                         }
389
390                         tc.spec.Modifiers = tc.ModFlags;
391
392                         if (next_part.attributes != null) {
393                                 if (tc.attributes == null)
394                                         tc.attributes = next_part.attributes;
395                                 else
396                                         tc.attributes.AddAttributes (next_part.attributes.Attrs);
397                         }
398
399                         next_part.PartialContainer = tc;
400                         tc.partial_parts.Add (next_part);
401                         return tc;
402                 }
403
404                 public virtual void RemoveTypeContainer (TypeContainer next_part)
405                 {
406                         if (types != null)
407                                 types.Remove (next_part);
408                         RemoveMemberType (next_part);
409                 }
410                 
411                 public virtual TypeSpec AddDelegate (Delegate d)
412                 {
413                         AddTypeContainer (d);
414                         return null;
415                 }
416
417                 private void AddMemberToList (MemberCore mc, List<MemberCore> alist, bool isexplicit)
418                 {
419                         if (ordered_explicit_member_list == null)  {
420                                 ordered_explicit_member_list = new List<MemberCore> ();
421                                 ordered_member_list = new List<MemberCore> ();
422                         }
423
424                         if (isexplicit) {
425                                 if (Kind == MemberKind.Interface) {
426                                         Report.Error (541, mc.Location,
427                                                 "`{0}': explicit interface declaration can only be declared in a class or struct",
428                                                 mc.GetSignatureForError ());
429                                 }
430
431                                 ordered_explicit_member_list.Add (mc);
432                                 alist.Insert (0, mc);
433                         } else {
434                                 ordered_member_list.Add (mc);
435                                 alist.Add (mc);
436                         }
437
438                 }
439                 
440                 public void AddMethod (MethodOrOperator method)
441                 {
442                         if (!AddToContainer (method, method.MemberName.Basename))
443                                 return;
444                         
445                         if (methods == null)
446                                 methods = new List<MemberCore> ();
447
448                         if (method.MemberName.Left != null) 
449                                 AddMemberToList (method, methods, true);
450                         else 
451                                 AddMemberToList (method, methods, false);
452                 }
453
454                 public void AddConstructor (Constructor c)
455                 {
456                         bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
457                         if (!AddToContainer (c, is_static ?
458                                 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
459                                 return;
460                         
461                         if (is_static && c.ParameterInfo.IsEmpty){
462                                 if (default_static_constructor != null) {
463                                     Report.SymbolRelatedToPreviousError (default_static_constructor);
464                                         Report.Error (111, c.Location,
465                                                 "A member `{0}' is already defined. Rename this member or use different parameter types",
466                                                 c.GetSignatureForError ());
467                                     return;
468                                 }
469
470                                 default_static_constructor = c;
471                         } else {
472                                 if (c.ParameterInfo.IsEmpty)
473                                         default_constructor = c;
474                                 
475                                 if (instance_constructors == null)
476                                         instance_constructors = new List<Constructor> ();
477                                 
478                                 instance_constructors.Add (c);
479                         }
480                 }
481
482                 public bool AddField (FieldBase field)
483                 {
484                         if (!AddMember (field))
485                                 return false;
486
487                         if (fields == null)
488                                 fields = new List<FieldBase> ();
489
490                         fields.Add (field);
491
492                         if ((field.ModFlags & Modifiers.STATIC) != 0)
493                                 return true;
494
495                         if (first_nonstatic_field == null) {
496                                 first_nonstatic_field = field;
497                                 return true;
498                         }
499
500                         if (Kind == MemberKind.Struct && first_nonstatic_field.Parent != field.Parent) {
501                                 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
502                                 Report.Warning (282, 3, field.Location,
503                                         "struct instance field `{0}' found in different declaration from instance field `{1}'",
504                                         field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
505                         }
506                         return true;
507                 }
508
509                 public void AddProperty (Property prop)
510                 {
511                         if (!AddMember (prop))
512                                 return;
513
514                         if (properties == null)
515                                 properties = new List<MemberCore> ();
516
517                         if (prop.MemberName.Left != null)
518                                 AddMemberToList (prop, properties, true);
519                         else 
520                                 AddMemberToList (prop, properties, false);
521                 }
522
523                 public void AddEvent (Event e)
524                 {
525                         if (!AddMember (e))
526                                 return;
527
528                         if (events == null)
529                                 events = new List<MemberCore> ();
530
531                         events.Add (e);
532                 }
533
534                 /// <summary>
535                 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
536                 /// </summary>
537                 public void AddIndexer (Indexer i)
538                 {
539                         if (indexers == null)
540                                 indexers = new List<MemberCore> ();
541
542                         if (i.IsExplicitImpl)
543                                 AddMemberToList (i, indexers, true);
544                         else 
545                                 AddMemberToList (i, indexers, false);
546                 }
547
548                 public void AddOperator (Operator op)
549                 {
550                         if (!AddMember (op))
551                                 return;
552
553                         if (operators == null)
554                                 operators = new List<MemberCore> ();
555
556                         operators.Add (op);
557                 }
558
559                 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
560                 {
561                         Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
562
563                         if (compiler_generated == null)
564                                 compiler_generated = new List<CompilerGeneratedClass> ();
565
566                         compiler_generated.Add (c);
567                 }
568
569                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
570                 {
571                         if (a.Type == pa.DefaultMember) {
572                                 if (Indexers != null) {
573                                         Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
574                                         return;
575                                 }
576                         }
577
578                         if (a.Type == pa.Required) {
579                                 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
580                                 return;
581                         }
582
583                         TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
584                 } 
585
586                 public override AttributeTargets AttributeTargets {
587                         get {
588                                 throw new NotSupportedException ();
589                         }
590                 }
591
592                 public IList<TypeContainer> Types {
593                         get {
594                                 return types;
595                         }
596                 }
597
598                 public IList<MemberCore> Methods {
599                         get {
600                                 return methods;
601                         }
602                 }
603
604                 public IList<MemberCore> Constants {
605                         get {
606                                 return constants;
607                         }
608                 }
609
610                 public TypeSpec BaseType {
611                         get {
612                                 return spec.BaseType;
613                         }
614                 }
615
616                 public IList<FieldBase> Fields {
617                         get {
618                                 return fields;
619                         }
620                 }
621
622                 public IList<Constructor> InstanceConstructors {
623                         get {
624                                 return instance_constructors;
625                         }
626                 }
627
628                 public IList<MemberCore> Properties {
629                         get {
630                                 return properties;
631                         }
632                 }
633
634                 public IList<MemberCore> Events {
635                         get {
636                                 return events;
637                         }
638                 }
639                 
640                 public IList<MemberCore> Indexers {
641                         get {
642                                 return indexers;
643                         }
644                 }
645
646                 public IList<MemberCore> Operators {
647                         get {
648                                 return operators;
649                         }
650                 }
651
652                 protected override TypeAttributes TypeAttr {
653                         get {
654                                 return ModifiersExtensions.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
655                         }
656                 }
657
658                 public int TypeParametersCount {
659                         get {
660                                 return MemberName.Arity;
661                         }
662                 }
663
664                 TypeParameterSpec[] ITypeDefinition.TypeParameters {
665                         get {
666                                 // TODO MemberCache: this is going to hurt
667                                 return PartialContainer.type_params.Select (l => l.Type).ToArray ();
668                         }
669                 }
670
671                 public string GetAttributeDefaultMember ()
672                 {
673                         return indexers == null ? DefaultIndexerName : indexer_name;
674                 }
675
676                 public bool IsComImport {
677                         get {
678                                 if (OptAttributes == null)
679                                         return false;
680
681                                 return OptAttributes.Contains (Compiler.PredefinedAttributes.ComImport);
682                         }
683                 }
684
685                 string ITypeDefinition.Namespace {
686                         get {
687                                 return NamespaceEntry.NS.MemberName.GetSignatureForError ();
688                         }
689                 }
690
691                 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
692                 {
693                         if ((field.ModFlags & Modifiers.STATIC) != 0){
694                                 if (initialized_static_fields == null) {
695                                         PartialContainer.HasStaticFieldInitializer = true;
696                                         initialized_static_fields = new List<FieldInitializer> (4);
697                                 }
698
699                                 initialized_static_fields.Add (expression);
700                         } else {
701                                 if (initialized_fields == null)
702                                         initialized_fields = new List<FieldInitializer> (4);
703
704                                 initialized_fields.Add (expression);
705                         }
706                 }
707
708                 public void ResolveFieldInitializers (BlockContext ec)
709                 {
710                         if (partial_parts != null) {
711                                 foreach (TypeContainer part in partial_parts) {
712                                         part.DoResolveFieldInitializers (ec);
713                                 }
714                         }
715                         DoResolveFieldInitializers (ec);
716                 }
717
718                 void DoResolveFieldInitializers (BlockContext ec)
719                 {
720                         if (ec.IsStatic) {
721                                 if (initialized_static_fields == null)
722                                         return;
723
724                                 bool has_complex_initializer = !RootContext.Optimize;
725                                 int i;
726                                 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
727                                 for (i = 0; i < initialized_static_fields.Count; ++i) {
728                                         FieldInitializer fi = initialized_static_fields [i];
729                                         ExpressionStatement s = fi.ResolveStatement (ec);
730                                         if (s == null) {
731                                                 s = EmptyExpressionStatement.Instance;
732                                         } else if (fi.IsComplexInitializer) {
733                                                 has_complex_initializer |= true;
734                                         }
735
736                                         init [i] = s;
737                                 }
738
739                                 for (i = 0; i < initialized_static_fields.Count; ++i) {
740                                         FieldInitializer fi = initialized_static_fields [i];
741                                         //
742                                         // Need special check to not optimize code like this
743                                         // static int a = b = 5;
744                                         // static int b = 0;
745                                         //
746                                         if (!has_complex_initializer && fi.IsDefaultInitializer)
747                                                 continue;
748
749                                         ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
750                                 }
751
752                                 return;
753                         }
754
755                         if (initialized_fields == null)
756                                 return;
757
758                         for (int i = 0; i < initialized_fields.Count; ++i) {
759                                 FieldInitializer fi = initialized_fields [i];
760                                 ExpressionStatement s = fi.ResolveStatement (ec);
761                                 if (s == null)
762                                         continue;
763
764                                 //
765                                 // Field is re-initialized to its default value => removed
766                                 //
767                                 if (fi.IsDefaultInitializer && RootContext.Optimize)
768                                         continue;
769
770                                 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
771                         }
772                 }
773
774                 public override string DocComment {
775                         get {
776                                 return comment;
777                         }
778                         set {
779                                 if (value == null)
780                                         return;
781
782                                 comment += value;
783                         }
784                 }
785
786                 public PendingImplementation PendingImplementations {
787                         get { return pending; }
788                 }
789
790                 public TypeSpec GetAttributeCoClass ()
791                 {
792                         if (OptAttributes == null)
793                                 return null;
794
795                         Attribute a = OptAttributes.Search (Compiler.PredefinedAttributes.CoClass);
796                         if (a == null)
797                                 return null;
798
799                         return a.GetCoClassAttributeValue ();
800                 }
801
802                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
803                 {
804                         Attribute a = null;
805                         if (OptAttributes != null) {
806                                 a = OptAttributes.Search (pa);
807                         }
808
809                         if (a == null)
810                                 return null;
811
812                         return a.GetAttributeUsageAttribute ();
813                 }
814
815                 public virtual void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
816                 {
817                         // FIXME: get rid of partial_parts and store lists of bases of each part here
818                         // assumed, not verified: 'part' is in 'partial_parts' 
819                         ((TypeContainer) part).type_bases = bases;
820                 }
821
822                 /// <summary>
823                 ///   This function computes the Base class and also the
824                 ///   list of interfaces that the class or struct @c implements.
825                 ///   
826                 ///   The return value is an array (might be null) of
827                 ///   interfaces implemented (as Types).
828                 ///   
829                 ///   The @base_class argument is set to the base object or null
830                 ///   if this is `System.Object'. 
831                 /// </summary>
832                 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
833                 {
834                         base_class = null;
835                         if (type_bases == null)
836                                 return null;
837
838                         int count = type_bases.Count;
839                         TypeExpr [] ifaces = null;
840                         var base_context = new BaseContext (this);
841                         for (int i = 0, j = 0; i < count; i++){
842                                 FullNamedExpression fne = type_bases [i];
843
844                                 TypeExpr fne_resolved = fne.ResolveAsTypeTerminal (base_context, false);
845                                 if (fne_resolved == null)
846                                         continue;
847
848                                 if (i == 0 && Kind == MemberKind.Class && !fne_resolved.Type.IsInterface) {
849                                         if (fne_resolved.Type == InternalType.Dynamic) {
850                                                 Report.Error (1965, Location, "Class `{0}' cannot derive from the dynamic type",
851                                                         GetSignatureForError ());
852
853                                                 continue;
854                                         }
855                                         
856                                         base_type = fne_resolved.Type;
857                                         base_class = fne_resolved;
858                                         continue;
859                                 }
860
861                                 if (ifaces == null)
862                                         ifaces = new TypeExpr [count - i];
863
864                                 if (fne_resolved.Type.IsInterface) {
865                                         for (int ii = 0; ii < j; ++ii) {
866                                                 if (fne_resolved.Type == ifaces [ii].Type) {
867                                                         Report.Error (528, Location, "`{0}' is already listed in interface list",
868                                                                 fne_resolved.GetSignatureForError ());
869                                                         break;
870                                                 }
871                                         }
872
873                                         if (Kind == MemberKind.Interface && !IsAccessibleAs (fne_resolved.Type)) {
874                                                 Report.Error (61, fne.Location,
875                                                         "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
876                                                         fne_resolved.GetSignatureForError (), GetSignatureForError ());
877                                         }
878                                 } else {
879                                         Report.SymbolRelatedToPreviousError (fne_resolved.Type);
880                                         if (Kind != MemberKind.Class) {
881                                                 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
882                                         } else if (base_class != null)
883                                                 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
884                                                         GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
885                                         else {
886                                                 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
887                                                         GetSignatureForError (), fne_resolved.GetSignatureForError ());
888                                         }
889                                 }
890
891                                 ifaces [j++] = fne_resolved;
892                         }
893
894                         return ifaces;
895                 }
896
897                 TypeExpr[] GetNormalPartialBases ()
898                 {
899                         var ifaces = new List<TypeExpr> (0);
900                         if (iface_exprs != null)
901                                 ifaces.AddRange (iface_exprs);
902
903                         foreach (TypeContainer part in partial_parts) {
904                                 TypeExpr new_base_class;
905                                 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
906                                 if (new_base_class != null) {
907                                         if (base_type_expr != null && new_base_class.Type != base_type) {
908                                                 Report.SymbolRelatedToPreviousError (new_base_class.Location, "");
909                                                 Report.Error (263, part.Location,
910                                                         "Partial declarations of `{0}' must not specify different base classes",
911                                                         part.GetSignatureForError ());
912                                         } else {
913                                                 base_type_expr = new_base_class;
914                                                 base_type = base_type_expr.Type;
915                                         }
916                                 }
917
918                                 if (new_ifaces == null)
919                                         continue;
920
921                                 foreach (TypeExpr iface in new_ifaces) {
922                                         if (ifaces.Contains (iface))
923                                                 continue;
924
925                                         ifaces.Add (iface);
926                                 }
927                         }
928
929                         if (ifaces.Count == 0)
930                                 return null;
931
932                         return ifaces.ToArray ();
933                 }
934
935                 //
936                 // Checks that some operators come in pairs:
937                 //  == and !=
938                 // > and <
939                 // >= and <=
940                 // true and false
941                 //
942                 // They are matched based on the return type and the argument types
943                 //
944                 void CheckPairedOperators ()
945                 {
946                         bool has_equality_or_inequality = false;
947                         var operators = this.operators.ToArray ();
948                         bool[] has_pair = new bool[operators.Length];
949
950                         for (int i = 0; i < operators.Length; ++i) {
951                                 if (operators[i] == null)
952                                         continue;
953
954                                 Operator o_a = (Operator) operators[i];
955                                 Operator.OpType o_type = o_a.OperatorType;
956                                 if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
957                                         has_equality_or_inequality = true;
958
959                                 Operator.OpType matching_type = o_a.GetMatchingOperator ();
960                                 if (matching_type == Operator.OpType.TOP) {
961                                         operators[i] = null;
962                                         continue;
963                                 }
964
965                                 for (int ii = 0; ii < operators.Length; ++ii) {
966                                         Operator o_b = (Operator) operators[ii];
967                                         if (o_b == null || o_b.OperatorType != matching_type)
968                                                 continue;
969
970                                         if (!TypeSpecComparer.IsEqual (o_a.ReturnType, o_b.ReturnType))
971                                                 continue;
972
973                                         if (!TypeSpecComparer.Equals (o_a.ParameterTypes, o_b.ParameterTypes))
974                                                 continue;
975
976                                         operators[i] = null;
977
978                                         //
979                                         // Used to ignore duplicate user conversions
980                                         //
981                                         has_pair[ii] = true;
982                                 }
983                         }
984
985                         for (int i = 0; i < operators.Length; ++i) {
986                                 if (operators[i] == null || has_pair[i])
987                                         continue;
988
989                                 Operator o = (Operator) operators [i];
990                                 Report.Error (216, o.Location,
991                                         "The operator `{0}' requires a matching operator `{1}' to also be defined",
992                                         o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
993                         }
994
995                         if (has_equality_or_inequality) {
996                                 if (Methods == null || !HasEquals)
997                                         Report.Warning (660, 2, Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)",
998                                                 GetSignatureForError ());
999
1000                                 if (Methods == null || !HasGetHashCode)
1001                                         Report.Warning (661, 2, Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()",
1002                                                 GetSignatureForError ());
1003                         }
1004                 }
1005         
1006                 bool CreateTypeBuilder ()
1007                 {
1008                         //
1009                         // Sets .size to 1 for structs with no instance fields
1010                         //
1011                         int type_size = Kind == MemberKind.Struct && first_nonstatic_field == null ? 1 : 0;
1012
1013                         if (IsTopLevel) {
1014                                 // TODO: Completely wrong
1015                                 if (Module.GlobalRootNamespace.IsNamespace (Name)) {
1016                                         Report.Error (519, Location, "`{0}' clashes with a predefined namespace", Name);
1017                                 }
1018
1019                                 TypeBuilder = Module.CreateBuilder (Name, TypeAttr, type_size);
1020                         } else {
1021                                 TypeBuilder builder = Parent.TypeBuilder;
1022
1023                                 TypeBuilder = builder.DefineNestedType (Basename, TypeAttr, null, type_size);
1024                         }
1025
1026                         spec.SetMetaInfo (TypeBuilder);
1027                         spec.MemberCache = new MemberCache (this);
1028                         spec.DeclaringType = Parent.CurrentType;
1029
1030                         if (!IsTopLevel)
1031                                 Parent.MemberCache.AddMember (spec);
1032
1033                         if (IsGeneric) {
1034                                 string[] param_names = new string[TypeParameters.Length];
1035                                 for (int i = 0; i < TypeParameters.Length; i++)
1036                                         param_names [i] = TypeParameters[i].Name;
1037
1038                                 all_tp_builders = TypeBuilder.DefineGenericParameters (param_names);
1039
1040                                 int offset = CurrentTypeParametersStartIndex;
1041                                 for (int i = offset; i < all_tp_builders.Length; i++) {
1042                                         CurrentTypeParameters [i - offset].Define (all_tp_builders [i], spec);
1043                                 }
1044                         }
1045
1046                         return true;
1047                 }
1048
1049                 //
1050                 // Creates a proxy base method call inside this container for hoisted base member calls
1051                 //
1052                 public MethodSpec CreateHoistedBaseCallProxy (ResolveContext rc, MethodSpec method)
1053                 {
1054                         Method proxy_method;
1055
1056                         //
1057                         // One proxy per base method is enough
1058                         //
1059                         if (hoisted_base_call_proxies == null) {
1060                                 hoisted_base_call_proxies = new Dictionary<MethodSpec, Method> ();
1061                                 proxy_method = null;
1062                         } else {
1063                                 hoisted_base_call_proxies.TryGetValue (method, out proxy_method);
1064                         }
1065
1066                         if (proxy_method == null) {
1067                                 string name = CompilerGeneratedClass.MakeName (method.Name, null, "BaseCallProxy", hoisted_base_call_proxies.Count);
1068                                 var base_parameters = new Parameter[method.Parameters.Count];
1069                                 for (int i = 0; i < base_parameters.Length; ++i) {
1070                                         var base_param = method.Parameters.FixedParameters[i];
1071                                         base_parameters[i] = new Parameter (new TypeExpression (method.Parameters.Types[i], Location),
1072                                                 base_param.Name, base_param.ModFlags, null, Location);
1073                                         base_parameters[i].Resolve (this, i);
1074                                 }
1075
1076                                 var cloned_params = ParametersCompiled.CreateFullyResolved (base_parameters, method.Parameters.Types);
1077                                 if (method.Parameters.HasArglist) {
1078                                         cloned_params.FixedParameters[0] = new Parameter (null, "__arglist", Parameter.Modifier.NONE, null, Location);
1079                                         cloned_params.Types[0] = TypeManager.runtime_argument_handle_type;
1080                                 }
1081
1082                                 GenericMethod generic_method;
1083                                 MemberName member_name;
1084                                 if (method.IsGeneric) {
1085                                         //
1086                                         // Copy all base generic method type parameters info
1087                                         //
1088                                         var hoisted_tparams = method.GenericDefinition.TypeParameters;
1089                                         var targs = new TypeArguments ();
1090                                         var type_params = new TypeParameter[hoisted_tparams.Length];
1091                                         for (int i = 0; i < type_params.Length; ++i) {
1092                                                 var tp = hoisted_tparams[i];
1093                                                 targs.Add (new TypeParameterName (tp.Name, null, Location));
1094                                                 type_params[i] = new TypeParameter (tp, null, null, new MemberName (tp.Name), null);
1095                                         }
1096
1097                                         member_name = new MemberName (name, targs, Location);
1098                                         generic_method = new GenericMethod (NamespaceEntry, this, member_name, type_params,
1099                                                 new TypeExpression (method.ReturnType, Location), cloned_params);
1100                                 } else {
1101                                         member_name = new MemberName (name);
1102                                         generic_method = null;
1103                                 }
1104
1105                                 // Compiler generated proxy
1106                                 proxy_method = new Method (this, generic_method, new TypeExpression (method.ReturnType, Location),
1107                                         Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN,
1108                                         member_name, cloned_params, null);
1109
1110                                 var block = new ToplevelBlock (Compiler, proxy_method.ParameterInfo, Location);
1111
1112                                 var mg = MethodGroupExpr.CreatePredefined (method, method.DeclaringType, Location);
1113                                 mg.InstanceExpression = new BaseThis (method.DeclaringType, Location);
1114
1115                                 // Get all the method parameters and pass them as arguments
1116                                 var real_base_call = new Invocation (mg, block.GetAllParametersArguments ());
1117                                 Statement statement;
1118                                 if (method.ReturnType == TypeManager.void_type)
1119                                         statement = new StatementExpression (real_base_call);
1120                                 else
1121                                         statement = new Return (real_base_call, Location);
1122
1123                                 block.AddStatement (statement);
1124                                 proxy_method.Block = block;
1125
1126                                 methods.Add (proxy_method);
1127                                 proxy_method.Define ();
1128
1129                                 hoisted_base_call_proxies.Add (method, proxy_method);
1130                         }
1131
1132                         return proxy_method.Spec;
1133                 }
1134
1135                 bool DefineBaseTypes ()
1136                 {
1137                         iface_exprs = ResolveBaseTypes (out base_type_expr);
1138                         if (partial_parts != null) {
1139                                 iface_exprs = GetNormalPartialBases ();
1140                         }
1141
1142                         var cycle = CheckRecursiveDefinition (this);
1143                         if (cycle != null) {
1144                                 Report.SymbolRelatedToPreviousError (cycle);
1145                                 if (this is Interface) {
1146                                         Report.Error (529, Location,
1147                                                 "Inherited interface `{0}' causes a cycle in the interface hierarchy of `{1}'",
1148                                             GetSignatureForError (), cycle.GetSignatureForError ());
1149
1150                                         iface_exprs = null;
1151                                 } else {
1152                                         Report.Error (146, Location,
1153                                                 "Circular base class dependency involving `{0}' and `{1}'",
1154                                                 GetSignatureForError (), cycle.GetSignatureForError ());
1155
1156                                         base_type = null;
1157                                 }
1158                         }
1159
1160                         if (iface_exprs != null) {
1161                                 foreach (TypeExpr iface in iface_exprs) {
1162                                         // Prevents a crash, the interface might not have been resolved: 442144
1163                                         if (iface == null)
1164                                                 continue;
1165                                         
1166                                         var iface_type = iface.Type;
1167
1168                                         if (!spec.AddInterface (iface_type))
1169                                                 continue;
1170
1171                                         if (iface_type.IsGeneric && spec.Interfaces != null) {
1172                                                 foreach (var prev_iface in iface_exprs) {
1173                                                         if (prev_iface == iface)
1174                                                                 break;
1175
1176                                                         if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1177                                                                 continue;
1178
1179                                                         Report.Error (695, Location,
1180                                                                 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1181                                                                 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1182                                                 }
1183                                         }
1184
1185                                         TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1186
1187                                         // Ensure the base is always setup
1188                                         var compiled_iface = iface_type.MemberDefinition as Interface;
1189                                         if (compiled_iface != null) {
1190                                                 // TODO: Need DefineBaseType only
1191                                                 compiled_iface.DefineType ();
1192                                         }
1193
1194                                         if (iface_type.Interfaces != null) {
1195                                                 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1196                                                 for (int i = 0; i < base_ifaces.Count; ++i) {
1197                                                         var ii_iface_type = base_ifaces[i];
1198                                                         if (spec.AddInterface (ii_iface_type)) {
1199                                                                 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1200
1201                                                                 if (ii_iface_type.Interfaces != null)
1202                                                                         base_ifaces.AddRange (ii_iface_type.Interfaces);
1203                                                         }
1204                                                 }
1205                                         }
1206                                 }
1207                         }
1208
1209                         if (Kind == MemberKind.Interface) {
1210                                 spec.BaseType = TypeManager.object_type;
1211                                 return true;
1212                         }
1213
1214                         if (base_type != null) {
1215                                 spec.BaseType = base_type;
1216
1217                                 // Set base type after type creation
1218                                 TypeBuilder.SetParent (base_type.GetMetaInfo ());
1219                         }
1220
1221                         return true;
1222                 }
1223
1224                 public virtual void DefineConstants ()
1225                 {
1226                         if (constants != null) {
1227                                 foreach (Const c in constants) {
1228                                         c.DefineValue ();
1229                                 }
1230                         }
1231
1232                         if (instance_constructors != null) {
1233                                 foreach (MethodCore m in instance_constructors) {
1234                                         var p = m.ParameterInfo;
1235                                         if (!p.IsEmpty) {
1236                                                 p.ResolveDefaultValues (m);
1237                                         }
1238                                 }
1239                         }
1240
1241                         if (methods != null) {
1242                                 foreach (MethodCore m in methods) {
1243                                         var p = m.ParameterInfo;
1244                                         if (!p.IsEmpty) {
1245                                                 p.ResolveDefaultValues (m);
1246                                         }
1247                                 }
1248                         }
1249
1250                         if (indexers != null) {
1251                                 foreach (Indexer i in indexers) {
1252                                         i.ParameterInfo.ResolveDefaultValues (i);
1253                                 }
1254                         }
1255
1256                         if (types != null) {
1257                                 foreach (var t in types)
1258                                         t.DefineConstants ();
1259                         }
1260                 }
1261
1262                 //
1263                 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1264                 //
1265                 public TypeBuilder CreateType ()
1266                 {
1267                         if (TypeBuilder != null)
1268                                 return TypeBuilder;
1269
1270                         if (error)
1271                                 return null;
1272
1273                         if (!CreateTypeBuilder ()) {
1274                                 error = true;
1275                                 return null;
1276                         }
1277
1278                         if (partial_parts != null) {
1279                                 foreach (TypeContainer part in partial_parts) {
1280                                         part.spec = spec;
1281                                         part.current_type = current_type;
1282                                         part.TypeBuilder = TypeBuilder;
1283                                 }
1284                         }
1285
1286                         if (Types != null) {
1287                                 foreach (TypeContainer tc in Types) {
1288                                         if (tc.CreateType () == null) {
1289                                                 error = true;
1290                                                 return null;
1291                                         }
1292                                 }
1293                         }
1294
1295                         return TypeBuilder;
1296                 }
1297
1298                 public override TypeBuilder DefineType ()
1299                 {
1300                         if (error)
1301                                 return null;
1302                         if (type_defined)
1303                                 return TypeBuilder;
1304
1305                         type_defined = true;
1306
1307                         if (!DefineBaseTypes ()) {
1308                                 error = true;
1309                                 return null;
1310                         }
1311
1312                         if (!DefineNestedTypes ()) {
1313                                 error = true;
1314                                 return null;
1315                         }
1316
1317                         return TypeBuilder;
1318                 }
1319
1320                 public override void SetParameterInfo (List<Constraints> constraints_list)
1321                 {
1322                         base.SetParameterInfo (constraints_list);
1323
1324                         if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1325                                 return;
1326
1327                         TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1328                         for (int i = 0; i < tc_names.Length; ++i) {
1329                                 if (tc_names [i].Name != type_params [i].Name) {
1330                                         Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1331                                         Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1332                                                 GetSignatureForError ());
1333                                         break;
1334                                 }
1335
1336                                 if (tc_names [i].Variance != type_params [i].Variance) {
1337                                         Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1338                                         Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1339                                                 GetSignatureForError ());
1340                                         break;
1341                                 }
1342                         }
1343                 }
1344
1345                 //
1346                 // Replaces normal spec with predefined one when compiling corlib
1347                 // and this type container defines predefined type
1348                 //
1349                 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1350                 {
1351                         this.spec = spec;
1352                 }
1353
1354                 void UpdateTypeParameterConstraints (TypeContainer part)
1355                 {
1356                         TypeParameter[] current_params = type_params;
1357                         for (int i = 0; i < current_params.Length; i++) {
1358                                 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1359                                         continue;
1360
1361                                 Report.SymbolRelatedToPreviousError (Location, "");
1362                                 Report.Error (265, part.Location,
1363                                         "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1364                                         GetSignatureForError (), current_params [i].GetSignatureForError ());
1365                         }
1366                 }
1367
1368                 public bool ResolveTypeParameters ()
1369                 {
1370                         if (!DoResolveTypeParameters ())
1371                                 return false;
1372
1373                         if (types != null) {
1374                                 foreach (var type in types)
1375                                         if (!type.ResolveTypeParameters ())
1376                                                 return false;
1377                         }
1378
1379                         if (compiler_generated != null) {
1380                                 foreach (CompilerGeneratedClass c in compiler_generated)
1381                                         if (!c.ResolveTypeParameters ())
1382                                                 return false;
1383                         }
1384
1385                         return true;
1386                 }
1387
1388                 protected virtual bool DoResolveTypeParameters ()
1389                 {
1390                         if (CurrentTypeParameters == null)
1391                                 return true;
1392
1393                         if (PartialContainer != this)
1394                                 throw new InternalErrorException ();
1395
1396                         var base_context = new BaseContext (this);
1397                         foreach (TypeParameter type_param in CurrentTypeParameters) {
1398                                 if (!type_param.ResolveConstraints (base_context)) {
1399                                         error = true;
1400                                         return false;
1401                                 }
1402                         }
1403
1404                         if (partial_parts != null) {
1405                                 foreach (TypeContainer part in partial_parts)
1406                                         UpdateTypeParameterConstraints (part);
1407                         }
1408
1409                         return true;
1410                 }
1411
1412                 protected virtual bool DefineNestedTypes ()
1413                 {
1414                         if (Types != null) {
1415                                 foreach (TypeContainer tc in Types)
1416                                         if (tc.DefineType () == null)
1417                                                 return false;
1418                         }
1419
1420                         return true;
1421                 }
1422
1423                 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1424                 {
1425                         if (InTransit != null)
1426                                 return spec;
1427
1428                         InTransit = tc;
1429
1430                         if (base_type_expr != null) {
1431                                 var ptc = base_type.MemberDefinition as TypeContainer;
1432                                 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1433                                         return base_type;
1434                         }
1435
1436                         if (iface_exprs != null) {
1437                                 foreach (TypeExpr iface in iface_exprs) {
1438                                         // the interface might not have been resolved, prevents a crash, see #442144
1439                                         if (iface == null)
1440                                                 continue;
1441                                         var ptc = iface.Type.MemberDefinition as Interface;
1442                                         if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1443                                                 return iface.Type;
1444                                 }
1445                         }
1446
1447                         if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1448                                 return spec;
1449
1450                         InTransit = null;
1451                         return null;
1452                 }
1453
1454                 /// <summary>
1455                 ///   Populates our TypeBuilder with fields and methods
1456                 /// </summary>
1457                 public sealed override bool Define ()
1458                 {
1459                         if (members_defined)
1460                                 return members_defined_ok;
1461
1462                         members_defined_ok = DoDefineMembers ();
1463                         members_defined = true;
1464
1465                         if (types != null) {
1466                                 foreach (var nested in types)
1467                                         nested.Define ();
1468                         }
1469
1470                         return members_defined_ok;
1471                 }
1472
1473                 protected virtual bool DoDefineMembers ()
1474                 {
1475                         if (iface_exprs != null) {
1476                                 foreach (TypeExpr iface in iface_exprs) {
1477                                         if (iface == null)
1478                                                 continue;
1479
1480                                         var iface_type = iface.Type;
1481
1482                                         // Ensure the base is always setup
1483                                         var compiled_iface = iface_type.MemberDefinition as Interface;
1484                                         if (compiled_iface != null)
1485                                                 compiled_iface.Define ();
1486
1487                                         if (Kind == MemberKind.Interface)
1488                                                 MemberCache.AddInterface (iface_type);
1489
1490                                         ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1491                                         if (oa != null && !IsObsolete)
1492                                                 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1493
1494                                         GenericTypeExpr ct = iface as GenericTypeExpr;
1495                                         if (ct != null) {
1496                                                 // TODO: passing `this' is wrong, should be base type iface instead
1497                                                 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1498
1499                                                 ct.CheckConstraints (this);
1500
1501                                                 if (ct.HasDynamicArguments () && !IsCompilerGenerated) {
1502                                                         Report.Error (1966, iface.Location,
1503                                                                 "`{0}': cannot implement a dynamic interface `{1}'",
1504                                                                 GetSignatureForError (), iface.GetSignatureForError ());
1505                                                         return false;
1506                                                 }
1507                                         }
1508                                 }
1509                         }
1510
1511                         if (base_type != null) {
1512                                 ObsoleteAttribute obsolete_attr = base_type.GetAttributeObsolete ();
1513                                 if (obsolete_attr != null && !IsObsolete)
1514                                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1515
1516                                 var ct = base_type_expr as GenericTypeExpr;
1517                                 if (ct != null)
1518                                         ct.CheckConstraints (this);
1519
1520                                 var baseContainer = base_type.MemberDefinition as ClassOrStruct;
1521                                 if (baseContainer != null) {
1522                                         baseContainer.Define ();
1523
1524                                         //
1525                                         // It can trigger define of this type (for generic types only)
1526                                         //
1527                                         if (HasMembersDefined)
1528                                                 return true;
1529                                 }
1530                         }
1531
1532                         if (type_params != null) {
1533                                 foreach (var tp in type_params) {
1534                                         tp.CheckGenericConstraints ();
1535                                 }
1536                         }
1537
1538                         DefineContainerMembers (constants);
1539                         DefineContainerMembers (fields);
1540
1541                         if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1542                                 pending = PendingImplementation.GetPendingImplementations (this);
1543
1544                                 if (requires_delayed_unmanagedtype_check) {
1545                                         requires_delayed_unmanagedtype_check = false;
1546                                         foreach (FieldBase f in fields) {
1547                                                 if (f.MemberType != null && f.MemberType.IsPointer)
1548                                                         TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1549                                         }
1550                                 }
1551                         }
1552                 
1553                         //
1554                         // Constructors are not in the defined_names array
1555                         //
1556                         DefineContainerMembers (instance_constructors);
1557                 
1558                         DefineContainerMembers (events);
1559                         DefineContainerMembers (ordered_explicit_member_list);
1560                         DefineContainerMembers (ordered_member_list);
1561
1562                         if (operators != null) {
1563                                 DefineContainerMembers (operators);
1564                                 CheckPairedOperators ();
1565                         }
1566
1567                         ComputeIndexerName();
1568                         CheckEqualsAndGetHashCode();
1569
1570                         return true;
1571                 }
1572
1573                 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1574                 {
1575                         if (mcal != null) {
1576                                 for (int i = 0; i < mcal.Count; ++i) {
1577                                         MemberCore mc = (MemberCore) mcal[i];
1578                                         try {
1579                                                 mc.Define ();
1580                                         } catch (Exception e) {
1581                                                 throw new InternalErrorException (mc, e);
1582                                         }
1583                                 }
1584                         }
1585                 }
1586                 
1587                 protected virtual void ComputeIndexerName ()
1588                 {
1589                         if (indexers == null)
1590                                 return;
1591
1592                         string class_indexer_name = null;
1593
1594                         //
1595                         // If there's both an explicit and an implicit interface implementation, the
1596                         // explicit one actually implements the interface while the other one is just
1597                         // a normal indexer.  See bug #37714.
1598                         //
1599
1600                         // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1601                         foreach (Indexer i in indexers) {
1602                                 if (i.InterfaceType != null) {
1603                                         if (seen_normal_indexers)
1604                                                 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1605                                         continue;
1606                                 }
1607
1608                                 seen_normal_indexers = true;
1609
1610                                 if (class_indexer_name == null) {
1611                                         class_indexer_name = i.ShortName;
1612                                         continue;
1613                                 }
1614
1615                                 if (i.ShortName != class_indexer_name)
1616                                         Report.Error (668, i.Location, "Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type");
1617                         }
1618
1619                         if (class_indexer_name != null)
1620                                 indexer_name = class_indexer_name;
1621                 }
1622
1623                 void EmitIndexerName ()
1624                 {
1625                         if (!seen_normal_indexers)
1626                                 return;
1627
1628                         PredefinedAttribute pa = Compiler.PredefinedAttributes.DefaultMember;
1629                         if (pa.Constructor == null &&
1630                                 !pa.ResolveConstructor (Location, TypeManager.string_type))
1631                                 return;
1632
1633                         var encoder = new AttributeEncoder (false);
1634                         encoder.Encode (GetAttributeDefaultMember ());
1635                         encoder.EncodeEmptyNamedArguments ();
1636
1637                         pa.EmitAttribute (TypeBuilder, encoder);
1638                 }
1639
1640                 protected virtual void CheckEqualsAndGetHashCode ()
1641                 {
1642                         if (methods == null)
1643                                 return;
1644
1645                         if (HasEquals && !HasGetHashCode) {
1646                                 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1647                         }
1648                 }
1649
1650                 // Indicated whether container has StructLayout attribute set Explicit
1651                 public bool HasExplicitLayout {
1652                         get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1653                         set { caching_flags |= Flags.HasExplicitLayout; }
1654                 }
1655
1656                 public bool HasStructLayout {
1657                         get { return (caching_flags & Flags.HasStructLayout) != 0; }
1658                         set { caching_flags |= Flags.HasStructLayout; }
1659                 }
1660
1661                 public MemberCache MemberCache {
1662                         get {
1663                                 return spec.MemberCache;
1664                         }
1665                 }
1666
1667                 void CheckMemberUsage (List<MemberCore> al, string member_type)
1668                 {
1669                         if (al == null)
1670                                 return;
1671
1672                         foreach (MemberCore mc in al) {
1673                                 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1674                                         continue;
1675
1676                                 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1677                                         Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1678                                 }
1679                         }
1680                 }
1681
1682                 public virtual void VerifyMembers ()
1683                 {
1684                         //
1685                         // Check for internal or private fields that were never assigned
1686                         //
1687                         if (Report.WarningLevel >= 3) {
1688                                 if (RootContext.EnhancedWarnings) {
1689                                         CheckMemberUsage (properties, "property");
1690                                         CheckMemberUsage (methods, "method");
1691                                         CheckMemberUsage (constants, "constant");
1692                                 }
1693
1694                                 if (fields != null){
1695                                         bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1696                                         foreach (FieldBase f in fields) {
1697                                                 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1698                                                         if (is_type_exposed)
1699                                                                 continue;
1700
1701                                                         f.SetIsUsed ();
1702                                                 }                               
1703                                                 
1704                                                 if (!f.IsUsed){
1705                                                         if ((f.caching_flags & Flags.IsAssigned) == 0)
1706                                                                 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1707                                                         else {
1708                                                                 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1709                                                                         f.GetSignatureForError ());
1710                                                         }
1711                                                         continue;
1712                                                 }
1713                                                 
1714                                                 //
1715                                                 // Only report 649 on level 4
1716                                                 //
1717                                                 if (Report.WarningLevel < 4)
1718                                                         continue;
1719                                                 
1720                                                 if ((f.caching_flags & Flags.IsAssigned) != 0)
1721                                                         continue;
1722
1723                                                 //
1724                                                 // Don't be pendatic over serializable attributes
1725                                                 //
1726                                                 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1727                                                         continue;
1728                                                 
1729                                                 Constant c = New.Constantify (f.MemberType, f.Location);
1730                                                 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1731                                                         f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1732                                         }
1733                                 }
1734                         }
1735                 }
1736
1737                 public override void Emit ()
1738                 {
1739                         if (!IsTopLevel) {
1740                                 MemberSpec candidate;
1741                                 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1742                                 if (conflict_symbol == null && candidate == null) {
1743                                         if ((ModFlags & Modifiers.NEW) != 0)
1744                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1745                                                         GetSignatureForError ());
1746                                 } else {
1747                                         if ((ModFlags & Modifiers.NEW) == 0) {
1748                                                 if (candidate == null)
1749                                                         candidate = conflict_symbol;
1750
1751                                                 Report.SymbolRelatedToPreviousError (candidate);
1752                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1753                                                         GetSignatureForError (), candidate.GetSignatureForError ());
1754                                         }
1755                                 }
1756                         }
1757
1758                         if (all_tp_builders != null) {
1759                                 int current_starts_index = CurrentTypeParametersStartIndex;
1760                                 for (int i = 0; i < all_tp_builders.Length; i++) {
1761                                         if (i < current_starts_index) {
1762                                                 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1763                                         } else {
1764                                                 CurrentTypeParameters [i - current_starts_index].Emit ();
1765                                         }
1766                                 }
1767                         }
1768
1769                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1770                                 Compiler.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1771
1772                         base.Emit ();
1773                 }
1774
1775                 // TODO: move to ClassOrStruct
1776                 void EmitConstructors ()
1777                 {
1778                         if (instance_constructors == null)
1779                                 return;
1780
1781                         if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1782                                 bool has_compliant_args = false;
1783
1784                                 foreach (Constructor c in instance_constructors) {
1785                                         try {
1786                                                 c.Emit ();
1787                                         }
1788                                         catch (Exception e) {
1789                                                 throw new InternalErrorException (c, e);
1790                                         }
1791
1792                                         if (has_compliant_args)
1793                                                 continue;
1794
1795                                         has_compliant_args = c.HasCompliantArgs;
1796                                 }
1797                                 if (!has_compliant_args)
1798                                         Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1799                         } else {
1800                                 foreach (Constructor c in instance_constructors) {
1801                                         try {
1802                                                 c.Emit ();
1803                                         }
1804                                         catch (Exception e) {
1805                                                 throw new InternalErrorException (c, e);
1806                                         }
1807                                 }
1808                         }
1809                 }
1810
1811                 /// <summary>
1812                 ///   Emits the code, this step is performed after all
1813                 ///   the types, enumerations, constructors
1814                 /// </summary>
1815                 public virtual void EmitType ()
1816                 {
1817                         if (OptAttributes != null)
1818                                 OptAttributes.Emit ();
1819
1820                         Emit ();
1821
1822                         EmitConstructors ();
1823
1824                         if (constants != null)
1825                                 foreach (Const con in constants)
1826                                         con.Emit ();
1827
1828                         if (default_static_constructor != null)
1829                                 default_static_constructor.Emit ();
1830                         
1831                         if (operators != null)
1832                                 foreach (Operator o in operators)
1833                                         o.Emit ();
1834
1835                         if (properties != null)
1836                                 foreach (Property p in properties)
1837                                         p.Emit ();
1838
1839                         if (indexers != null) {
1840                                 foreach (Indexer indx in indexers)
1841                                         indx.Emit ();
1842                                 EmitIndexerName ();
1843                         }
1844
1845                         if (events != null){
1846                                 foreach (Event e in Events)
1847                                         e.Emit ();
1848                         }
1849
1850                         if (methods != null) {
1851                                 for (int i = 0; i < methods.Count; ++i)
1852                                         ((MethodOrOperator) methods [i]).Emit ();
1853                         }
1854                         
1855                         if (fields != null)
1856                                 foreach (FieldBase f in fields)
1857                                         f.Emit ();
1858
1859                         if (types != null) {
1860                                 foreach (TypeContainer t in types)
1861                                         t.EmitType ();
1862                         }
1863
1864                         if (pending != null)
1865                                 pending.VerifyPendingMethods (Report);
1866
1867                         if (Report.Errors > 0)
1868                                 return;
1869
1870                         if (compiler_generated != null) {
1871                                 for (int i = 0; i < compiler_generated.Count; ++i)
1872                                         compiler_generated [i].EmitType ();
1873                         }
1874                 }
1875
1876                 public void CloseType ()
1877                 {
1878                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
1879                                 return;
1880
1881                         // Close base type container first to avoid TypeLoadException
1882                         if (spec.BaseType != null) {
1883                                 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1884                                 if (btype != null)
1885                                         btype.CloseType ();
1886                         }
1887
1888                         try {
1889                                 caching_flags |= Flags.CloseTypeCreated;
1890                                 TypeBuilder.CreateType ();
1891                         } catch (TypeLoadException){
1892                                 //
1893                                 // This is fine, the code still created the type
1894                                 //
1895 //                              Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1896 //                              Console.WriteLine (e.Message);
1897                         } catch (Exception e) {
1898                                 throw new InternalErrorException (this, e);
1899                         }
1900                         
1901                         if (Types != null){
1902                                 foreach (TypeContainer tc in Types)
1903                                         tc.CloseType ();
1904                         }
1905
1906                         if (compiler_generated != null)
1907                                 foreach (CompilerGeneratedClass c in compiler_generated)
1908                                         c.CloseType ();
1909                         
1910                         types = null;
1911                         fields = null;
1912                         initialized_fields = null;
1913                         initialized_static_fields = null;
1914                         constants = null;
1915                         ordered_explicit_member_list = null;
1916                         ordered_member_list = null;
1917                         methods = null;
1918                         events = null;
1919                         indexers = null;
1920                         operators = null;
1921                         compiler_generated = null;
1922                         default_constructor = null;
1923                         default_static_constructor = null;
1924                         type_bases = null;
1925                         OptAttributes = null;
1926                 }
1927
1928                 //
1929                 // Performs the validation on a Method's modifiers (properties have
1930                 // the same properties).
1931                 //
1932                 // TODO: Why is it not done at parse stage ?
1933                 //
1934                 public bool MethodModifiersValid (MemberCore mc)
1935                 {
1936                         const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1937                         const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1938                         bool ok = true;
1939                         var flags = mc.ModFlags;
1940                         
1941                         //
1942                         // At most one of static, virtual or override
1943                         //
1944                         if ((flags & Modifiers.STATIC) != 0){
1945                                 if ((flags & vao) != 0){
1946                                         Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1947                                                 mc.GetSignatureForError ());
1948                                         ok = false;
1949                                 }
1950                         }
1951
1952                         if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1953                                 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1954                                         mc.GetSignatureForError ());
1955                                 ok = false;
1956                         }
1957
1958                         //
1959                         // If the declaration includes the abstract modifier, then the
1960                         // declaration does not include static, virtual or extern
1961                         //
1962                         if ((flags & Modifiers.ABSTRACT) != 0){
1963                                 if ((flags & Modifiers.EXTERN) != 0){
1964                                         Report.Error (
1965                                                 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1966                                         ok = false;
1967                                 }
1968
1969                                 if ((flags & Modifiers.SEALED) != 0) {
1970                                         Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1971                                         ok = false;
1972                                 }
1973
1974                                 if ((flags & Modifiers.VIRTUAL) != 0){
1975                                         Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1976                                         ok = false;
1977                                 }
1978
1979                                 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1980                                         Report.SymbolRelatedToPreviousError (this);
1981                                         Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1982                                                 mc.GetSignatureForError (), GetSignatureForError ());
1983                                         ok = false;
1984                                 }
1985                         }
1986
1987                         if ((flags & Modifiers.PRIVATE) != 0){
1988                                 if ((flags & vao) != 0){
1989                                         Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1990                                         ok = false;
1991                                 }
1992                         }
1993
1994                         if ((flags & Modifiers.SEALED) != 0){
1995                                 if ((flags & Modifiers.OVERRIDE) == 0){
1996                                         Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1997                                         ok = false;
1998                                 }
1999                         }
2000
2001                         return ok;
2002                 }
2003
2004                 public Constructor DefaultStaticConstructor {
2005                         get { return default_static_constructor; }
2006                 }
2007
2008                 protected override bool VerifyClsCompliance ()
2009                 {
2010                         if (!base.VerifyClsCompliance ())
2011                                 return false;
2012
2013                         // Check this name against other containers
2014                         NamespaceEntry.NS.VerifyClsCompliance ();
2015
2016                         // Check all container names for user classes
2017                         if (Kind != MemberKind.Delegate)
2018                                 MemberCache.VerifyClsCompliance (Definition, Report);
2019
2020                         if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2021                                 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2022                                         GetSignatureForError (), BaseType.GetSignatureForError ());
2023                         }
2024                         return true;
2025                 }
2026
2027                 /// <summary>
2028                 ///   Performs checks for an explicit interface implementation.  First it
2029                 ///   checks whether the `interface_type' is a base inteface implementation.
2030                 ///   Then it checks whether `name' exists in the interface type.
2031                 /// </summary>
2032                 public bool VerifyImplements (InterfaceMemberBase mb)
2033                 {
2034                         var ifaces = spec.Interfaces;
2035                         if (ifaces != null) {
2036                                 foreach (TypeSpec t in ifaces){
2037                                         if (t == mb.InterfaceType)
2038                                                 return true;
2039                                 }
2040                         }
2041                         
2042                         Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2043                         Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2044                                 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2045                         return false;
2046                 }
2047
2048                 //
2049                 // Used for visiblity checks to tests whether this definition shares
2050                 // base type baseType, it does member-definition search
2051                 //
2052                 public bool IsBaseTypeDefinition (TypeSpec baseType)
2053                 {
2054                         // RootContext check
2055                         if (TypeBuilder == null)
2056                                 return false;
2057
2058                         var type = spec;
2059                         do {
2060                                 if (type.MemberDefinition == baseType.MemberDefinition)
2061                                         return true;
2062
2063                                 type = type.BaseType;
2064                         } while (type != null);
2065
2066                         return false;
2067                 }
2068
2069                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2070                 {
2071                         return Module.DeclaringAssembly == assembly;
2072                 }
2073
2074                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2075                 {
2076                         throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2077                 }
2078
2079                 //
2080                 // Public function used to locate types.
2081                 //
2082                 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2083                 //
2084                 // Returns: Type or null if they type can not be found.
2085                 //
2086                 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2087                 {
2088                         FullNamedExpression e;
2089                         if (arity == 0 && Cache.TryGetValue (name, out e))
2090                                 return e;
2091
2092                         e = null;
2093                         int errors = Report.Errors;
2094
2095                         if (arity == 0) {
2096                                 TypeParameter[] tp = CurrentTypeParameters;
2097                                 if (tp != null) {
2098                                         TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2099                                         if (tparam != null)
2100                                                 e = new TypeParameterExpr (tparam, Location.Null);
2101                                 }
2102                         }
2103
2104                         if (e == null) {
2105                                 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2106
2107                                 if (t != null)
2108                                         e = new TypeExpression (t, Location.Null);
2109                                 else if (Parent != null) {
2110                                         e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2111                                 } else
2112                                         e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2113                         }
2114
2115                         // TODO MemberCache: How to cache arity stuff ?
2116                         if (errors == Report.Errors && arity == 0)
2117                                 Cache[name] = e;
2118
2119                         return e;
2120                 }
2121
2122                 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2123                 {
2124                         // TODO: GenericMethod only
2125                         if (PartialContainer == null)
2126                                 return null;
2127
2128                         // Has any nested type
2129                         // Does not work, because base type can have
2130                         //if (PartialContainer.Types == null)
2131                         //      return null;
2132
2133                         var container = PartialContainer.CurrentType;
2134
2135                         // Is not Root container
2136                         if (container == null)
2137                                 return null;
2138
2139                         var t = MemberCache.FindNestedType (container, name, arity);
2140                         if (t == null)
2141                                 return null;
2142
2143                         // FIXME: Breaks error reporting
2144                         if (!t.IsAccessible (CurrentType))
2145                                 return null;
2146
2147                         return t;
2148                 }
2149
2150                 public void Mark_HasEquals ()
2151                 {
2152                         cached_method |= CachedMethods.Equals;
2153                 }
2154
2155                 public void Mark_HasGetHashCode ()
2156                 {
2157                         cached_method |= CachedMethods.GetHashCode;
2158                 }
2159
2160                 /// <summary>
2161                 /// Method container contains Equals method
2162                 /// </summary>
2163                 public bool HasEquals {
2164                         get {
2165                                 return (cached_method & CachedMethods.Equals) != 0;
2166                         }
2167                 }
2168  
2169                 /// <summary>
2170                 /// Method container contains GetHashCode method
2171                 /// </summary>
2172                 public bool HasGetHashCode {
2173                         get {
2174                                 return (cached_method & CachedMethods.GetHashCode) != 0;
2175                         }
2176                 }
2177
2178                 public bool HasStaticFieldInitializer {
2179                         get {
2180                                 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2181                         }
2182                         set {
2183                                 if (value)
2184                                         cached_method |= CachedMethods.HasStaticFieldInitializer;
2185                                 else
2186                                         cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2187                         }
2188                 }
2189
2190                 //
2191                 // Generates xml doc comments (if any), and if required,
2192                 // handle warning report.
2193                 //
2194                 internal override void GenerateDocComment (DeclSpace ds)
2195                 {
2196                         DocUtil.GenerateTypeDocComment (this, ds, Report);
2197                 }
2198
2199                 public override string DocCommentHeader {
2200                         get { return "T:"; }
2201                 }
2202         }
2203
2204         public abstract class ClassOrStruct : TypeContainer
2205         {
2206                 Dictionary<SecurityAction, PermissionSet> declarative_security;
2207
2208                 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2209                                       MemberName name, Attributes attrs, MemberKind kind)
2210                         : base (ns, parent, name, attrs, kind)
2211                 {
2212                 }
2213
2214                 protected override bool AddToContainer (MemberCore symbol, string name)
2215                 {
2216                         if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2217                                 if (symbol is TypeParameter) {
2218                                         Report.Error (694, symbol.Location,
2219                                                 "Type parameter `{0}' has same name as containing type, or method",
2220                                                 symbol.GetSignatureForError ());
2221                                         return false;
2222                                 }
2223                         
2224                                 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2225                                 if (imb == null || !imb.IsExplicitImpl) {
2226                                         Report.SymbolRelatedToPreviousError (this);
2227                                         Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2228                                                 symbol.GetSignatureForError ());
2229                                         return false;
2230                                 }
2231                         }
2232
2233                         return base.AddToContainer (symbol, name);
2234                 }
2235
2236                 public override void VerifyMembers ()
2237                 {
2238                         base.VerifyMembers ();
2239
2240                         if ((events != null) && Report.WarningLevel >= 3) {
2241                                 foreach (Event e in events){
2242                                         // Note: The event can be assigned from same class only, so we can report
2243                                         // this warning for all accessibility modes
2244                                         if ((e.caching_flags & Flags.IsUsed) == 0)
2245                                                 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2246                                 }
2247                         }
2248                 }
2249
2250                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2251                 {
2252                         if (a.IsValidSecurityAttribute ()) {
2253                                 if (declarative_security == null)
2254                                         declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2255
2256                                 a.ExtractSecurityPermissionSet (declarative_security);
2257                                 return;
2258                         }
2259
2260                         if (a.Type == pa.StructLayout) {
2261                                 PartialContainer.HasStructLayout = true;
2262
2263                                 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2264                                         PartialContainer.HasExplicitLayout = true;
2265                         }
2266
2267                         if (a.Type == pa.Dynamic) {
2268                                 a.Error_MisusedDynamicAttribute ();
2269                                 return;
2270                         }
2271
2272                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2273                 }
2274
2275                 /// <summary>
2276                 /// Defines the default constructors 
2277                 /// </summary>
2278                 protected void DefineDefaultConstructor (bool is_static)
2279                 {
2280                         // The default instance constructor is public
2281                         // If the class is abstract, the default constructor is protected
2282                         // The default static constructor is private
2283
2284                         Modifiers mods;
2285                         if (is_static) {
2286                                 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2287                         } else {
2288                                 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2289                         }
2290
2291                         Constructor c = new Constructor (this, MemberName.Name, mods,
2292                                 null, ParametersCompiled.EmptyReadOnlyParameters,
2293                                 new GeneratedBaseInitializer (Location),
2294                                 Location);
2295                         
2296                         AddConstructor (c);
2297                         c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2298                 }
2299
2300                 protected override bool DoDefineMembers ()
2301                 {
2302                         CheckProtectedModifier ();
2303
2304                         base.DoDefineMembers ();
2305
2306                         if (default_static_constructor != null)
2307                                 default_static_constructor.Define ();
2308
2309                         return true;
2310                 }
2311
2312                 public override void Emit ()
2313                 {
2314                         if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2315                                 DefineDefaultConstructor (true);
2316                                 default_static_constructor.Define ();
2317                         }
2318
2319                         base.Emit ();
2320
2321                         if (declarative_security != null) {
2322                                 foreach (var de in declarative_security) {
2323                                         TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2324                                 }
2325                         }
2326                 }
2327
2328                 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2329                 {
2330                         DeclSpace top_level = Parent;
2331                         if (top_level != null) {
2332                                 while (top_level.Parent != null)
2333                                         top_level = top_level.Parent;
2334
2335                                 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2336                                 if (candidates != null) {
2337                                         scope = NamespaceEntry;
2338                                         return candidates;
2339                                 }
2340                         }
2341
2342                         return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2343                 }
2344
2345                 protected override TypeAttributes TypeAttr {
2346                         get {
2347                                 if (default_static_constructor == null)
2348                                         return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2349
2350                                 return base.TypeAttr;
2351                         }
2352                 }
2353         }
2354
2355
2356         // TODO: should be sealed
2357         public class Class : ClassOrStruct {
2358                 const Modifiers AllowedModifiers =
2359                         Modifiers.NEW |
2360                         Modifiers.PUBLIC |
2361                         Modifiers.PROTECTED |
2362                         Modifiers.INTERNAL |
2363                         Modifiers.PRIVATE |
2364                         Modifiers.ABSTRACT |
2365                         Modifiers.SEALED |
2366                         Modifiers.STATIC |
2367                         Modifiers.UNSAFE;
2368
2369                 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2370
2371                 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2372                               Attributes attrs)
2373                         : base (ns, parent, name, attrs, MemberKind.Class)
2374                 {
2375                         var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2376                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2377                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2378
2379                         if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2380                                 Report.FeatureIsNotAvailable (Location, "static classes");
2381                         }
2382                 }
2383
2384                 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2385                 {
2386                         if (part.Name == "System.Object")
2387                                 Report.Error (537, part.Location,
2388                                         "The class System.Object cannot have a base class or implement an interface.");
2389                         base.AddBasesForPart (part, bases);
2390                 }
2391
2392                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2393                 {
2394                         if (a.Type == pa.AttributeUsage) {
2395                                 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2396                                         Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2397                                 }
2398                         }
2399
2400                         if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2401                                 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2402                                 return;
2403                         }
2404
2405                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2406                                 a.Error_MissingGuidAttribute ();
2407                                 return;
2408                         }
2409
2410                         if (a.Type == pa.Extension) {
2411                                 a.Error_MisusedExtensionAttribute ();
2412                                 return;
2413                         }
2414
2415                         if (a.Type.IsConditionallyExcluded (Location))
2416                                 return;
2417
2418                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2419                 }
2420
2421                 public override AttributeTargets AttributeTargets {
2422                         get {
2423                                 return AttributeTargets.Class;
2424                         }
2425                 }
2426
2427                 protected override void DefineContainerMembers (System.Collections.IList list)
2428                 {
2429                         if (list == null)
2430                                 return;
2431
2432                         if (!IsStatic) {
2433                                 base.DefineContainerMembers (list);
2434                                 return;
2435                         }
2436
2437                         foreach (MemberCore m in list) {
2438                                 if (m is Operator) {
2439                                         Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2440                                         continue;
2441                                 }
2442
2443                                 if (m is Destructor) {
2444                                         Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2445                                         continue;
2446                                 }
2447
2448                                 if (m is Indexer) {
2449                                         Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2450                                         continue;
2451                                 }
2452
2453                                 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2454                                         continue;
2455
2456                                 if (m is Constructor) {
2457                                         Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2458                                         continue;
2459                                 }
2460
2461                                 Method method = m as Method;
2462                                 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2463                                         Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2464                                         continue;
2465                                 }
2466
2467                                 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2468                         }
2469
2470                         base.DefineContainerMembers (list);
2471                 }
2472
2473                 protected override bool DoDefineMembers ()
2474                 {
2475                         if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2476                                 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2477                         }
2478
2479                         if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2480                                 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2481                         }
2482
2483                         if (InstanceConstructors == null && !IsStatic)
2484                                 DefineDefaultConstructor (false);
2485
2486                         return base.DoDefineMembers ();
2487                 }
2488
2489                 public override void Emit ()
2490                 {
2491                         base.Emit ();
2492
2493                         if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2494                                 Compiler.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2495
2496                         if (base_type != null && base_type.HasDynamicElement) {
2497                                 Compiler.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type);
2498                         }
2499                 }
2500
2501                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2502                 {
2503                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2504
2505                         if (base_class == null) {
2506                                 if (spec != TypeManager.object_type)
2507                                         base_type = TypeManager.object_type;
2508                         } else {
2509                                 if (base_type.IsGenericParameter){
2510                                         Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2511                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2512                                 } else if (IsGeneric && base_type.IsAttribute) {
2513                                         Report.Error (698, base_class.Location,
2514                                                 "A generic type cannot derive from `{0}' because it is an attribute class",
2515                                                 base_class.GetSignatureForError ());
2516                                 } else if (base_type.IsStatic) {
2517                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2518                                         Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2519                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2520                                 } else if (base_type.IsSealed) {
2521                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2522                                         Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2523                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2524                                 } else if (PartialContainer.IsStatic && base_class.Type != TypeManager.object_type) {
2525                                         Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2526                                                 GetSignatureForError (), base_class.GetSignatureForError ());
2527                                 }
2528
2529                                 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2530                                         (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2531                                         base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2532                                         Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2533                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2534
2535                                         base_type = TypeManager.object_type;
2536                                 }
2537
2538                                 if (!IsAccessibleAs (base_type)) {
2539                                         Report.SymbolRelatedToPreviousError (base_type);
2540                                         Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2541                                                 base_type.GetSignatureForError (), GetSignatureForError ());
2542                                 }
2543                         }
2544
2545                         if (PartialContainer.IsStatic && ifaces != null) {
2546                                 foreach (TypeExpr t in ifaces)
2547                                         Report.SymbolRelatedToPreviousError (t.Type);
2548                                 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2549                         }
2550
2551                         return ifaces;
2552                 }
2553
2554                 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2555                 /// Valid only for attribute classes.
2556                 public override string[] ConditionalConditions ()
2557                 {
2558                         if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2559                                 return null;
2560
2561                         caching_flags &= ~Flags.Excluded_Undetected;
2562
2563                         if (OptAttributes == null)
2564                                 return null;
2565
2566                         Attribute[] attrs = OptAttributes.SearchMulti (Compiler.PredefinedAttributes.Conditional);
2567                         if (attrs == null)
2568                                 return null;
2569
2570                         string[] conditions = new string[attrs.Length];
2571                         for (int i = 0; i < conditions.Length; ++i)
2572                                 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2573
2574                         caching_flags |= Flags.Excluded;
2575                         return conditions;
2576                 }
2577
2578                 //
2579                 // FIXME: How do we deal with the user specifying a different
2580                 // layout?
2581                 //
2582                 protected override TypeAttributes TypeAttr {
2583                         get {
2584                                 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2585                                 if (IsStatic)
2586                                         ta |= StaticClassAttribute;
2587                                 return ta;
2588                         }
2589                 }
2590         }
2591
2592         public sealed class Struct : ClassOrStruct {
2593
2594                 bool is_unmanaged, has_unmanaged_check_done;
2595                 bool InTransit;
2596
2597                 // <summary>
2598                 //   Modifiers allowed in a struct declaration
2599                 // </summary>
2600                 const Modifiers AllowedModifiers =
2601                         Modifiers.NEW       |
2602                         Modifiers.PUBLIC    |
2603                         Modifiers.PROTECTED |
2604                         Modifiers.INTERNAL  |
2605                         Modifiers.UNSAFE    |
2606                         Modifiers.PRIVATE;
2607
2608                 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2609                                Modifiers mod, Attributes attrs)
2610                         : base (ns, parent, name, attrs, MemberKind.Struct)
2611                 {
2612                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;                   
2613                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2614                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2615                 }
2616
2617                 public override AttributeTargets AttributeTargets {
2618                         get {
2619                                 return AttributeTargets.Struct;
2620                         }
2621                 }
2622
2623                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2624                 {
2625                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2626
2627                         //
2628                         // When struct constains fixed fixed and struct layout has explicitly
2629                         // set CharSet, its value has to be propagated to compiler generated
2630                         // fixed types
2631                         //
2632                         if (a.Type == pa.StructLayout && Fields != null) {
2633                                 var value = a.GetNamedValue ("CharSet");
2634                                 if (value == null)
2635                                         return;
2636
2637                                 for (int i = 0; i < Fields.Count; ++i) {
2638                                         FixedField ff = Fields [i] as FixedField;
2639                                         if (ff == null)
2640                                                 continue;
2641
2642                                         ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2643                                 }
2644                         }
2645                 }
2646
2647                 bool CheckStructCycles (Struct s)
2648                 {
2649                         if (s.Fields == null)
2650                                 return true;
2651
2652                         if (s.InTransit)
2653                                 return false;
2654
2655                         s.InTransit = true;
2656                         foreach (FieldBase field in s.Fields) {
2657                                 TypeSpec ftype = field.Spec.MemberType;
2658                                 if (!ftype.IsStruct)
2659                                         continue;
2660
2661                                 if (ftype is PredefinedTypeSpec)
2662                                         continue;
2663
2664                                 foreach (var targ in ftype.TypeArguments) {
2665                                         if (!CheckFieldTypeCycle (targ)) {
2666                                                 Report.Error (523, field.Location,
2667                                                         "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2668                                                         field.GetSignatureForError (), ftype.GetSignatureForError ());
2669                                                 break;
2670                                         }
2671                                 }
2672
2673                                 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2674                                         continue;
2675
2676                                 if (!CheckFieldTypeCycle (ftype)) {
2677                                         Report.Error (523, field.Location,
2678                                                 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2679                                                 field.GetSignatureForError (), ftype.GetSignatureForError ());
2680                                         break;
2681                                 }
2682                         }
2683
2684                         s.InTransit = false;
2685                         return true;
2686                 }
2687
2688                 bool CheckFieldTypeCycle (TypeSpec ts)
2689                 {
2690                         var fts = ts.MemberDefinition as Struct;
2691                         if (fts == null)
2692                                 return true;
2693
2694                         return CheckStructCycles (fts);
2695                 }
2696
2697                 public override void Emit ()
2698                 {
2699                         CheckStructCycles (this);
2700
2701                         base.Emit ();
2702                 }
2703
2704                 public override bool IsUnmanagedType ()
2705                 {
2706                         if (fields == null)
2707                                 return true;
2708
2709                         if (has_unmanaged_check_done)
2710                                 return is_unmanaged;
2711
2712                         if (requires_delayed_unmanagedtype_check)
2713                                 return true;
2714
2715                         requires_delayed_unmanagedtype_check = true;
2716
2717                         foreach (FieldBase f in fields) {
2718                                 if (f.IsStatic)
2719                                         continue;
2720
2721                                 // It can happen when recursive unmanaged types are defined
2722                                 // struct S { S* s; }
2723                                 TypeSpec mt = f.MemberType;
2724                                 if (mt == null) {
2725                                         return true;
2726                                 }
2727
2728                                 while (mt.IsPointer)
2729                                         mt = TypeManager.GetElementType (mt);
2730
2731                                 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2732                                         has_unmanaged_check_done = true;
2733                                         return false;
2734                                 }
2735
2736                                 if (TypeManager.IsUnmanagedType (mt))
2737                                         continue;
2738
2739                                 has_unmanaged_check_done = true;
2740                                 return false;
2741                         }
2742
2743                         has_unmanaged_check_done = true;
2744                         is_unmanaged = true;
2745                         return true;
2746                 }
2747
2748                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2749                 {
2750                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2751                         base_type = TypeManager.value_type;
2752                         return ifaces;
2753                 }
2754
2755                 protected override TypeAttributes TypeAttr {
2756                         get {
2757                                 const TypeAttributes DefaultTypeAttributes =
2758                                         TypeAttributes.SequentialLayout |
2759                                         TypeAttributes.Sealed;
2760
2761                                 return base.TypeAttr | DefaultTypeAttributes;
2762                         }
2763                 }
2764
2765                 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2766                 {
2767                         if ((field.ModFlags & Modifiers.STATIC) == 0) {
2768                                 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2769                                         field.GetSignatureForError ());
2770                                 return;
2771                         }
2772                         base.RegisterFieldForInitialization (field, expression);
2773                 }
2774
2775         }
2776
2777         /// <summary>
2778         ///   Interfaces
2779         /// </summary>
2780         public sealed class Interface : TypeContainer {
2781
2782                 /// <summary>
2783                 ///   Modifiers allowed in a class declaration
2784                 /// </summary>
2785                 public const Modifiers AllowedModifiers =
2786                         Modifiers.NEW       |
2787                         Modifiers.PUBLIC    |
2788                         Modifiers.PROTECTED |
2789                         Modifiers.INTERNAL  |
2790                         Modifiers.UNSAFE    |
2791                         Modifiers.PRIVATE;
2792
2793                 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2794                                   Attributes attrs)
2795                         : base (ns, parent, name, attrs, MemberKind.Interface)
2796                 {
2797                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2798
2799                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2800                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2801                 }
2802
2803                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2804                 {
2805                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2806                                 a.Error_MissingGuidAttribute ();
2807                                 return;
2808                         }
2809
2810                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2811                 }
2812
2813
2814                 public override AttributeTargets AttributeTargets {
2815                         get {
2816                                 return AttributeTargets.Interface;
2817                         }
2818                 }
2819
2820                 protected override TypeAttributes TypeAttr {
2821                         get {
2822                                 const TypeAttributes DefaultTypeAttributes =
2823                                         TypeAttributes.AutoLayout |
2824                                         TypeAttributes.Abstract |
2825                                         TypeAttributes.Interface;
2826
2827                                 return base.TypeAttr | DefaultTypeAttributes;
2828                         }
2829                 }
2830
2831                 protected override bool VerifyClsCompliance ()
2832                 {
2833                         if (!base.VerifyClsCompliance ())
2834                                 return false;
2835
2836                         if (iface_exprs != null) {
2837                                 foreach (var iface in iface_exprs) {
2838                                         if (iface.Type.IsCLSCompliant ())
2839                                                 continue;
2840
2841                                         Report.SymbolRelatedToPreviousError (iface.Type);
2842                                         Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2843                                                 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2844                                 }
2845                         }
2846
2847                         return true;
2848                 }
2849         }
2850
2851         public abstract class InterfaceMemberBase : MemberBase
2852         {
2853                 //
2854                 // Common modifiers allowed in a class declaration
2855                 //
2856                 protected const Modifiers AllowedModifiersClass =
2857                         Modifiers.NEW |
2858                         Modifiers.PUBLIC |
2859                         Modifiers.PROTECTED |
2860                         Modifiers.INTERNAL |
2861                         Modifiers.PRIVATE |
2862                         Modifiers.STATIC |
2863                         Modifiers.VIRTUAL |
2864                         Modifiers.SEALED |
2865                         Modifiers.OVERRIDE |
2866                         Modifiers.ABSTRACT |
2867                         Modifiers.UNSAFE |
2868                         Modifiers.EXTERN;
2869
2870                 //
2871                 // Common modifiers allowed in a struct declaration
2872                 //
2873                 protected const Modifiers AllowedModifiersStruct =
2874                         Modifiers.NEW |
2875                         Modifiers.PUBLIC |
2876                         Modifiers.PROTECTED |
2877                         Modifiers.INTERNAL |
2878                         Modifiers.PRIVATE |
2879                         Modifiers.STATIC |
2880                         Modifiers.OVERRIDE |
2881                         Modifiers.UNSAFE |
2882                         Modifiers.EXTERN;
2883
2884                 //
2885                 // Common modifiers allowed in a interface declaration
2886                 //
2887                 protected const Modifiers AllowedModifiersInterface =
2888                         Modifiers.NEW |
2889                         Modifiers.UNSAFE;
2890
2891                 //
2892                 // Whether this is an interface member.
2893                 //
2894                 public bool IsInterface;
2895
2896                 //
2897                 // If true, this is an explicit interface implementation
2898                 //
2899                 public bool IsExplicitImpl;
2900
2901                 protected bool is_external_implementation;
2902
2903                 //
2904                 // The interface type we are explicitly implementing
2905                 //
2906                 public TypeSpec InterfaceType;
2907
2908                 //
2909                 // The method we're overriding if this is an override method.
2910                 //
2911                 protected MethodSpec base_method;
2912
2913                 readonly Modifiers explicit_mod_flags;
2914                 public MethodAttributes flags;
2915
2916                 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2917                                    FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2918                                    MemberName name, Attributes attrs)
2919                         : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2920                                 name, attrs)
2921                 {
2922                         IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2923                         IsExplicitImpl = (MemberName.Left != null);
2924                         explicit_mod_flags = mod;
2925                 }
2926                 
2927                 protected override bool CheckBase ()
2928                 {
2929                         if (!base.CheckBase ())
2930                                 return false;
2931
2932                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2933                                 CheckForDuplications ();
2934                         
2935                         if (IsExplicitImpl)
2936                                 return true;
2937
2938                         // For System.Object only
2939                         if (Parent.BaseType == null)
2940                                 return true;
2941
2942                         MemberSpec candidate;
2943                         var base_member = FindBaseMember (out candidate);
2944
2945                         if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2946                                 if (base_member == null) {
2947                                         if (candidate == null) {
2948                                                 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2949                                                         Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2950                                                                 "object.Finalize()");
2951                                                 } else {
2952                                                         Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2953                                                                 GetSignatureForError (), SimpleName.GetMemberType (this));
2954                                                 }
2955                                         } else {
2956                                                 Report.SymbolRelatedToPreviousError (candidate);
2957                                                 if (this is Event)
2958                                                         Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2959                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2960                                                 else if (this is PropertyBase)
2961                                                         Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2962                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2963                                                 else
2964                                                         Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2965                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2966                                         }
2967
2968                                         return false;
2969                                 }
2970
2971                                 if (!CheckOverrideAgainstBase (base_member))
2972                                         return false;
2973
2974                                 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2975                                 if (oa != null) {
2976                                         if (OptAttributes == null || !OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2977                                                 Report.SymbolRelatedToPreviousError (base_member);
2978                                                 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2979                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2980                                         }
2981                                 } else {
2982                                         if (OptAttributes != null && OptAttributes.Contains (Compiler.PredefinedAttributes.Obsolete)) {
2983                                                 Report.SymbolRelatedToPreviousError (base_member);
2984                                                 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2985                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2986                                         }
2987                                 }
2988
2989                                 base_method = base_member as MethodSpec;
2990                                 return true;
2991                         }
2992
2993                         if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2994                                 base_member = candidate;
2995
2996                         if (base_member == null) {
2997                                 if ((ModFlags & Modifiers.NEW) != 0) {
2998                                         if (base_member == null) {
2999                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3000                                                         GetSignatureForError ());
3001                                         }
3002                                 }
3003                         } else {
3004                                 if ((ModFlags & Modifiers.NEW) == 0) {
3005                                         ModFlags |= Modifiers.NEW;
3006                                         if (!IsCompilerGenerated) {
3007                                                 Report.SymbolRelatedToPreviousError (base_member);
3008                                                 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3009                                                         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",
3010                                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3011                                                 } else {
3012                                                         Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3013                                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3014                                                 }
3015                                         }
3016                                 }
3017
3018                                 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3019                                         Report.SymbolRelatedToPreviousError (base_member);
3020                                         Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3021                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3022                                 }
3023                         }
3024
3025                         return true;
3026                 }
3027
3028                 protected virtual bool CheckForDuplications ()
3029                 {
3030                         return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3031                 }
3032
3033                 //
3034                 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3035                 // that have been defined.
3036                 //
3037                 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3038                 {
3039                         bool ok = true;
3040
3041                         if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3042                                 Report.SymbolRelatedToPreviousError (base_member);
3043                                 Report.Error (506, Location,
3044                                         "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3045                                          GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3046                                 ok = false;
3047                         }
3048
3049                         // Now we check that the overriden method is not final  
3050                         if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3051                                 Report.SymbolRelatedToPreviousError (base_member);
3052                                 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3053                                                           GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3054                                 ok = false;
3055                         }
3056
3057                         var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3058                         if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3059                                 Report.SymbolRelatedToPreviousError (base_member);
3060                                 if (this is PropertyBasedMember) {
3061                                         Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3062                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3063                                 } else {
3064                                         Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3065                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3066                                 }
3067                                 ok = false;
3068                         }
3069
3070                         return ok;
3071                 }
3072
3073                 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3074                 {
3075                         var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3076                         var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3077
3078                         if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3079                                 //
3080                                 // when overriding protected internal, the method can be declared
3081                                 // protected internal only within the same assembly or assembly
3082                                 // which has InternalsVisibleTo
3083                                 //
3084                                 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3085                                         return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3086                                 } 
3087                                 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
3088                                         //
3089                                         // if it's not "protected internal", it must be "protected"
3090                                         //
3091
3092                                         return false;
3093                                 }
3094                                 if (this_member.Parent.PartialContainer.DeclaringAssembly == base_member.DeclaringType.MemberDefinition.DeclaringAssembly) {
3095                                         //
3096                                         // protected within the same assembly - an error
3097                                         //
3098                                         return false;
3099                                 }
3100                                 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
3101                                            (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
3102                                         //
3103                                         // protected ok, but other attributes differ - report an error
3104                                         //
3105                                         return false;
3106                                 }
3107                                 return true;
3108                         }
3109
3110                         return thisp == base_classp;
3111                 }
3112
3113                 public override bool Define ()
3114                 {
3115                         if (IsInterface) {
3116                                 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3117                                         Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3118
3119                                 flags = MethodAttributes.Public |
3120                                         MethodAttributes.Abstract |
3121                                         MethodAttributes.HideBySig |
3122                                         MethodAttributes.NewSlot |
3123                                         MethodAttributes.Virtual;
3124                         } else {
3125                                 Parent.PartialContainer.MethodModifiersValid (this);
3126
3127                                 flags = ModifiersExtensions.MethodAttr (ModFlags);
3128                         }
3129
3130                         if (IsExplicitImpl) {
3131                                 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3132                                 if (iface_texpr == null)
3133                                         return false;
3134
3135                                 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3136                                         Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3137                                                 GetSignatureForError ());
3138                                 }
3139
3140                                 InterfaceType = iface_texpr.Type;
3141
3142                                 if (!InterfaceType.IsInterface) {
3143                                         Report.SymbolRelatedToPreviousError (InterfaceType);
3144                                         Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3145                                                 TypeManager.CSharpName (InterfaceType));
3146                                 } else {
3147                                         Parent.PartialContainer.VerifyImplements (this);
3148                                 }
3149
3150                                 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3151                         }
3152
3153                         return base.Define ();
3154                 }
3155
3156                 protected bool DefineParameters (ParametersCompiled parameters)
3157                 {
3158                         if (!parameters.Resolve (this))
3159                                 return false;
3160
3161                         bool error = false;
3162                         for (int i = 0; i < parameters.Count; ++i) {
3163                                 Parameter p = parameters [i];
3164
3165                                 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3166                                         p.Warning_UselessOptionalParameter (Report);
3167
3168                                 if (p.CheckAccessibility (this))
3169                                         continue;
3170
3171                                 TypeSpec t = parameters.Types [i];
3172                                 Report.SymbolRelatedToPreviousError (t);
3173                                 if (this is Indexer)
3174                                         Report.Error (55, Location,
3175                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3176                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3177                                 else if (this is Operator)
3178                                         Report.Error (57, Location,
3179                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3180                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3181                                 else
3182                                         Report.Error (51, Location,
3183                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3184                                                 TypeManager.CSharpName (t), GetSignatureForError ());
3185                                 error = true;
3186                         }
3187                         return !error;
3188                 }
3189
3190                 public override void Emit()
3191                 {
3192                         // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3193                         // We are more strict than csc and report this as an error because SRE does not allow emit that
3194                         if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3195                                 if (this is Constructor) {
3196                                         Report.Error (824, Location,
3197                                                 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3198                                 } else {
3199                                         Report.Error (626, Location,
3200                                                 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3201                                                 GetSignatureForError ());
3202                                 }
3203                         }
3204
3205                         base.Emit ();
3206                 }
3207
3208                 public override bool EnableOverloadChecks (MemberCore overload)
3209                 {
3210                         //
3211                         // Two members can differ in their explicit interface
3212                         // type parameter only
3213                         //
3214                         InterfaceMemberBase imb = overload as InterfaceMemberBase;
3215                         if (imb != null && imb.IsExplicitImpl) {
3216                                 if (IsExplicitImpl) {
3217                                         caching_flags |= Flags.MethodOverloadsExist;
3218                                 }
3219                                 return true;
3220                         }
3221
3222                         return IsExplicitImpl;
3223                 }
3224
3225                 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3226                 {
3227                         Report.SymbolRelatedToPreviousError (base_member);
3228                         Report.Error (507, member.Location,
3229                                 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3230                                 member.GetSignatureForError (),
3231                                 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3232                                 base_member.GetSignatureForError ());
3233                 }
3234
3235                 protected void Error_StaticReturnType ()
3236                 {
3237                         Report.Error (722, Location,
3238                                 "`{0}': static types cannot be used as return types",
3239                                 MemberType.GetSignatureForError ());
3240                 }
3241
3242                 /// <summary>
3243                 /// Gets base method and its return type
3244                 /// </summary>
3245                 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3246                 {
3247                         return MemberCache.FindBaseMember (this, out bestCandidate);
3248                 }
3249
3250                 //
3251                 // The "short" name of this property / indexer / event.  This is the
3252                 // name without the explicit interface.
3253                 //
3254                 public string ShortName {
3255                         get { return MemberName.Name; }
3256                         set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3257                 }
3258                 
3259                 //
3260                 // Returns full metadata method name
3261                 //
3262                 public string GetFullName (MemberName name)
3263                 {
3264                         return GetFullName (name.Name);
3265                 }
3266
3267                 public string GetFullName (string name)
3268                 {
3269                         if (!IsExplicitImpl)
3270                                 return name;
3271
3272                         //
3273                         // When dealing with explicit members a full interface type
3274                         // name is added to member name to avoid possible name conflicts
3275                         //
3276                         // We use CSharpName which gets us full name with benefit of
3277                         // replacing predefined names which saves some space and name
3278                         // is still unique
3279                         //
3280                         return TypeManager.CSharpName (InterfaceType) + "." + name;
3281                 }
3282
3283                 protected override bool VerifyClsCompliance ()
3284                 {
3285                         if (!base.VerifyClsCompliance ()) {
3286                                 return false;
3287                         }
3288
3289                         if (GenericMethod != null)
3290                                 GenericMethod.VerifyClsCompliance ();
3291
3292                         return true;
3293                 }
3294
3295                 public override bool IsUsed 
3296                 {
3297                         get { return IsExplicitImpl || base.IsUsed; }
3298                 }
3299
3300         }
3301
3302         public abstract class MemberBase : MemberCore
3303         {
3304                 protected FullNamedExpression type_expr;
3305                 protected TypeSpec member_type;
3306
3307                 public readonly DeclSpace ds;
3308                 public readonly GenericMethod GenericMethod;
3309
3310                 protected MemberBase (DeclSpace parent, GenericMethod generic,
3311                                       FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3312                                       MemberName name, Attributes attrs)
3313                         : base (parent, name, attrs)
3314                 {
3315                         this.ds = generic != null ? generic : (DeclSpace) parent;
3316                         this.type_expr = type;
3317                         ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3318                         GenericMethod = generic;
3319                         if (GenericMethod != null)
3320                                 GenericMethod.ModFlags = ModFlags;
3321                 }
3322
3323                 #region Properties
3324
3325                 public TypeSpec MemberType {
3326                         get {
3327                                 return member_type;
3328                         }
3329                 }
3330
3331                 public FullNamedExpression TypeExpression {
3332                         get {
3333                                 return type_expr;
3334                         }
3335                 }
3336
3337                 #endregion
3338
3339                 //
3340                 // Main member define entry
3341                 //
3342                 public override bool Define ()
3343                 {
3344                         DoMemberTypeIndependentChecks ();
3345
3346                         //
3347                         // Returns false only when type resolution failed
3348                         //
3349                         if (!ResolveMemberType ())
3350                                 return false;
3351
3352                         DoMemberTypeDependentChecks ();
3353                         return true;
3354                 }
3355
3356                 //
3357                 // Any type_name independent checks
3358                 //
3359                 protected virtual void DoMemberTypeIndependentChecks ()
3360                 {
3361                         if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3362                                 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3363                                 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3364                                         GetSignatureForError (), Parent.GetSignatureForError ());
3365                         }
3366                 }
3367
3368                 //
3369                 // Any type_name dependent checks
3370                 //
3371                 protected virtual void DoMemberTypeDependentChecks ()
3372                 {
3373                         // verify accessibility
3374                         if (!IsAccessibleAs (MemberType)) {
3375                                 Report.SymbolRelatedToPreviousError (MemberType);
3376                                 if (this is Property)
3377                                         Report.Error (53, Location,
3378                                                       "Inconsistent accessibility: property type `" +
3379                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3380                                                       "accessible than property `" + GetSignatureForError () + "'");
3381                                 else if (this is Indexer)
3382                                         Report.Error (54, Location,
3383                                                       "Inconsistent accessibility: indexer return type `" +
3384                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3385                                                       "accessible than indexer `" + GetSignatureForError () + "'");
3386                                 else if (this is MethodCore) {
3387                                         if (this is Operator)
3388                                                 Report.Error (56, Location,
3389                                                               "Inconsistent accessibility: return type `" +
3390                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3391                                                               "accessible than operator `" + GetSignatureForError () + "'");
3392                                         else
3393                                                 Report.Error (50, Location,
3394                                                               "Inconsistent accessibility: return type `" +
3395                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3396                                                               "accessible than method `" + GetSignatureForError () + "'");
3397                                 } else {
3398                                         Report.Error (52, Location,
3399                                                       "Inconsistent accessibility: field type `" +
3400                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3401                                                       "accessible than field `" + GetSignatureForError () + "'");
3402                                 }
3403                         }
3404
3405                         Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3406                         TypeManager.CheckTypeVariance (MemberType, variance, this);
3407                 }
3408
3409                 protected bool IsTypePermitted ()
3410                 {
3411                         if (TypeManager.IsSpecialType (MemberType)) {
3412                                 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3413                                 return false;
3414                         }
3415                         return true;
3416                 }
3417
3418                 protected virtual bool CheckBase ()
3419                 {
3420                         CheckProtectedModifier ();
3421
3422                         return true;
3423                 }
3424
3425                 protected virtual bool ResolveMemberType ()
3426                 {
3427                         if (member_type != null)
3428                                 throw new InternalErrorException ("Multi-resolve");
3429
3430                         TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3431                         if (te == null)
3432                                 return false;
3433                         
3434                         //
3435                         // Replace original type name, error reporting can use fully resolved name
3436                         //
3437                         type_expr = te;
3438
3439                         member_type = te.Type;
3440                         return true;
3441                 }
3442         }
3443 }
3444