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