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