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