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