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