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