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