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