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