2010-05-05 Miguel de Icaza <miguel@novell.com>
[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                                         // Prevents a crash, the interface might not have been resolved: 442144
1067                                         if (iface == null)
1068                                                 continue;
1069                                         
1070                                         var iface_type = iface.Type;
1071
1072                                         if (!spec.AddInterface (iface_type))
1073                                                 continue;
1074
1075                                         if (iface_type.IsGeneric && spec.Interfaces != null) {
1076                                                 foreach (var prev_iface in iface_exprs) {
1077                                                         if (prev_iface == iface)
1078                                                                 break;
1079
1080                                                         if (!TypeSpecComparer.Unify.IsEqual (iface_type, prev_iface.Type))
1081                                                                 continue;
1082
1083                                                         Report.Error (695, Location,
1084                                                                 "`{0}' cannot implement both `{1}' and `{2}' because they may unify for some type parameter substitutions",
1085                                                                 GetSignatureForError (), prev_iface.GetSignatureForError (), iface_type.GetSignatureForError ());
1086                                                 }
1087                                         }
1088
1089                                         TypeBuilder.AddInterfaceImplementation (iface_type.GetMetaInfo ());
1090
1091                                         // Ensure the base is always setup
1092                                         var compiled_iface = iface_type.MemberDefinition as Interface;
1093                                         if (compiled_iface != null) {
1094                                                 // TODO: Need DefineBaseType only
1095                                                 compiled_iface.DefineType ();
1096                                         }
1097
1098                                         if (iface_type.Interfaces != null) {
1099                                                 var base_ifaces = new List<TypeSpec> (iface_type.Interfaces);
1100                                                 for (int i = 0; i < base_ifaces.Count; ++i) {
1101                                                         var ii_iface_type = base_ifaces[i];
1102                                                         if (spec.AddInterface (ii_iface_type)) {
1103                                                                 TypeBuilder.AddInterfaceImplementation (ii_iface_type.GetMetaInfo ());
1104
1105                                                                 if (ii_iface_type.Interfaces != null)
1106                                                                         base_ifaces.AddRange (ii_iface_type.Interfaces);
1107                                                         }
1108                                                 }
1109                                         }
1110                                 }
1111                         }
1112
1113                         if (Kind == MemberKind.Interface) {
1114                                 spec.BaseType = TypeManager.object_type;
1115                                 return true;
1116                         }
1117
1118                         TypeSpec base_ts;
1119                         if (base_type != null)
1120                                 base_ts = base_type.Type;
1121                         else if (spec.IsStruct)
1122                                 base_ts = TypeManager.value_type;
1123                         else if (spec.IsEnum)
1124                                 base_ts = TypeManager.enum_type;
1125                         else if (spec.IsDelegate)
1126                                 base_ts = TypeManager.multicast_delegate_type;
1127                         else
1128                                 base_ts = null;
1129
1130                         if (base_ts != null) {
1131                                 spec.BaseType = base_ts;
1132
1133                                 // Set base type after type creation
1134                                 TypeBuilder.SetParent (base_ts.GetMetaInfo ());
1135                         }
1136
1137                         return true;
1138                 }
1139
1140                 public virtual void DefineConstants ()
1141                 {
1142                         if (constants != null) {
1143                                 foreach (Const c in constants) {
1144                                         c.DefineValue ();
1145                                 }
1146                         }
1147
1148                         if (instance_constructors != null) {
1149                                 foreach (MethodCore m in instance_constructors) {
1150                                         var p = m.ParameterInfo;
1151                                         if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1152                                                 var rc = new ResolveContext (m);
1153                                                 p.ResolveDefaultValues (rc);
1154                                         }
1155                                 }
1156                         }
1157
1158                         if (methods != null) {
1159                                 foreach (MethodCore m in methods) {
1160                                         var p = m.ParameterInfo;
1161                                         if (!p.IsEmpty && p[p.Count - 1].HasDefaultValue) {
1162                                                 var rc = new ResolveContext (m);
1163                                                 p.ResolveDefaultValues (rc);
1164                                         }
1165                                 }
1166                         }
1167
1168                         if (indexers != null) {
1169                                 foreach (Indexer i in indexers) {
1170                                         var p = i.ParameterInfo;
1171                                         if (p[p.Count - 1].HasDefaultValue) {
1172                                             var rc = new ResolveContext (i);
1173                                                 p.ResolveDefaultValues (rc);
1174                                         }
1175                                 }
1176                         }
1177
1178                         if (types != null) {
1179                                 foreach (var t in types)
1180                                         t.DefineConstants ();
1181                         }
1182                 }
1183
1184                 //
1185                 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1186                 //
1187                 public TypeBuilder CreateType ()
1188                 {
1189                         if (TypeBuilder != null)
1190                                 return TypeBuilder;
1191
1192                         if (error)
1193                                 return null;
1194
1195                         if (!CreateTypeBuilder ()) {
1196                                 error = true;
1197                                 return null;
1198                         }
1199
1200                         if (partial_parts != null) {
1201                                 foreach (TypeContainer part in partial_parts) {
1202                                         part.spec = spec;
1203                                         part.current_type = current_type;
1204                                         part.TypeBuilder = TypeBuilder;
1205                                 }
1206                         }
1207
1208                         if (Types != null) {
1209                                 foreach (TypeContainer tc in Types) {
1210                                         if (tc.CreateType () == null) {
1211                                                 error = true;
1212                                                 return null;
1213                                         }
1214                                 }
1215                         }
1216
1217                         return TypeBuilder;
1218                 }
1219
1220                 public override TypeBuilder DefineType ()
1221                 {
1222                         if (error)
1223                                 return null;
1224                         if (type_defined)
1225                                 return TypeBuilder;
1226
1227                         type_defined = true;
1228
1229                         if (!DefineBaseTypes ()) {
1230                                 error = true;
1231                                 return null;
1232                         }
1233
1234                         if (!DefineNestedTypes ()) {
1235                                 error = true;
1236                                 return null;
1237                         }
1238
1239                         return TypeBuilder;
1240                 }
1241
1242                 public override void SetParameterInfo (List<Constraints> constraints_list)
1243                 {
1244                         base.SetParameterInfo (constraints_list);
1245
1246                         if (PartialContainer.CurrentTypeParameters == null || PartialContainer == this)
1247                                 return;
1248
1249                         TypeParameter[] tc_names = PartialContainer.CurrentTypeParameters;
1250                         for (int i = 0; i < tc_names.Length; ++i) {
1251                                 if (tc_names [i].Name != type_params [i].Name) {
1252                                         Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1253                                         Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1254                                                 GetSignatureForError ());
1255                                         break;
1256                                 }
1257
1258                                 if (tc_names [i].Variance != type_params [i].Variance) {
1259                                         Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1260                                         Report.Error (1067, Location, "Partial declarations of `{0}' must have the same type parameter variance modifiers",
1261                                                 GetSignatureForError ());
1262                                         break;
1263                                 }
1264                         }
1265                 }
1266
1267                 //
1268                 // Replaces normal spec with predefined one when compiling corlib
1269                 // and this type container defines predefined type
1270                 //
1271                 public void SetPredefinedSpec (PredefinedTypeSpec spec)
1272                 {
1273                         this.spec = spec;
1274                 }
1275
1276                 void UpdateTypeParameterConstraints (TypeContainer part)
1277                 {
1278                         TypeParameter[] current_params = type_params;
1279                         for (int i = 0; i < current_params.Length; i++) {
1280                                 if (current_params [i].AddPartialConstraints (part, part.type_params [i]))
1281                                         continue;
1282
1283                                 Report.SymbolRelatedToPreviousError (Location, "");
1284                                 Report.Error (265, part.Location,
1285                                         "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1286                                         GetSignatureForError (), current_params [i].GetSignatureForError ());
1287                         }
1288                 }
1289
1290                 public bool ResolveTypeParameters ()
1291                 {
1292                         if (!DoResolveTypeParameters ())
1293                                 return false;
1294
1295                         if (types != null) {
1296                                 foreach (var type in types)
1297                                         if (!type.ResolveTypeParameters ())
1298                                                 return false;
1299                         }
1300
1301                         if (compiler_generated != null) {
1302                                 foreach (CompilerGeneratedClass c in compiler_generated)
1303                                         if (!c.ResolveTypeParameters ())
1304                                                 return false;
1305                         }
1306
1307                         return true;
1308                 }
1309
1310                 protected virtual bool DoResolveTypeParameters ()
1311                 {
1312                         if (CurrentTypeParameters == null)
1313                                 return true;
1314
1315                         if (PartialContainer != this)
1316                                 throw new InternalErrorException ();
1317
1318                         var base_context = new BaseContext (this);
1319                         foreach (TypeParameter type_param in CurrentTypeParameters) {
1320                                 if (!type_param.ResolveConstraints (base_context)) {
1321                                         error = true;
1322                                         return false;
1323                                 }
1324                         }
1325
1326                         if (partial_parts != null) {
1327                                 foreach (TypeContainer part in partial_parts)
1328                                         UpdateTypeParameterConstraints (part);
1329                         }
1330
1331                         return true;
1332                 }
1333
1334                 protected virtual bool DefineNestedTypes ()
1335                 {
1336                         if (Types != null) {
1337                                 foreach (TypeContainer tc in Types)
1338                                         if (tc.DefineType () == null)
1339                                                 return false;
1340                         }
1341
1342                         return true;
1343                 }
1344
1345                 TypeSpec CheckRecursiveDefinition (TypeContainer tc)
1346                 {
1347                         if (InTransit != null)
1348                                 return spec;
1349
1350                         InTransit = tc;
1351
1352                         if (base_type != null && base_type.Type != null) {
1353                                 var ptc = base_type.Type.MemberDefinition as TypeContainer;
1354                                 if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1355                                         return base_type.Type;
1356                         }
1357
1358                         if (iface_exprs != null) {
1359                                 foreach (TypeExpr iface in iface_exprs) {
1360                                         // the interface might not have been resolved, prevents a crash, see #442144
1361                                         if (iface == null)
1362                                                 continue;
1363                                         var ptc = iface.Type.MemberDefinition as Interface;
1364                                         if (ptc != null && ptc.CheckRecursiveDefinition (this) != null)
1365                                                 return iface.Type;
1366                                 }
1367                         }
1368
1369                         if (!IsTopLevel && Parent.PartialContainer.CheckRecursiveDefinition (this) != null)
1370                                 return spec;
1371
1372                         InTransit = null;
1373                         return null;
1374                 }
1375
1376                 /// <summary>
1377                 ///   Populates our TypeBuilder with fields and methods
1378                 /// </summary>
1379                 public sealed override bool Define ()
1380                 {
1381                         if (members_defined)
1382                                 return members_defined_ok;
1383
1384                         members_defined_ok = DoDefineMembers ();
1385                         members_defined = true;
1386
1387                         if (types != null) {
1388                                 foreach (var nested in types)
1389                                         nested.Define ();
1390                         }
1391
1392                         return members_defined_ok;
1393                 }
1394
1395                 protected virtual bool DoDefineMembers ()
1396                 {
1397                         if (iface_exprs != null) {
1398                                 foreach (TypeExpr iface in iface_exprs) {
1399                                         var iface_type = iface.Type;
1400
1401                                         // Ensure the base is always setup
1402                                         var compiled_iface = iface_type.MemberDefinition as Interface;
1403                                         if (compiled_iface != null)
1404                                                 compiled_iface.Define ();
1405
1406                                         if (Kind == MemberKind.Interface)
1407                                                 MemberCache.AddInterface (iface_type);
1408
1409                                         ObsoleteAttribute oa = iface_type.GetAttributeObsolete ();
1410                                         if (oa != null && !IsObsolete)
1411                                                 AttributeTester.Report_ObsoleteMessage (oa, iface.GetSignatureForError (), Location, Report);
1412
1413                                         GenericTypeExpr ct = iface as GenericTypeExpr;
1414                                         if (ct != null) {
1415                                                 // TODO: passing `this' is wrong, should be base type iface instead
1416                                                 TypeManager.CheckTypeVariance (ct.Type, Variance.Covariant, this);
1417
1418                                                 ct.CheckConstraints (this);
1419
1420                                                 if (ct.HasDynamicArguments ()) {
1421                                                         Report.Error (1966, iface.Location,
1422                                                                 "`{0}': cannot implement a dynamic interface `{1}'",
1423                                                                 GetSignatureForError (), iface.GetSignatureForError ());
1424                                                         return false;
1425                                                 }
1426                                         }
1427                                 }
1428                         }
1429
1430                         if (base_type != null) {
1431                                 ObsoleteAttribute obsolete_attr = base_type.Type.GetAttributeObsolete ();
1432                                 if (obsolete_attr != null && !IsObsolete)
1433                                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location, Report);
1434
1435                                 var ct = base_type as GenericTypeExpr;
1436                                 if (ct != null)
1437                                         ct.CheckConstraints (this);
1438
1439                                 var baseContainer = base_type.Type.MemberDefinition as ClassOrStruct;
1440                                 if (baseContainer != null) {
1441                                         baseContainer.Define ();
1442
1443                                         //
1444                                         // It can trigger define of this type (for generic types only)
1445                                         //
1446                                         if (HasMembersDefined)
1447                                                 return true;
1448                                 }
1449                         }
1450
1451                         if (type_params != null) {
1452                                 foreach (var tp in type_params) {
1453                                         tp.CheckGenericConstraints ();
1454                                 }
1455                         }
1456
1457                         if (!IsTopLevel) {
1458                                 MemberSpec candidate;
1459                                 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1460                                 if (conflict_symbol == null && candidate == null) {
1461                                         if ((ModFlags & Modifiers.NEW) != 0)
1462                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1463                                                         GetSignatureForError ());
1464                                 } else {
1465                                         if ((ModFlags & Modifiers.NEW) == 0) {
1466                                                 if (candidate == null)
1467                                                         candidate = conflict_symbol;
1468
1469                                                 Report.SymbolRelatedToPreviousError (candidate);
1470                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1471                                                         GetSignatureForError (), candidate.GetSignatureForError ());
1472                                         }
1473                                 }
1474                         }
1475
1476                         DefineContainerMembers (constants);
1477                         DefineContainerMembers (fields);
1478
1479                         if (Kind == MemberKind.Struct || Kind == MemberKind.Class) {
1480                                 pending = PendingImplementation.GetPendingImplementations (this);
1481
1482                                 if (requires_delayed_unmanagedtype_check) {
1483                                         requires_delayed_unmanagedtype_check = false;
1484                                         foreach (FieldBase f in fields) {
1485                                                 if (f.MemberType != null && f.MemberType.IsPointer)
1486                                                         TypeManager.VerifyUnmanaged (Compiler, f.MemberType, f.Location);
1487                                         }
1488                                 }
1489                         }
1490                 
1491                         //
1492                         // Constructors are not in the defined_names array
1493                         //
1494                         DefineContainerMembers (instance_constructors);
1495                 
1496                         DefineContainerMembers (events);
1497                         DefineContainerMembers (ordered_explicit_member_list);
1498                         DefineContainerMembers (ordered_member_list);
1499
1500                         if (operators != null) {
1501                                 DefineContainerMembers (operators);
1502                                 CheckPairedOperators ();
1503                         }
1504
1505                         ComputeIndexerName();
1506                         CheckEqualsAndGetHashCode();
1507
1508                         return true;
1509                 }
1510
1511                 protected virtual void DefineContainerMembers (System.Collections.IList mcal) // IList<MemberCore>
1512                 {
1513                         if (mcal != null) {
1514                                 foreach (MemberCore mc in mcal) {
1515                                         try {
1516                                                 mc.Define ();
1517                                         } catch (Exception e) {
1518                                                 throw new InternalErrorException (mc, e);
1519                                         }
1520                                 }
1521                         }
1522                 }
1523                 
1524                 protected virtual void ComputeIndexerName ()
1525                 {
1526                         if (indexers == null)
1527                                 return;
1528
1529                         string class_indexer_name = null;
1530
1531                         //
1532                         // If there's both an explicit and an implicit interface implementation, the
1533                         // explicit one actually implements the interface while the other one is just
1534                         // a normal indexer.  See bug #37714.
1535                         //
1536
1537                         // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1538                         foreach (Indexer i in indexers) {
1539                                 if (i.InterfaceType != null) {
1540                                         if (seen_normal_indexers)
1541                                                 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1542                                         continue;
1543                                 }
1544
1545                                 seen_normal_indexers = true;
1546
1547                                 if (class_indexer_name == null) {
1548                                         class_indexer_name = i.ShortName;
1549                                         continue;
1550                                 }
1551
1552                                 if (i.ShortName != class_indexer_name)
1553                                         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");
1554                         }
1555
1556                         if (class_indexer_name != null)
1557                                 indexer_name = class_indexer_name;
1558                 }
1559
1560                 void EmitIndexerName ()
1561                 {
1562                         if (!seen_normal_indexers)
1563                                 return;
1564
1565                         PredefinedAttribute pa = PredefinedAttributes.Get.DefaultMember;
1566                         if (pa.Constructor == null &&
1567                                 !pa.ResolveConstructor (Location, TypeManager.string_type))
1568                                 return;
1569
1570                         CustomAttributeBuilder cb = new CustomAttributeBuilder (pa.Constructor, new string [] { GetAttributeDefaultMember () });
1571                         TypeBuilder.SetCustomAttribute (cb);
1572                 }
1573
1574                 protected virtual void CheckEqualsAndGetHashCode ()
1575                 {
1576                         if (methods == null)
1577                                 return;
1578
1579                         if (HasEquals && !HasGetHashCode) {
1580                                 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1581                         }
1582                 }
1583
1584                 // Indicated whether container has StructLayout attribute set Explicit
1585                 public bool HasExplicitLayout {
1586                         get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1587                         set { caching_flags |= Flags.HasExplicitLayout; }
1588                 }
1589
1590                 public bool HasStructLayout {
1591                         get { return (caching_flags & Flags.HasStructLayout) != 0; }
1592                         set { caching_flags |= Flags.HasStructLayout; }
1593                 }
1594
1595                 public MemberCache MemberCache {
1596                         get {
1597                                 return spec.MemberCache;
1598                         }
1599                 }
1600
1601                 void CheckMemberUsage (List<MemberCore> al, string member_type)
1602                 {
1603                         if (al == null)
1604                                 return;
1605
1606                         foreach (MemberCore mc in al) {
1607                                 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1608                                         continue;
1609
1610                                 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1611                                         Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1612                                 }
1613                         }
1614                 }
1615
1616                 public virtual void VerifyMembers ()
1617                 {
1618                         //
1619                         // Check for internal or private fields that were never assigned
1620                         //
1621                         if (Report.WarningLevel >= 3) {
1622                                 if (RootContext.EnhancedWarnings) {
1623                                         CheckMemberUsage (properties, "property");
1624                                         CheckMemberUsage (methods, "method");
1625                                         CheckMemberUsage (constants, "constant");
1626                                 }
1627
1628                                 if (fields != null){
1629                                         bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1630                                         foreach (FieldBase f in fields) {
1631                                                 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1632                                                         if (is_type_exposed)
1633                                                                 continue;
1634
1635                                                         f.SetIsUsed ();
1636                                                 }                               
1637                                                 
1638                                                 if (!f.IsUsed){
1639                                                         if ((f.caching_flags & Flags.IsAssigned) == 0)
1640                                                                 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1641                                                         else {
1642                                                                 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1643                                                                         f.GetSignatureForError ());
1644                                                         }
1645                                                         continue;
1646                                                 }
1647                                                 
1648                                                 //
1649                                                 // Only report 649 on level 4
1650                                                 //
1651                                                 if (Report.WarningLevel < 4)
1652                                                         continue;
1653                                                 
1654                                                 if ((f.caching_flags & Flags.IsAssigned) != 0)
1655                                                         continue;
1656
1657                                                 //
1658                                                 // Don't be pendatic over serializable attributes
1659                                                 //
1660                                                 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1661                                                         continue;
1662                                                 
1663                                                 Constant c = New.Constantify (f.MemberType);
1664                                                 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1665                                                         f.GetSignatureForError (), c == null ? "null" : c.AsString ());
1666                                         }
1667                                 }
1668                         }
1669                 }
1670
1671                 public override void Emit ()
1672                 {
1673                         if (all_tp_builders != null) {
1674                                 int current_starts_index = CurrentTypeParametersStartIndex;
1675                                 for (int i = 0; i < all_tp_builders.Length; i++) {
1676                                         if (i < current_starts_index) {
1677                                                 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1678                                         } else {
1679                                                 CurrentTypeParameters [i - current_starts_index].Emit ();
1680                                         }
1681                                 }
1682                         }
1683
1684                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1685                                 PredefinedAttributes.Get.CompilerGenerated.EmitAttribute (TypeBuilder);
1686
1687                         base.Emit ();
1688                 }
1689
1690                 // TODO: move to ClassOrStruct
1691                 void EmitConstructors ()
1692                 {
1693                         if (instance_constructors == null)
1694                                 return;
1695
1696                         if (spec.IsAttribute && IsExposedFromAssembly () && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
1697                                 bool has_compliant_args = false;
1698
1699                                 foreach (Constructor c in instance_constructors) {
1700                                         try {
1701                                                 c.Emit ();
1702                                         }
1703                                         catch (Exception e) {
1704                                                 throw new InternalErrorException (c, e);
1705                                         }
1706
1707                                         if (has_compliant_args)
1708                                                 continue;
1709
1710                                         has_compliant_args = c.HasCompliantArgs;
1711                                 }
1712                                 if (!has_compliant_args)
1713                                         Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1714                         } else {
1715                                 foreach (Constructor c in instance_constructors) {
1716                                         try {
1717                                                 c.Emit ();
1718                                         }
1719                                         catch (Exception e) {
1720                                                 throw new InternalErrorException (c, e);
1721                                         }
1722                                 }
1723                         }
1724                 }
1725
1726                 /// <summary>
1727                 ///   Emits the code, this step is performed after all
1728                 ///   the types, enumerations, constructors
1729                 /// </summary>
1730                 public virtual void EmitType ()
1731                 {
1732                         if (OptAttributes != null)
1733                                 OptAttributes.Emit ();
1734
1735                         Emit ();
1736
1737                         EmitConstructors ();
1738
1739                         if (constants != null)
1740                                 foreach (Const con in constants)
1741                                         con.Emit ();
1742
1743                         if (default_static_constructor != null)
1744                                 default_static_constructor.Emit ();
1745                         
1746                         if (operators != null)
1747                                 foreach (Operator o in operators)
1748                                         o.Emit ();
1749
1750                         if (properties != null)
1751                                 foreach (Property p in properties)
1752                                         p.Emit ();
1753
1754                         if (indexers != null) {
1755                                 foreach (Indexer indx in indexers)
1756                                         indx.Emit ();
1757                                 EmitIndexerName ();
1758                         }
1759
1760                         if (events != null){
1761                                 foreach (Event e in Events)
1762                                         e.Emit ();
1763                         }
1764
1765                         if (methods != null) {
1766                                 for (int i = 0; i < methods.Count; ++i)
1767                                         ((MethodOrOperator) methods [i]).Emit ();
1768                         }
1769                         
1770                         if (fields != null)
1771                                 foreach (FieldBase f in fields)
1772                                         f.Emit ();
1773
1774                         if (types != null) {
1775                                 foreach (TypeContainer t in types)
1776                                         t.EmitType ();
1777                         }
1778
1779                         if (pending != null)
1780                                 pending.VerifyPendingMethods (Report);
1781
1782                         if (Report.Errors > 0)
1783                                 return;
1784
1785                         if (compiler_generated != null) {
1786                                 for (int i = 0; i < compiler_generated.Count; ++i)
1787                                         compiler_generated [i].EmitType ();
1788                         }
1789                 }
1790
1791                 public void CloseType ()
1792                 {
1793                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
1794                                 return;
1795
1796                         // Close base type container first to avoid TypeLoadException
1797                         if (spec.BaseType != null) {
1798                                 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1799                                 if (btype != null)
1800                                         btype.CloseType ();
1801                         }
1802
1803                         try {
1804                                 caching_flags |= Flags.CloseTypeCreated;
1805                                 TypeBuilder.CreateType ();
1806                         } catch (TypeLoadException){
1807                                 //
1808                                 // This is fine, the code still created the type
1809                                 //
1810 //                              Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1811 //                              Console.WriteLine (e.Message);
1812                         } catch (Exception e) {
1813                                 throw new InternalErrorException (this, e);
1814                         }
1815                         
1816                         if (Types != null){
1817                                 foreach (TypeContainer tc in Types)
1818                                         tc.CloseType ();
1819                         }
1820
1821                         if (compiler_generated != null)
1822                                 foreach (CompilerGeneratedClass c in compiler_generated)
1823                                         c.CloseType ();
1824                         
1825                         types = null;
1826                         fields = null;
1827                         initialized_fields = null;
1828                         initialized_static_fields = null;
1829                         constants = null;
1830                         ordered_explicit_member_list = null;
1831                         ordered_member_list = null;
1832                         methods = null;
1833                         events = null;
1834                         indexers = null;
1835                         operators = null;
1836                         compiler_generated = null;
1837                         default_constructor = null;
1838                         default_static_constructor = null;
1839                         type_bases = null;
1840                         OptAttributes = null;
1841                 }
1842
1843                 //
1844                 // Performs the validation on a Method's modifiers (properties have
1845                 // the same properties).
1846                 //
1847                 public bool MethodModifiersValid (MemberCore mc)
1848                 {
1849                         const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1850                         const Modifiers va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
1851                         const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1852                         bool ok = true;
1853                         var flags = mc.ModFlags;
1854                         
1855                         //
1856                         // At most one of static, virtual or override
1857                         //
1858                         if ((flags & Modifiers.STATIC) != 0){
1859                                 if ((flags & vao) != 0){
1860                                         Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1861                                                 mc.GetSignatureForError ());
1862                                         ok = false;
1863                                 }
1864                         }
1865
1866                         if (Kind == MemberKind.Struct){
1867                                 if ((flags & va) != 0){
1868                                         ModifiersExtensions.Error_InvalidModifier (mc.Location, "virtual or abstract", Report);
1869                                         ok = false;
1870                                 }
1871                         }
1872
1873                         if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1874                                 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1875                                         mc.GetSignatureForError ());
1876                                 ok = false;
1877                         }
1878
1879                         //
1880                         // If the declaration includes the abstract modifier, then the
1881                         // declaration does not include static, virtual or extern
1882                         //
1883                         if ((flags & Modifiers.ABSTRACT) != 0){
1884                                 if ((flags & Modifiers.EXTERN) != 0){
1885                                         Report.Error (
1886                                                 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
1887                                         ok = false;
1888                                 }
1889
1890                                 if ((flags & Modifiers.SEALED) != 0) {
1891                                         Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
1892                                         ok = false;
1893                                 }
1894
1895                                 if ((flags & Modifiers.VIRTUAL) != 0){
1896                                         Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
1897                                         ok = false;
1898                                 }
1899
1900                                 if ((ModFlags & Modifiers.ABSTRACT) == 0){
1901                                         Report.SymbolRelatedToPreviousError (this);
1902                                         Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
1903                                                 mc.GetSignatureForError (), GetSignatureForError ());
1904                                         ok = false;
1905                                 }
1906                         }
1907
1908                         if ((flags & Modifiers.PRIVATE) != 0){
1909                                 if ((flags & vao) != 0){
1910                                         Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
1911                                         ok = false;
1912                                 }
1913                         }
1914
1915                         if ((flags & Modifiers.SEALED) != 0){
1916                                 if ((flags & Modifiers.OVERRIDE) == 0){
1917                                         Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
1918                                         ok = false;
1919                                 }
1920                         }
1921
1922                         return ok;
1923                 }
1924
1925                 public Constructor DefaultStaticConstructor {
1926                         get { return default_static_constructor; }
1927                 }
1928
1929                 protected override bool VerifyClsCompliance ()
1930                 {
1931                         if (!base.VerifyClsCompliance ())
1932                                 return false;
1933
1934                         // Check this name against other containers
1935                         NamespaceEntry.NS.VerifyClsCompliance ();
1936
1937                         // Check all container names for user classes
1938                         if (Kind != MemberKind.Delegate)
1939                                 MemberCache.VerifyClsCompliance (Definition, Report);
1940
1941                         if (BaseType != null && !BaseType.IsCLSCompliant ()) {
1942                                 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
1943                                         GetSignatureForError (), BaseType.GetSignatureForError ());
1944                         }
1945                         return true;
1946                 }
1947
1948                 /// <summary>
1949                 ///   Performs checks for an explicit interface implementation.  First it
1950                 ///   checks whether the `interface_type' is a base inteface implementation.
1951                 ///   Then it checks whether `name' exists in the interface type.
1952                 /// </summary>
1953                 public bool VerifyImplements (InterfaceMemberBase mb)
1954                 {
1955                         var ifaces = spec.Interfaces;
1956                         if (ifaces != null) {
1957                                 foreach (TypeSpec t in ifaces){
1958                                         if (TypeManager.IsEqual (t, mb.InterfaceType))
1959                                                 return true;
1960                                 }
1961                         }
1962                         
1963                         Report.SymbolRelatedToPreviousError (mb.InterfaceType);
1964                         Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
1965                                 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
1966                         return false;
1967                 }
1968
1969                 //
1970                 // Used for visiblity checks to tests whether this definition shares
1971                 // base type baseType, it does member-definition search
1972                 //
1973                 public bool IsBaseTypeDefinition (TypeSpec baseType)
1974                 {
1975                         // RootContext check
1976                         if (TypeBuilder == null)
1977                                 return false;
1978
1979                         var type = spec;
1980                         do {
1981                                 if (type.MemberDefinition == baseType.MemberDefinition)
1982                                         return true;
1983
1984                                 type = type.BaseType;
1985                         } while (type != null);
1986
1987                         return false;
1988                 }
1989
1990                 public MemberCache LoadMembers (TypeSpec declaringType)
1991                 {
1992                         throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
1993                 }
1994
1995                 public void Mark_HasEquals ()
1996                 {
1997                         cached_method |= CachedMethods.Equals;
1998                 }
1999
2000                 public void Mark_HasGetHashCode ()
2001                 {
2002                         cached_method |= CachedMethods.GetHashCode;
2003                 }
2004
2005                 /// <summary>
2006                 /// Method container contains Equals method
2007                 /// </summary>
2008                 public bool HasEquals {
2009                         get {
2010                                 return (cached_method & CachedMethods.Equals) != 0;
2011                         }
2012                 }
2013  
2014                 /// <summary>
2015                 /// Method container contains GetHashCode method
2016                 /// </summary>
2017                 public bool HasGetHashCode {
2018                         get {
2019                                 return (cached_method & CachedMethods.GetHashCode) != 0;
2020                         }
2021                 }
2022
2023                 public bool HasStaticFieldInitializer {
2024                         get {
2025                                 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2026                         }
2027                         set {
2028                                 if (value)
2029                                         cached_method |= CachedMethods.HasStaticFieldInitializer;
2030                                 else
2031                                         cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2032                         }
2033                 }
2034
2035                 //
2036                 // Generates xml doc comments (if any), and if required,
2037                 // handle warning report.
2038                 //
2039                 internal override void GenerateDocComment (DeclSpace ds)
2040                 {
2041                         DocUtil.GenerateTypeDocComment (this, ds, Report);
2042                 }
2043
2044                 public override string DocCommentHeader {
2045                         get { return "T:"; }
2046                 }
2047         }
2048
2049         public abstract class ClassOrStruct : TypeContainer
2050         {
2051                 Dictionary<SecurityAction, PermissionSet> declarative_security;
2052
2053                 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2054                                       MemberName name, Attributes attrs, MemberKind kind)
2055                         : base (ns, parent, name, attrs, kind)
2056                 {
2057                 }
2058
2059                 protected override bool AddToContainer (MemberCore symbol, string name)
2060                 {
2061                         if (name == MemberName.Name) {
2062                                 if (symbol is TypeParameter) {
2063                                         Report.Error (694, symbol.Location,
2064                                                 "Type parameter `{0}' has same name as containing type, or method",
2065                                                 symbol.GetSignatureForError ());
2066                                         return false;
2067                                 }
2068
2069                                 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2070                                 if (imb == null || !imb.IsExplicitImpl) {
2071                                         Report.SymbolRelatedToPreviousError (this);
2072                                         Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2073                                                 symbol.GetSignatureForError ());
2074                                         return false;
2075                                 }
2076                         }
2077
2078                         return base.AddToContainer (symbol, name);
2079                 }
2080
2081                 public override void VerifyMembers ()
2082                 {
2083                         base.VerifyMembers ();
2084
2085                         if ((events != null) && Report.WarningLevel >= 3) {
2086                                 foreach (Event e in events){
2087                                         // Note: The event can be assigned from same class only, so we can report
2088                                         // this warning for all accessibility modes
2089                                         if ((e.caching_flags & Flags.IsUsed) == 0)
2090                                                 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2091                                 }
2092                         }
2093                 }
2094
2095                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2096                 {
2097                         if (a.IsValidSecurityAttribute ()) {
2098                                 if (declarative_security == null)
2099                                         declarative_security = new Dictionary<SecurityAction, PermissionSet> ();
2100
2101                                 a.ExtractSecurityPermissionSet (declarative_security);
2102                                 return;
2103                         }
2104
2105                         if (a.Type == pa.StructLayout) {
2106                                 PartialContainer.HasStructLayout = true;
2107
2108                                 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2109                                         PartialContainer.HasExplicitLayout = true;
2110                         }
2111
2112                         if (a.Type == pa.Dynamic) {
2113                                 a.Error_MisusedDynamicAttribute ();
2114                                 return;
2115                         }
2116
2117                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2118                 }
2119
2120                 /// <summary>
2121                 /// Defines the default constructors 
2122                 /// </summary>
2123                 protected void DefineDefaultConstructor (bool is_static)
2124                 {
2125                         // The default instance constructor is public
2126                         // If the class is abstract, the default constructor is protected
2127                         // The default static constructor is private
2128
2129                         Modifiers mods;
2130                         if (is_static) {
2131                                 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2132                         } else {
2133                                 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2134                         }
2135
2136                         Constructor c = new Constructor (this, MemberName.Name, mods,
2137                                 null, ParametersCompiled.EmptyReadOnlyParameters,
2138                                 new GeneratedBaseInitializer (Location),
2139                                 Location);
2140                         
2141                         AddConstructor (c);
2142                         c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2143                 }
2144
2145                 protected override bool DoDefineMembers ()
2146                 {
2147                         CheckProtectedModifier ();
2148
2149                         base.DoDefineMembers ();
2150
2151                         if (default_static_constructor != null)
2152                                 default_static_constructor.Define ();
2153
2154                         return true;
2155                 }
2156
2157                 public override void Emit ()
2158                 {
2159                         if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2160                                 DefineDefaultConstructor (true);
2161                                 default_static_constructor.Define ();
2162                         }
2163
2164                         base.Emit ();
2165
2166                         if (declarative_security != null) {
2167                                 foreach (var de in declarative_security) {
2168                                         TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2169                                 }
2170                         }
2171                 }
2172
2173                 public override ExtensionMethodGroupExpr LookupExtensionMethod (TypeSpec extensionType, string name, int arity, Location loc)
2174                 {
2175                         DeclSpace top_level = Parent;
2176                         if (top_level != null) {
2177                                 while (top_level.Parent != null)
2178                                         top_level = top_level.Parent;
2179
2180                                 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2181                                 if (candidates != null)
2182                                         return new ExtensionMethodGroupExpr (candidates, NamespaceEntry, extensionType, loc);
2183                         }
2184
2185                         return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, loc);
2186                 }
2187
2188                 protected override TypeAttributes TypeAttr {
2189                         get {
2190                                 if (default_static_constructor == null)
2191                                         return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2192
2193                                 return base.TypeAttr;
2194                         }
2195                 }
2196         }
2197
2198
2199         // TODO: should be sealed
2200         public class Class : ClassOrStruct {
2201                 const Modifiers AllowedModifiers =
2202                         Modifiers.NEW |
2203                         Modifiers.PUBLIC |
2204                         Modifiers.PROTECTED |
2205                         Modifiers.INTERNAL |
2206                         Modifiers.PRIVATE |
2207                         Modifiers.ABSTRACT |
2208                         Modifiers.SEALED |
2209                         Modifiers.STATIC |
2210                         Modifiers.UNSAFE;
2211
2212                 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2213
2214                 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2215                               Attributes attrs)
2216                         : base (ns, parent, name, attrs, MemberKind.Class)
2217                 {
2218                         var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2219                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2220                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2221
2222                         if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2223                                 Report.FeatureIsNotAvailable (Location, "static classes");
2224                         }
2225                 }
2226
2227                 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2228                 {
2229                         if (part.Name == "System.Object")
2230                                 Report.Error (537, part.Location,
2231                                         "The class System.Object cannot have a base class or implement an interface.");
2232                         base.AddBasesForPart (part, bases);
2233                 }
2234
2235                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2236                 {
2237                         if (a.Type == pa.AttributeUsage) {
2238                                 if (!BaseType.IsAttribute && spec != TypeManager.attribute_type) {
2239                                         Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2240                                 }
2241                         }
2242
2243                         if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2244                                 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2245                                 return;
2246                         }
2247
2248                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2249                                 a.Error_MissingGuidAttribute ();
2250                                 return;
2251                         }
2252
2253                         if (a.Type == pa.Extension) {
2254                                 a.Error_MisusedExtensionAttribute ();
2255                                 return;
2256                         }
2257
2258                         if (a.Type.IsConditionallyExcluded (Location))
2259                                 return;
2260
2261                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2262                 }
2263
2264                 public override AttributeTargets AttributeTargets {
2265                         get {
2266                                 return AttributeTargets.Class;
2267                         }
2268                 }
2269
2270                 protected override void DefineContainerMembers (System.Collections.IList list)
2271                 {
2272                         if (list == null)
2273                                 return;
2274
2275                         if (!IsStatic) {
2276                                 base.DefineContainerMembers (list);
2277                                 return;
2278                         }
2279
2280                         foreach (MemberCore m in list) {
2281                                 if (m is Operator) {
2282                                         Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2283                                         continue;
2284                                 }
2285
2286                                 if (m is Destructor) {
2287                                         Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2288                                         continue;
2289                                 }
2290
2291                                 if (m is Indexer) {
2292                                         Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2293                                         continue;
2294                                 }
2295
2296                                 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2297                                         continue;
2298
2299                                 if (m is Constructor) {
2300                                         Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2301                                         continue;
2302                                 }
2303
2304                                 Method method = m as Method;
2305                                 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2306                                         Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2307                                         continue;
2308                                 }
2309
2310                                 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2311                         }
2312
2313                         base.DefineContainerMembers (list);
2314                 }
2315
2316                 protected override bool DoDefineMembers ()
2317                 {
2318                         if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2319                                 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2320                         }
2321
2322                         if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2323                                 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2324                         }
2325
2326                         if (InstanceConstructors == null && !IsStatic)
2327                                 DefineDefaultConstructor (false);
2328
2329                         return base.DoDefineMembers ();
2330                 }
2331
2332                 public override void Emit ()
2333                 {
2334                         base.Emit ();
2335
2336                         if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2337                                 PredefinedAttributes.Get.Extension.EmitAttribute (TypeBuilder);
2338                 }
2339
2340                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2341                 {
2342                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2343
2344                         if (base_class == null) {
2345                                 if (spec != TypeManager.object_type)
2346                                         base_class = TypeManager.system_object_expr;
2347                         } else {
2348                                 var base_type = base_class.Type;
2349
2350                                 if (base_type.IsGenericParameter){
2351                                         Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2352                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2353                                 } else if (IsGeneric && base_type.IsAttribute) {
2354                                         Report.Error (698, base_class.Location,
2355                                                 "A generic type cannot derive from `{0}' because it is an attribute class",
2356                                                 base_class.GetSignatureForError ());
2357                                 } else if (base_type.IsStatic) {
2358                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2359                                         Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2360                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2361                                 } else if (base_type.IsSealed){
2362                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2363                                         Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2364                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2365                                 }
2366
2367                                 if (base_type is PredefinedTypeSpec && !(spec is PredefinedTypeSpec) &&
2368                                         (base_type == TypeManager.enum_type || base_type == TypeManager.value_type || base_type == TypeManager.multicast_delegate_type ||
2369                                         base_type == TypeManager.delegate_type || base_type == TypeManager.array_type)) {
2370                                         Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2371                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2372                                         base_class = TypeManager.system_object_expr;
2373                                 }
2374
2375                                 if (!IsAccessibleAs (base_type)) {
2376                                         Report.SymbolRelatedToPreviousError (base_type);
2377                                         Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2378                                                 base_type.GetSignatureForError (), GetSignatureForError ());
2379                                 }
2380                         }
2381
2382                         if (PartialContainer.IsStatic) {
2383                                 if (base_class.Type != TypeManager.object_type) {
2384                                         Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2385                                                 GetSignatureForError (), base_class.GetSignatureForError ());
2386                                         return ifaces;
2387                                 }
2388
2389                                 if (ifaces != null) {
2390                                         foreach (TypeExpr t in ifaces)
2391                                                 Report.SymbolRelatedToPreviousError (t.Type);
2392                                         Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2393                                 }
2394                         }
2395
2396                         return ifaces;
2397                 }
2398
2399                 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2400                 /// Valid only for attribute classes.
2401                 public override string[] ConditionalConditions ()
2402                 {
2403                         if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2404                                 return null;
2405
2406                         caching_flags &= ~Flags.Excluded_Undetected;
2407
2408                         if (OptAttributes == null)
2409                                 return null;
2410
2411                         Attribute[] attrs = OptAttributes.SearchMulti (PredefinedAttributes.Get.Conditional);
2412                         if (attrs == null)
2413                                 return null;
2414
2415                         string[] conditions = new string[attrs.Length];
2416                         for (int i = 0; i < conditions.Length; ++i)
2417                                 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2418
2419                         caching_flags |= Flags.Excluded;
2420                         return conditions;
2421                 }
2422
2423                 //
2424                 // FIXME: How do we deal with the user specifying a different
2425                 // layout?
2426                 //
2427                 protected override TypeAttributes TypeAttr {
2428                         get {
2429                                 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2430                                 if (IsStatic)
2431                                         ta |= StaticClassAttribute;
2432                                 return ta;
2433                         }
2434                 }
2435         }
2436
2437         public sealed class Struct : ClassOrStruct {
2438
2439                 bool is_unmanaged, has_unmanaged_check_done;
2440                 bool InTransit;
2441
2442                 // <summary>
2443                 //   Modifiers allowed in a struct declaration
2444                 // </summary>
2445                 const Modifiers AllowedModifiers =
2446                         Modifiers.NEW       |
2447                         Modifiers.PUBLIC    |
2448                         Modifiers.PROTECTED |
2449                         Modifiers.INTERNAL  |
2450                         Modifiers.UNSAFE    |
2451                         Modifiers.PRIVATE;
2452
2453                 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2454                                Modifiers mod, Attributes attrs)
2455                         : base (ns, parent, name, attrs, MemberKind.Struct)
2456                 {
2457                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;                   
2458                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2459                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2460                 }
2461
2462                 public override AttributeTargets AttributeTargets {
2463                         get {
2464                                 return AttributeTargets.Struct;
2465                         }
2466                 }
2467
2468                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2469                 {
2470                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2471
2472                         //
2473                         // When struct constains fixed fixed and struct layout has explicitly
2474                         // set CharSet, its value has to be propagated to compiler generated
2475                         // fixed field types
2476                         //
2477                         if (a.Type == pa.StructLayout && Fields != null && a.HasField ("CharSet")) {
2478                                 for (int i = 0; i < Fields.Count; ++i) {
2479                                         FixedField ff = Fields [i] as FixedField;
2480                                         if (ff != null)
2481                                                 ff.SetCharSet (TypeBuilder.Attributes);
2482                                 }
2483                         }
2484                 }
2485
2486                 bool CheckStructCycles (Struct s)
2487                 {
2488                         if (s.Fields == null)
2489                                 return true;
2490
2491                         if (s.InTransit)
2492                                 return false;
2493
2494                         s.InTransit = true;
2495                         foreach (FieldBase field in s.Fields) {
2496                                 TypeSpec ftype = field.Spec.MemberType;
2497                                 if (!ftype.IsStruct)
2498                                         continue;
2499
2500                                 if (ftype is PredefinedTypeSpec)
2501                                         continue;
2502
2503                                 foreach (var targ in ftype.TypeArguments) {
2504                                         if (!CheckFieldTypeCycle (targ)) {
2505                                                 Report.Error (523, field.Location,
2506                                                         "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2507                                                         field.GetSignatureForError (), ftype.GetSignatureForError ());
2508                                                 break;
2509                                         }
2510                                 }
2511
2512                                 if ((field.IsStatic && !ftype.IsGeneric))
2513                                         continue;
2514
2515                                 if (!CheckFieldTypeCycle (ftype)) {
2516                                         Report.Error (523, field.Location,
2517                                                 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2518                                                 field.GetSignatureForError (), ftype.GetSignatureForError ());
2519                                         break;
2520                                 }
2521                         }
2522
2523                         s.InTransit = false;
2524                         return true;
2525                 }
2526
2527                 bool CheckFieldTypeCycle (TypeSpec ts)
2528                 {
2529                         var fts = ts.MemberDefinition as Struct;
2530                         if (fts == null)
2531                                 return true;
2532
2533                         return CheckStructCycles (fts);
2534                 }
2535
2536                 public override void Emit ()
2537                 {
2538                         CheckStructCycles (this);
2539
2540                         base.Emit ();
2541                 }
2542
2543                 public override bool IsUnmanagedType ()
2544                 {
2545                         if (fields == null)
2546                                 return true;
2547
2548                         if (has_unmanaged_check_done)
2549                                 return is_unmanaged;
2550
2551                         if (requires_delayed_unmanagedtype_check)
2552                                 return true;
2553
2554                         requires_delayed_unmanagedtype_check = true;
2555
2556                         foreach (FieldBase f in fields) {
2557                                 if (f.IsStatic)
2558                                         continue;
2559
2560                                 // It can happen when recursive unmanaged types are defined
2561                                 // struct S { S* s; }
2562                                 TypeSpec mt = f.MemberType;
2563                                 if (mt == null) {
2564                                         return true;
2565                                 }
2566
2567                                 while (mt.IsPointer)
2568                                         mt = TypeManager.GetElementType (mt);
2569
2570                                 if (mt.MemberDefinition == this) {
2571                                         for (var p = Parent; p != null; p = p.Parent) {
2572                                                 if (p.Kind == MemberKind.Class) {
2573                                                         has_unmanaged_check_done = true;
2574                                                         return false;
2575                                                 }
2576                                         }
2577                                         continue;
2578                                 }
2579
2580                                 if (TypeManager.IsUnmanagedType (mt))
2581                                         continue;
2582
2583                                 has_unmanaged_check_done = true;
2584                                 return false;
2585                         }
2586
2587                         has_unmanaged_check_done = true;
2588                         is_unmanaged = true;
2589                         return true;
2590                 }
2591
2592                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2593                 {
2594                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2595                         base_class = TypeManager.system_valuetype_expr;
2596                         return ifaces;
2597                 }
2598
2599                 protected override TypeAttributes TypeAttr {
2600                         get {
2601                                 const TypeAttributes DefaultTypeAttributes =
2602                                         TypeAttributes.SequentialLayout |
2603                                         TypeAttributes.Sealed;
2604
2605                                 return base.TypeAttr | DefaultTypeAttributes;
2606                         }
2607                 }
2608
2609                 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2610                 {
2611                         if ((field.ModFlags & Modifiers.STATIC) == 0) {
2612                                 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2613                                         field.GetSignatureForError ());
2614                                 return;
2615                         }
2616                         base.RegisterFieldForInitialization (field, expression);
2617                 }
2618
2619         }
2620
2621         /// <summary>
2622         ///   Interfaces
2623         /// </summary>
2624         public sealed class Interface : TypeContainer {
2625
2626                 /// <summary>
2627                 ///   Modifiers allowed in a class declaration
2628                 /// </summary>
2629                 public const Modifiers AllowedModifiers =
2630                         Modifiers.NEW       |
2631                         Modifiers.PUBLIC    |
2632                         Modifiers.PROTECTED |
2633                         Modifiers.INTERNAL  |
2634                         Modifiers.UNSAFE    |
2635                         Modifiers.PRIVATE;
2636
2637                 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2638                                   Attributes attrs)
2639                         : base (ns, parent, name, attrs, MemberKind.Interface)
2640                 {
2641                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2642
2643                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2644                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2645                 }
2646
2647                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2648                 {
2649                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2650                                 a.Error_MissingGuidAttribute ();
2651                                 return;
2652                         }
2653
2654                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2655                 }
2656
2657
2658                 public override AttributeTargets AttributeTargets {
2659                         get {
2660                                 return AttributeTargets.Interface;
2661                         }
2662                 }
2663
2664                 protected override TypeAttributes TypeAttr {
2665                         get {
2666                                 const TypeAttributes DefaultTypeAttributes =
2667                                         TypeAttributes.AutoLayout |
2668                                         TypeAttributes.Abstract |
2669                                         TypeAttributes.Interface;
2670
2671                                 return base.TypeAttr | DefaultTypeAttributes;
2672                         }
2673                 }
2674
2675                 protected override bool VerifyClsCompliance ()
2676                 {
2677                         if (!base.VerifyClsCompliance ())
2678                                 return false;
2679
2680                         if (iface_exprs != null) {
2681                                 foreach (var iface in iface_exprs) {
2682                                         if (iface.Type.IsCLSCompliant ())
2683                                                 continue;
2684
2685                                         Report.SymbolRelatedToPreviousError (iface.Type);
2686                                         Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2687                                                 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2688                                 }
2689                         }
2690
2691                         return true;
2692                 }
2693         }
2694
2695         public abstract class InterfaceMemberBase : MemberBase {
2696                 //
2697                 // Whether this is an interface member.
2698                 //
2699                 public bool IsInterface;
2700
2701                 //
2702                 // If true, this is an explicit interface implementation
2703                 //
2704                 public bool IsExplicitImpl;
2705
2706                 protected bool is_external_implementation;
2707
2708                 //
2709                 // The interface type we are explicitly implementing
2710                 //
2711                 public TypeSpec InterfaceType;
2712
2713                 //
2714                 // The method we're overriding if this is an override method.
2715                 //
2716                 protected MethodSpec base_method;
2717
2718                 readonly Modifiers explicit_mod_flags;
2719                 public MethodAttributes flags;
2720
2721                 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2722                                    FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2723                                    MemberName name, Attributes attrs)
2724                         : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2725                                 name, attrs)
2726                 {
2727                         IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2728                         IsExplicitImpl = (MemberName.Left != null);
2729                         explicit_mod_flags = mod;
2730                 }
2731                 
2732                 protected override bool CheckBase ()
2733                 {
2734                         if (!base.CheckBase ())
2735                                 return false;
2736
2737                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2738                                 CheckForDuplications ();
2739                         
2740                         if (IsExplicitImpl)
2741                                 return true;
2742
2743                         // For System.Object only
2744                         if (Parent.BaseType == null)
2745                                 return true;
2746
2747                         MemberSpec candidate;
2748                         var base_member = FindBaseMember (out candidate);
2749
2750                         if ((ModFlags & Modifiers.OVERRIDE) != 0) {
2751                                 if (base_member == null) {
2752                                         if (candidate == null) {
2753                                                 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
2754                                                         Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
2755                                                                 "object.Finalize()");
2756                                                 } else {
2757                                                         Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
2758                                                                 GetSignatureForError (), SimpleName.GetMemberType (this));
2759                                                 }
2760                                         } else {
2761                                                 Report.SymbolRelatedToPreviousError (candidate);
2762                                                 if (this is Event)
2763                                                         Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
2764                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2765                                                 else if (this is PropertyBase)
2766                                                         Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
2767                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2768                                                 else
2769                                                         Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
2770                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
2771                                         }
2772
2773                                         return false;
2774                                 }
2775
2776                                 if (!CheckOverrideAgainstBase (base_member))
2777                                         return false;
2778
2779                                 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
2780                                 if (oa != null) {
2781                                         if (OptAttributes == null || !OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2782                                                 Report.SymbolRelatedToPreviousError (base_member);
2783                                                 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
2784                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2785                                         }
2786                                 } else {
2787                                         if (OptAttributes != null && OptAttributes.Contains (PredefinedAttributes.Get.Obsolete)) {
2788                                                 Report.SymbolRelatedToPreviousError (base_member);
2789                                                 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
2790                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
2791                                         }
2792                                 }
2793
2794                                 base_method = base_member as MethodSpec;
2795                                 return true;
2796                         }
2797
2798                         if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
2799                                 base_member = candidate;
2800
2801                         if (base_member == null) {
2802                                 if ((ModFlags & Modifiers.NEW) != 0) {
2803                                         if (base_member == null) {
2804                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
2805                                                         GetSignatureForError ());
2806                                         }
2807                                 }
2808                         } else {
2809                                 if ((ModFlags & Modifiers.NEW) == 0) {
2810                                         ModFlags |= Modifiers.NEW;
2811                                         Report.SymbolRelatedToPreviousError (base_member);
2812                                         if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
2813                                                 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",
2814                                                         GetSignatureForError (), base_member.GetSignatureForError ());
2815                                         } else {
2816                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
2817                                                         GetSignatureForError (), base_member.GetSignatureForError ());
2818                                         }
2819                                 }
2820
2821                                 if (!IsInterface && base_member.IsAbstract) {
2822                                         Report.SymbolRelatedToPreviousError (base_member);
2823                                         Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
2824                                                 GetSignatureForError (), base_member.GetSignatureForError ());
2825                                 }
2826                         }
2827
2828                         return true;
2829                 }
2830
2831                 protected virtual bool CheckForDuplications ()
2832                 {
2833                         return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
2834                 }
2835
2836                 //
2837                 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
2838                 // that have been defined.
2839                 //
2840                 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
2841                 {
2842                         bool ok = true;
2843
2844                         if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE | Modifiers.OVERRIDE_UNCHECKED)) == 0) {
2845                                 Report.SymbolRelatedToPreviousError (base_member);
2846                                 Report.Error (506, Location,
2847                                         "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
2848                                          GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2849                                 ok = false;
2850                         }
2851
2852                         // Now we check that the overriden method is not final  
2853                         if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
2854                                 Report.SymbolRelatedToPreviousError (base_member);
2855                                 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
2856                                                           GetSignatureForError (), TypeManager.CSharpSignature (base_member));
2857                                 ok = false;
2858                         }
2859
2860                         var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
2861                         if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
2862                                 Report.SymbolRelatedToPreviousError (base_member);
2863                                 if (this is PropertyBasedMember) {
2864                                         Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
2865                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2866                                 } else {
2867                                         Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
2868                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
2869                                 }
2870                                 ok = false;
2871                         }
2872
2873                         return ok;
2874                 }
2875
2876                 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
2877                 {
2878                         var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
2879                         var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
2880
2881                         if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2882                                 //
2883                                 // when overriding protected internal, the method can be declared
2884                                 // protected internal only within the same assembly or assembly
2885                                 // which has InternalsVisibleTo
2886                                 //
2887                                 if ((thisp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
2888                                         return TypeManager.IsThisOrFriendAssembly (this_member.Assembly, base_member.Assembly);
2889                                 } 
2890                                 if ((thisp & Modifiers.PROTECTED) != Modifiers.PROTECTED) {
2891                                         //
2892                                         // if it's not "protected internal", it must be "protected"
2893                                         //
2894
2895                                         return false;
2896                                 }
2897                                 if (this_member.Parent.PartialContainer.Module.Assembly == base_member.Assembly) {
2898                                         //
2899                                         // protected within the same assembly - an error
2900                                         //
2901                                         return false;
2902                                 }
2903                                 if ((thisp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL)) !=
2904                                            (base_classp & ~(Modifiers.PROTECTED | Modifiers.INTERNAL))) {
2905                                         //
2906                                         // protected ok, but other attributes differ - report an error
2907                                         //
2908                                         return false;
2909                                 }
2910                                 return true;
2911                         }
2912
2913                         return thisp == base_classp;
2914                 }
2915
2916                 public override bool Define ()
2917                 {
2918                         if (IsInterface) {
2919                                 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
2920                                         Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
2921
2922                                 flags = MethodAttributes.Public |
2923                                         MethodAttributes.Abstract |
2924                                         MethodAttributes.HideBySig |
2925                                         MethodAttributes.NewSlot |
2926                                         MethodAttributes.Virtual;
2927                         } else {
2928                                 Parent.PartialContainer.MethodModifiersValid (this);
2929
2930                                 flags = ModifiersExtensions.MethodAttr (ModFlags);
2931                         }
2932
2933                         if (IsExplicitImpl) {
2934                                 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
2935                                 if (iface_texpr == null)
2936                                         return false;
2937
2938                                 if ((ModFlags & Modifiers.PARTIAL) != 0) {
2939                                         Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
2940                                                 GetSignatureForError ());
2941                                 }
2942
2943                                 InterfaceType = iface_texpr.Type;
2944
2945                                 if (!InterfaceType.IsInterface) {
2946                                         Report.SymbolRelatedToPreviousError (InterfaceType);
2947                                         Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
2948                                                 TypeManager.CSharpName (InterfaceType));
2949                                 } else {
2950                                         Parent.PartialContainer.VerifyImplements (this);
2951                                 }
2952
2953                                 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
2954                         }
2955
2956                         return base.Define ();
2957                 }
2958
2959                 protected bool DefineParameters (ParametersCompiled parameters)
2960                 {
2961                         if (!parameters.Resolve (this))
2962                                 return false;
2963
2964                         bool error = false;
2965                         for (int i = 0; i < parameters.Count; ++i) {
2966                                 Parameter p = parameters [i];
2967
2968                                 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
2969                                         p.Warning_UselessOptionalParameter (Report);
2970
2971                                 if (p.CheckAccessibility (this))
2972                                         continue;
2973
2974                                 TypeSpec t = parameters.Types [i];
2975                                 Report.SymbolRelatedToPreviousError (t);
2976                                 if (this is Indexer)
2977                                         Report.Error (55, Location,
2978                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
2979                                                       TypeManager.CSharpName (t), GetSignatureForError ());
2980                                 else if (this is Operator)
2981                                         Report.Error (57, Location,
2982                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
2983                                                       TypeManager.CSharpName (t), GetSignatureForError ());
2984                                 else
2985                                         Report.Error (51, Location,
2986                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
2987                                                 TypeManager.CSharpName (t), GetSignatureForError ());
2988                                 error = true;
2989                         }
2990                         return !error;
2991                 }
2992
2993                 public override void Emit()
2994                 {
2995                         // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
2996                         // We are more strict than csc and report this as an error because SRE does not allow emit that
2997                         if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
2998                                 if (this is Constructor) {
2999                                         Report.Error (824, Location,
3000                                                 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3001                                 } else {
3002                                         Report.Error (626, Location,
3003                                                 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3004                                                 GetSignatureForError ());
3005                                 }
3006                         }
3007
3008                         base.Emit ();
3009                 }
3010
3011                 public override bool EnableOverloadChecks (MemberCore overload)
3012                 {
3013                         //
3014                         // Two members can differ in their explicit interface
3015                         // type parameter only
3016                         //
3017                         InterfaceMemberBase imb = overload as InterfaceMemberBase;
3018                         if (imb != null && imb.IsExplicitImpl) {
3019                                 if (IsExplicitImpl) {
3020                                         caching_flags |= Flags.MethodOverloadsExist;
3021                                 }
3022                                 return true;
3023                         }
3024
3025                         return IsExplicitImpl;
3026                 }
3027
3028                 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3029                 {
3030                         Report.SymbolRelatedToPreviousError (base_member);
3031                         Report.Error (507, member.Location,
3032                                 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3033                                 member.GetSignatureForError (),
3034                                 ModifiersExtensions.AccessibilityName (base_member.Modifiers),
3035                                 base_member.GetSignatureForError ());
3036                 }
3037
3038                 protected void Error_StaticReturnType ()
3039                 {
3040                         Report.Error (722, Location,
3041                                 "`{0}': static types cannot be used as return types",
3042                                 MemberType.GetSignatureForError ());
3043                 }
3044
3045                 /// <summary>
3046                 /// Gets base method and its return type
3047                 /// </summary>
3048                 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3049                 {
3050                         return MemberCache.FindBaseMember (this, out bestCandidate);
3051                 }
3052
3053                 //
3054                 // The "short" name of this property / indexer / event.  This is the
3055                 // name without the explicit interface.
3056                 //
3057                 public string ShortName {
3058                         get { return MemberName.Name; }
3059                         set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3060                 }
3061                 
3062                 //
3063                 // Returns full metadata method name
3064                 //
3065                 public string GetFullName (MemberName name)
3066                 {
3067                         return GetFullName (name.Name);
3068                 }
3069
3070                 public string GetFullName (string name)
3071                 {
3072                         if (!IsExplicitImpl)
3073                                 return name;
3074
3075                         //
3076                         // When dealing with explicit members a full interface type
3077                         // name is added to member name to avoid possible name conflicts
3078                         //
3079                         // We use CSharpName which gets us full name with benefit of
3080                         // replacing predefined names which saves some space and name
3081                         // is still unique
3082                         //
3083                         return TypeManager.CSharpName (InterfaceType) + "." + name;
3084                 }
3085
3086                 protected override bool VerifyClsCompliance ()
3087                 {
3088                         if (!base.VerifyClsCompliance ()) {
3089                                 return false;
3090                         }
3091
3092                         if (GenericMethod != null)
3093                                 GenericMethod.VerifyClsCompliance ();
3094
3095                         return true;
3096                 }
3097
3098                 public override bool IsUsed 
3099                 {
3100                         get { return IsExplicitImpl || base.IsUsed; }
3101                 }
3102
3103         }
3104
3105         public abstract class MemberBase : MemberCore
3106         {
3107                 protected FullNamedExpression type_expr;
3108                 protected TypeSpec member_type;
3109
3110                 public readonly DeclSpace ds;
3111                 public readonly GenericMethod GenericMethod;
3112
3113                 protected MemberBase (DeclSpace parent, GenericMethod generic,
3114                                       FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3115                                       MemberName name, Attributes attrs)
3116                         : base (parent, name, attrs)
3117                 {
3118                         this.ds = generic != null ? generic : (DeclSpace) parent;
3119                         this.type_expr = type;
3120                         ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3121                         GenericMethod = generic;
3122                         if (GenericMethod != null)
3123                                 GenericMethod.ModFlags = ModFlags;
3124                 }
3125
3126                 //
3127                 // Main member define entry
3128                 //
3129                 public override bool Define ()
3130                 {
3131                         DoMemberTypeIndependentChecks ();
3132
3133                         //
3134                         // Returns false only when type resolution failed
3135                         //
3136                         if (!ResolveMemberType ())
3137                                 return false;
3138
3139                         DoMemberTypeDependentChecks ();
3140                         return true;
3141                 }
3142
3143                 //
3144                 // Any type_name independent checks
3145                 //
3146                 protected virtual void DoMemberTypeIndependentChecks ()
3147                 {
3148                         if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3149                                 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3150                                 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3151                                         GetSignatureForError (), Parent.GetSignatureForError ());
3152                         }
3153                 }
3154
3155                 //
3156                 // Any type_name dependent checks
3157                 //
3158                 protected virtual void DoMemberTypeDependentChecks ()
3159                 {
3160                         // verify accessibility
3161                         if (!IsAccessibleAs (MemberType)) {
3162                                 Report.SymbolRelatedToPreviousError (MemberType);
3163                                 if (this is Property)
3164                                         Report.Error (53, Location,
3165                                                       "Inconsistent accessibility: property type `" +
3166                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3167                                                       "accessible than property `" + GetSignatureForError () + "'");
3168                                 else if (this is Indexer)
3169                                         Report.Error (54, Location,
3170                                                       "Inconsistent accessibility: indexer return type `" +
3171                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3172                                                       "accessible than indexer `" + GetSignatureForError () + "'");
3173                                 else if (this is MethodCore) {
3174                                         if (this is Operator)
3175                                                 Report.Error (56, Location,
3176                                                               "Inconsistent accessibility: return type `" +
3177                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3178                                                               "accessible than operator `" + GetSignatureForError () + "'");
3179                                         else
3180                                                 Report.Error (50, Location,
3181                                                               "Inconsistent accessibility: return type `" +
3182                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3183                                                               "accessible than method `" + GetSignatureForError () + "'");
3184                                 } else {
3185                                         Report.Error (52, Location,
3186                                                       "Inconsistent accessibility: field type `" +
3187                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3188                                                       "accessible than field `" + GetSignatureForError () + "'");
3189                                 }
3190                         }
3191
3192                         Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3193                         TypeManager.CheckTypeVariance (MemberType, variance, this);
3194                 }
3195
3196                 protected bool IsTypePermitted ()
3197                 {
3198                         if (TypeManager.IsSpecialType (MemberType)) {
3199                                 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3200                                 return false;
3201                         }
3202                         return true;
3203                 }
3204
3205                 protected virtual bool CheckBase ()
3206                 {
3207                         CheckProtectedModifier ();
3208
3209                         return true;
3210                 }
3211
3212                 public TypeSpec MemberType {
3213                         get { return member_type; }
3214                 }
3215
3216                 protected virtual bool ResolveMemberType ()
3217                 {
3218                         if (member_type != null)
3219                                 throw new InternalErrorException ("Multi-resolve");
3220
3221                         TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3222                         if (te == null)
3223                                 return false;
3224                         
3225                         //
3226                         // Replace original type name, error reporting can use fully resolved name
3227                         //
3228                         type_expr = te;
3229
3230                         member_type = te.Type;
3231                         return true;
3232                 }
3233         }
3234 }
3235