[xbuild] Implement FileLogger . Fix #676650 .
[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.BuildinType == BuildinTypeSpec.Type.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.Kind == MemberKind.Void)
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 = Compiler.BuildinTypes.Object;
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                         var ctor = Module.PredefinedMembers.DefaultMemberAttributeCtor.Get ();
1657                         if (ctor == null)
1658                                 return;
1659
1660                         var encoder = new AttributeEncoder ();
1661                         encoder.Encode (GetAttributeDefaultMember ());
1662                         encoder.EncodeEmptyNamedArguments ();
1663
1664                         TypeBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), encoder.ToArray ());
1665                 }
1666
1667                 protected virtual void CheckEqualsAndGetHashCode ()
1668                 {
1669                         if (methods == null)
1670                                 return;
1671
1672                         if (HasEquals && !HasGetHashCode) {
1673                                 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1674                         }
1675                 }
1676
1677                 // Indicated whether container has StructLayout attribute set Explicit
1678                 public bool HasExplicitLayout {
1679                         get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1680                         set { caching_flags |= Flags.HasExplicitLayout; }
1681                 }
1682
1683                 public bool HasStructLayout {
1684                         get { return (caching_flags & Flags.HasStructLayout) != 0; }
1685                         set { caching_flags |= Flags.HasStructLayout; }
1686                 }
1687
1688                 public MemberCache MemberCache {
1689                         get {
1690                                 return spec.MemberCache;
1691                         }
1692                 }
1693
1694                 void CheckMemberUsage (List<MemberCore> al, string member_type)
1695                 {
1696                         if (al == null)
1697                                 return;
1698
1699                         foreach (MemberCore mc in al) {
1700                                 if ((mc.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE)
1701                                         continue;
1702
1703                                 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
1704                                         Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
1705                                 }
1706                         }
1707                 }
1708
1709                 public virtual void VerifyMembers ()
1710                 {
1711                         //
1712                         // Check for internal or private fields that were never assigned
1713                         //
1714                         if (Report.WarningLevel >= 3) {
1715                                 if (Compiler.Settings.EnhancedWarnings) {
1716                                         CheckMemberUsage (properties, "property");
1717                                         CheckMemberUsage (methods, "method");
1718                                         CheckMemberUsage (constants, "constant");
1719                                 }
1720
1721                                 if (fields != null){
1722                                         bool is_type_exposed = Kind == MemberKind.Struct || IsExposedFromAssembly ();
1723                                         foreach (FieldBase f in fields) {
1724                                                 if ((f.ModFlags & Modifiers.AccessibilityMask) != Modifiers.PRIVATE) {
1725                                                         if (is_type_exposed)
1726                                                                 continue;
1727
1728                                                         f.SetIsUsed ();
1729                                                 }                               
1730                                                 
1731                                                 if (!f.IsUsed){
1732                                                         if ((f.caching_flags & Flags.IsAssigned) == 0)
1733                                                                 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
1734                                                         else {
1735                                                                 Report.Warning (414, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
1736                                                                         f.GetSignatureForError ());
1737                                                         }
1738                                                         continue;
1739                                                 }
1740                                                 
1741                                                 //
1742                                                 // Only report 649 on level 4
1743                                                 //
1744                                                 if (Report.WarningLevel < 4)
1745                                                         continue;
1746                                                 
1747                                                 if ((f.caching_flags & Flags.IsAssigned) != 0)
1748                                                         continue;
1749
1750                                                 //
1751                                                 // Don't be pendatic over serializable attributes
1752                                                 //
1753                                                 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
1754                                                         continue;
1755                                                 
1756                                                 Constant c = New.Constantify (f.MemberType, f.Location);
1757                                                 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
1758                                                         f.GetSignatureForError (), c == null ? "null" : c.GetValueAsLiteral ());
1759                                         }
1760                                 }
1761                         }
1762                 }
1763
1764                 public override void Emit ()
1765                 {
1766                         if (!IsTopLevel) {
1767                                 MemberSpec candidate;
1768                                 var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
1769                                 if (conflict_symbol == null && candidate == null) {
1770                                         if ((ModFlags & Modifiers.NEW) != 0)
1771                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
1772                                                         GetSignatureForError ());
1773                                 } else {
1774                                         if ((ModFlags & Modifiers.NEW) == 0) {
1775                                                 if (candidate == null)
1776                                                         candidate = conflict_symbol;
1777
1778                                                 Report.SymbolRelatedToPreviousError (candidate);
1779                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1780                                                         GetSignatureForError (), candidate.GetSignatureForError ());
1781                                         }
1782                                 }
1783                         }
1784
1785                         if (all_tp_builders != null) {
1786                                 int current_starts_index = CurrentTypeParametersStartIndex;
1787                                 for (int i = 0; i < all_tp_builders.Length; i++) {
1788                                         if (i < current_starts_index) {
1789                                                 TypeParameters[i].EmitConstraints (all_tp_builders [i]);
1790                                         } else {
1791                                                 CurrentTypeParameters [i - current_starts_index].Emit ();
1792                                         }
1793                                 }
1794                         }
1795
1796                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
1797                                 Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (TypeBuilder);
1798
1799 #if STATIC
1800                         if ((TypeBuilder.Attributes & TypeAttributes.StringFormatMask) == 0 && Module.HasDefaultCharSet)
1801                                 TypeBuilder.__SetAttributes (TypeBuilder.Attributes | Module.DefaultCharSetType);
1802 #endif
1803
1804                         base.Emit ();
1805                 }
1806
1807                 // TODO: move to ClassOrStruct
1808                 void EmitConstructors ()
1809                 {
1810                         if (instance_constructors == null)
1811                                 return;
1812
1813                         if (spec.IsAttribute && IsExposedFromAssembly () && Compiler.Settings.VerifyClsCompliance && IsClsComplianceRequired ()) {
1814                                 bool has_compliant_args = false;
1815
1816                                 foreach (Constructor c in instance_constructors) {
1817                                         try {
1818                                                 c.Emit ();
1819                                         }
1820                                         catch (Exception e) {
1821                                                 throw new InternalErrorException (c, e);
1822                                         }
1823
1824                                         if (has_compliant_args)
1825                                                 continue;
1826
1827                                         has_compliant_args = c.HasCompliantArgs;
1828                                 }
1829                                 if (!has_compliant_args)
1830                                         Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
1831                         } else {
1832                                 foreach (Constructor c in instance_constructors) {
1833                                         try {
1834                                                 c.Emit ();
1835                                         }
1836                                         catch (Exception e) {
1837                                                 throw new InternalErrorException (c, e);
1838                                         }
1839                                 }
1840                         }
1841                 }
1842
1843                 /// <summary>
1844                 ///   Emits the code, this step is performed after all
1845                 ///   the types, enumerations, constructors
1846                 /// </summary>
1847                 public virtual void EmitType ()
1848                 {
1849                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
1850                                 return;
1851
1852                         if (OptAttributes != null)
1853                                 OptAttributes.Emit ();
1854
1855                         Emit ();
1856
1857                         EmitConstructors ();
1858
1859                         if (constants != null)
1860                                 foreach (Const con in constants)
1861                                         con.Emit ();
1862
1863                         if (default_static_constructor != null)
1864                                 default_static_constructor.Emit ();
1865                         
1866                         if (operators != null)
1867                                 foreach (Operator o in operators)
1868                                         o.Emit ();
1869
1870                         if (properties != null)
1871                                 foreach (Property p in properties)
1872                                         p.Emit ();
1873
1874                         if (indexers != null) {
1875                                 foreach (Indexer indx in indexers)
1876                                         indx.Emit ();
1877                                 EmitIndexerName ();
1878                         }
1879
1880                         if (events != null){
1881                                 foreach (Event e in Events)
1882                                         e.Emit ();
1883                         }
1884
1885                         if (methods != null) {
1886                                 for (int i = 0; i < methods.Count; ++i)
1887                                         ((MethodOrOperator) methods [i]).Emit ();
1888                         }
1889                         
1890                         if (fields != null)
1891                                 foreach (FieldBase f in fields)
1892                                         f.Emit ();
1893
1894                         if (types != null) {
1895                                 foreach (TypeContainer t in types)
1896                                         t.EmitType ();
1897                         }
1898
1899                         if (pending != null)
1900                                 pending.VerifyPendingMethods (Report);
1901
1902                         if (Report.Errors > 0)
1903                                 return;
1904
1905                         if (compiler_generated != null) {
1906                                 for (int i = 0; i < compiler_generated.Count; ++i)
1907                                         compiler_generated [i].EmitType ();
1908                         }
1909                 }
1910
1911                 public virtual void CloseType ()
1912                 {
1913                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
1914                                 return;
1915
1916                         // Close base type container first to avoid TypeLoadException
1917                         if (spec.BaseType != null) {
1918                                 var btype = spec.BaseType.MemberDefinition as TypeContainer;
1919                                 if (btype != null) {
1920                                         btype.CloseType ();
1921
1922                                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
1923                                                 return;
1924                                 }
1925                         }
1926
1927                         try {
1928                                 caching_flags |= Flags.CloseTypeCreated;
1929                                 TypeBuilder.CreateType ();
1930                         } catch (TypeLoadException){
1931                                 //
1932                                 // This is fine, the code still created the type
1933                                 //
1934 //                              Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
1935 //                              Console.WriteLine (e.Message);
1936                         } catch (Exception e) {
1937                                 throw new InternalErrorException (this, e);
1938                         }
1939                         
1940                         if (Types != null){
1941                                 foreach (TypeContainer tc in Types)
1942                                         tc.CloseType ();
1943                         }
1944
1945                         if (compiler_generated != null)
1946                                 foreach (CompilerGeneratedClass c in compiler_generated)
1947                                         c.CloseType ();
1948                         
1949                         types = null;
1950                         initialized_fields = null;
1951                         initialized_static_fields = null;
1952                         constants = null;
1953                         ordered_explicit_member_list = null;
1954                         ordered_member_list = null;
1955                         methods = null;
1956                         events = null;
1957                         indexers = null;
1958                         operators = null;
1959                         compiler_generated = null;
1960                         default_constructor = null;
1961                         default_static_constructor = null;
1962                         type_bases = null;
1963                         OptAttributes = null;
1964                 }
1965
1966                 //
1967                 // Performs the validation on a Method's modifiers (properties have
1968                 // the same properties).
1969                 //
1970                 // TODO: Why is it not done at parse stage ?
1971                 //
1972                 public bool MethodModifiersValid (MemberCore mc)
1973                 {
1974                         const Modifiers vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
1975                         const Modifiers nv = (Modifiers.NEW | Modifiers.VIRTUAL);
1976                         bool ok = true;
1977                         var flags = mc.ModFlags;
1978                         
1979                         //
1980                         // At most one of static, virtual or override
1981                         //
1982                         if ((flags & Modifiers.STATIC) != 0){
1983                                 if ((flags & vao) != 0){
1984                                         Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
1985                                                 mc.GetSignatureForError ());
1986                                         ok = false;
1987                                 }
1988                         }
1989
1990                         if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
1991                                 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
1992                                         mc.GetSignatureForError ());
1993                                 ok = false;
1994                         }
1995
1996                         //
1997                         // If the declaration includes the abstract modifier, then the
1998                         // declaration does not include static, virtual or extern
1999                         //
2000                         if ((flags & Modifiers.ABSTRACT) != 0){
2001                                 if ((flags & Modifiers.EXTERN) != 0){
2002                                         Report.Error (
2003                                                 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2004                                         ok = false;
2005                                 }
2006
2007                                 if ((flags & Modifiers.SEALED) != 0) {
2008                                         Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2009                                         ok = false;
2010                                 }
2011
2012                                 if ((flags & Modifiers.VIRTUAL) != 0){
2013                                         Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2014                                         ok = false;
2015                                 }
2016
2017                                 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2018                                         Report.SymbolRelatedToPreviousError (this);
2019                                         Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2020                                                 mc.GetSignatureForError (), GetSignatureForError ());
2021                                         ok = false;
2022                                 }
2023                         }
2024
2025                         if ((flags & Modifiers.PRIVATE) != 0){
2026                                 if ((flags & vao) != 0){
2027                                         Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2028                                         ok = false;
2029                                 }
2030                         }
2031
2032                         if ((flags & Modifiers.SEALED) != 0){
2033                                 if ((flags & Modifiers.OVERRIDE) == 0){
2034                                         Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2035                                         ok = false;
2036                                 }
2037                         }
2038
2039                         return ok;
2040                 }
2041
2042                 public Constructor DefaultStaticConstructor {
2043                         get { return default_static_constructor; }
2044                 }
2045
2046                 protected override bool VerifyClsCompliance ()
2047                 {
2048                         if (!base.VerifyClsCompliance ())
2049                                 return false;
2050
2051                         // Check this name against other containers
2052                         NamespaceEntry.NS.VerifyClsCompliance ();
2053
2054                         // Check all container names for user classes
2055                         if (Kind != MemberKind.Delegate)
2056                                 MemberCache.VerifyClsCompliance (Definition, Report);
2057
2058                         if (BaseType != null && !BaseType.IsCLSCompliant ()) {
2059                                 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant",
2060                                         GetSignatureForError (), BaseType.GetSignatureForError ());
2061                         }
2062                         return true;
2063                 }
2064
2065                 /// <summary>
2066                 ///   Performs checks for an explicit interface implementation.  First it
2067                 ///   checks whether the `interface_type' is a base inteface implementation.
2068                 ///   Then it checks whether `name' exists in the interface type.
2069                 /// </summary>
2070                 public bool VerifyImplements (InterfaceMemberBase mb)
2071                 {
2072                         var ifaces = spec.Interfaces;
2073                         if (ifaces != null) {
2074                                 foreach (TypeSpec t in ifaces){
2075                                         if (t == mb.InterfaceType)
2076                                                 return true;
2077                                 }
2078                         }
2079                         
2080                         Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2081                         Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2082                                 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2083                         return false;
2084                 }
2085
2086                 //
2087                 // Used for visiblity checks to tests whether this definition shares
2088                 // base type baseType, it does member-definition search
2089                 //
2090                 public bool IsBaseTypeDefinition (TypeSpec baseType)
2091                 {
2092                         // RootContext check
2093                         if (TypeBuilder == null)
2094                                 return false;
2095
2096                         var type = spec;
2097                         do {
2098                                 if (type.MemberDefinition == baseType.MemberDefinition)
2099                                         return true;
2100
2101                                 type = type.BaseType;
2102                         } while (type != null);
2103
2104                         return false;
2105                 }
2106
2107                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2108                 {
2109                         return Module.DeclaringAssembly == assembly;
2110                 }
2111
2112                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2113                 {
2114                         throw new NotSupportedException ("Not supported for compiled definition " + GetSignatureForError ());
2115                 }
2116
2117                 //
2118                 // Public function used to locate types.
2119                 //
2120                 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
2121                 //
2122                 // Returns: Type or null if they type can not be found.
2123                 //
2124                 public override FullNamedExpression LookupNamespaceOrType (string name, int arity, Location loc, bool ignore_cs0104)
2125                 {
2126                         FullNamedExpression e;
2127                         if (arity == 0 && Cache.TryGetValue (name, out e))
2128                                 return e;
2129
2130                         e = null;
2131                         int errors = Report.Errors;
2132
2133                         if (arity == 0) {
2134                                 TypeParameter[] tp = CurrentTypeParameters;
2135                                 if (tp != null) {
2136                                         TypeParameter tparam = TypeParameter.FindTypeParameter (tp, name);
2137                                         if (tparam != null)
2138                                                 e = new TypeParameterExpr (tparam, Location.Null);
2139                                 }
2140                         }
2141
2142                         if (e == null) {
2143                                 TypeSpec t = LookupNestedTypeInHierarchy (name, arity);
2144
2145                                 if (t != null)
2146                                         e = new TypeExpression (t, Location.Null);
2147                                 else if (Parent != null) {
2148                                         e = Parent.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2149                                 } else
2150                                         e = NamespaceEntry.LookupNamespaceOrType (name, arity, loc, ignore_cs0104);
2151                         }
2152
2153                         // TODO MemberCache: How to cache arity stuff ?
2154                         if (errors == Report.Errors && arity == 0)
2155                                 Cache[name] = e;
2156
2157                         return e;
2158                 }
2159
2160                 TypeSpec LookupNestedTypeInHierarchy (string name, int arity)
2161                 {
2162                         // TODO: GenericMethod only
2163                         if (PartialContainer == null)
2164                                 return null;
2165
2166                         // Has any nested type
2167                         // Does not work, because base type can have
2168                         //if (PartialContainer.Types == null)
2169                         //      return null;
2170
2171                         var container = PartialContainer.CurrentType;
2172
2173                         // Is not Root container
2174                         if (container == null)
2175                                 return null;
2176
2177                         var t = MemberCache.FindNestedType (container, name, arity);
2178                         if (t == null)
2179                                 return null;
2180
2181                         // FIXME: Breaks error reporting
2182                         if (!t.IsAccessible (CurrentType))
2183                                 return null;
2184
2185                         return t;
2186                 }
2187
2188                 public void Mark_HasEquals ()
2189                 {
2190                         cached_method |= CachedMethods.Equals;
2191                 }
2192
2193                 public void Mark_HasGetHashCode ()
2194                 {
2195                         cached_method |= CachedMethods.GetHashCode;
2196                 }
2197
2198                 /// <summary>
2199                 /// Method container contains Equals method
2200                 /// </summary>
2201                 public bool HasEquals {
2202                         get {
2203                                 return (cached_method & CachedMethods.Equals) != 0;
2204                         }
2205                 }
2206  
2207                 /// <summary>
2208                 /// Method container contains GetHashCode method
2209                 /// </summary>
2210                 public bool HasGetHashCode {
2211                         get {
2212                                 return (cached_method & CachedMethods.GetHashCode) != 0;
2213                         }
2214                 }
2215
2216                 public bool HasStaticFieldInitializer {
2217                         get {
2218                                 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2219                         }
2220                         set {
2221                                 if (value)
2222                                         cached_method |= CachedMethods.HasStaticFieldInitializer;
2223                                 else
2224                                         cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2225                         }
2226                 }
2227
2228                 //
2229                 // Generates xml doc comments (if any), and if required,
2230                 // handle warning report.
2231                 //
2232                 internal override void GenerateDocComment (DeclSpace ds)
2233                 {
2234                         DocUtil.GenerateTypeDocComment (this, ds, Report);
2235                 }
2236
2237                 public override string DocCommentHeader {
2238                         get { return "T:"; }
2239                 }
2240         }
2241
2242         public abstract class ClassOrStruct : TypeContainer
2243         {
2244                 SecurityType declarative_security;
2245
2246                 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2247                                       MemberName name, Attributes attrs, MemberKind kind)
2248                         : base (ns, parent, name, attrs, kind)
2249                 {
2250                 }
2251
2252                 protected override bool AddToContainer (MemberCore symbol, string name)
2253                 {
2254                         if (!(symbol is Constructor) && symbol.MemberName.Name == MemberName.Name) {
2255                                 if (symbol is TypeParameter) {
2256                                         Report.Error (694, symbol.Location,
2257                                                 "Type parameter `{0}' has same name as containing type, or method",
2258                                                 symbol.GetSignatureForError ());
2259                                         return false;
2260                                 }
2261                         
2262                                 InterfaceMemberBase imb = symbol as InterfaceMemberBase;
2263                                 if (imb == null || !imb.IsExplicitImpl) {
2264                                         Report.SymbolRelatedToPreviousError (this);
2265                                         Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2266                                                 symbol.GetSignatureForError ());
2267                                         return false;
2268                                 }
2269                         }
2270
2271                         return base.AddToContainer (symbol, name);
2272                 }
2273
2274                 public override void VerifyMembers ()
2275                 {
2276                         base.VerifyMembers ();
2277
2278                         if ((events != null) && Report.WarningLevel >= 3) {
2279                                 foreach (Event e in events){
2280                                         // Note: The event can be assigned from same class only, so we can report
2281                                         // this warning for all accessibility modes
2282                                         if ((e.caching_flags & Flags.IsUsed) == 0)
2283                                                 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2284                                 }
2285                         }
2286
2287                         if (types != null) {
2288                                 foreach (var t in types)
2289                                         t.VerifyMembers ();
2290                         }
2291                 }
2292
2293                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2294                 {
2295                         if (a.IsValidSecurityAttribute ()) {
2296                                 a.ExtractSecurityPermissionSet (ctor, ref declarative_security);
2297                                 return;
2298                         }
2299
2300                         if (a.Type == pa.StructLayout) {
2301                                 PartialContainer.HasStructLayout = true;
2302                                 if (a.IsExplicitLayoutKind ())
2303                                         PartialContainer.HasExplicitLayout = true;
2304                         }
2305
2306                         if (a.Type == pa.Dynamic) {
2307                                 a.Error_MisusedDynamicAttribute ();
2308                                 return;
2309                         }
2310
2311                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2312                 }
2313
2314                 /// <summary>
2315                 /// Defines the default constructors 
2316                 /// </summary>
2317                 protected void DefineDefaultConstructor (bool is_static)
2318                 {
2319                         // The default instance constructor is public
2320                         // If the class is abstract, the default constructor is protected
2321                         // The default static constructor is private
2322
2323                         Modifiers mods;
2324                         if (is_static) {
2325                                 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2326                         } else {
2327                                 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2328                         }
2329
2330                         Constructor c = new Constructor (this, MemberName.Name, mods,
2331                                 null, ParametersCompiled.EmptyReadOnlyParameters,
2332                                 new GeneratedBaseInitializer (Location),
2333                                 Location);
2334                         
2335                         AddConstructor (c);
2336                         c.Block = new ToplevelBlock (Compiler, ParametersCompiled.EmptyReadOnlyParameters, Location);
2337                 }
2338
2339                 protected override bool DoDefineMembers ()
2340                 {
2341                         CheckProtectedModifier ();
2342
2343                         base.DoDefineMembers ();
2344
2345                         if (default_static_constructor != null)
2346                                 default_static_constructor.Define ();
2347
2348                         return true;
2349                 }
2350
2351                 public override void Emit ()
2352                 {
2353                         if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2354                                 DefineDefaultConstructor (true);
2355                                 default_static_constructor.Define ();
2356                         }
2357
2358                         base.Emit ();
2359
2360                         if (declarative_security != null) {
2361                                 foreach (var de in declarative_security) {
2362 #if STATIC
2363                                         TypeBuilder.__AddDeclarativeSecurity (de);
2364 #else
2365                                         TypeBuilder.AddDeclarativeSecurity (de.Key, de.Value);
2366 #endif
2367                                 }
2368                         }
2369                 }
2370
2371                 public override IList<MethodSpec> LookupExtensionMethod (TypeSpec extensionType, string name, int arity, ref NamespaceEntry scope)
2372                 {
2373                         DeclSpace top_level = Parent;
2374                         if (top_level != null) {
2375                                 while (top_level.Parent != null)
2376                                         top_level = top_level.Parent;
2377
2378                                 var candidates = NamespaceEntry.NS.LookupExtensionMethod (extensionType, this, name, arity);
2379                                 if (candidates != null) {
2380                                         scope = NamespaceEntry;
2381                                         return candidates;
2382                                 }
2383                         }
2384
2385                         return NamespaceEntry.LookupExtensionMethod (extensionType, name, arity, ref scope);
2386                 }
2387
2388                 protected override TypeAttributes TypeAttr {
2389                         get {
2390                                 if (default_static_constructor == null)
2391                                         return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2392
2393                                 return base.TypeAttr;
2394                         }
2395                 }
2396         }
2397
2398
2399         // TODO: should be sealed
2400         public class Class : ClassOrStruct {
2401                 const Modifiers AllowedModifiers =
2402                         Modifiers.NEW |
2403                         Modifiers.PUBLIC |
2404                         Modifiers.PROTECTED |
2405                         Modifiers.INTERNAL |
2406                         Modifiers.PRIVATE |
2407                         Modifiers.ABSTRACT |
2408                         Modifiers.SEALED |
2409                         Modifiers.STATIC |
2410                         Modifiers.UNSAFE;
2411
2412                 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2413
2414                 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2415                               Attributes attrs)
2416                         : base (ns, parent, name, attrs, MemberKind.Class)
2417                 {
2418                         var accmods = (Parent == null || Parent.Parent == null) ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2419                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report);
2420                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2421                 }
2422
2423                 public override void Accept (StructuralVisitor visitor)
2424                 {
2425                         visitor.Visit (this);
2426                 }
2427
2428                 public override void AddBasesForPart (DeclSpace part, List<FullNamedExpression> bases)
2429                 {
2430                         if (part.Name == "System.Object")
2431                                 Report.Error (537, part.Location,
2432                                         "The class System.Object cannot have a base class or implement an interface.");
2433                         base.AddBasesForPart (part, bases);
2434                 }
2435
2436                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2437                 {
2438                         if (a.Type == pa.AttributeUsage) {
2439                                 if (!BaseType.IsAttribute && spec.BuildinType != BuildinTypeSpec.Type.Attribute) {
2440                                         Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2441                                 }
2442                         }
2443
2444                         if (a.Type == pa.Conditional && !BaseType.IsAttribute) {
2445                                 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2446                                 return;
2447                         }
2448
2449                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2450                                 a.Error_MissingGuidAttribute ();
2451                                 return;
2452                         }
2453
2454                         if (a.Type == pa.Extension) {
2455                                 a.Error_MisusedExtensionAttribute ();
2456                                 return;
2457                         }
2458
2459                         if (a.Type.IsConditionallyExcluded (Location))
2460                                 return;
2461
2462                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2463                 }
2464
2465                 public override AttributeTargets AttributeTargets {
2466                         get {
2467                                 return AttributeTargets.Class;
2468                         }
2469                 }
2470
2471                 protected override void DefineContainerMembers (System.Collections.IList list)
2472                 {
2473                         if (list == null)
2474                                 return;
2475
2476                         if (!IsStatic) {
2477                                 base.DefineContainerMembers (list);
2478                                 return;
2479                         }
2480
2481                         foreach (MemberCore m in list) {
2482                                 if (m is Operator) {
2483                                         Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2484                                         continue;
2485                                 }
2486
2487                                 if (m is Destructor) {
2488                                         Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2489                                         continue;
2490                                 }
2491
2492                                 if (m is Indexer) {
2493                                         Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2494                                         continue;
2495                                 }
2496
2497                                 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2498                                         continue;
2499
2500                                 if (m is Constructor) {
2501                                         Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2502                                         continue;
2503                                 }
2504
2505                                 Method method = m as Method;
2506                                 if (method != null && method.ParameterInfo.HasExtensionMethodType) {
2507                                         Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2508                                         continue;
2509                                 }
2510
2511                                 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2512                         }
2513
2514                         base.DefineContainerMembers (list);
2515                 }
2516
2517                 protected override bool DoDefineMembers ()
2518                 {
2519                         if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2520                                 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2521                         }
2522
2523                         if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2524                                 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2525                         }
2526
2527                         if (InstanceConstructors == null && !IsStatic)
2528                                 DefineDefaultConstructor (false);
2529
2530                         return base.DoDefineMembers ();
2531                 }
2532
2533                 public override void Emit ()
2534                 {
2535                         base.Emit ();
2536
2537                         if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2538                                 Module.PredefinedAttributes.Extension.EmitAttribute (TypeBuilder);
2539
2540                         if (base_type != null && base_type.HasDynamicElement) {
2541                                 Module.PredefinedAttributes.Dynamic.EmitAttribute (TypeBuilder, base_type, Location);
2542                         }
2543                 }
2544
2545                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2546                 {
2547                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2548
2549                         if (base_class == null) {
2550                                 if (spec != TypeManager.object_type)
2551                                         base_type = Compiler.BuildinTypes.Object;
2552                         } else {
2553                                 if (base_type.IsGenericParameter){
2554                                         Report.Error (689, base_class.Location, "`{0}': Cannot derive from type parameter `{1}'",
2555                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2556                                 } else if (IsGeneric && base_type.IsAttribute) {
2557                                         Report.Error (698, base_class.Location,
2558                                                 "A generic type cannot derive from `{0}' because it is an attribute class",
2559                                                 base_class.GetSignatureForError ());
2560                                 } else if (base_type.IsStatic) {
2561                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2562                                         Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2563                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2564                                 } else if (base_type.IsSealed) {
2565                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2566                                         Report.Error (509, Location, "`{0}': cannot derive from sealed type `{1}'",
2567                                                 GetSignatureForError (), base_type.GetSignatureForError ());
2568                                 } else if (PartialContainer.IsStatic && base_class.Type.BuildinType != BuildinTypeSpec.Type.Object) {
2569                                         Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2570                                                 GetSignatureForError (), base_class.GetSignatureForError ());
2571                                 }
2572
2573                                 switch (base_type.BuildinType) {
2574                                 case BuildinTypeSpec.Type.Enum:
2575                                 case BuildinTypeSpec.Type.ValueType:
2576                                 case BuildinTypeSpec.Type.MulticastDelegate:
2577                                 case BuildinTypeSpec.Type.Delegate:
2578                                 case BuildinTypeSpec.Type.Array:
2579                                         if (!(spec is BuildinTypeSpec)) {
2580                                                 Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2581                                                         GetSignatureForError (), base_type.GetSignatureForError ());
2582
2583                                                 base_type = Compiler.BuildinTypes.Object;
2584                                         }
2585                                         break;
2586                                 }
2587
2588                                 if (!IsAccessibleAs (base_type)) {
2589                                         Report.SymbolRelatedToPreviousError (base_type);
2590                                         Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'",
2591                                                 base_type.GetSignatureForError (), GetSignatureForError ());
2592                                 }
2593                         }
2594
2595                         if (PartialContainer.IsStatic && ifaces != null) {
2596                                 foreach (TypeExpr t in ifaces)
2597                                         Report.SymbolRelatedToPreviousError (t.Type);
2598                                 Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2599                         }
2600
2601                         return ifaces;
2602                 }
2603
2604                 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2605                 /// Valid only for attribute classes.
2606                 public override string[] ConditionalConditions ()
2607                 {
2608                         if ((caching_flags & (Flags.Excluded_Undetected | Flags.Excluded)) == 0)
2609                                 return null;
2610
2611                         caching_flags &= ~Flags.Excluded_Undetected;
2612
2613                         if (OptAttributes == null)
2614                                 return null;
2615
2616                         Attribute[] attrs = OptAttributes.SearchMulti (Module.PredefinedAttributes.Conditional);
2617                         if (attrs == null)
2618                                 return null;
2619
2620                         string[] conditions = new string[attrs.Length];
2621                         for (int i = 0; i < conditions.Length; ++i)
2622                                 conditions[i] = attrs[i].GetConditionalAttributeValue ();
2623
2624                         caching_flags |= Flags.Excluded;
2625                         return conditions;
2626                 }
2627
2628                 //
2629                 // FIXME: How do we deal with the user specifying a different
2630                 // layout?
2631                 //
2632                 protected override TypeAttributes TypeAttr {
2633                         get {
2634                                 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2635                                 if (IsStatic)
2636                                         ta |= StaticClassAttribute;
2637                                 return ta;
2638                         }
2639                 }
2640         }
2641
2642         public sealed class Struct : ClassOrStruct {
2643
2644                 bool is_unmanaged, has_unmanaged_check_done;
2645                 bool InTransit;
2646
2647                 // <summary>
2648                 //   Modifiers allowed in a struct declaration
2649                 // </summary>
2650                 const Modifiers AllowedModifiers =
2651                         Modifiers.NEW       |
2652                         Modifiers.PUBLIC    |
2653                         Modifiers.PROTECTED |
2654                         Modifiers.INTERNAL  |
2655                         Modifiers.UNSAFE    |
2656                         Modifiers.PRIVATE;
2657
2658                 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2659                                Modifiers mod, Attributes attrs)
2660                         : base (ns, parent, name, attrs, MemberKind.Struct)
2661                 {
2662                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;                   
2663                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, Location, Report) | Modifiers.SEALED ;
2664                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2665                 }
2666
2667                 public override AttributeTargets AttributeTargets {
2668                         get {
2669                                 return AttributeTargets.Struct;
2670                         }
2671                 }
2672
2673                 public override void Accept (StructuralVisitor visitor)
2674                 {
2675                         visitor.Visit (this);
2676                 }
2677
2678                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2679                 {
2680                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2681
2682                         //
2683                         // When struct constains fixed fixed and struct layout has explicitly
2684                         // set CharSet, its value has to be propagated to compiler generated
2685                         // fixed types
2686                         //
2687                         if (a.Type == pa.StructLayout && Fields != null) {
2688                                 var value = a.GetNamedValue ("CharSet");
2689                                 if (value == null)
2690                                         return;
2691
2692                                 for (int i = 0; i < Fields.Count; ++i) {
2693                                         FixedField ff = Fields [i] as FixedField;
2694                                         if (ff == null)
2695                                                 continue;
2696
2697                                         ff.CharSet = (CharSet) System.Enum.Parse (typeof (CharSet), value.GetValue ().ToString ());
2698                                 }
2699                         }
2700                 }
2701
2702                 bool CheckStructCycles (Struct s)
2703                 {
2704                         if (s.Fields == null)
2705                                 return true;
2706
2707                         if (s.InTransit)
2708                                 return false;
2709
2710                         s.InTransit = true;
2711                         foreach (FieldBase field in s.Fields) {
2712                                 TypeSpec ftype = field.Spec.MemberType;
2713                                 if (!ftype.IsStruct)
2714                                         continue;
2715
2716                                 if (ftype is BuildinTypeSpec)
2717                                         continue;
2718
2719                                 foreach (var targ in ftype.TypeArguments) {
2720                                         if (!CheckFieldTypeCycle (targ)) {
2721                                                 Report.Error (523, field.Location,
2722                                                         "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2723                                                         field.GetSignatureForError (), ftype.GetSignatureForError ());
2724                                                 break;
2725                                         }
2726                                 }
2727
2728                                 if ((field.IsStatic && (!ftype.IsGeneric || ftype == CurrentType)))
2729                                         continue;
2730
2731                                 if (!CheckFieldTypeCycle (ftype)) {
2732                                         Report.Error (523, field.Location,
2733                                                 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
2734                                                 field.GetSignatureForError (), ftype.GetSignatureForError ());
2735                                         break;
2736                                 }
2737                         }
2738
2739                         s.InTransit = false;
2740                         return true;
2741                 }
2742
2743                 bool CheckFieldTypeCycle (TypeSpec ts)
2744                 {
2745                         var fts = ts.MemberDefinition as Struct;
2746                         if (fts == null)
2747                                 return true;
2748
2749                         return CheckStructCycles (fts);
2750                 }
2751
2752                 public override void Emit ()
2753                 {
2754                         CheckStructCycles (this);
2755
2756                         base.Emit ();
2757                 }
2758
2759                 public override bool IsUnmanagedType ()
2760                 {
2761                         if (fields == null)
2762                                 return true;
2763
2764                         if (has_unmanaged_check_done)
2765                                 return is_unmanaged;
2766
2767                         if (requires_delayed_unmanagedtype_check)
2768                                 return true;
2769
2770                         requires_delayed_unmanagedtype_check = true;
2771
2772                         foreach (FieldBase f in fields) {
2773                                 if (f.IsStatic)
2774                                         continue;
2775
2776                                 // It can happen when recursive unmanaged types are defined
2777                                 // struct S { S* s; }
2778                                 TypeSpec mt = f.MemberType;
2779                                 if (mt == null) {
2780                                         return true;
2781                                 }
2782
2783                                 while (mt.IsPointer)
2784                                         mt = TypeManager.GetElementType (mt);
2785
2786                                 if (mt.IsGenericOrParentIsGeneric || mt.IsGenericParameter) {
2787                                         has_unmanaged_check_done = true;
2788                                         return false;
2789                                 }
2790
2791                                 if (TypeManager.IsUnmanagedType (mt))
2792                                         continue;
2793
2794                                 has_unmanaged_check_done = true;
2795                                 return false;
2796                         }
2797
2798                         has_unmanaged_check_done = true;
2799                         is_unmanaged = true;
2800                         return true;
2801                 }
2802
2803                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2804                 {
2805                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2806                         base_type = Compiler.BuildinTypes.ValueType;
2807                         return ifaces;
2808                 }
2809
2810                 protected override TypeAttributes TypeAttr {
2811                         get {
2812                                 const TypeAttributes DefaultTypeAttributes =
2813                                         TypeAttributes.SequentialLayout |
2814                                         TypeAttributes.Sealed;
2815
2816                                 return base.TypeAttr | DefaultTypeAttributes;
2817                         }
2818                 }
2819
2820                 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
2821                 {
2822                         if ((field.ModFlags & Modifiers.STATIC) == 0) {
2823                                 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
2824                                         field.GetSignatureForError ());
2825                                 return;
2826                         }
2827                         base.RegisterFieldForInitialization (field, expression);
2828                 }
2829
2830         }
2831
2832         /// <summary>
2833         ///   Interfaces
2834         /// </summary>
2835         public sealed class Interface : TypeContainer {
2836
2837                 /// <summary>
2838                 ///   Modifiers allowed in a class declaration
2839                 /// </summary>
2840                 public const Modifiers AllowedModifiers =
2841                         Modifiers.NEW       |
2842                         Modifiers.PUBLIC    |
2843                         Modifiers.PROTECTED |
2844                         Modifiers.INTERNAL  |
2845                         Modifiers.UNSAFE    |
2846                         Modifiers.PRIVATE;
2847
2848                 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, Modifiers mod,
2849                                   Attributes attrs)
2850                         : base (ns, parent, name, attrs, MemberKind.Interface)
2851                 {
2852                         var accmods = parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2853
2854                         this.ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod, accmods, name.Location, Report);
2855                         spec = new TypeSpec (Kind, null, this, null, ModFlags);
2856                 }
2857
2858                 #region Properties
2859
2860                 public override AttributeTargets AttributeTargets {
2861                         get {
2862                                 return AttributeTargets.Interface;
2863                         }
2864                 }
2865
2866                 protected override TypeAttributes TypeAttr {
2867                         get {
2868                                 const TypeAttributes DefaultTypeAttributes =
2869                                         TypeAttributes.AutoLayout |
2870                                         TypeAttributes.Abstract |
2871                                         TypeAttributes.Interface;
2872
2873                                 return base.TypeAttr | DefaultTypeAttributes;
2874                         }
2875                 }
2876
2877                 #endregion
2878
2879                 public override void Accept (StructuralVisitor visitor)
2880                 {
2881                         visitor.Visit (this);
2882                 }
2883
2884                 public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
2885                 {
2886                         if (a.Type == pa.ComImport && !attributes.Contains (pa.Guid)) {
2887                                 a.Error_MissingGuidAttribute ();
2888                                 return;
2889                         }
2890
2891                         base.ApplyAttributeBuilder (a, ctor, cdata, pa);
2892                 }
2893
2894                 protected override bool VerifyClsCompliance ()
2895                 {
2896                         if (!base.VerifyClsCompliance ())
2897                                 return false;
2898
2899                         if (iface_exprs != null) {
2900                                 foreach (var iface in iface_exprs) {
2901                                         if (iface.Type.IsCLSCompliant ())
2902                                                 continue;
2903
2904                                         Report.SymbolRelatedToPreviousError (iface.Type);
2905                                         Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
2906                                                 GetSignatureForError (), TypeManager.CSharpName (iface.Type));
2907                                 }
2908                         }
2909
2910                         return true;
2911                 }
2912         }
2913
2914         public abstract class InterfaceMemberBase : MemberBase
2915         {
2916                 //
2917                 // Common modifiers allowed in a class declaration
2918                 //
2919                 protected const Modifiers AllowedModifiersClass =
2920                         Modifiers.NEW |
2921                         Modifiers.PUBLIC |
2922                         Modifiers.PROTECTED |
2923                         Modifiers.INTERNAL |
2924                         Modifiers.PRIVATE |
2925                         Modifiers.STATIC |
2926                         Modifiers.VIRTUAL |
2927                         Modifiers.SEALED |
2928                         Modifiers.OVERRIDE |
2929                         Modifiers.ABSTRACT |
2930                         Modifiers.UNSAFE |
2931                         Modifiers.EXTERN;
2932
2933                 //
2934                 // Common modifiers allowed in a struct declaration
2935                 //
2936                 protected const Modifiers AllowedModifiersStruct =
2937                         Modifiers.NEW |
2938                         Modifiers.PUBLIC |
2939                         Modifiers.PROTECTED |
2940                         Modifiers.INTERNAL |
2941                         Modifiers.PRIVATE |
2942                         Modifiers.STATIC |
2943                         Modifiers.OVERRIDE |
2944                         Modifiers.UNSAFE |
2945                         Modifiers.EXTERN;
2946
2947                 //
2948                 // Common modifiers allowed in a interface declaration
2949                 //
2950                 protected const Modifiers AllowedModifiersInterface =
2951                         Modifiers.NEW |
2952                         Modifiers.UNSAFE;
2953
2954                 //
2955                 // Whether this is an interface member.
2956                 //
2957                 public bool IsInterface;
2958
2959                 //
2960                 // If true, this is an explicit interface implementation
2961                 //
2962                 public bool IsExplicitImpl;
2963
2964                 protected bool is_external_implementation;
2965
2966                 //
2967                 // The interface type we are explicitly implementing
2968                 //
2969                 public TypeSpec InterfaceType;
2970
2971                 //
2972                 // The method we're overriding if this is an override method.
2973                 //
2974                 protected MethodSpec base_method;
2975
2976                 readonly Modifiers explicit_mod_flags;
2977                 public MethodAttributes flags;
2978
2979                 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
2980                                    FullNamedExpression type, Modifiers mod, Modifiers allowed_mod,
2981                                    MemberName name, Attributes attrs)
2982                         : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
2983                                 name, attrs)
2984                 {
2985                         IsInterface = parent.PartialContainer.Kind == MemberKind.Interface;
2986                         IsExplicitImpl = (MemberName.Left != null);
2987                         explicit_mod_flags = mod;
2988                 }
2989                 
2990                 protected override bool CheckBase ()
2991                 {
2992                         if (!base.CheckBase ())
2993                                 return false;
2994
2995                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
2996                                 CheckForDuplications ();
2997                         
2998                         if (IsExplicitImpl)
2999                                 return true;
3000
3001                         // For System.Object only
3002                         if (Parent.BaseType == null)
3003                                 return true;
3004
3005                         MemberSpec candidate;
3006                         var base_member = FindBaseMember (out candidate);
3007
3008                         if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3009                                 if (base_member == null) {
3010                                         if (candidate == null) {
3011                                                 if (this is Method && ((Method)this).ParameterInfo.IsEmpty && MemberName.Name == Destructor.MetadataName && MemberName.Arity == 0) {
3012                                                         Report.Error (249, Location, "Do not override `{0}'. Use destructor syntax instead",
3013                                                                 "object.Finalize()");
3014                                                 } else {
3015                                                         Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3016                                                                 GetSignatureForError (), SimpleName.GetMemberType (this));
3017                                                 }
3018                                         } else {
3019                                                 Report.SymbolRelatedToPreviousError (candidate);
3020                                                 if (this is Event)
3021                                                         Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event",
3022                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3023                                                 else if (this is PropertyBase)
3024                                                         Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property",
3025                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3026                                                 else
3027                                                         Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method",
3028                                                                 GetSignatureForError (), TypeManager.GetFullNameSignature (candidate));
3029                                         }
3030
3031                                         return false;
3032                                 }
3033
3034                                 if (!CheckOverrideAgainstBase (base_member))
3035                                         return false;
3036
3037                                 ObsoleteAttribute oa = base_member.GetAttributeObsolete ();
3038                                 if (oa != null) {
3039                                         if (OptAttributes == null || !OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3040                                                 Report.SymbolRelatedToPreviousError (base_member);
3041                                                 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3042                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3043                                         }
3044                                 } else {
3045                                         if (OptAttributes != null && OptAttributes.Contains (Module.PredefinedAttributes.Obsolete)) {
3046                                                 Report.SymbolRelatedToPreviousError (base_member);
3047                                                 Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3048                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_member));
3049                                         }
3050                                 }
3051
3052                                 base_method = base_member as MethodSpec;
3053                                 return true;
3054                         }
3055
3056                         if (base_member == null && candidate != null && (!(candidate is IParametersMember) || !(this is IParametersMember)))
3057                                 base_member = candidate;
3058
3059                         if (base_member == null) {
3060                                 if ((ModFlags & Modifiers.NEW) != 0) {
3061                                         if (base_member == null) {
3062                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
3063                                                         GetSignatureForError ());
3064                                         }
3065                                 }
3066                         } else {
3067                                 if ((ModFlags & Modifiers.NEW) == 0) {
3068                                         ModFlags |= Modifiers.NEW;
3069                                         if (!IsCompilerGenerated) {
3070                                                 Report.SymbolRelatedToPreviousError (base_member);
3071                                                 if (!IsInterface && (base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
3072                                                         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",
3073                                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3074                                                 } else {
3075                                                         Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3076                                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3077                                                 }
3078                                         }
3079                                 }
3080
3081                                 if (!IsInterface && base_member.IsAbstract && candidate == null) {
3082                                         Report.SymbolRelatedToPreviousError (base_member);
3083                                         Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3084                                                 GetSignatureForError (), base_member.GetSignatureForError ());
3085                                 }
3086                         }
3087
3088                         return true;
3089                 }
3090
3091                 protected virtual bool CheckForDuplications ()
3092                 {
3093                         return Parent.MemberCache.CheckExistingMembersOverloads (this, ParametersCompiled.EmptyReadOnlyParameters);
3094                 }
3095
3096                 //
3097                 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3098                 // that have been defined.
3099                 //
3100                 protected virtual bool CheckOverrideAgainstBase (MemberSpec base_member)
3101                 {
3102                         bool ok = true;
3103
3104                         if ((base_member.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) == 0) {
3105                                 Report.SymbolRelatedToPreviousError (base_member);
3106                                 Report.Error (506, Location,
3107                                         "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3108                                          GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3109                                 ok = false;
3110                         }
3111
3112                         // Now we check that the overriden method is not final  
3113                         if ((base_member.Modifiers & Modifiers.SEALED) != 0) {
3114                                 Report.SymbolRelatedToPreviousError (base_member);
3115                                 Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3116                                                           GetSignatureForError (), TypeManager.CSharpSignature (base_member));
3117                                 ok = false;
3118                         }
3119
3120                         var base_member_type = ((IInterfaceMemberSpec) base_member).MemberType;
3121                         if (!TypeSpecComparer.Override.IsEqual (MemberType, base_member_type)) {
3122                                 Report.SymbolRelatedToPreviousError (base_member);
3123                                 if (this is PropertyBasedMember) {
3124                                         Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'",
3125                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3126                                 } else {
3127                                         Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3128                                                 GetSignatureForError (), TypeManager.CSharpName (base_member_type), TypeManager.CSharpSignature (base_member));
3129                                 }
3130                                 ok = false;
3131                         }
3132
3133                         return ok;
3134                 }
3135
3136                 protected static bool CheckAccessModifiers (MemberCore this_member, MemberSpec base_member)
3137                 {
3138                         var thisp = this_member.ModFlags & Modifiers.AccessibilityMask;
3139                         var base_classp = base_member.Modifiers & Modifiers.AccessibilityMask;
3140
3141                         if ((base_classp & (Modifiers.PROTECTED | Modifiers.INTERNAL)) == (Modifiers.PROTECTED | Modifiers.INTERNAL)) {
3142                                 //
3143                                 // It must be at least "protected"
3144                                 //
3145                                 if ((thisp & Modifiers.PROTECTED) == 0) {
3146                                         return false;
3147                                 }
3148
3149                                 //
3150                                 // when overriding protected internal, the method can be declared
3151                                 // protected internal only within the same assembly or assembly
3152                                 // which has InternalsVisibleTo
3153                                 //
3154                                 if ((thisp & Modifiers.INTERNAL) != 0) {
3155                                         return base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly);
3156                                 }
3157
3158                                 //
3159                                 // protected overriding protected internal inside same assembly
3160                                 // requires internal modifier as well
3161                                 //
3162                                 if (base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (this_member.Module.DeclaringAssembly)) {
3163                                         return false;
3164                                 }
3165
3166                                 return true;
3167                         }
3168
3169                         return thisp == base_classp;
3170                 }
3171
3172                 public override bool Define ()
3173                 {
3174                         if (IsInterface) {
3175                                 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3176                                         Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3177
3178                                 flags = MethodAttributes.Public |
3179                                         MethodAttributes.Abstract |
3180                                         MethodAttributes.HideBySig |
3181                                         MethodAttributes.NewSlot |
3182                                         MethodAttributes.Virtual;
3183                         } else {
3184                                 Parent.PartialContainer.MethodModifiersValid (this);
3185
3186                                 flags = ModifiersExtensions.MethodAttr (ModFlags);
3187                         }
3188
3189                         if (IsExplicitImpl) {
3190                                 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (Parent, false);
3191                                 if (iface_texpr == null)
3192                                         return false;
3193
3194                                 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3195                                         Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3196                                                 GetSignatureForError ());
3197                                 }
3198
3199                                 InterfaceType = iface_texpr.Type;
3200
3201                                 if (!InterfaceType.IsInterface) {
3202                                         Report.SymbolRelatedToPreviousError (InterfaceType);
3203                                         Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3204                                                 TypeManager.CSharpName (InterfaceType));
3205                                 } else {
3206                                         Parent.PartialContainer.VerifyImplements (this);
3207                                 }
3208
3209                                 ModifiersExtensions.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location, Report);
3210                         }
3211
3212                         return base.Define ();
3213                 }
3214
3215                 protected bool DefineParameters (ParametersCompiled parameters)
3216                 {
3217                         if (!parameters.Resolve (this))
3218                                 return false;
3219
3220                         bool error = false;
3221                         for (int i = 0; i < parameters.Count; ++i) {
3222                                 Parameter p = parameters [i];
3223
3224                                 if (p.HasDefaultValue && (IsExplicitImpl || this is Operator || (this is Indexer && parameters.Count == 1)))
3225                                         p.Warning_UselessOptionalParameter (Report);
3226
3227                                 if (p.CheckAccessibility (this))
3228                                         continue;
3229
3230                                 TypeSpec t = parameters.Types [i];
3231                                 Report.SymbolRelatedToPreviousError (t);
3232                                 if (this is Indexer)
3233                                         Report.Error (55, Location,
3234                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3235                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3236                                 else if (this is Operator)
3237                                         Report.Error (57, Location,
3238                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3239                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3240                                 else
3241                                         Report.Error (51, Location,
3242                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3243                                                 TypeManager.CSharpName (t), GetSignatureForError ());
3244                                 error = true;
3245                         }
3246                         return !error;
3247                 }
3248
3249                 public override void Emit()
3250                 {
3251                         // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3252                         // We are more strict than csc and report this as an error because SRE does not allow emit that
3253                         if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3254                                 if (this is Constructor) {
3255                                         Report.Warning (824, 1, Location,
3256                                                 "Constructor `{0}' is marked `external' but has no external implementation specified", GetSignatureForError ());
3257                                 } else {
3258                                         Report.Warning (626, 1, Location,
3259                                                 "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3260                                                 GetSignatureForError ());
3261                                 }
3262                         }
3263
3264                         base.Emit ();
3265                 }
3266
3267                 public override bool EnableOverloadChecks (MemberCore overload)
3268                 {
3269                         //
3270                         // Two members can differ in their explicit interface
3271                         // type parameter only
3272                         //
3273                         InterfaceMemberBase imb = overload as InterfaceMemberBase;
3274                         if (imb != null && imb.IsExplicitImpl) {
3275                                 if (IsExplicitImpl) {
3276                                         caching_flags |= Flags.MethodOverloadsExist;
3277                                 }
3278                                 return true;
3279                         }
3280
3281                         return IsExplicitImpl;
3282                 }
3283
3284                 protected void Error_CannotChangeAccessModifiers (MemberCore member, MemberSpec base_member)
3285                 {
3286                         var base_modifiers = base_member.Modifiers;
3287
3288                         // Remove internal modifier from types which are not internally accessible
3289                         if ((base_modifiers & Modifiers.AccessibilityMask) == (Modifiers.PROTECTED | Modifiers.INTERNAL) &&
3290                                 !base_member.DeclaringType.MemberDefinition.IsInternalAsPublic (member.Module.DeclaringAssembly))
3291                                 base_modifiers = Modifiers.PROTECTED;
3292
3293                         Report.SymbolRelatedToPreviousError (base_member);
3294                         Report.Error (507, member.Location,
3295                                 "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3296                                 member.GetSignatureForError (),
3297                                 ModifiersExtensions.AccessibilityName (base_modifiers),
3298                                 base_member.GetSignatureForError ());
3299                 }
3300
3301                 protected void Error_StaticReturnType ()
3302                 {
3303                         Report.Error (722, Location,
3304                                 "`{0}': static types cannot be used as return types",
3305                                 MemberType.GetSignatureForError ());
3306                 }
3307
3308                 /// <summary>
3309                 /// Gets base method and its return type
3310                 /// </summary>
3311                 protected virtual MemberSpec FindBaseMember (out MemberSpec bestCandidate)
3312                 {
3313                         return MemberCache.FindBaseMember (this, out bestCandidate);
3314                 }
3315
3316                 //
3317                 // The "short" name of this property / indexer / event.  This is the
3318                 // name without the explicit interface.
3319                 //
3320                 public string ShortName {
3321                         get { return MemberName.Name; }
3322                         set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3323                 }
3324                 
3325                 //
3326                 // Returns full metadata method name
3327                 //
3328                 public string GetFullName (MemberName name)
3329                 {
3330                         return GetFullName (name.Name);
3331                 }
3332
3333                 public string GetFullName (string name)
3334                 {
3335                         if (!IsExplicitImpl)
3336                                 return name;
3337
3338                         //
3339                         // When dealing with explicit members a full interface type
3340                         // name is added to member name to avoid possible name conflicts
3341                         //
3342                         // We use CSharpName which gets us full name with benefit of
3343                         // replacing predefined names which saves some space and name
3344                         // is still unique
3345                         //
3346                         return TypeManager.CSharpName (InterfaceType) + "." + name;
3347                 }
3348
3349                 protected override bool VerifyClsCompliance ()
3350                 {
3351                         if (!base.VerifyClsCompliance ()) {
3352                                 return false;
3353                         }
3354
3355                         if (GenericMethod != null)
3356                                 GenericMethod.VerifyClsCompliance ();
3357
3358                         return true;
3359                 }
3360
3361                 public override bool IsUsed 
3362                 {
3363                         get { return IsExplicitImpl || base.IsUsed; }
3364                 }
3365
3366         }
3367
3368         public abstract class MemberBase : MemberCore
3369         {
3370                 protected FullNamedExpression type_expr;
3371                 protected TypeSpec member_type;
3372
3373                 public readonly DeclSpace ds;
3374                 public readonly GenericMethod GenericMethod;
3375
3376                 protected MemberBase (DeclSpace parent, GenericMethod generic,
3377                                       FullNamedExpression type, Modifiers mod, Modifiers allowed_mod, Modifiers def_mod,
3378                                       MemberName name, Attributes attrs)
3379                         : base (parent, name, attrs)
3380                 {
3381                         this.ds = generic != null ? generic : (DeclSpace) parent;
3382                         this.type_expr = type;
3383                         ModFlags = ModifiersExtensions.Check (allowed_mod, mod, def_mod, Location, Report);
3384                         GenericMethod = generic;
3385                         if (GenericMethod != null)
3386                                 GenericMethod.ModFlags = ModFlags;
3387                 }
3388
3389                 #region Properties
3390
3391                 public TypeSpec MemberType {
3392                         get {
3393                                 return member_type;
3394                         }
3395                 }
3396
3397                 public FullNamedExpression TypeExpression {
3398                         get {
3399                                 return type_expr;
3400                         }
3401                 }
3402
3403                 #endregion
3404
3405                 //
3406                 // Main member define entry
3407                 //
3408                 public override bool Define ()
3409                 {
3410                         DoMemberTypeIndependentChecks ();
3411
3412                         //
3413                         // Returns false only when type resolution failed
3414                         //
3415                         if (!ResolveMemberType ())
3416                                 return false;
3417
3418                         DoMemberTypeDependentChecks ();
3419                         return true;
3420                 }
3421
3422                 //
3423                 // Any type_name independent checks
3424                 //
3425                 protected virtual void DoMemberTypeIndependentChecks ()
3426                 {
3427                         if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
3428                                 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
3429                                 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
3430                                         GetSignatureForError (), Parent.GetSignatureForError ());
3431                         }
3432                 }
3433
3434                 //
3435                 // Any type_name dependent checks
3436                 //
3437                 protected virtual void DoMemberTypeDependentChecks ()
3438                 {
3439                         // verify accessibility
3440                         if (!IsAccessibleAs (MemberType)) {
3441                                 Report.SymbolRelatedToPreviousError (MemberType);
3442                                 if (this is Property)
3443                                         Report.Error (53, Location,
3444                                                       "Inconsistent accessibility: property type `" +
3445                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3446                                                       "accessible than property `" + GetSignatureForError () + "'");
3447                                 else if (this is Indexer)
3448                                         Report.Error (54, Location,
3449                                                       "Inconsistent accessibility: indexer return type `" +
3450                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3451                                                       "accessible than indexer `" + GetSignatureForError () + "'");
3452                                 else if (this is MethodCore) {
3453                                         if (this is Operator)
3454                                                 Report.Error (56, Location,
3455                                                               "Inconsistent accessibility: return type `" +
3456                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3457                                                               "accessible than operator `" + GetSignatureForError () + "'");
3458                                         else
3459                                                 Report.Error (50, Location,
3460                                                               "Inconsistent accessibility: return type `" +
3461                                                               TypeManager.CSharpName (MemberType) + "' is less " +
3462                                                               "accessible than method `" + GetSignatureForError () + "'");
3463                                 } else {
3464                                         Report.Error (52, Location,
3465                                                       "Inconsistent accessibility: field type `" +
3466                                                       TypeManager.CSharpName (MemberType) + "' is less " +
3467                                                       "accessible than field `" + GetSignatureForError () + "'");
3468                                 }
3469                         }
3470
3471                         Variance variance = this is Event ? Variance.Contravariant : Variance.Covariant;
3472                         TypeManager.CheckTypeVariance (MemberType, variance, this);
3473                 }
3474
3475                 protected bool IsTypePermitted ()
3476                 {
3477                         if (MemberType.IsSpecialRuntimeType) {
3478                                 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
3479                                 return false;
3480                         }
3481                         return true;
3482                 }
3483
3484                 protected virtual bool CheckBase ()
3485                 {
3486                         CheckProtectedModifier ();
3487
3488                         return true;
3489                 }
3490
3491                 protected virtual bool ResolveMemberType ()
3492                 {
3493                         if (member_type != null)
3494                                 throw new InternalErrorException ("Multi-resolve");
3495
3496                         TypeExpr te = type_expr.ResolveAsTypeTerminal (this, false);
3497                         if (te == null)
3498                                 return false;
3499                         
3500                         //
3501                         // Replace original type name, error reporting can use fully resolved name
3502                         //
3503                         type_expr = te;
3504
3505                         member_type = te.Type;
3506                         return true;
3507                 }
3508         }
3509 }
3510