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