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