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