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