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