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