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