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