670f956068e099c1f96fbc789966009c15fbc02e
[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;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.CompilerServices;
20 using System.Runtime.InteropServices;
21 using System.Security;
22 using System.Security.Permissions;
23 using System.Text;
24
25 #if BOOTSTRAP_WITH_OLDLIB || NET_2_1
26 using XmlElement = System.Object;
27 #else
28 using System.Xml;
29 #endif
30
31 using Mono.CompilerServices.SymbolWriter;
32
33 namespace Mono.CSharp {
34
35         public enum Kind {
36                 Root,
37                 Struct,
38                 Class,
39                 Interface,
40                 Enum,
41                 Delegate
42         }
43
44         /// <summary>
45         ///   This is the base class for structs and classes.  
46         /// </summary>
47         public abstract class TypeContainer : DeclSpace, IMemberContainer {
48
49                 public class MemberCoreArrayList: ArrayList
50                 {
51                         /// <summary>
52                         ///   Defines the MemberCore objects that are in this array
53                         /// </summary>
54                         public virtual void DefineContainerMembers ()
55                         {
56                                 foreach (MemberCore mc in this) {
57                                         try {
58                                                 mc.Define ();
59                                         } catch (Exception e) {
60                                                 throw new InternalErrorException (mc, e);
61                                         }
62                                 }
63                         }
64
65                         public virtual void Emit ()
66                         {
67                                 foreach (MemberCore mc in this)
68                                         mc.Emit ();
69                         }
70                 }
71
72                 public class OperatorArrayList: MemberCoreArrayList
73                 {
74                         TypeContainer container;
75
76                         public OperatorArrayList (TypeContainer container)
77                         {
78                                 this.container = container;
79                         }
80
81                         //
82                         // Checks that some operators come in pairs:
83                         //  == and !=
84                         // > and <
85                         // >= and <=
86                         // true and false
87                         //
88                         // They are matched based on the return type and the argument types
89                         //
90                         void CheckPairedOperators ()
91                         {
92                                 bool has_equality_or_inequality = false;
93                                 Operator[] operators = (Operator[]) ToArray (typeof (Operator));
94                                 bool [] has_pair = new bool [operators.Length];
95
96                                 for (int i = 0; i < Count; ++i) {
97                                         if (operators [i] == null)
98                                                 continue;
99
100                                         Operator o_a = operators [i];
101                                         Operator.OpType o_type = o_a.OperatorType;
102                                         if (o_type == Operator.OpType.Equality || o_type == Operator.OpType.Inequality)
103                                                 has_equality_or_inequality = true;
104
105                                         Operator.OpType matching_type = o_a.GetMatchingOperator ();
106                                         if (matching_type == Operator.OpType.TOP) {
107                                                 operators [i] = null;
108                                                 continue;
109                                         }
110         
111                                         for (int ii = 0; ii < Count; ++ii) {
112                                                 Operator o_b = operators [ii];
113                                                 if (o_b == null || o_b.OperatorType != matching_type)
114                                                         continue;
115
116                                                 if (!TypeManager.IsEqual (o_a.ReturnType, o_b.ReturnType))
117                                                         continue;
118
119                                                 if (!TypeManager.IsEqual (o_a.ParameterTypes, o_b.ParameterTypes))
120                                                         continue;
121
122                                                 operators [i] = null;
123
124                                                 //
125                                                 // Used to ignore duplicate user conversions
126                                                 //
127                                                 has_pair [ii] = true;
128                                         }
129                                 }
130
131                                 for (int i = 0; i < Count; ++i) {
132                                         if (operators [i] == null || has_pair [i])
133                                                 continue;
134
135                                         Operator o = operators [i];
136                                         Report.Error (216, o.Location,
137                                                 "The operator `{0}' requires a matching operator `{1}' to also be defined",
138                                                 o.GetSignatureForError (), Operator.GetName (o.GetMatchingOperator ()));
139                                 }
140
141                                 if (has_equality_or_inequality && Report.WarningLevel > 2) {
142                                         if (container.Methods == null || !container.HasEquals)
143                                                 Report.Warning (660, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.Equals(object o)", container.GetSignatureForError ());
144  
145                                         if (container.Methods == null || !container.HasGetHashCode)
146                                                 Report.Warning (661, 2, container.Location, "`{0}' defines operator == or operator != but does not override Object.GetHashCode()", container.GetSignatureForError ());
147                                 }
148                         }
149
150                         public override void DefineContainerMembers ()
151                         {
152                                 base.DefineContainerMembers ();
153                                 CheckPairedOperators ();
154                         }
155                 }
156
157                 [Flags]
158                 enum CachedMethods
159                 {
160                         Equals                          = 1,
161                         GetHashCode                     = 1 << 1,
162                         HasStaticFieldInitializer       = 1 << 2
163                 }
164
165
166                 // Whether this is a struct, class or interface
167                 public readonly Kind Kind;
168
169                 // Holds a list of classes and structures
170                 protected ArrayList types;
171
172                 MemberCoreArrayList ordered_explicit_member_list;
173                 MemberCoreArrayList ordered_member_list;
174
175                 // Holds the list of properties
176                 MemberCoreArrayList properties;
177
178                 // Holds the list of delegates
179                 MemberCoreArrayList delegates;
180                 
181                 // Holds the list of constructors
182                 protected MemberCoreArrayList instance_constructors;
183
184                 // Holds the list of fields
185                 protected MemberCoreArrayList fields;
186
187                 // Holds a list of fields that have initializers
188                 protected ArrayList initialized_fields;
189
190                 // Holds a list of static fields that have initializers
191                 protected ArrayList initialized_static_fields;
192
193                 // Holds the list of constants
194                 protected MemberCoreArrayList constants;
195
196                 // Holds the methods.
197                 MemberCoreArrayList methods;
198
199                 // Holds the events
200                 protected MemberCoreArrayList events;
201
202                 // Holds the indexers
203                 ArrayList indexers;
204
205                 // Holds the operators
206                 MemberCoreArrayList operators;
207
208                 // Holds the compiler generated classes
209                 ArrayList compiler_generated;
210
211                 //
212                 // Pointers to the default constructor and the default static constructor
213                 //
214                 protected Constructor default_constructor;
215                 protected Constructor default_static_constructor;
216
217                 //
218                 // Points to the first non-static field added to the container.
219                 //
220                 // This is an arbitrary choice.  We are interested in looking at _some_ non-static field,
221                 // and the first one's as good as any.
222                 //
223                 FieldBase first_nonstatic_field = null;
224
225                 //
226                 // This one is computed after we can distinguish interfaces
227                 // from classes from the arraylist `type_bases' 
228                 //
229                 TypeExpr base_type;
230                 TypeExpr[] iface_exprs;
231                 Type GenericType;
232
233                 protected ArrayList type_bases;
234
235                 protected bool members_defined;
236                 bool members_defined_ok;
237
238                 // The interfaces we implement.
239                 protected Type[] ifaces;
240
241                 // The base member cache and our member cache
242                 MemberCache base_cache;
243                 protected MemberCache member_cache;
244
245                 public const string DefaultIndexerName = "Item";
246
247                 private bool seen_normal_indexers = false;
248                 private string indexer_name = DefaultIndexerName;
249                 protected bool requires_delayed_unmanagedtype_check;
250
251                 private CachedMethods cached_method;
252
253                 ArrayList partial_parts;
254
255                 /// <remarks>
256                 ///  The pending methods that need to be implemented
257                 //   (interfaces or abstract methods)
258                 /// </remarks>
259                 PendingImplementation pending;
260
261                 public TypeContainer (NamespaceEntry ns, DeclSpace parent, MemberName name,
262                                       Attributes attrs, Kind kind)
263                         : base (ns, parent, name, attrs)
264                 {
265                         if (parent != null && parent.NamespaceEntry != ns)
266                                 throw new InternalErrorException ("A nested type should be in the same NamespaceEntry as its enclosing class");
267
268                         this.Kind = kind;
269                         this.PartialContainer = this;
270                 }
271
272                 public bool AddMember (MemberCore symbol)
273                 {
274                         return AddToContainer (symbol, symbol.MemberName.Basename);
275                 }
276
277                 protected virtual bool AddMemberType (DeclSpace ds)
278                 {
279                         return AddToContainer (ds, ds.Basename);
280                 }
281
282                 protected virtual void RemoveMemberType (DeclSpace ds)
283                 {
284                         RemoveFromContainer (ds.Basename);
285                 }
286
287                 public void AddConstant (Const constant)
288                 {
289                         if (!AddMember (constant))
290                                 return;
291
292                         if (constants == null)
293                                 constants = new MemberCoreArrayList ();
294                         
295                         constants.Add (constant);
296                 }
297
298                 public TypeContainer AddTypeContainer (TypeContainer tc)
299                 {
300                         if (!AddMemberType (tc))
301                                 return tc;
302
303                         if (types == null)
304                                 types = new MemberCoreArrayList ();
305                         types.Add (tc);
306
307                         return tc;
308                 }
309
310                 public virtual TypeContainer AddPartial (TypeContainer next_part)
311                 {
312                         return AddPartial (next_part, next_part.Basename);
313                 }
314
315                 protected TypeContainer AddPartial (TypeContainer next_part, string name)
316                 {
317                         next_part.ModFlags |= Modifiers.PARTIAL;
318                         TypeContainer tc = defined_names [name] as TypeContainer;
319
320                         if (tc == null)
321                                 return AddTypeContainer (next_part);
322
323                         if ((tc.ModFlags & Modifiers.PARTIAL) == 0) {
324                                 Report.SymbolRelatedToPreviousError (next_part);
325                                 Error_MissingPartialModifier (tc);
326                         }
327
328                         if (tc.Kind != next_part.Kind) {
329                                 Report.SymbolRelatedToPreviousError (tc);
330                                 Report.Error (261, next_part.Location,
331                                         "Partial declarations of `{0}' must be all classes, all structs or all interfaces",
332                                         next_part.GetSignatureForError ());
333                         }
334
335                         if ((tc.ModFlags & Modifiers.Accessibility) != (next_part.ModFlags & Modifiers.Accessibility) &&
336                                 ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0 &&
337                                  (next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) == 0)) {
338                                 Report.SymbolRelatedToPreviousError (tc);
339                                 Report.Error (262, next_part.Location,
340                                         "Partial declarations of `{0}' have conflicting accessibility modifiers",
341                                         next_part.GetSignatureForError ());
342                         }
343
344                         if (tc.partial_parts == null)
345                                 tc.partial_parts = new ArrayList (1);
346
347                         if ((next_part.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
348                                 tc.ModFlags |= next_part.ModFlags & ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
349                         } else if ((tc.ModFlags & Modifiers.DEFAULT_ACCESS_MODIFER) != 0) {
350                                 tc.ModFlags &= ~(Modifiers.DEFAULT_ACCESS_MODIFER | Modifiers.Accessibility);
351                                 tc.ModFlags |= next_part.ModFlags;
352                         } else {
353                                 tc.ModFlags |= next_part.ModFlags;
354                         }
355
356                         if (next_part.attributes != null) {
357                                 if (tc.attributes == null)
358                                         tc.attributes = next_part.attributes;
359                                 else
360                                         tc.attributes.AddAttributes (next_part.attributes.Attrs);
361                         }
362
363                         next_part.PartialContainer = tc;
364                         tc.partial_parts.Add (next_part);
365                         return tc;
366                 }
367
368                 public virtual void RemoveTypeContainer (TypeContainer next_part)
369                 {
370                         if (types != null)
371                                 types.Remove (next_part);
372                         RemoveMemberType (next_part);
373                 }
374                 
375                 public void AddDelegate (Delegate d)
376                 {
377                         if (!AddMemberType (d))
378                                 return;
379
380                         if (delegates == null)
381                                 delegates = new MemberCoreArrayList ();
382
383                         delegates.Add (d);
384                 }
385
386                 private void AddMemberToList (MemberCore mc, ArrayList alist, bool isexplicit)
387                 {
388                         if (ordered_explicit_member_list == null)  {
389                                 ordered_explicit_member_list = new MemberCoreArrayList ();
390                                 ordered_member_list = new MemberCoreArrayList ();
391                         }
392
393                         if (isexplicit) {
394                                 if (Kind == Kind.Interface) {
395                                         Report.Error (541, mc.Location,
396                                                 "`{0}': explicit interface declaration can only be declared in a class or struct",
397                                                 mc.GetSignatureForError ());
398                                 }
399
400                                 ordered_explicit_member_list.Add (mc);
401                                 alist.Insert (0, mc);
402                         } else {
403                                 ordered_member_list.Add (mc);
404                                 alist.Add (mc);
405                         }
406
407                 }
408                 
409                 public void AddMethod (Method method)
410                 {
411                         if (!AddToContainer (method, method.MemberName.Basename))
412                                 return;
413                         
414                         if (methods == null)
415                                 methods = new MemberCoreArrayList ();
416
417                         if (method.MemberName.Left != null) 
418                                 AddMemberToList (method, methods, true);
419                         else 
420                                 AddMemberToList (method, methods, false);
421                 }
422
423                 public void AddConstructor (Constructor c)
424                 {
425                         bool is_static = (c.ModFlags & Modifiers.STATIC) != 0;
426                         if (!AddToContainer (c, is_static ?
427                                 ConstructorBuilder.ConstructorName : ConstructorBuilder.TypeConstructorName))
428                                 return;
429                         
430                         if (is_static && c.Parameters.IsEmpty){
431                                 if (default_static_constructor != null) {
432                                     Report.SymbolRelatedToPreviousError (default_static_constructor);
433                                         Report.Error (111, c.Location,
434                                                 "A member `{0}' is already defined. Rename this member or use different parameter types",
435                                                 c.GetSignatureForError ());
436                                     return;
437                                 }
438
439                                 default_static_constructor = c;
440                         } else {
441                                 if (c.Parameters.IsEmpty)
442                                         default_constructor = c;
443                                 
444                                 if (instance_constructors == null)
445                                         instance_constructors = new MemberCoreArrayList ();
446                                 
447                                 instance_constructors.Add (c);
448                         }
449                 }
450
451                 public bool AddField (FieldBase field)
452                 {
453                         if (!AddMember (field))
454                                 return false;
455
456                         if (fields == null)
457                                 fields = new MemberCoreArrayList ();
458
459                         fields.Add (field);
460
461                         if ((field.ModFlags & Modifiers.STATIC) != 0)
462                                 return true;
463
464                         if (first_nonstatic_field == null) {
465                                 first_nonstatic_field = field;
466                                 return true;
467                         }
468
469                         if (Kind == Kind.Struct && first_nonstatic_field.Parent != field.Parent) {
470                                 Report.SymbolRelatedToPreviousError (first_nonstatic_field.Parent);
471                                 Report.Warning (282, 3, field.Location,
472                                         "struct instance field `{0}' found in different declaration from instance field `{1}'",
473                                         field.GetSignatureForError (), first_nonstatic_field.GetSignatureForError ());
474                         }
475                         return true;
476                 }
477
478                 public void AddProperty (Property prop)
479                 {
480                         if (!AddMember (prop) || 
481                                 !AddMember (prop.Get) || !AddMember (prop.Set))
482                                 return;
483
484                         if (properties == null)
485                                 properties = new MemberCoreArrayList ();
486
487                         if (prop.MemberName.Left != null)
488                                 AddMemberToList (prop, properties, true);
489                         else 
490                                 AddMemberToList (prop, properties, false);
491                 }
492
493                 public void AddEvent (Event e)
494                 {
495                         if (!AddMember (e))
496                                 return;
497
498                         if (e is EventProperty) {
499                                 if (!AddMember (e.Add))
500                                         return;
501
502                                 if (!AddMember (e.Remove))
503                                         return;
504                         }
505
506                         if (events == null)
507                                 events = new MemberCoreArrayList ();
508
509                         events.Add (e);
510                 }
511
512                 /// <summary>
513                 /// Indexer has special handling in constrast to other AddXXX because the name can be driven by IndexerNameAttribute
514                 /// </summary>
515                 public void AddIndexer (Indexer i)
516                 {
517                         if (indexers == null)
518                                 indexers = new ArrayList ();
519
520                         if (i.IsExplicitImpl)
521                                 AddMemberToList (i, indexers, true);
522                         else 
523                                 AddMemberToList (i, indexers, false);
524                 }
525
526                 public void AddOperator (Operator op)
527                 {
528                         if (!AddMember (op))
529                                 return;
530
531                         if (operators == null)
532                                 operators = new OperatorArrayList (this);
533
534                         operators.Add (op);
535                 }
536
537                 public void AddCompilerGeneratedClass (CompilerGeneratedClass c)
538                 {
539                         Report.Debug (64, "ADD COMPILER GENERATED CLASS", this, c);
540
541                         if (compiler_generated == null)
542                                 compiler_generated = new ArrayList ();
543
544                         compiler_generated.Add (c);
545                 }
546
547                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
548                 {
549                         if (a.Type == TypeManager.default_member_type) {
550                                 if (Indexers != null) {
551                                         Report.Error (646, a.Location, "Cannot specify the `DefaultMember' attribute on type containing an indexer");
552                                         return;
553                                 }
554                         }
555                         
556                         base.ApplyAttributeBuilder (a, cb);
557                 } 
558
559                 public override AttributeTargets AttributeTargets {
560                         get {
561                                 throw new NotSupportedException ();
562                         }
563                 }
564
565                 public ArrayList Types {
566                         get {
567                                 return types;
568                         }
569                 }
570
571                 public MemberCoreArrayList Methods {
572                         get {
573                                 return methods;
574                         }
575                 }
576
577                 public ArrayList Constants {
578                         get {
579                                 return constants;
580                         }
581                 }
582
583                 protected Type BaseType {
584                         get {
585                                 return TypeBuilder.BaseType;
586                         }
587                 }
588
589                 public ArrayList Fields {
590                         get {
591                                 return fields;
592                         }
593                 }
594
595                 public ArrayList InstanceConstructors {
596                         get {
597                                 return instance_constructors;
598                         }
599                 }
600
601                 public ArrayList Properties {
602                         get {
603                                 return properties;
604                         }
605                 }
606
607                 public ArrayList Events {
608                         get {
609                                 return events;
610                         }
611                 }
612                 
613                 public ArrayList Indexers {
614                         get {
615                                 return indexers;
616                         }
617                 }
618
619                 public ArrayList Operators {
620                         get {
621                                 return operators;
622                         }
623                 }
624
625                 public ArrayList Delegates {
626                         get {
627                                 return delegates;
628                         }
629                 }
630                 
631                 protected override TypeAttributes TypeAttr {
632                         get {
633                                 return Modifiers.TypeAttr (ModFlags, IsTopLevel) | base.TypeAttr;
634                         }
635                 }
636
637                 public string IndexerName {
638                         get {
639                                 return indexers == null ? DefaultIndexerName : indexer_name;
640                         }
641                 }
642
643                 public bool IsComImport {
644                         get {
645                                 if (OptAttributes == null || TypeManager.comimport_attr_type == null)
646                                         return false;
647
648                                 return OptAttributes.Contains (TypeManager.comimport_attr_type);
649                         }
650                 }
651
652                 public virtual void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
653                 {
654                         if ((field.ModFlags & Modifiers.STATIC) != 0){
655                                 if (initialized_static_fields == null) {
656                                         PartialContainer.HasStaticFieldInitializer = true;
657                                         initialized_static_fields = new ArrayList (4);
658                                 }
659
660                                 initialized_static_fields.Add (expression);
661                         } else {
662                                 if (initialized_fields == null)
663                                         initialized_fields = new ArrayList (4);
664
665                                 initialized_fields.Add (expression);
666                         }
667                 }
668
669                 public void ResolveFieldInitializers (EmitContext ec)
670                 {
671                         if (partial_parts != null) {
672                                 foreach (TypeContainer part in partial_parts) {
673                                         part.DoResolveFieldInitializers (ec);
674                                 }
675                         }
676                         DoResolveFieldInitializers (ec);
677                 }
678
679                 void DoResolveFieldInitializers (EmitContext ec)
680                 {
681                         if (ec.IsStatic) {
682                                 if (initialized_static_fields == null)
683                                         return;
684
685                                 bool has_complex_initializer = !RootContext.Optimize;
686                                 int i;
687                                 ExpressionStatement [] init = new ExpressionStatement [initialized_static_fields.Count];
688                                 for (i = 0; i < initialized_static_fields.Count; ++i) {
689                                         FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
690                                         ExpressionStatement s = fi.ResolveStatement (ec);
691                                         if (s == null) {
692                                                 s = EmptyExpressionStatement.Instance;
693                                         } else if (fi.IsComplexInitializer) {
694                                                 has_complex_initializer |= true;
695                                         }
696
697                                         init [i] = s;
698                                 }
699
700                                 for (i = 0; i < initialized_static_fields.Count; ++i) {
701                                         FieldInitializer fi = (FieldInitializer) initialized_static_fields [i];
702                                         //
703                                         // Need special check to not optimize code like this
704                                         // static int a = b = 5;
705                                         // static int b = 0;
706                                         //
707                                         if (!has_complex_initializer && fi.IsDefaultInitializer)
708                                                 continue;
709
710                                         ec.CurrentBlock.AddScopeStatement (new StatementExpression (init [i]));
711                                 }
712
713                                 return;
714                         }
715
716                         if (initialized_fields == null)
717                                 return;
718
719                         for (int i = 0; i < initialized_fields.Count; ++i) {
720                                 FieldInitializer fi = (FieldInitializer) initialized_fields [i];
721                                 ExpressionStatement s = fi.ResolveStatement (ec);
722                                 if (s == null)
723                                         continue;
724
725                                 //
726                                 // Field is re-initialized to its default value => removed
727                                 //
728                                 if (fi.IsDefaultInitializer && RootContext.Optimize)
729                                         continue;
730
731                                 ec.CurrentBlock.AddScopeStatement (new StatementExpression (s));
732                         }
733                 }
734
735                 //
736                 // Emits the instance field initializers
737                 //
738                 public bool EmitFieldInitializers (EmitContext ec)
739                 {
740                         if (partial_parts != null) {
741                                 foreach (TypeContainer part in partial_parts)
742                                         part.EmitFieldInitializers (ec);
743                         }
744
745                         ArrayList fields;
746                         
747                         if (ec.IsStatic){
748                                 fields = initialized_static_fields;
749                         } else {
750                                 fields = initialized_fields;
751                         }
752
753                         if (fields == null)
754                                 return true;
755
756                         foreach (FieldInitializer f in fields) {
757                                 f.EmitStatement (ec);
758                         }
759                         return true;
760                 }
761                 
762                 public override string DocComment {
763                         get {
764                                 return comment;
765                         }
766                         set {
767                                 if (value == null)
768                                         return;
769
770                                 comment += value;
771                         }
772                 }
773
774                 public PendingImplementation PendingImplementations {
775                         get { return pending; }
776                 }
777
778                 public override bool GetClsCompliantAttributeValue ()
779                 {
780                         if (PartialContainer != this)
781                                 return PartialContainer.GetClsCompliantAttributeValue ();
782
783                         return base.GetClsCompliantAttributeValue ();
784                 }
785
786                 public virtual void AddBasesForPart (DeclSpace part, ArrayList bases)
787                 {
788                         // FIXME: get rid of partial_parts and store lists of bases of each part here
789                         // assumed, not verified: 'part' is in 'partial_parts' 
790                         ((TypeContainer) part).type_bases = bases;
791                 }
792
793                 /// <summary>
794                 ///   This function computes the Base class and also the
795                 ///   list of interfaces that the class or struct @c implements.
796                 ///   
797                 ///   The return value is an array (might be null) of
798                 ///   interfaces implemented (as Types).
799                 ///   
800                 ///   The @base_class argument is set to the base object or null
801                 ///   if this is `System.Object'. 
802                 /// </summary>
803                 protected virtual TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
804                 {
805                         base_class = null;
806                         if (type_bases == null)
807                                 return null;
808
809                         int count = type_bases.Count;
810                         TypeExpr [] ifaces = null;
811                         for (int i = 0, j = 0; i < count; i++){
812                                 FullNamedExpression fne = (FullNamedExpression) type_bases [i];
813
814                                 //
815                                 // Standard ResolveAsTypeTerminal cannot be used in this case because
816                                 // it does ObsoleteAttribute and constraint checks which require
817                                 // base type to be set
818                                 //
819                                 TypeExpr fne_resolved = fne.ResolveAsBaseTerminal (this, false);
820                                 if (fne_resolved == null)
821                                         continue;
822
823                                 if (i == 0 && Kind == Kind.Class && !fne_resolved.Type.IsInterface) {
824                                         base_class = fne_resolved;
825                                         continue;
826                                 }
827
828                                 if (ifaces == null)
829                                         ifaces = new TypeExpr [count - i];
830
831                                 if (fne_resolved.Type.IsInterface) {
832                                         for (int ii = 0; ii < j; ++ii) {
833                                                 if (TypeManager.IsEqual (fne_resolved.Type, ifaces [ii].Type)) {
834                                                         Report.Error (528, Location, "`{0}' is already listed in interface list",
835                                                                 fne_resolved.GetSignatureForError ());
836                                                         break;
837                                                 }
838                                         }
839
840                                         if (Kind == Kind.Interface && !fne_resolved.AsAccessible (this)) {
841                                                 Report.Error (61, fne.Location,
842                                                         "Inconsistent accessibility: base interface `{0}' is less accessible than interface `{1}'",
843                                                         fne_resolved.GetSignatureForError (), GetSignatureForError ());
844                                         }
845                                 } else {
846                                         Report.SymbolRelatedToPreviousError (fne_resolved.Type);
847                                         if (Kind != Kind.Class) {
848                                                 Report.Error (527, fne.Location, "Type `{0}' in interface list is not an interface", fne_resolved.GetSignatureForError ());
849                                         } else if (base_class != null)
850                                                 Report.Error (1721, fne.Location, "`{0}': Classes cannot have multiple base classes (`{1}' and `{2}')",
851                                                         GetSignatureForError (), base_class.GetSignatureForError (), fne_resolved.GetSignatureForError ());
852                                         else {
853                                                 Report.Error (1722, fne.Location, "`{0}': Base class `{1}' must be specified as first",
854                                                         GetSignatureForError (), fne_resolved.GetSignatureForError ());
855                                         }
856                                 }
857
858                                 ifaces [j++] = fne_resolved;
859                         }
860
861                         return ifaces;
862                 }
863
864                 TypeExpr[] GetNormalPartialBases (ref TypeExpr base_class)
865                 {
866                         ArrayList ifaces = new ArrayList (0);
867                         if (iface_exprs != null)
868                                 ifaces.AddRange (iface_exprs);
869
870                         foreach (TypeContainer part in partial_parts) {
871                                 TypeExpr new_base_class;
872                                 TypeExpr[] new_ifaces = part.ResolveBaseTypes (out new_base_class);
873                                 if (new_base_class != TypeManager.system_object_expr) {
874                                         if (base_class == TypeManager.system_object_expr)
875                                                 base_class = new_base_class;
876                                         else {
877                                                 if (new_base_class != null && !new_base_class.Equals (base_class)) {
878                                                         Report.SymbolRelatedToPreviousError (base_class.Location, "");
879                                                         Report.Error (263, part.Location,
880                                                                 "Partial declarations of `{0}' must not specify different base classes",
881                                                                 part.GetSignatureForError ());
882
883                                                         return null;
884                                                 }
885                                         }
886                                 }
887
888                                 if (new_ifaces == null)
889                                         continue;
890
891                                 foreach (TypeExpr iface in new_ifaces) {
892                                         if (ifaces.Contains (iface))
893                                                 continue;
894
895                                         ifaces.Add (iface);
896                                 }
897                         }
898
899                         if (ifaces.Count == 0)
900                                 return null;
901
902                         return (TypeExpr[])ifaces.ToArray (typeof (TypeExpr));
903                 }
904
905                 bool CheckGenericInterfaces (Type[] ifaces)
906                 {
907 #if GMCS_SOURCE
908                         ArrayList already_checked = new ArrayList ();
909
910                         for (int i = 0; i < ifaces.Length; i++) {
911                                 Type iface = ifaces [i];
912                                 foreach (Type t in already_checked) {
913                                         if (iface == t)
914                                                 continue;
915
916                                         Type[] inferred = new Type [CountTypeParameters];
917                                         if (!TypeManager.MayBecomeEqualGenericInstances (iface, t, inferred, null))
918                                                 continue;
919
920                                         Report.Error (695, Location,
921                                                 "`{0}' cannot implement both `{1}' and `{2}' " +
922                                                 "because they may unify for some type parameter substitutions",
923                                                 TypeManager.CSharpName (TypeBuilder), TypeManager.CSharpName (iface),
924                                                 TypeManager.CSharpName (t));
925                                         return false;
926                                 }
927
928                                 already_checked.Add (iface);
929                         }
930 #endif
931
932                         return true;
933                 }
934
935                 bool error = false;
936                 
937                 bool CreateTypeBuilder ()
938                 {
939                         try {
940                                 Type default_parent = null;
941                                 if (Kind == Kind.Struct)
942                                         default_parent = TypeManager.value_type;
943                                 else if (Kind == Kind.Enum)
944                                         default_parent = TypeManager.enum_type;
945
946                                 //
947                                 // Sets .size to 1 for structs with no instance fields
948                                 //
949                                 int type_size = Kind == Kind.Struct && first_nonstatic_field == null ? 1 : 0;
950
951                                 if (IsTopLevel){
952                                         if (TypeManager.NamespaceClash (Name, Location)) {
953                                                 return false;
954                                         }
955
956                                         ModuleBuilder builder = CodeGen.Module.Builder;
957                                         TypeBuilder = builder.DefineType (
958                                                 Name, TypeAttr, default_parent, type_size);
959                                 } else {
960                                         TypeBuilder builder = Parent.TypeBuilder;
961
962                                         TypeBuilder = builder.DefineNestedType (
963                                                 Basename, TypeAttr, default_parent, type_size);
964                                 }
965                         } catch (ArgumentException) {
966                                 Report.RuntimeMissingSupport (Location, "static classes");
967                                 return false;
968                         }
969
970                         TypeManager.AddUserType (this);
971
972 #if GMCS_SOURCE
973                         if (IsGeneric) {
974                                 string[] param_names = new string [TypeParameters.Length];
975                                 for (int i = 0; i < TypeParameters.Length; i++)
976                                         param_names [i] = TypeParameters [i].Name;
977
978                                 GenericTypeParameterBuilder[] gen_params = TypeBuilder.DefineGenericParameters (param_names);
979
980                                 int offset = CountTypeParameters - CurrentTypeParameters.Length;
981                                 for (int i = offset; i < gen_params.Length; i++)
982                                         CurrentTypeParameters [i - offset].Define (gen_params [i]);
983                         }
984 #endif
985
986                         return true;
987                 }
988
989                 bool DefineBaseTypes ()
990                 {
991                         iface_exprs = ResolveBaseTypes (out base_type);
992                         if (partial_parts != null) {
993                                 iface_exprs = GetNormalPartialBases (ref base_type);
994                         }
995
996                         //
997                         // GetClassBases calls ResolveBaseTypeExpr() on the various type expressions involved,
998                         // which in turn should have called DefineType()s on base types if necessary.
999                         //
1000                         // None of the code below should trigger DefineType()s on classes that we depend on.
1001                         // Thus, we are eligible to be on the topological sort `type_container_resolve_order'.
1002                         //
1003                         // Let's do it as soon as possible, since code below can call DefineType() on classes
1004                         // that depend on us to be populated before they are.
1005                         //
1006                         if (!(this is CompilerGeneratedClass))
1007                                 RootContext.RegisterOrder (this); 
1008
1009                         if (!CheckRecursiveDefinition (this))
1010                                 return false;
1011
1012                         if (base_type != null && base_type.Type != null) {
1013                                 TypeBuilder.SetParent (base_type.Type);
1014                         }
1015
1016                         // add interfaces that were not added at type creation
1017                         if (iface_exprs != null) {
1018                                 ifaces = TypeManager.ExpandInterfaces (iface_exprs);
1019                                 if (ifaces == null)
1020                                         return false;
1021
1022                                 foreach (Type itype in ifaces)
1023                                         TypeBuilder.AddInterfaceImplementation (itype);
1024
1025                                 if (!CheckGenericInterfaces (ifaces))
1026                                         return false;
1027
1028                                 TypeManager.RegisterBuilder (TypeBuilder, ifaces);
1029                         }
1030
1031                         return true;
1032                 }
1033
1034                 //
1035                 // Defines the type in the appropriate ModuleBuilder or TypeBuilder.
1036                 //
1037                 public TypeBuilder CreateType ()
1038                 {
1039                         if (TypeBuilder != null)
1040                                 return TypeBuilder;
1041
1042                         if (error)
1043                                 return null;
1044
1045                         if (!CreateTypeBuilder ()) {
1046                                 error = true;
1047                                 return null;
1048                         }
1049
1050                         if (partial_parts != null) {
1051                                 foreach (TypeContainer part in partial_parts)
1052                                         part.TypeBuilder = TypeBuilder;
1053                         }
1054
1055                         if (Types != null) {
1056                                 foreach (TypeContainer tc in Types) {
1057                                         if (tc.CreateType () == null) {
1058                                                 error = true;
1059                                                 return null;
1060                                         }
1061                                 }
1062                         }
1063
1064                         return TypeBuilder;
1065                 }
1066
1067                 bool type_defined;
1068
1069                 public override TypeBuilder DefineType ()
1070                 {
1071                         if (error)
1072                                 return null;
1073                         if (type_defined)
1074                                 return TypeBuilder;
1075
1076                         type_defined = true;
1077
1078                         if (CreateType () == null) {
1079                                 error = true;
1080                                 return null;
1081                         }
1082
1083                         if (!DefineBaseTypes ()) {
1084                                 error = true;
1085                                 return null;
1086                         }
1087
1088                         if (!DefineNestedTypes ()) {
1089                                 error = true;
1090                                 return null;
1091                         }
1092
1093                         return TypeBuilder;
1094                 }
1095
1096                 public override void SetParameterInfo (ArrayList constraints_list)
1097                 {
1098                         base.SetParameterInfo (constraints_list);
1099
1100                         if (!is_generic || PartialContainer == this)
1101                                 return;
1102
1103                         TypeParameter[] tc_names = PartialContainer.TypeParameters;
1104                         for (int i = 0; i < tc_names.Length; ++i) {
1105                                 if (tc_names [i].Name != type_params [i].Name) {
1106                                         Report.SymbolRelatedToPreviousError (PartialContainer.Location, "");
1107                                         Report.Error (264, Location, "Partial declarations of `{0}' must have the same type parameter names in the same order",
1108                                                 GetSignatureForError ());
1109                                         break;
1110                                 }
1111                         }
1112                 }
1113
1114                 void UpdateTypeParameterConstraints (TypeContainer part)
1115                 {
1116                         TypeParameter[] current_params = CurrentTypeParameters;
1117                         for (int i = 0; i < current_params.Length; i++) {
1118                                 Constraints c = part.CurrentTypeParameters [i].Constraints;
1119                                 if (c == null)
1120                                         continue;
1121
1122                                 if (current_params [i].UpdateConstraints (part, c))
1123                                         continue;
1124
1125                                 Report.SymbolRelatedToPreviousError (Location, "");
1126                                 Report.Error (265, part.Location,
1127                                         "Partial declarations of `{0}' have inconsistent constraints for type parameter `{1}'",
1128                                         GetSignatureForError (), current_params [i].GetSignatureForError ());
1129                         }
1130                 }
1131
1132                 public bool ResolveType ()
1133                 {
1134                         if (!DoResolveType ())
1135                                 return false;
1136
1137                         if (compiler_generated != null) {
1138                                 foreach (CompilerGeneratedClass c in compiler_generated)
1139                                         if (!c.ResolveType ())
1140                                                 return false;
1141                         }
1142
1143                         return true;
1144                 }
1145
1146                 protected virtual bool DoResolveType ()
1147                 {
1148                         if ((base_type != null) &&
1149                             (base_type.ResolveAsTypeTerminal (this, false) == null)) {
1150                                 error = true;
1151                                 return false;
1152                         }
1153
1154                         if (!IsGeneric)
1155                                 return true;
1156
1157                         if (PartialContainer != this)
1158                                 throw new InternalErrorException ();
1159
1160                         TypeExpr current_type = null;
1161
1162                         foreach (TypeParameter type_param in CurrentTypeParameters) {
1163                                 if (!type_param.Resolve (this)) {
1164                                         error = true;
1165                                         return false;
1166                                 }
1167                         }
1168
1169                         if (partial_parts != null && is_generic) {
1170                                 foreach (TypeContainer part in partial_parts)
1171                                         UpdateTypeParameterConstraints (part);
1172                         }
1173
1174                         foreach (TypeParameter type_param in TypeParameters) {
1175                                 if (!type_param.DefineType (this)) {
1176                                         error = true;
1177                                         return false;
1178                                 }
1179                         }
1180
1181                         // TODO: Very strange, why not simple make generic type from
1182                         // current type parameters
1183                         current_type = new GenericTypeExpr (this, Location);
1184                         current_type = current_type.ResolveAsTypeTerminal (this, false);
1185                         if (current_type == null) {
1186                                 error = true;
1187                                 return false;
1188                         }
1189
1190                         CurrentType = current_type.Type;
1191                         return true;
1192                 }
1193
1194                 protected virtual bool DefineNestedTypes ()
1195                 {
1196                         if (Types != null) {
1197                                 foreach (TypeContainer tc in Types)
1198                                         if (tc.DefineType () == null)
1199                                                 return false;
1200                         }
1201
1202                         if (Delegates != null) {
1203                                 foreach (Delegate d in Delegates)
1204                                         if (d.DefineType () == null)
1205                                                 return false;
1206                         }
1207
1208                         return true;
1209                 }
1210
1211                 TypeContainer InTransit;
1212
1213                 protected bool CheckRecursiveDefinition (TypeContainer tc)
1214                 {
1215                         if (InTransit != null) {
1216                                 Report.SymbolRelatedToPreviousError (this);
1217                                 if (this is Interface)
1218                                         Report.Error (
1219                                                 529, tc.Location, "Inherited interface `{0}' causes a " +
1220                                                 "cycle in the interface hierarchy of `{1}'",
1221                                                 GetSignatureForError (), tc.GetSignatureForError ());
1222                                 else
1223                                         Report.Error (
1224                                                 146, tc.Location, "Circular base class dependency " +
1225                                                 "involving `{0}' and `{1}'",
1226                                                 tc.GetSignatureForError (), GetSignatureForError ());
1227                                 return false;
1228                         }
1229
1230                         InTransit = tc;
1231
1232                         if (base_type != null && base_type.Type != null) {
1233                                 Type t = TypeManager.DropGenericTypeArguments (base_type.Type);
1234                                 TypeContainer ptc = TypeManager.LookupTypeContainer (t);
1235                                 if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1236                                         return false;
1237                         }
1238
1239                         if (iface_exprs != null) {
1240                                 foreach (TypeExpr iface in iface_exprs) {
1241                                         Type itype = TypeManager.DropGenericTypeArguments (iface.Type);
1242                                         TypeContainer ptc = TypeManager.LookupTypeContainer (itype);
1243                                         if ((ptc != null) && !ptc.CheckRecursiveDefinition (this))
1244                                                 return false;
1245                                 }
1246                         }
1247
1248                         if (!IsTopLevel && !Parent.PartialContainer.CheckRecursiveDefinition (this))
1249                                 return false;
1250
1251                         InTransit = null;
1252                         return true;
1253                 }
1254
1255                 /// <summary>
1256                 ///   Populates our TypeBuilder with fields and methods
1257                 /// </summary>
1258                 public override bool Define ()
1259                 {
1260                         if (members_defined)
1261                                 return members_defined_ok;
1262
1263                         members_defined_ok = DoDefineMembers ();
1264                         members_defined = true;
1265
1266                         return members_defined_ok;
1267                 }
1268
1269                 protected virtual bool DoDefineMembers ()
1270                 {
1271                         if (iface_exprs != null) {
1272                                 foreach (TypeExpr iface in iface_exprs) {
1273                                         ObsoleteAttribute oa = AttributeTester.GetObsoleteAttribute (iface.Type);
1274                                         if ((oa != null) && !IsInObsoleteScope)
1275                                                 AttributeTester.Report_ObsoleteMessage (
1276                                                         oa, iface.GetSignatureForError (), Location);
1277
1278                                         GenericTypeExpr ct = iface as GenericTypeExpr;
1279                                         if ((ct != null) && !ct.CheckConstraints (this))
1280                                                 return false;
1281                                 }
1282                         }
1283
1284                         if (base_type != null) {
1285                                 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (base_type.Type);
1286                                 if (obsolete_attr != null && !IsInObsoleteScope)
1287                                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, base_type.GetSignatureForError (), Location);
1288
1289                                 GenericTypeExpr ct = base_type as GenericTypeExpr;
1290                                 if ((ct != null) && !ct.CheckConstraints (this))
1291                                         return false;
1292                                 
1293                                 member_cache = new MemberCache (base_type.Type, this);
1294                         } else if (Kind == Kind.Interface) {
1295                                 member_cache = new MemberCache (null, this);
1296                                 Type [] ifaces = TypeManager.GetInterfaces (TypeBuilder);
1297                                 for (int i = 0; i < ifaces.Length; ++i)
1298                                         member_cache.AddInterface (TypeManager.LookupMemberCache (ifaces [i]));
1299                         } else {
1300                                 member_cache = new MemberCache (null, this);
1301                         }
1302
1303                         if (types != null)
1304                                 foreach (TypeContainer tc in types)
1305                                         member_cache.AddNestedType (tc);
1306
1307                         if (delegates != null)
1308                                 foreach (Delegate d in delegates)
1309                                         member_cache.AddNestedType (d);
1310
1311                         if (partial_parts != null) {
1312                                 foreach (TypeContainer part in partial_parts)
1313                                         part.member_cache = member_cache;
1314                         }
1315
1316                         if (!IsTopLevel) {
1317                                 MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Basename, false);
1318                                 if (conflict_symbol == null) {
1319                                         if ((ModFlags & Modifiers.NEW) != 0)
1320                                                 Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
1321                                 } else {
1322                                         if ((ModFlags & Modifiers.NEW) == 0) {
1323                                                 Report.SymbolRelatedToPreviousError (conflict_symbol);
1324                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
1325                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
1326                                         }
1327                                 }
1328                         }
1329
1330                         DefineContainerMembers (constants);
1331                         DefineContainerMembers (fields);
1332
1333                         if (Kind == Kind.Struct || Kind == Kind.Class) {
1334                                 pending = PendingImplementation.GetPendingImplementations (this);
1335
1336                                 if (requires_delayed_unmanagedtype_check) {
1337                                         requires_delayed_unmanagedtype_check = false;
1338                                         foreach (Field f in fields) {
1339                                                 if (f.MemberType != null && f.MemberType.IsPointer)
1340                                                         TypeManager.VerifyUnManaged (f.MemberType, f.Location);
1341                                         }
1342                                 }
1343                         }
1344                 
1345                         //
1346                         // Constructors are not in the defined_names array
1347                         //
1348                         DefineContainerMembers (instance_constructors);
1349                 
1350                         DefineContainerMembers (events);
1351                         DefineContainerMembers (ordered_explicit_member_list);
1352                         DefineContainerMembers (ordered_member_list);
1353
1354                         DefineContainerMembers (operators);
1355                         DefineContainerMembers (delegates);
1356
1357                         ComputeIndexerName();
1358                         CheckEqualsAndGetHashCode();
1359
1360                         if (CurrentType != null) {
1361                                 GenericType = CurrentType;
1362                         }
1363
1364 #if GMCS_SOURCE
1365                         //
1366                         // FIXME: This hack is needed because member cache does not work
1367                         // with generic types, we rely on runtime to inflate dynamic types.
1368                         // TODO: This hack requires member cache refactoring to be removed
1369                         //
1370                         if (TypeBuilder.IsGenericType)
1371                                 member_cache = new MemberCache (this);
1372 #endif                  
1373
1374                         return true;
1375                 }
1376
1377                 protected virtual void DefineContainerMembers (MemberCoreArrayList mcal)
1378                 {
1379                         if (mcal != null)
1380                                 mcal.DefineContainerMembers ();
1381                 }
1382                 
1383                 protected virtual void ComputeIndexerName ()
1384                 {
1385                         if (indexers == null)
1386                                 return;
1387
1388                         string class_indexer_name = null;
1389
1390                         //
1391                         // If there's both an explicit and an implicit interface implementation, the
1392                         // explicit one actually implements the interface while the other one is just
1393                         // a normal indexer.  See bug #37714.
1394                         //
1395
1396                         // Invariant maintained by AddIndexer(): All explicit interface indexers precede normal indexers
1397                         foreach (Indexer i in indexers) {
1398                                 if (i.InterfaceType != null) {
1399                                         if (seen_normal_indexers)
1400                                                 throw new Exception ("Internal Error: 'Indexers' array not sorted properly.");
1401                                         continue;
1402                                 }
1403
1404                                 seen_normal_indexers = true;
1405
1406                                 if (class_indexer_name == null) {
1407                                         class_indexer_name = i.ShortName;
1408                                         continue;
1409                                 }
1410
1411                                 if (i.ShortName != class_indexer_name)
1412                                         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");
1413                         }
1414
1415                         if (class_indexer_name != null)
1416                                 indexer_name = class_indexer_name;
1417                 }
1418
1419                 protected virtual void EmitIndexerName ()
1420                 {
1421                         if (!seen_normal_indexers)
1422                                 return;
1423
1424                         if (TypeManager.default_member_ctor == null) {
1425                                 if (TypeManager.default_member_type == null) {
1426                                         TypeManager.default_member_type = TypeManager.CoreLookupType (
1427                                                 "System.Reflection", "DefaultMemberAttribute", Kind.Class, true);
1428
1429                                         if (TypeManager.default_member_type == null)
1430                                                 return;
1431                                 }
1432
1433                                 TypeManager.default_member_ctor = TypeManager.GetPredefinedConstructor (
1434                                         TypeManager.default_member_type, Location, TypeManager.string_type);
1435
1436                                 if (TypeManager.default_member_ctor == null)
1437                                         return;
1438                         }
1439
1440                         CustomAttributeBuilder cb = new CustomAttributeBuilder (TypeManager.default_member_ctor, new string [] { IndexerName });
1441                         TypeBuilder.SetCustomAttribute (cb);
1442                 }
1443
1444                 protected virtual void CheckEqualsAndGetHashCode ()
1445                 {
1446                         if (methods == null)
1447                                 return;
1448
1449                         if (HasEquals && !HasGetHashCode) {
1450                                 Report.Warning (659, 3, this.Location, "`{0}' overrides Object.Equals(object) but does not override Object.GetHashCode()", this.GetSignatureForError ());
1451                         }
1452                 }
1453
1454                 public MemberInfo FindBaseMemberWithSameName (string name, bool ignore_methods)
1455                 {
1456                         return BaseCache == null ? null : BaseCache.FindMemberWithSameName (name, ignore_methods, null);
1457                 }
1458
1459                 /// <summary>
1460                 ///   This function is based by a delegate to the FindMembers routine
1461                 /// </summary>
1462                 static bool AlwaysAccept (MemberInfo m, object filterCriteria)
1463                 {
1464                         return true;
1465                 }
1466
1467                 /// <summary>
1468                 ///   This filter is used by FindMembers, and we just keep
1469                 ///   a global for the filter to `AlwaysAccept'
1470                 /// </summary>
1471                 static MemberFilter accepting_filter;
1472
1473                 
1474                 static TypeContainer ()
1475                 {
1476                         accepting_filter = new MemberFilter (AlwaysAccept);
1477                 }
1478
1479                 public MethodInfo[] GetMethods ()
1480                 {
1481                         ArrayList members = new ArrayList ();
1482
1483                         Define ();
1484
1485                         if (methods != null) {
1486                                 int len = methods.Count;
1487                                 for (int i = 0; i < len; i++) {
1488                                         Method m = (Method) methods [i];
1489
1490                                         members.Add (m.MethodBuilder);
1491                                 }
1492                         }
1493
1494                         if (operators != null) {
1495                                 int len = operators.Count;
1496                                 for (int i = 0; i < len; i++) {
1497                                         Operator o = (Operator) operators [i];
1498
1499                                         members.Add (o.MethodBuilder);
1500                                 }
1501                         }
1502
1503                         if (properties != null) {
1504                                 int len = properties.Count;
1505                                 for (int i = 0; i < len; i++) {
1506                                         Property p = (Property) properties [i];
1507
1508                                         if (p.GetBuilder != null)
1509                                                 members.Add (p.GetBuilder);
1510                                         if (p.SetBuilder != null)
1511                                                 members.Add (p.SetBuilder);
1512                                 }
1513                         }
1514                                 
1515                         if (indexers != null) {
1516                                 int len = indexers.Count;
1517                                 for (int i = 0; i < len; i++) {
1518                                         Indexer ix = (Indexer) indexers [i];
1519
1520                                         if (ix.GetBuilder != null)
1521                                                 members.Add (ix.GetBuilder);
1522                                         if (ix.SetBuilder != null)
1523                                                 members.Add (ix.SetBuilder);
1524                                 }
1525                         }
1526
1527                         if (events != null) {
1528                                 int len = events.Count;
1529                                 for (int i = 0; i < len; i++) {
1530                                         Event e = (Event) events [i];
1531
1532                                         if (e.AddBuilder != null)
1533                                                 members.Add (e.AddBuilder);
1534                                         if (e.RemoveBuilder != null)
1535                                                 members.Add (e.RemoveBuilder);
1536                                 }
1537                         }
1538
1539                         MethodInfo[] retMethods = new MethodInfo [members.Count];
1540                         members.CopyTo (retMethods, 0);
1541                         return retMethods;
1542                 }
1543                 
1544                 // Indicated whether container has StructLayout attribute set Explicit
1545                 public bool HasExplicitLayout {
1546                         get { return (caching_flags & Flags.HasExplicitLayout) != 0; }
1547                         set { caching_flags |= Flags.HasExplicitLayout; }
1548                 }
1549
1550                 public bool HasStructLayout {
1551                         get { return (caching_flags & Flags.HasStructLayout) != 0; }
1552                         set { caching_flags |= Flags.HasStructLayout; }
1553                 }
1554
1555                 //
1556                 // Return the nested type with name @name.  Ensures that the nested type
1557                 // is defined if necessary.  Do _not_ use this when you have a MemberCache handy.
1558                 //
1559                 public Type FindNestedType (string name)
1560                 {
1561                         if (PartialContainer != this)
1562                                 throw new InternalErrorException ("should not happen");
1563
1564                         ArrayList [] lists = { types, delegates };
1565
1566                         for (int j = 0; j < lists.Length; ++j) {
1567                                 ArrayList list = lists [j];
1568                                 if (list == null)
1569                                         continue;
1570                                 
1571                                 int len = list.Count;
1572                                 for (int i = 0; i < len; ++i) {
1573                                         DeclSpace ds = (DeclSpace) list [i];
1574                                         if (ds.Basename == name) {
1575                                                 return ds.DefineType ();
1576                                         }
1577                                 }
1578                         }
1579
1580                         return null;
1581                 }
1582
1583                 private void FindMembers_NestedTypes (int modflags,
1584                                                       BindingFlags bf, MemberFilter filter, object criteria,
1585                                                       ref ArrayList members)
1586                 {
1587                         ArrayList [] lists = { types, delegates };
1588
1589                         for (int j = 0; j < lists.Length; ++j) {
1590                                 ArrayList list = lists [j];
1591                                 if (list == null)
1592                                         continue;
1593                         
1594                                 int len = list.Count;
1595                                 for (int i = 0; i < len; i++) {
1596                                         DeclSpace ds = (DeclSpace) list [i];
1597                                         
1598                                         if ((ds.ModFlags & modflags) == 0)
1599                                                 continue;
1600                                         
1601                                         TypeBuilder tb = ds.TypeBuilder;
1602                                         if (tb == null) {
1603                                                 if (!(criteria is string) || ds.Basename.Equals (criteria))
1604                                                         tb = ds.DefineType ();
1605                                         }
1606                                         
1607                                         if (tb != null && (filter (tb, criteria) == true)) {
1608                                                 if (members == null)
1609                                                         members = new ArrayList ();
1610                                                 
1611                                                 members.Add (tb);
1612                                         }
1613                                 }
1614                         }
1615                 }
1616                 
1617                 /// <summary>
1618                 ///   This method returns the members of this type just like Type.FindMembers would
1619                 ///   Only, we need to use this for types which are _being_ defined because MS' 
1620                 ///   implementation can't take care of that.
1621                 /// </summary>
1622                 //
1623                 // FIXME: return an empty static array instead of null, that cleans up
1624                 // some code and is consistent with some coding conventions I just found
1625                 // out existed ;-)
1626                 //
1627                 //
1628                 // Notice that in various cases we check if our field is non-null,
1629                 // something that would normally mean that there was a bug elsewhere.
1630                 //
1631                 // The problem happens while we are defining p-invoke methods, as those
1632                 // will trigger a FindMembers, but this happens before things are defined
1633                 //
1634                 // Since the whole process is a no-op, it is fine to check for null here.
1635                 //
1636                 // TODO: This approach will be one day completely removed, it's already
1637                 // used at few places only
1638                 //
1639                 //
1640                 public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1641                                                         MemberFilter filter, object criteria)
1642                 {
1643                         ArrayList members = null;
1644
1645                         int modflags = 0;
1646                         if ((bf & BindingFlags.Public) != 0)
1647                                 modflags |= Modifiers.PUBLIC | Modifiers.PROTECTED |
1648                                         Modifiers.INTERNAL;
1649                         if ((bf & BindingFlags.NonPublic) != 0)
1650                                 modflags |= Modifiers.PRIVATE;
1651
1652                         int static_mask = 0, static_flags = 0;
1653                         switch (bf & (BindingFlags.Static | BindingFlags.Instance)) {
1654                         case BindingFlags.Static:
1655                                 static_mask = static_flags = Modifiers.STATIC;
1656                                 break;
1657
1658                         case BindingFlags.Instance:
1659                                 static_mask = Modifiers.STATIC;
1660                                 static_flags = 0;
1661                                 break;
1662
1663                         default:
1664                                 static_mask = static_flags = 0;
1665                                 break;
1666                         }
1667
1668                         Timer.StartTimer (TimerType.TcFindMembers);
1669
1670                         if (filter == null)
1671                                 filter = accepting_filter; 
1672
1673                         if ((mt & MemberTypes.Field) != 0) {
1674                                 if (fields != null) {
1675                                         int len = fields.Count;
1676                                         for (int i = 0; i < len; i++) {
1677                                                 FieldBase f = (FieldBase) fields [i];
1678                                                 
1679                                                 if ((f.ModFlags & modflags) == 0)
1680                                                         continue;
1681                                                 if ((f.ModFlags & static_mask) != static_flags)
1682                                                         continue;
1683
1684                                                 FieldBuilder fb = f.FieldBuilder;
1685                                                 if (fb != null && filter (fb, criteria) == true) {
1686                                                         if (members == null)
1687                                                                 members = new ArrayList ();
1688                                                         
1689                                                         members.Add (fb);
1690                                                 }
1691                                         }
1692                                 }
1693
1694                                 if (constants != null) {
1695                                         int len = constants.Count;
1696                                         for (int i = 0; i < len; i++) {
1697                                                 Const con = (Const) constants [i];
1698                                                 
1699                                                 if ((con.ModFlags & modflags) == 0)
1700                                                         continue;
1701                                                 if ((con.ModFlags & static_mask) != static_flags)
1702                                                         continue;
1703
1704                                                 FieldBuilder fb = con.FieldBuilder;
1705                                                 if (fb == null) {
1706                                                         if (con.Define ())
1707                                                                 fb = con.FieldBuilder;
1708                                                 }
1709                                                 if (fb != null && filter (fb, criteria) == true) {
1710                                                         if (members == null)
1711                                                                 members = new ArrayList ();
1712                                                         
1713                                                         members.Add (fb);
1714                                                 }
1715                                         }
1716                                 }
1717                         }
1718
1719                         if ((mt & MemberTypes.Method) != 0) {
1720                                 if (methods != null) {
1721                                         int len = methods.Count;
1722                                         for (int i = 0; i < len; i++) {
1723                                                 Method m = (Method) methods [i];
1724                                                 
1725                                                 if ((m.ModFlags & modflags) == 0)
1726                                                         continue;
1727                                                 if ((m.ModFlags & static_mask) != static_flags)
1728                                                         continue;
1729                                                 
1730                                                 MethodBuilder mb = m.MethodBuilder;
1731
1732                                                 if (mb != null && filter (mb, criteria) == true) {
1733                                                         if (members == null)
1734                                                                 members = new ArrayList ();
1735                                                         
1736                                                         members.Add (mb);
1737                                                 }
1738                                         }
1739                                 }
1740
1741                                 if (operators != null) {
1742                                         int len = operators.Count;
1743                                         for (int i = 0; i < len; i++) {
1744                                                 Operator o = (Operator) operators [i];
1745                                                 
1746                                                 if ((o.ModFlags & modflags) == 0)
1747                                                         continue;
1748                                                 if ((o.ModFlags & static_mask) != static_flags)
1749                                                         continue;
1750                                                 
1751                                                 MethodBuilder ob = o.MethodBuilder;
1752                                                 if (ob != null && filter (ob, criteria) == true) {
1753                                                         if (members == null)
1754                                                                 members = new ArrayList ();
1755                                                         
1756                                                         members.Add (ob);
1757                                                 }
1758                                         }
1759                                 }
1760
1761                                 if (events != null) {
1762                                         foreach (Event e in events) {
1763                                                 if ((e.ModFlags & modflags) == 0)
1764                                                         continue;
1765                                                 if ((e.ModFlags & static_mask) != static_flags)
1766                                                         continue;
1767
1768                                                 MethodBuilder b = e.AddBuilder;
1769                                                 if (b != null && filter (b, criteria)) {
1770                                                         if (members == null)
1771                                                                 members = new ArrayList (4);
1772
1773                                                         members.Add (b);
1774                                                 }
1775
1776                                                 b = e.RemoveBuilder;
1777                                                 if (b != null && filter (b, criteria)) {
1778                                                         if (members == null) 
1779                                                                 members = new ArrayList (4);
1780
1781                                                         members.Add (b);
1782                                                 }
1783                                         }
1784                                 }
1785
1786                                 if (properties != null) {
1787                                         int len = properties.Count;
1788                                         for (int i = 0; i < len; i++) {
1789                                                 Property p = (Property) properties [i];
1790                                                 
1791                                                 if ((p.ModFlags & modflags) == 0)
1792                                                         continue;
1793                                                 if ((p.ModFlags & static_mask) != static_flags)
1794                                                         continue;
1795                                                 
1796                                                 MethodBuilder b;
1797
1798                                                 b = p.GetBuilder;
1799                                                 if (b != null && filter (b, criteria) == true) {
1800                                                         if (members == null)
1801                                                                 members = new ArrayList ();
1802                                                         
1803                                                         members.Add (b);
1804                                                 }
1805
1806                                                 b = p.SetBuilder;
1807                                                 if (b != null && filter (b, criteria) == true) {
1808                                                         if (members == null)
1809                                                                 members = new ArrayList ();
1810                                                         
1811                                                         members.Add (b);
1812                                                 }
1813                                         }
1814                                 }
1815                                 
1816                                 if (indexers != null) {
1817                                         int len = indexers.Count;
1818                                         for (int i = 0; i < len; i++) {
1819                                                 Indexer ix = (Indexer) indexers [i];
1820                                                 
1821                                                 if ((ix.ModFlags & modflags) == 0)
1822                                                         continue;
1823                                                 if ((ix.ModFlags & static_mask) != static_flags)
1824                                                         continue;
1825                                                 
1826                                                 MethodBuilder b;
1827
1828                                                 b = ix.GetBuilder;
1829                                                 if (b != null && filter (b, criteria) == true) {
1830                                                         if (members == null)
1831                                                                 members = new ArrayList ();
1832                                                         
1833                                                         members.Add (b);
1834                                                 }
1835
1836                                                 b = ix.SetBuilder;
1837                                                 if (b != null && filter (b, criteria) == true) {
1838                                                         if (members == null)
1839                                                                 members = new ArrayList ();
1840                                                         
1841                                                         members.Add (b);
1842                                                 }
1843                                         }
1844                                 }
1845                         }
1846
1847                         if ((mt & MemberTypes.Event) != 0) {
1848                                 if (events != null) {
1849                                         int len = events.Count;
1850                                         for (int i = 0; i < len; i++) {
1851                                                 Event e = (Event) events [i];
1852                                                 
1853                                                 if ((e.ModFlags & modflags) == 0)
1854                                                         continue;
1855                                                 if ((e.ModFlags & static_mask) != static_flags)
1856                                                         continue;
1857
1858                                                 MemberInfo eb = e.EventBuilder;
1859                                                 if (eb != null && filter (eb, criteria) == true) {
1860                                                         if (members == null)
1861                                                                 members = new ArrayList ();
1862                                                         
1863                                                         members.Add (e.EventBuilder);
1864                                                 }
1865                                         }
1866                                 }
1867                         }
1868                         
1869                         if ((mt & MemberTypes.Property) != 0){
1870                                 if (properties != null) {
1871                                         int len = properties.Count;
1872                                         for (int i = 0; i < len; i++) {
1873                                                 Property p = (Property) properties [i];
1874                                                 
1875                                                 if ((p.ModFlags & modflags) == 0)
1876                                                         continue;
1877                                                 if ((p.ModFlags & static_mask) != static_flags)
1878                                                         continue;
1879
1880                                                 MemberInfo pb = p.PropertyBuilder;
1881                                                 if (pb != null && filter (pb, criteria) == true) {
1882                                                         if (members == null)
1883                                                                 members = new ArrayList ();
1884                                                         
1885                                                         members.Add (p.PropertyBuilder);
1886                                                 }
1887                                         }
1888                                 }
1889
1890                                 if (indexers != null) {
1891                                         int len = indexers.Count;
1892                                         for (int i = 0; i < len; i++) {
1893                                                 Indexer ix = (Indexer) indexers [i];
1894                                                 
1895                                                 if ((ix.ModFlags & modflags) == 0)
1896                                                         continue;
1897                                                 if ((ix.ModFlags & static_mask) != static_flags)
1898                                                         continue;
1899
1900                                                 MemberInfo ib = ix.PropertyBuilder;
1901                                                 if (ib != null && filter (ib, criteria) == true) {
1902                                                         if (members == null)
1903                                                                 members = new ArrayList ();
1904                                                         
1905                                                         members.Add (ix.PropertyBuilder);
1906                                                 }
1907                                         }
1908                                 }
1909                         }
1910                         
1911                         if ((mt & MemberTypes.NestedType) != 0)
1912                                 FindMembers_NestedTypes (modflags, bf, filter, criteria, ref members);
1913
1914                         if ((mt & MemberTypes.Constructor) != 0){
1915                                 if (((bf & BindingFlags.Instance) != 0) && (instance_constructors != null)){
1916                                         int len = instance_constructors.Count;
1917                                         for (int i = 0; i < len; i++) {
1918                                                 Constructor c = (Constructor) instance_constructors [i];
1919                                                 
1920                                                 ConstructorBuilder cb = c.ConstructorBuilder;
1921                                                 if (cb != null && filter (cb, criteria) == true) {
1922                                                         if (members == null)
1923                                                                 members = new ArrayList ();
1924                                                         
1925                                                         members.Add (cb);
1926                                                 }
1927                                         }
1928                                 }
1929
1930                                 if (((bf & BindingFlags.Static) != 0) && (default_static_constructor != null)){
1931                                         ConstructorBuilder cb =
1932                                                 default_static_constructor.ConstructorBuilder;
1933                                         
1934                                         if (cb != null && filter (cb, criteria) == true) {
1935                                                 if (members == null)
1936                                                         members = new ArrayList ();
1937                                                 
1938                                                 members.Add (cb);
1939                                         }
1940                                 }
1941                         }
1942
1943                         //
1944                         // Lookup members in base if requested.
1945                         //
1946                         if ((bf & BindingFlags.DeclaredOnly) == 0) {
1947                                 if (TypeBuilder.BaseType != null) {
1948                                         MemberList list = FindMembers (TypeBuilder.BaseType, mt, bf, filter, criteria);
1949                                         if (list.Count > 0) {
1950                                                 if (members == null)
1951                                                         members = new ArrayList ();
1952                                         
1953                                                 members.AddRange (list);
1954                                         }
1955                                 }
1956                         }
1957
1958                         Timer.StopTimer (TimerType.TcFindMembers);
1959
1960                         if (members == null)
1961                                 return MemberList.Empty;
1962                         else
1963                                 return new MemberList (members);
1964                 }
1965
1966                 public override MemberCache MemberCache {
1967                         get {
1968                                 return member_cache;
1969                         }
1970                 }
1971
1972                 public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1973                                                       MemberFilter filter, object criteria)
1974                 {
1975                         DeclSpace ds = TypeManager.LookupDeclSpace (t);
1976
1977                         if (ds != null)
1978                                 return ds.FindMembers (mt, bf, filter, criteria);
1979                         else
1980                                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1981                 }
1982
1983                 /// <summary>
1984                 ///   Emits the values for the constants
1985                 /// </summary>
1986                 public void EmitConstants ()
1987                 {
1988                         if (constants != null)
1989                                 foreach (Const con in constants)
1990                                         con.Emit ();
1991                         return;
1992                 }
1993
1994                 static void CheckMemberUsage (MemberCoreArrayList al, string member_type)
1995                 {
1996                         if (al == null)
1997                                 return;
1998
1999                         foreach (MemberCore mc in al) {
2000                                 if ((mc.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE)
2001                                         continue;
2002
2003                                 if (!mc.IsUsed && (mc.caching_flags & Flags.Excluded) == 0) {
2004                                         Report.Warning (169, 3, mc.Location, "The private {0} `{1}' is never used", member_type, mc.GetSignatureForError ());
2005                                 }
2006                         }
2007                 }
2008
2009                 public virtual void VerifyMembers ()
2010                 {
2011                         //
2012                         // Check for internal or private fields that were never assigned
2013                         //
2014                         if (Report.WarningLevel >= 3) {
2015                                 CheckMemberUsage (properties, "property");
2016                                 CheckMemberUsage (methods, "method");
2017                                 CheckMemberUsage (constants, "constant");
2018
2019                                 if (fields != null){
2020                                         bool is_type_exposed = Kind == Kind.Struct || IsExposedFromAssembly ();
2021                                         foreach (FieldBase f in fields) {
2022                                                 if ((f.ModFlags & Modifiers.Accessibility) != Modifiers.PRIVATE) {
2023                                                         if (is_type_exposed)
2024                                                                 continue;
2025
2026                                                         f.SetMemberIsUsed ();
2027                                                 }                               
2028                                                 
2029                                                 if (!f.IsUsed){
2030                                                         if ((f.caching_flags & Flags.IsAssigned) == 0)
2031                                                                 Report.Warning (169, 3, f.Location, "The private field `{0}' is never used", f.GetSignatureForError ());
2032                                                         else {
2033 #if NET_2_0
2034                                                                 const int error_code = 414;
2035 #else
2036                                                                 const int error_code = 169;
2037 #endif
2038                                                                 Report.Warning (error_code, 3, f.Location, "The private field `{0}' is assigned but its value is never used",
2039                                                                         f.GetSignatureForError ());
2040                                                         }
2041                                                         continue;
2042                                                 }
2043                                                 
2044                                                 //
2045                                                 // Only report 649 on level 4
2046                                                 //
2047                                                 if (Report.WarningLevel < 4)
2048                                                         continue;
2049                                                 
2050                                                 if ((f.caching_flags & Flags.IsAssigned) != 0)
2051                                                         continue;
2052
2053                                                 //
2054                                                 // Don't be pendatic over serializable attributes
2055                                                 //
2056                                                 if (f.OptAttributes != null || PartialContainer.HasStructLayout)
2057                                                         continue;
2058                                                 
2059                                                 Constant c = New.Constantify (f.MemberType);
2060                                                 Report.Warning (649, 4, f.Location, "Field `{0}' is never assigned to, and will always have its default value `{1}'",
2061                                                         f.GetSignatureForError (), c == null ? "null" : c.AsString ());
2062                                         }
2063                                 }
2064                         }
2065                 }
2066
2067                 // TODO: move to ClassOrStruct
2068                 void EmitConstructors ()
2069                 {
2070                         if (instance_constructors == null)
2071                                 return;
2072
2073                         if (TypeBuilder.IsSubclassOf (TypeManager.attribute_type) && RootContext.VerifyClsCompliance && IsClsComplianceRequired ()) {
2074                                 bool has_compliant_args = false;
2075
2076                                 foreach (Constructor c in instance_constructors) {
2077                                         try {
2078                                                 c.Emit ();
2079                                         }
2080                                         catch (Exception e) {
2081                                                 throw new InternalErrorException (c, e);
2082                                         }
2083
2084                                         if (has_compliant_args)
2085                                                 continue;
2086
2087                                         has_compliant_args = c.HasCompliantArgs;
2088                                 }
2089                                 if (!has_compliant_args)
2090                                         Report.Warning (3015, 1, Location, "`{0}' has no accessible constructors which use only CLS-compliant types", GetSignatureForError ());
2091                         } else {
2092                                 foreach (Constructor c in instance_constructors) {
2093                                         try {
2094                                                 c.Emit ();
2095                                         }
2096                                         catch (Exception e) {
2097                                                 throw new InternalErrorException (c, e);
2098                                         }
2099                                 }
2100                         }
2101                 }
2102
2103                 /// <summary>
2104                 ///   Emits the code, this step is performed after all
2105                 ///   the types, enumerations, constructors
2106                 /// </summary>
2107                 public virtual void EmitType ()
2108                 {
2109                         if (OptAttributes != null)
2110                                 OptAttributes.Emit ();
2111
2112                         Emit ();
2113
2114                         EmitConstructors ();
2115
2116                         // Can not continue if constants are broken
2117                         EmitConstants ();
2118                         if (Report.Errors > 0)
2119                                 return;
2120
2121                         if (default_static_constructor != null)
2122                                 default_static_constructor.Emit ();
2123                         
2124                         if (operators != null)
2125                                 foreach (Operator o in operators)
2126                                         o.Emit ();
2127
2128                         if (properties != null)
2129                                 foreach (Property p in properties)
2130                                         p.Emit ();
2131
2132                         if (indexers != null) {
2133                                 foreach (Indexer indx in indexers)
2134                                         indx.Emit ();
2135                                 EmitIndexerName ();
2136                         }
2137
2138                         if (events != null){
2139                                 foreach (Event e in Events)
2140                                         e.Emit ();
2141                         }
2142
2143                         if (methods != null) {
2144                                 for (int i = 0; i < methods.Count; ++i)
2145                                         ((Method) methods [i]).Emit ();
2146                         }
2147                         
2148                         if (fields != null)
2149                                 foreach (FieldBase f in fields)
2150                                         f.Emit ();
2151
2152                         if (delegates != null) {
2153                                 foreach (Delegate d in Delegates) {
2154                                         d.Emit ();
2155                                 }
2156                         }
2157
2158                         if (pending != null)
2159                                 pending.VerifyPendingMethods ();
2160
2161                         if (Report.Errors > 0)
2162                                 return;
2163
2164                         if (compiler_generated != null) {
2165                                 for (int i = 0; i < compiler_generated.Count; ++i)
2166                                         ((CompilerGeneratedClass) compiler_generated [i]).EmitType ();
2167                         }
2168                 }
2169                 
2170                 public override void CloseType ()
2171                 {
2172                         if ((caching_flags & Flags.CloseTypeCreated) != 0)
2173                                 return;
2174
2175                         try {
2176                                 caching_flags |= Flags.CloseTypeCreated;
2177                                 TypeBuilder.CreateType ();
2178                         } catch (TypeLoadException){
2179                                 //
2180                                 // This is fine, the code still created the type
2181                                 //
2182 //                              Report.Warning (-20, "Exception while creating class: " + TypeBuilder.Name);
2183 //                              Console.WriteLine (e.Message);
2184                         } catch (Exception e) {
2185                                 throw new InternalErrorException (this, e);
2186                         }
2187                         
2188                         if (Types != null){
2189                                 foreach (TypeContainer tc in Types)
2190                                         if (tc.Kind == Kind.Struct)
2191                                                 tc.CloseType ();
2192
2193                                 foreach (TypeContainer tc in Types)
2194                                         if (tc.Kind != Kind.Struct)
2195                                                 tc.CloseType ();
2196                         }
2197
2198                         if (Delegates != null)
2199                                 foreach (Delegate d in Delegates)
2200                                         d.CloseType ();
2201
2202                         if (compiler_generated != null)
2203                                 foreach (CompilerGeneratedClass c in compiler_generated)
2204                                         c.CloseType ();
2205                         
2206                         types = null;
2207                         properties = null;
2208                         delegates = null;
2209                         fields = null;
2210                         initialized_fields = null;
2211                         initialized_static_fields = null;
2212                         constants = null;
2213                         ordered_explicit_member_list = null;
2214                         ordered_member_list = null;
2215                         methods = null;
2216                         events = null;
2217                         indexers = null;
2218                         operators = null;
2219                         compiler_generated = null;
2220                         default_constructor = null;
2221                         default_static_constructor = null;
2222                         type_bases = null;
2223                         OptAttributes = null;
2224                         ifaces = null;
2225                         base_cache = null;
2226                         member_cache = null;
2227                 }
2228
2229                 //
2230                 // Performs the validation on a Method's modifiers (properties have
2231                 // the same properties).
2232                 //
2233                 public bool MethodModifiersValid (MemberCore mc)
2234                 {
2235                         const int vao = (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE);
2236                         const int va = (Modifiers.VIRTUAL | Modifiers.ABSTRACT);
2237                         const int nv = (Modifiers.NEW | Modifiers.VIRTUAL);
2238                         bool ok = true;
2239                         int flags = mc.ModFlags;
2240                         
2241                         //
2242                         // At most one of static, virtual or override
2243                         //
2244                         if ((flags & Modifiers.STATIC) != 0){
2245                                 if ((flags & vao) != 0){
2246                                         Report.Error (112, mc.Location, "A static member `{0}' cannot be marked as override, virtual or abstract",
2247                                                 mc.GetSignatureForError ());
2248                                         ok = false;
2249                                 }
2250                         }
2251
2252                         if (Kind == Kind.Struct){
2253                                 if ((flags & va) != 0){
2254                                         Modifiers.Error_InvalidModifier (mc.Location, "virtual or abstract");
2255                                         ok = false;
2256                                 }
2257                         }
2258
2259                         if ((flags & Modifiers.OVERRIDE) != 0 && (flags & nv) != 0){
2260                                 Report.Error (113, mc.Location, "A member `{0}' marked as override cannot be marked as new or virtual",
2261                                         mc.GetSignatureForError ());
2262                                 ok = false;
2263                         }
2264
2265                         //
2266                         // If the declaration includes the abstract modifier, then the
2267                         // declaration does not include static, virtual or extern
2268                         //
2269                         if ((flags & Modifiers.ABSTRACT) != 0){
2270                                 if ((flags & Modifiers.EXTERN) != 0){
2271                                         Report.Error (
2272                                                 180, mc.Location, "`{0}' cannot be both extern and abstract", mc.GetSignatureForError ());
2273                                         ok = false;
2274                                 }
2275
2276                                 if ((flags & Modifiers.SEALED) != 0) {
2277                                         Report.Error (502, mc.Location, "`{0}' cannot be both abstract and sealed", mc.GetSignatureForError ());
2278                                         ok = false;
2279                                 }
2280
2281                                 if ((flags & Modifiers.VIRTUAL) != 0){
2282                                         Report.Error (503, mc.Location, "The abstract method `{0}' cannot be marked virtual", mc.GetSignatureForError ());
2283                                         ok = false;
2284                                 }
2285
2286                                 if ((ModFlags & Modifiers.ABSTRACT) == 0){
2287                                         Report.SymbolRelatedToPreviousError (this);
2288                                         Report.Error (513, mc.Location, "`{0}' is abstract but it is declared in the non-abstract class `{1}'",
2289                                                 mc.GetSignatureForError (), GetSignatureForError ());
2290                                         ok = false;
2291                                 }
2292                         }
2293
2294                         if ((flags & Modifiers.PRIVATE) != 0){
2295                                 if ((flags & vao) != 0){
2296                                         Report.Error (621, mc.Location, "`{0}': virtual or abstract members cannot be private", mc.GetSignatureForError ());
2297                                         ok = false;
2298                                 }
2299                         }
2300
2301                         if ((flags & Modifiers.SEALED) != 0){
2302                                 if ((flags & Modifiers.OVERRIDE) == 0){
2303                                         Report.Error (238, mc.Location, "`{0}' cannot be sealed because it is not an override", mc.GetSignatureForError ());
2304                                         ok = false;
2305                                 }
2306                         }
2307
2308                         return ok;
2309                 }
2310
2311                 public Constructor DefaultStaticConstructor {
2312                         get { return default_static_constructor; }
2313                 }
2314
2315                 protected override bool VerifyClsCompliance ()
2316                 {
2317                         if (!base.VerifyClsCompliance ())
2318                                 return false;
2319
2320                         VerifyClsName ();
2321
2322                         Type base_type = TypeBuilder.BaseType;
2323                         if (base_type != null && !AttributeTester.IsClsCompliant (base_type)) {
2324                                 Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (base_type));
2325                         }
2326                         return true;
2327                 }
2328
2329
2330                 /// <summary>
2331                 /// Checks whether container name is CLS Compliant
2332                 /// </summary>
2333                 void VerifyClsName ()
2334                 {
2335                         Hashtable base_members = base_cache == null ? 
2336                                 new Hashtable () :
2337                                 base_cache.GetPublicMembers ();
2338                         Hashtable this_members = new Hashtable ();
2339
2340                         foreach (DictionaryEntry entry in defined_names) {
2341                                 MemberCore mc = (MemberCore)entry.Value;
2342                                 if (!mc.IsClsComplianceRequired ())
2343                                         continue;
2344
2345                                 string name = (string) entry.Key;
2346                                 string basename = name.Substring (name.LastIndexOf ('.') + 1);
2347
2348                                 string lcase = basename.ToLower (System.Globalization.CultureInfo.InvariantCulture);
2349                                 object found = base_members [lcase];
2350                                 if (found == null) {
2351                                         found = this_members [lcase];
2352                                         if (found == null) {
2353                                                 this_members.Add (lcase, mc);
2354                                                 continue;
2355                                         }
2356                                 }
2357
2358                                 if ((mc.ModFlags & Modifiers.OVERRIDE) != 0)
2359                                         continue;                                       
2360
2361                                 if (found is MemberInfo) {
2362                                         if (basename == ((MemberInfo) found).Name)
2363                                                 continue;
2364                                         Report.SymbolRelatedToPreviousError ((MemberInfo) found);
2365                                 } else {
2366                                         Report.SymbolRelatedToPreviousError ((MemberCore) found);
2367                                 }
2368
2369                                 Report.Warning (3005, 1, mc.Location, "Identifier `{0}' differing only in case is not CLS-compliant", mc.GetSignatureForError ());
2370                         }
2371                 }
2372
2373
2374                 /// <summary>
2375                 ///   Performs checks for an explicit interface implementation.  First it
2376                 ///   checks whether the `interface_type' is a base inteface implementation.
2377                 ///   Then it checks whether `name' exists in the interface type.
2378                 /// </summary>
2379                 public bool VerifyImplements (InterfaceMemberBase mb)
2380                 {
2381                         if (ifaces != null) {
2382                                 foreach (Type t in ifaces){
2383                                         if (TypeManager.IsEqual (t, mb.InterfaceType))
2384                                                 return true;
2385                                 }
2386                         }
2387                         
2388                         Report.SymbolRelatedToPreviousError (mb.InterfaceType);
2389                         Report.Error (540, mb.Location, "`{0}': containing type does not implement interface `{1}'",
2390                                 mb.GetSignatureForError (), TypeManager.CSharpName (mb.InterfaceType));
2391                         return false;
2392                 }
2393
2394                 public override Type LookupAnyGeneric (string typeName)
2395                 {
2396                         if (types != null) {
2397                                 foreach (TypeContainer tc in types) {
2398                                         if (!tc.IsGeneric)
2399                                                 continue;
2400
2401                                         int pos = tc.Basename.LastIndexOf ('`');
2402                                         if (pos == typeName.Length && String.Compare (typeName, 0, tc.Basename, 0, pos) == 0)
2403                                                 return tc.TypeBuilder;
2404                                 }
2405                         }
2406
2407                         return base.LookupAnyGeneric (typeName);
2408                 }
2409
2410                 public void Mark_HasEquals ()
2411                 {
2412                         cached_method |= CachedMethods.Equals;
2413                 }
2414
2415                 public void Mark_HasGetHashCode ()
2416                 {
2417                         cached_method |= CachedMethods.GetHashCode;
2418                 }
2419
2420                 /// <summary>
2421                 /// Method container contains Equals method
2422                 /// </summary>
2423                 public bool HasEquals {
2424                         get {
2425                                 return (cached_method & CachedMethods.Equals) != 0;
2426                         }
2427                 }
2428  
2429                 /// <summary>
2430                 /// Method container contains GetHashCode method
2431                 /// </summary>
2432                 public bool HasGetHashCode {
2433                         get {
2434                                 return (cached_method & CachedMethods.GetHashCode) != 0;
2435                         }
2436                 }
2437
2438                 public bool HasStaticFieldInitializer {
2439                         get {
2440                                 return (cached_method & CachedMethods.HasStaticFieldInitializer) != 0;
2441                         }
2442                         set {
2443                                 if (value)
2444                                         cached_method |= CachedMethods.HasStaticFieldInitializer;
2445                                 else
2446                                         cached_method &= ~CachedMethods.HasStaticFieldInitializer;
2447                         }
2448                 }
2449
2450                 //
2451                 // IMemberContainer
2452                 //
2453
2454                 string IMemberContainer.Name {
2455                         get {
2456                                 return Name;
2457                         }
2458                 }
2459
2460                 Type IMemberContainer.Type {
2461                         get {
2462                                 return TypeBuilder;
2463                         }
2464                 }
2465
2466                 bool IMemberContainer.IsInterface {
2467                         get {
2468                                 return Kind == Kind.Interface;
2469                         }
2470                 }
2471
2472                 MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
2473                 {
2474                         BindingFlags new_bf = bf | BindingFlags.DeclaredOnly;
2475
2476                         if (GenericType != null)
2477                                 return TypeManager.FindMembers (GenericType, mt, new_bf,
2478                                                                 null, null);
2479                         else
2480                                 return FindMembers (mt, new_bf, null, null);
2481                 }
2482
2483                 //
2484                 // Generates xml doc comments (if any), and if required,
2485                 // handle warning report.
2486                 //
2487                 internal override void GenerateDocComment (DeclSpace ds)
2488                 {
2489                         DocUtil.GenerateTypeDocComment (this, ds);
2490                 }
2491
2492                 public override string DocCommentHeader {
2493                         get { return "T:"; }
2494                 }
2495
2496                 public MemberCache BaseCache {
2497                         get {
2498                                 if (base_cache != null)
2499                                         return base_cache;
2500                                 if (TypeBuilder.BaseType != null)
2501                                         base_cache = TypeManager.LookupMemberCache (TypeBuilder.BaseType);
2502                                 if (TypeBuilder.IsInterface)
2503                                         base_cache = TypeManager.LookupBaseInterfacesCache (TypeBuilder);
2504                                 return base_cache;
2505                         }
2506                 }
2507         }
2508
2509         public abstract class ClassOrStruct : TypeContainer {
2510                 ListDictionary declarative_security;
2511
2512                 public ClassOrStruct (NamespaceEntry ns, DeclSpace parent,
2513                                       MemberName name, Attributes attrs, Kind kind)
2514                         : base (ns, parent, name, attrs, kind)
2515                 {
2516                 }
2517
2518                 protected override bool AddToContainer (MemberCore symbol, string name)
2519                 {
2520                         if (name == MemberName.Name && symbol.MemberName.Left == null) {
2521                                 if (symbol is TypeParameter) {
2522                                         Report.Error (694, symbol.Location,
2523                                                 "Type parameter `{0}' has same name as containing type, or method",
2524                                                 symbol.GetSignatureForError ());
2525                                         return false;
2526                                 }
2527
2528                                 Report.SymbolRelatedToPreviousError (this);
2529                                 Report.Error (542, symbol.Location, "`{0}': member names cannot be the same as their enclosing type",
2530                                         symbol.GetSignatureForError ());
2531                                 return false;
2532                         }
2533
2534                         return base.AddToContainer (symbol, name);
2535                 }
2536
2537                 public override void VerifyMembers ()
2538                 {
2539                         base.VerifyMembers ();
2540
2541                         if ((events != null) && Report.WarningLevel >= 3) {
2542                                 foreach (Event e in events){
2543                                         // Note: The event can be assigned from same class only, so we can report
2544                                         // this warning for all accessibility modes
2545                                         if ((e.caching_flags & Flags.IsUsed) == 0)
2546                                                 Report.Warning (67, 3, e.Location, "The event `{0}' is never used", e.GetSignatureForError ());
2547                                 }
2548                         }
2549                 }
2550
2551                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2552                 {
2553                         if (a.IsValidSecurityAttribute ()) {
2554                                 if (declarative_security == null)
2555                                         declarative_security = new ListDictionary ();
2556
2557                                 a.ExtractSecurityPermissionSet (declarative_security);
2558                                 return;
2559                         }
2560
2561                         if (a.Type == TypeManager.struct_layout_attribute_type) {
2562                                 PartialContainer.HasStructLayout = true;
2563
2564                                 if (a.GetLayoutKindValue () == LayoutKind.Explicit)
2565                                         PartialContainer.HasExplicitLayout = true;
2566                         }
2567
2568                         base.ApplyAttributeBuilder (a, cb);
2569                 }
2570
2571                 /// <summary>
2572                 /// Defines the default constructors 
2573                 /// </summary>
2574                 protected void DefineDefaultConstructor (bool is_static)
2575                 {
2576                         // The default instance constructor is public
2577                         // If the class is abstract, the default constructor is protected
2578                         // The default static constructor is private
2579
2580                         int mods;
2581                         if (is_static) {
2582                                 mods = Modifiers.STATIC | Modifiers.PRIVATE;
2583                         } else {
2584                                 mods = ((ModFlags & Modifiers.ABSTRACT) != 0) ? Modifiers.PROTECTED : Modifiers.PUBLIC;
2585                         }
2586
2587                         Constructor c = new Constructor (this, MemberName.Name, mods,
2588                                 null, Parameters.EmptyReadOnlyParameters,
2589                                 new GeneratedBaseInitializer (Location),
2590                                 Location);
2591                         
2592                         AddConstructor (c);
2593                         c.Block = new ToplevelBlock (Parameters.EmptyReadOnlyParameters, Location);
2594                 }
2595
2596                 public override bool Define ()
2597                 {
2598                         CheckProtectedModifier ();
2599
2600                         base.Define ();
2601
2602                         if (default_static_constructor != null)
2603                                 default_static_constructor.Define ();
2604
2605                         return true;
2606                 }
2607
2608                 public override void Emit ()
2609                 {
2610                         if (default_static_constructor == null && PartialContainer.HasStaticFieldInitializer) {
2611                                 DefineDefaultConstructor (true);
2612                                 default_static_constructor.Define ();
2613                         }
2614
2615                         base.Emit ();
2616
2617                         if (declarative_security != null) {
2618                                 foreach (DictionaryEntry de in declarative_security) {
2619                                         TypeBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
2620                                 }
2621                         }
2622                 }
2623
2624                 public override ExtensionMethodGroupExpr LookupExtensionMethod (Type extensionType, string name, Location loc)
2625                 {
2626                         return NamespaceEntry.LookupExtensionMethod (extensionType, this, name, loc);
2627                 }
2628
2629                 protected override TypeAttributes TypeAttr {
2630                         get {
2631                                 if (default_static_constructor == null)
2632                                         return base.TypeAttr | TypeAttributes.BeforeFieldInit;
2633
2634                                 return base.TypeAttr;
2635                         }
2636                 }
2637         }
2638
2639
2640         // TODO: should be sealed
2641         public class Class : ClassOrStruct {
2642                 const int AllowedModifiers =
2643                         Modifiers.NEW |
2644                         Modifiers.PUBLIC |
2645                         Modifiers.PROTECTED |
2646                         Modifiers.INTERNAL |
2647                         Modifiers.PRIVATE |
2648                         Modifiers.ABSTRACT |
2649                         Modifiers.SEALED |
2650                         Modifiers.STATIC |
2651                         Modifiers.UNSAFE;
2652
2653                 public const TypeAttributes StaticClassAttribute = TypeAttributes.Abstract | TypeAttributes.Sealed;
2654
2655                 public Class (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
2656                               Attributes attrs)
2657                         : base (ns, parent, name, attrs, Kind.Class)
2658                 {
2659                         int accmods = Parent.Parent == null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
2660                         this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2661
2662                         if (IsStatic && RootContext.Version == LanguageVersion.ISO_1) {
2663                                 Report.FeatureIsNotAvailable (Location, "static classes");
2664                         }
2665                 }
2666
2667                 public override void AddBasesForPart (DeclSpace part, ArrayList bases)
2668                 {
2669                         if (part.Name == "System.Object")
2670                                 Report.Error (537, part.Location,
2671                                         "The class System.Object cannot have a base class or implement an interface.");
2672                         base.AddBasesForPart (part, bases);
2673                 }
2674
2675                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
2676                 {
2677                         if (a.Type == TypeManager.attribute_usage_type) {
2678                                 if (!TypeManager.IsAttributeType (BaseType) &&
2679                                         TypeBuilder.FullName != "System.Attribute") {
2680                                         Report.Error (641, a.Location, "Attribute `{0}' is only valid on classes derived from System.Attribute", a.GetSignatureForError ());
2681                                 }
2682                         }
2683
2684                         if (a.Type == TypeManager.conditional_attribute_type && !TypeManager.IsAttributeType (BaseType)) {
2685                                 Report.Error (1689, a.Location, "Attribute `System.Diagnostics.ConditionalAttribute' is only valid on methods or attribute classes");
2686                                 return;
2687                         }
2688
2689                         if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
2690                                 !attributes.Contains (TypeManager.guid_attr_type)) {
2691                                         a.Error_MissingGuidAttribute ();
2692                                         return;
2693                         }
2694
2695                         if (a.Type == TypeManager.extension_attribute_type) {
2696                                 a.Error_MisusedExtensionAttribute ();
2697                                 return;
2698                         }
2699
2700                         if (AttributeTester.IsAttributeExcluded (a.Type, Location))
2701                                 return;
2702
2703                         base.ApplyAttributeBuilder (a, cb);
2704                 }
2705
2706                 public override AttributeTargets AttributeTargets {
2707                         get {
2708                                 return AttributeTargets.Class;
2709                         }
2710                 }
2711
2712                 protected override void DefineContainerMembers (MemberCoreArrayList list)
2713                 {
2714                         if (list == null)
2715                                 return;
2716
2717                         if (!IsStatic) {
2718                                 base.DefineContainerMembers (list);
2719                                 return;
2720                         }
2721
2722                         foreach (MemberCore m in list) {
2723                                 if (m is Operator) {
2724                                         Report.Error (715, m.Location, "`{0}': Static classes cannot contain user-defined operators", m.GetSignatureForError ());
2725                                         continue;
2726                                 }
2727
2728                                 if (m is Destructor) {
2729                                         Report.Error (711, m.Location, "`{0}': Static classes cannot contain destructor", GetSignatureForError ());
2730                                         continue;
2731                                 }
2732
2733                                 if (m is Indexer) {
2734                                         Report.Error (720, m.Location, "`{0}': cannot declare indexers in a static class", m.GetSignatureForError ());
2735                                         continue;
2736                                 }
2737
2738                                 if ((m.ModFlags & Modifiers.STATIC) != 0 || m is Enum || m is Delegate)
2739                                         continue;
2740
2741                                 if (m is Constructor) {
2742                                         Report.Error (710, m.Location, "`{0}': Static classes cannot have instance constructors", GetSignatureForError ());
2743                                         continue;
2744                                 }
2745
2746                                 Method method = m as Method;
2747                                 if (method != null && method.Parameters.HasExtensionMethodType) {
2748                                         Report.Error (1105, m.Location, "`{0}': Extension methods must be declared static", m.GetSignatureForError ());
2749                                         continue;
2750                                 }
2751
2752                                 Report.Error (708, m.Location, "`{0}': cannot declare instance members in a static class", m.GetSignatureForError ());
2753                         }
2754
2755                         base.DefineContainerMembers (list);
2756                 }
2757
2758                 public override bool Define ()
2759                 {
2760                         if ((ModFlags & Modifiers.ABSTRACT) == Modifiers.ABSTRACT && (ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) != 0) {
2761                                 Report.Error (418, Location, "`{0}': an abstract class cannot be sealed or static", GetSignatureForError ());
2762                         }
2763
2764                         if ((ModFlags & (Modifiers.SEALED | Modifiers.STATIC)) == (Modifiers.SEALED | Modifiers.STATIC)) {
2765                                 Report.Error (441, Location, "`{0}': a class cannot be both static and sealed", GetSignatureForError ());
2766                         }
2767
2768                         return base.Define ();
2769                 }
2770
2771                 protected override bool DoDefineMembers ()
2772                 {
2773                         if (InstanceConstructors == null && !IsStatic)
2774                                 DefineDefaultConstructor (false);
2775
2776                         return base.DoDefineMembers ();
2777                 }
2778
2779                 public override void Emit ()
2780                 {
2781                         base.Emit ();
2782
2783 #if GMCS_SOURCE
2784                         if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
2785                                 TypeBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
2786 #endif                  
2787                 }
2788
2789                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2790                 {
2791                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2792
2793                         if (base_class == null) {
2794                                 if (RootContext.StdLib)
2795                                         base_class = TypeManager.system_object_expr;
2796                                 else if (Name != "System.Object")
2797                                         base_class = TypeManager.system_object_expr;
2798                         } else {
2799                                 if (Kind == Kind.Class && base_class is TypeParameterExpr){
2800                                         Report.Error (
2801                                                 689, base_class.Location,
2802                                                 "Cannot derive from `{0}' because it is a type parameter",
2803                                                 base_class.GetSignatureForError ());
2804                                         return ifaces;
2805                                 }
2806
2807                                 if (IsGeneric && TypeManager.IsAttributeType (base_class.Type)) {
2808                                         Report.Error (698, base_class.Location,
2809                                                 "A generic type cannot derive from `{0}' because it is an attribute class",
2810                                                 base_class.GetSignatureForError ());
2811                                 }
2812
2813                                 if (base_class.IsSealed){
2814                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2815                                         if (base_class.Type.IsAbstract) {
2816                                                 Report.Error (709, Location, "`{0}': Cannot derive from static class `{1}'",
2817                                                         GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2818                                         } else {
2819                                                 Report.Error (509, Location, "`{0}': cannot derive from sealed class `{1}'",
2820                                                         GetSignatureForError (), TypeManager.CSharpName (base_class.Type));
2821                                         }
2822                                         return ifaces;
2823                                 }
2824
2825                                 if (!base_class.CanInheritFrom ()){
2826                                         Report.Error (644, Location, "`{0}' cannot derive from special class `{1}'",
2827                                                 GetSignatureForError (), base_class.GetSignatureForError ());
2828                                         return ifaces;
2829                                 }
2830
2831                                 if (!base_class.AsAccessible (this)) {
2832                                         Report.SymbolRelatedToPreviousError (base_class.Type);
2833                                         Report.Error (60, Location, "Inconsistent accessibility: base class `{0}' is less accessible than class `{1}'", 
2834                                                 TypeManager.CSharpName (base_class.Type), GetSignatureForError ());
2835                                 }
2836                         }
2837
2838                         if (PartialContainer.IsStaticClass) {
2839                                 if (base_class.Type != TypeManager.object_type) {
2840                                         Report.Error (713, Location, "Static class `{0}' cannot derive from type `{1}'. Static classes must derive from object",
2841                                                 GetSignatureForError (), base_class.GetSignatureForError ());
2842                                         return ifaces;
2843                                 }
2844
2845                                 if (ifaces != null) {
2846                                         foreach (TypeExpr t in ifaces)
2847                                                 Report.SymbolRelatedToPreviousError (t.Type);
2848                                         Report.Error (714, Location, "Static class `{0}' cannot implement interfaces", GetSignatureForError ());
2849                                 }
2850                         }
2851
2852                         return ifaces;
2853                 }
2854
2855                 /// Search for at least one defined condition in ConditionalAttribute of attribute class
2856                 /// Valid only for attribute classes.
2857                 public bool IsExcluded ()
2858                 {
2859                         if ((caching_flags & Flags.Excluded_Undetected) == 0)
2860                                 return (caching_flags & Flags.Excluded) != 0;
2861
2862                         caching_flags &= ~Flags.Excluded_Undetected;
2863
2864                         if (OptAttributes == null)
2865                                 return false;
2866
2867                         if (TypeManager.conditional_attribute_type == null)
2868                                 return false;
2869
2870                         Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
2871
2872                         if (attrs == null)
2873                                 return false;
2874
2875                         foreach (Attribute a in attrs) {
2876                                 string condition = a.GetConditionalAttributeValue ();
2877                                 if (Location.CompilationUnit.IsConditionalDefined (condition))
2878                                         return false;
2879                         }
2880
2881                         caching_flags |= Flags.Excluded;
2882                         return true;
2883                 }
2884
2885                 bool IsStatic {
2886                         get {
2887                                 return (ModFlags & Modifiers.STATIC) != 0;
2888                         }
2889                 }
2890
2891                 //
2892                 // FIXME: How do we deal with the user specifying a different
2893                 // layout?
2894                 //
2895                 protected override TypeAttributes TypeAttr {
2896                         get {
2897                                 TypeAttributes ta = base.TypeAttr | TypeAttributes.AutoLayout | TypeAttributes.Class;
2898                                 if (IsStatic)
2899                                         ta |= StaticClassAttribute;
2900                                 return ta;
2901                         }
2902                 }
2903         }
2904
2905         public sealed class Struct : ClassOrStruct {
2906                 // <summary>
2907                 //   Modifiers allowed in a struct declaration
2908                 // </summary>
2909                 const int AllowedModifiers =
2910                         Modifiers.NEW       |
2911                         Modifiers.PUBLIC    |
2912                         Modifiers.PROTECTED |
2913                         Modifiers.INTERNAL  |
2914                         Modifiers.UNSAFE    |
2915                         Modifiers.PRIVATE;
2916
2917                 public Struct (NamespaceEntry ns, DeclSpace parent, MemberName name,
2918                                int mod, Attributes attrs)
2919                         : base (ns, parent, name, attrs, Kind.Struct)
2920                 {
2921                         int accmods;
2922                         
2923                         if (parent.Parent == null)
2924                                 accmods = Modifiers.INTERNAL;
2925                         else
2926                                 accmods = Modifiers.PRIVATE;
2927                         
2928                         this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, Location);
2929
2930                         this.ModFlags |= Modifiers.SEALED;
2931                 }
2932
2933                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
2934                 {
2935                         base.ApplyAttributeBuilder (a, cb);
2936
2937                         //
2938                         // When struct constains fixed fixed and struct layout has explicitly
2939                         // set CharSet, its value has to be propagated to compiler generated
2940                         // fixed field types
2941                         //
2942                         if (a.Type == TypeManager.struct_layout_attribute_type && Fields != null && a.HasField ("CharSet")) {
2943                                 for (int i = 0; i < Fields.Count; ++i) {
2944                                         FixedField ff = Fields [i] as FixedField;
2945                                         if (ff != null)
2946                                                 ff.SetCharSet (TypeBuilder.Attributes);
2947                                 }
2948                         }
2949                 }
2950
2951                 public override AttributeTargets AttributeTargets {
2952                         get {
2953                                 return AttributeTargets.Struct;
2954                         }
2955                 }
2956
2957                 public override bool IsUnmanagedType ()
2958                 {
2959                         if (fields == null)
2960                                 return true;
2961
2962                         if (requires_delayed_unmanagedtype_check)
2963                                 return true;
2964
2965                         foreach (FieldBase f in fields) {
2966                                 if ((f.ModFlags & Modifiers.STATIC) != 0)
2967                                         continue;
2968
2969                                 // It can happen when recursive unmanaged types are defined
2970                                 // struct S { S* s; }
2971                                 Type mt = f.MemberType;
2972                                 if (mt == null) {
2973                                         requires_delayed_unmanagedtype_check = true;
2974                                         return true;
2975                                 }
2976
2977                                 // TODO: Remove when pointer types are under mcs control
2978                                 while (mt.IsPointer)
2979                                         mt = TypeManager.GetElementType (mt);
2980                                 if (TypeManager.IsEqual (mt, TypeBuilder))
2981                                         continue;
2982
2983                                 if (TypeManager.IsUnmanagedType (mt))
2984                                         continue;
2985
2986                                 return false;
2987                         }
2988
2989                         return true;
2990                 }
2991
2992                 protected override TypeExpr[] ResolveBaseTypes (out TypeExpr base_class)
2993                 {
2994                         TypeExpr[] ifaces = base.ResolveBaseTypes (out base_class);
2995                         //
2996                         // If we are compiling our runtime,
2997                         // and we are defining ValueType, then our
2998                         // base is `System.Object'.
2999                         //
3000                         if (base_class == null) {
3001                                 if (!RootContext.StdLib && Name == "System.ValueType")
3002                                         base_class = TypeManager.system_object_expr;
3003                                 else
3004                                         base_class = TypeManager.system_valuetype_expr;
3005                         }
3006
3007                         return ifaces;
3008                 }
3009
3010                 //
3011                 // FIXME: Allow the user to specify a different set of attributes
3012                 // in some cases (Sealed for example is mandatory for a class,
3013                 // but what SequentialLayout can be changed
3014                 //
3015                 protected override TypeAttributes TypeAttr {
3016                         get {
3017                                 const TypeAttributes DefaultTypeAttributes =
3018                                         TypeAttributes.SequentialLayout |
3019                                         TypeAttributes.Sealed |
3020                                         TypeAttributes.BeforeFieldInit;
3021
3022                                 return base.TypeAttr | DefaultTypeAttributes;
3023                         }
3024                 }
3025
3026                 public override void RegisterFieldForInitialization (MemberCore field, FieldInitializer expression)
3027                 {
3028                         if ((field.ModFlags & Modifiers.STATIC) == 0) {
3029                                 Report.Error (573, field.Location, "`{0}': Structs cannot have instance field initializers",
3030                                         field.GetSignatureForError ());
3031                                 return;
3032                         }
3033                         base.RegisterFieldForInitialization (field, expression);
3034                 }
3035
3036         }
3037
3038         /// <summary>
3039         ///   Interfaces
3040         /// </summary>
3041         public sealed class Interface : TypeContainer, IMemberContainer {
3042
3043                 /// <summary>
3044                 ///   Modifiers allowed in a class declaration
3045                 /// </summary>
3046                 public const int AllowedModifiers =
3047                         Modifiers.NEW       |
3048                         Modifiers.PUBLIC    |
3049                         Modifiers.PROTECTED |
3050                         Modifiers.INTERNAL  |
3051                         Modifiers.UNSAFE    |
3052                         Modifiers.PRIVATE;
3053
3054                 public Interface (NamespaceEntry ns, DeclSpace parent, MemberName name, int mod,
3055                                   Attributes attrs)
3056                         : base (ns, parent, name, attrs, Kind.Interface)
3057                 {
3058                         int accmods;
3059
3060                         if (parent.Parent == null)
3061                                 accmods = Modifiers.INTERNAL;
3062                         else
3063                                 accmods = Modifiers.PRIVATE;
3064
3065                         this.ModFlags = Modifiers.Check (AllowedModifiers, mod, accmods, name.Location);
3066                 }
3067
3068                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3069                 {
3070                         if (a.Type == TypeManager.comimport_attr_type && TypeManager.guid_attr_type != null &&
3071                                 !attributes.Contains (TypeManager.guid_attr_type)) {
3072                                         a.Error_MissingGuidAttribute ();
3073                                         return;
3074                         }
3075                         base.ApplyAttributeBuilder (a, cb);
3076                 }
3077
3078
3079                 public override AttributeTargets AttributeTargets {
3080                         get {
3081                                 return AttributeTargets.Interface;
3082                         }
3083                 }
3084
3085                 protected override TypeAttributes TypeAttr {
3086                         get {
3087                                 const TypeAttributes DefaultTypeAttributes =
3088                                         TypeAttributes.AutoLayout |
3089                                         TypeAttributes.Abstract |
3090                                         TypeAttributes.Interface;
3091
3092                                 return base.TypeAttr | DefaultTypeAttributes;
3093                         }
3094                 }
3095
3096                 protected override bool VerifyClsCompliance ()
3097                 {
3098                         if (!base.VerifyClsCompliance ())
3099                                 return false;
3100
3101                         if (ifaces != null) {
3102                                 foreach (Type t in ifaces) {
3103                                         if (AttributeTester.IsClsCompliant (t))
3104                                                 continue;
3105
3106                                         Report.SymbolRelatedToPreviousError (t);
3107                                         Report.Warning (3027, 1, Location, "`{0}' is not CLS-compliant because base interface `{1}' is not CLS-compliant",
3108                                                 GetSignatureForError (), TypeManager.CSharpName (t));
3109                                 }
3110                         }
3111
3112                         return true;
3113                 }
3114         }
3115
3116         // It is used as a base class for all property based members
3117         // This includes properties, indexers, and events
3118         public abstract class PropertyBasedMember : InterfaceMemberBase
3119         {
3120                 public PropertyBasedMember (DeclSpace parent, GenericMethod generic,
3121                         FullNamedExpression type, int mod, int allowed_mod,
3122                         MemberName name, Attributes attrs)
3123                         : base (parent, generic, type, mod, allowed_mod, name, attrs)
3124                 {
3125                 }
3126
3127                 protected override bool VerifyClsCompliance ()
3128                 {
3129                         if (!base.VerifyClsCompliance ())
3130                                 return false;
3131
3132                         if (!AttributeTester.IsClsCompliant (MemberType)) {
3133                                 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
3134                                         GetSignatureForError ());
3135                         }
3136                         return true;
3137                 }
3138
3139         }
3140
3141
3142         public abstract class MethodCore : InterfaceMemberBase
3143         {
3144                 public readonly Parameters Parameters;
3145                 protected ToplevelBlock block;
3146
3147                 public MethodCore (DeclSpace parent, GenericMethod generic,
3148                         FullNamedExpression type, int mod, int allowed_mod,
3149                         MemberName name, Attributes attrs, Parameters parameters)
3150                         : base (parent, generic, type, mod, allowed_mod, name, attrs)
3151                 {
3152                         Parameters = parameters;
3153                 }
3154
3155                 //
3156                 //  Returns the System.Type array for the parameters of this method
3157                 //
3158                 public Type [] ParameterTypes {
3159                         get {
3160                                 return Parameters.Types;
3161                         }
3162                 }
3163
3164                 public Parameters ParameterInfo
3165                 {
3166                         get {
3167                                 return Parameters;
3168                         }
3169                 }
3170                 
3171                 public ToplevelBlock Block {
3172                         get {
3173                                 return block;
3174                         }
3175
3176                         set {
3177                                 block = value;
3178                         }
3179                 }
3180
3181                 protected override bool CheckBase ()
3182                 {
3183                         // Check whether arguments were correct.
3184                         if (!DefineParameters (Parameters))
3185                                 return false;
3186
3187                         return base.CheckBase ();
3188                 }
3189
3190                 //
3191                 // Returns a string that represents the signature for this 
3192                 // member which should be used in XML documentation.
3193                 //
3194                 public override string GetDocCommentName (DeclSpace ds)
3195                 {
3196                         return DocUtil.GetMethodDocCommentName (this, Parameters, ds);
3197                 }
3198
3199                 //
3200                 // Raised (and passed an XmlElement that contains the comment)
3201                 // when GenerateDocComment is writing documentation expectedly.
3202                 //
3203                 // FIXME: with a few effort, it could be done with XmlReader,
3204                 // that means removal of DOM use.
3205                 //
3206                 internal override void OnGenerateDocComment (XmlElement el)
3207                 {
3208                         DocUtil.OnMethodGenerateDocComment (this, el);
3209                 }
3210
3211                 //
3212                 //   Represents header string for documentation comment.
3213                 //
3214                 public override string DocCommentHeader 
3215                 {
3216                         get { return "M:"; }
3217                 }
3218
3219                 public override bool EnableOverloadChecks (MemberCore overload)
3220                 {
3221                         if (overload is MethodCore || overload is AbstractPropertyEventMethod) {
3222                                 caching_flags |= Flags.MethodOverloadsExist;
3223                                 return true;
3224                         }
3225
3226                         return base.EnableOverloadChecks (overload);
3227                 }
3228
3229                 protected override bool VerifyClsCompliance ()
3230                 {
3231                         if (!base.VerifyClsCompliance ())
3232                                 return false;
3233
3234                         if (Parameters.HasArglist) {
3235                                 Report.Warning (3000, 1, Location, "Methods with variable arguments are not CLS-compliant");
3236                         }
3237
3238                         if (!AttributeTester.IsClsCompliant (MemberType)) {
3239                                 Report.Warning (3002, 1, Location, "Return type of `{0}' is not CLS-compliant",
3240                                         GetSignatureForError ());
3241                         }
3242
3243                         Parameters.VerifyClsCompliance ();
3244                         return true;
3245                 }
3246
3247         }
3248
3249         public abstract class InterfaceMemberBase : MemberBase {
3250                 //
3251                 // Whether this is an interface member.
3252                 //
3253                 public bool IsInterface;
3254
3255                 //
3256                 // If true, this is an explicit interface implementation
3257                 //
3258                 public bool IsExplicitImpl;
3259
3260                 protected bool is_external_implementation;
3261
3262                 //
3263                 // The interface type we are explicitly implementing
3264                 //
3265                 public Type InterfaceType;
3266
3267                 //
3268                 // The method we're overriding if this is an override method.
3269                 //
3270                 protected MethodInfo base_method;
3271
3272                 readonly int explicit_mod_flags;
3273                 public MethodAttributes flags;
3274
3275                 public InterfaceMemberBase (DeclSpace parent, GenericMethod generic,
3276                                    FullNamedExpression type, int mod, int allowed_mod,
3277                                    MemberName name, Attributes attrs)
3278                         : base (parent, generic, type, mod, allowed_mod, Modifiers.PRIVATE,
3279                                 name, attrs)
3280                 {
3281                         IsInterface = parent.PartialContainer.Kind == Kind.Interface;
3282                         IsExplicitImpl = (MemberName.Left != null);
3283                         explicit_mod_flags = mod;
3284                 }
3285                 
3286                 protected override bool CheckBase ()
3287                 {
3288                         if (!base.CheckBase ())
3289                                 return false;
3290
3291                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
3292                                 CheckForDuplications ();
3293                         
3294                         if (IsExplicitImpl)
3295                                 return true;
3296
3297                         // Is null for System.Object while compiling corlib and base interfaces
3298                         if (Parent.PartialContainer.BaseCache == null) {
3299                                 if ((ModFlags & Modifiers.NEW) != 0) {
3300                                         Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3301                                 }
3302                                 return true;
3303                         }
3304
3305                         Type base_ret_type = null;
3306                         base_method = FindOutBaseMethod (ref base_ret_type);
3307
3308                         // method is override
3309                         if (base_method != null) {
3310                                 if (!CheckMethodAgainstBase (base_ret_type))
3311                                         return false;
3312
3313                                 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3314                                         ObsoleteAttribute oa = AttributeTester.GetMethodObsoleteAttribute (base_method);
3315                                         if (oa != null) {
3316                                                 if (OptAttributes == null || TypeManager.obsolete_attribute_type == null || !OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3317                                                         Report.SymbolRelatedToPreviousError (base_method);
3318                                                                 Report.Warning (672, 1, Location, "Member `{0}' overrides obsolete member `{1}'. Add the Obsolete attribute to `{0}'",
3319                                                                         GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3320                                                 }
3321                                         } else {
3322                                                 if (OptAttributes != null && TypeManager.obsolete_attribute_type != null && OptAttributes.Contains (TypeManager.obsolete_attribute_type)) {
3323                                                         Report.SymbolRelatedToPreviousError (base_method);
3324                                                         Report.Warning (809, 1, Location, "Obsolete member `{0}' overrides non-obsolete member `{1}'",
3325                                                                 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3326                                                 }
3327                                         }
3328                                 }
3329                                 return true;
3330                         }
3331
3332                         MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, !((this is Event) || (this is Property)));
3333                         if ((ModFlags & Modifiers.OVERRIDE) != 0) {
3334                                 if (conflict_symbol != null) {
3335                                         Report.SymbolRelatedToPreviousError (conflict_symbol);
3336                                         if (this is Event)
3337                                                 Report.Error (72, Location, "`{0}': cannot override because `{1}' is not an event", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3338                                         else if (this is PropertyBase)
3339                                                 Report.Error (544, Location, "`{0}': cannot override because `{1}' is not a property", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3340                                         else
3341                                                 Report.Error (505, Location, "`{0}': cannot override because `{1}' is not a method", GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3342                                 } else {
3343                                         Report.Error (115, Location, "`{0}' is marked as an override but no suitable {1} found to override",
3344                                                 GetSignatureForError (), SimpleName.GetMemberType (this));
3345                                 }
3346                                 return false;
3347                         }
3348
3349                         if (conflict_symbol == null) {
3350                                 if ((ModFlags & Modifiers.NEW) != 0) {
3351                                         Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
3352                                 }
3353                                 return true;
3354                         }
3355
3356                         if ((ModFlags & Modifiers.NEW) == 0) {
3357                                 if (this is MethodOrOperator && conflict_symbol.MemberType == MemberTypes.Method)
3358                                         return true;
3359
3360                                 Report.SymbolRelatedToPreviousError (conflict_symbol);
3361                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3362                                         GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
3363                         }
3364
3365                         return true;
3366                 }
3367
3368                 protected virtual bool CheckForDuplications ()
3369                 {
3370                         return Parent.MemberCache.CheckExistingMembersOverloads (
3371                                 this, GetFullName (MemberName), Parameters.EmptyReadOnlyParameters);
3372                 }
3373
3374                 //
3375                 // Performs various checks on the MethodInfo `mb' regarding the modifier flags
3376                 // that have been defined.
3377                 //
3378                 // `name' is the user visible name for reporting errors (this is used to
3379                 // provide the right name regarding method names and properties)
3380                 //
3381                 bool CheckMethodAgainstBase (Type base_method_type)
3382                 {
3383                         bool ok = true;
3384
3385                         if ((ModFlags & Modifiers.OVERRIDE) != 0){
3386                                 if (!(base_method.IsAbstract || base_method.IsVirtual)){
3387                                         Report.Error (506, Location,
3388                                                 "`{0}': cannot override inherited member `{1}' because it is not marked virtual, abstract or override",
3389                                                  GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3390                                         ok = false;
3391                                 }
3392                                 
3393                                 // Now we check that the overriden method is not final
3394                                 
3395                                 if (base_method.IsFinal) {
3396                                         Report.SymbolRelatedToPreviousError (base_method);
3397                                         Report.Error (239, Location, "`{0}': cannot override inherited member `{1}' because it is sealed",
3398                                                               GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3399                                         ok = false;
3400                                 }
3401                                 //
3402                                 // Check that the permissions are not being changed
3403                                 //
3404                                 MethodAttributes thisp = flags & MethodAttributes.MemberAccessMask;
3405                                 MethodAttributes base_classp = base_method.Attributes & MethodAttributes.MemberAccessMask;
3406
3407                                 if (!CheckAccessModifiers (thisp, base_classp, base_method)) {
3408                                         Error_CannotChangeAccessModifiers (Location, base_method, base_classp, null);
3409                                         ok = false;
3410                                 }
3411
3412                                 if (!TypeManager.IsEqual (MemberType, TypeManager.TypeToCoreType (base_method_type))) {
3413                                         Report.SymbolRelatedToPreviousError (base_method);
3414                                         if (this is PropertyBasedMember) {
3415                                                 Report.Error (1715, Location, "`{0}': type must be `{1}' to match overridden member `{2}'", 
3416                                                         GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3417                                         }
3418                                         else {
3419                                                 Report.Error (508, Location, "`{0}': return type must be `{1}' to match overridden member `{2}'",
3420                                                         GetSignatureForError (), TypeManager.CSharpName (base_method_type), TypeManager.CSharpSignature (base_method));
3421                                         }
3422                                         ok = false;
3423                                 }
3424                         }
3425
3426                         if ((ModFlags & Modifiers.NEW) == 0) {
3427                                 if ((ModFlags & Modifiers.OVERRIDE) == 0 && Name != "Finalize") {
3428                                         ModFlags |= Modifiers.NEW;
3429                                         Report.SymbolRelatedToPreviousError (base_method);
3430                                         if (!IsInterface && (base_method.IsVirtual || base_method.IsAbstract)) {
3431                                                 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",
3432                                                         GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3433                                         } else {
3434                                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
3435                                                         GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3436                                         }
3437                                 }
3438                         } else {
3439                                 if (base_method.IsAbstract && !IsInterface) {
3440                                         Report.SymbolRelatedToPreviousError (base_method);
3441                                         Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
3442                                                 GetSignatureForError (), TypeManager.CSharpSignature (base_method));
3443                                         return ok = false;
3444                                 }
3445                         }
3446
3447                         return ok;
3448                 }
3449                 
3450                 protected bool CheckAccessModifiers (MethodAttributes thisp, MethodAttributes base_classp, MethodInfo base_method)
3451                 {
3452                         if ((base_classp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3453                                 //
3454                                 // when overriding protected internal, the method can be declared
3455                                 // protected internal only within the same assembly or assembly
3456                                 // which has InternalsVisibleTo
3457                                 //
3458                                 if ((thisp & MethodAttributes.FamORAssem) == MethodAttributes.FamORAssem){
3459                                         return TypeManager.IsThisOrFriendAssembly (base_method.DeclaringType.Assembly);
3460                                 } else if ((thisp & MethodAttributes.Family) != MethodAttributes.Family) {
3461                                         //
3462                                         // if it's not "protected internal", it must be "protected"
3463                                         //
3464
3465                                         return false;
3466                                 } else if (Parent.TypeBuilder.Assembly == base_method.DeclaringType.Assembly) {
3467                                         //
3468                                         // protected within the same assembly - an error
3469                                         //
3470                                         return false;
3471                                 } else if ((thisp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem)) != 
3472                                            (base_classp & ~(MethodAttributes.Family | MethodAttributes.FamORAssem))) {
3473                                         //
3474                                         // protected ok, but other attributes differ - report an error
3475                                         //
3476                                         return false;
3477                                 }
3478                                 return true;
3479                         } else {
3480                                 return (thisp == base_classp);
3481                         }
3482                 }
3483
3484                 public override bool Define ()
3485                 {
3486                         if (IsInterface) {
3487                                 ModFlags = Modifiers.PUBLIC | Modifiers.ABSTRACT |
3488                                         Modifiers.VIRTUAL | (ModFlags & (Modifiers.UNSAFE | Modifiers.NEW));
3489
3490                                 flags = MethodAttributes.Public |
3491                                         MethodAttributes.Abstract |
3492                                         MethodAttributes.HideBySig |
3493                                         MethodAttributes.NewSlot |
3494                                         MethodAttributes.Virtual;
3495                         } else {
3496                                 Parent.PartialContainer.MethodModifiersValid (this);
3497
3498                                 flags = Modifiers.MethodAttr (ModFlags);
3499                         }
3500
3501                         if (IsExplicitImpl) {
3502                                 TypeExpr iface_texpr = MemberName.Left.GetTypeExpression ().ResolveAsTypeTerminal (this, false);
3503                                 if (iface_texpr == null)
3504                                         return false;
3505
3506                                 if ((ModFlags & Modifiers.PARTIAL) != 0) {
3507                                         Report.Error (754, Location, "A partial method `{0}' cannot explicitly implement an interface",
3508                                                 GetSignatureForError ());
3509                                 }
3510
3511                                 InterfaceType = iface_texpr.Type;
3512
3513                                 if (!InterfaceType.IsInterface) {
3514                                         Report.SymbolRelatedToPreviousError (InterfaceType);
3515                                         Report.Error (538, Location, "The type `{0}' in explicit interface declaration is not an interface",
3516                                                 TypeManager.CSharpName (InterfaceType));
3517                                 } else {
3518                                         Parent.PartialContainer.VerifyImplements (this);
3519                                 }
3520
3521                                 Modifiers.Check (Modifiers.AllowedExplicitImplFlags, explicit_mod_flags, 0, Location);
3522                         }
3523
3524                         return base.Define ();
3525                 }
3526
3527                 protected bool DefineParameters (Parameters parameters)
3528                 {
3529                         IResolveContext rc = GenericMethod == null ? this : (IResolveContext)ds;
3530
3531                         if (!parameters.Resolve (rc))
3532                                 return false;
3533
3534                         bool error = false;
3535                         for (int i = 0; i < parameters.Count; ++i) {
3536                                 Parameter p = parameters [i];
3537                                 if (p.CheckAccessibility (this))
3538                                         continue;
3539
3540                                 Type t = parameters.Types [i];
3541                                 Report.SymbolRelatedToPreviousError (t);
3542                                 if (this is Indexer)
3543                                         Report.Error (55, Location,
3544                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than indexer `{1}'",
3545                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3546                                 else if (this is Operator)
3547                                         Report.Error (57, Location,
3548                                                       "Inconsistent accessibility: parameter type `{0}' is less accessible than operator `{1}'",
3549                                                       TypeManager.CSharpName (t), GetSignatureForError ());
3550                                 else
3551                                         Report.Error (51, Location,
3552                                                 "Inconsistent accessibility: parameter type `{0}' is less accessible than method `{1}'",
3553                                                 TypeManager.CSharpName (t), GetSignatureForError ());
3554                                 error = true;
3555                         }
3556                         return !error;
3557                 }
3558
3559                 public override void Emit()
3560                 {
3561                         // for extern static method must be specified either DllImport attribute or MethodImplAttribute.
3562                         // We are more strict than Microsoft and report CS0626 as error
3563                         if ((ModFlags & Modifiers.EXTERN) != 0 && !is_external_implementation) {
3564                                 Report.Error (626, Location,
3565                                         "`{0}' is marked as an external but has no DllImport attribute. Consider adding a DllImport attribute to specify the external implementation",
3566                                         GetSignatureForError ());
3567                         }
3568
3569                         base.Emit ();
3570                 }
3571
3572                 public override bool EnableOverloadChecks (MemberCore overload)
3573                 {
3574                         //
3575                         // Two members can differ in their explicit interface
3576                         // type parameter only
3577                         //
3578                         InterfaceMemberBase imb = overload as InterfaceMemberBase;
3579                         if (imb != null && imb.IsExplicitImpl) {
3580                                 if (IsExplicitImpl) {
3581                                         caching_flags |= Flags.MethodOverloadsExist;
3582                                 }
3583                                 return true;
3584                         }
3585
3586                         return IsExplicitImpl;
3587                 }
3588
3589                 protected void Error_CannotChangeAccessModifiers (Location loc, MemberInfo base_method, MethodAttributes ma, string suffix)
3590                 {
3591                         Report.SymbolRelatedToPreviousError (base_method);
3592                         string base_name = TypeManager.GetFullNameSignature (base_method);
3593                         string this_name = GetSignatureForError ();
3594                         if (suffix != null) {
3595                                 base_name += suffix;
3596                                 this_name += suffix;
3597                         }
3598
3599                         Report.Error (507, loc, "`{0}': cannot change access modifiers when overriding `{1}' inherited member `{2}'",
3600                                 this_name, Modifiers.GetDescription (ma), base_name);
3601                 }
3602
3603                 protected static string Error722 {
3604                         get {
3605                                 return "`{0}': static types cannot be used as return types";
3606                         }
3607                 }
3608
3609                 /// <summary>
3610                 /// Gets base method and its return type
3611                 /// </summary>
3612                 protected abstract MethodInfo FindOutBaseMethod (ref Type base_ret_type);
3613
3614                 //
3615                 // The "short" name of this property / indexer / event.  This is the
3616                 // name without the explicit interface.
3617                 //
3618                 public string ShortName 
3619                 {
3620                         get { return MemberName.Name; }
3621                         set { SetMemberName (new MemberName (MemberName.Left, value, Location)); }
3622                 }
3623                 
3624                 //
3625                 // Returns full metadata method name
3626                 //
3627                 public string GetFullName (MemberName name)
3628                 {
3629                         if (!IsExplicitImpl)
3630                                 return name.Name;
3631
3632                         //
3633                         // When dealing with explicit members a full interface type
3634                         // name is added to member name to avoid possible name conflicts
3635                         //
3636                         // We use CSharpName which gets us full name with benefit of
3637                         // replacing predefined names which saves some space and name
3638                         // is still unique
3639                         //
3640                         return TypeManager.CSharpName (InterfaceType) + "." + name.Name;
3641                 }
3642
3643                 protected override bool VerifyClsCompliance ()
3644                 {
3645                         if (!base.VerifyClsCompliance ()) {
3646                                 if (IsInterface && HasClsCompliantAttribute && Parent.IsClsComplianceRequired ()) {
3647                                         Report.Warning (3010, 1, Location, "`{0}': CLS-compliant interfaces must have only CLS-compliant members", GetSignatureForError ());
3648                                 }
3649
3650                                 if ((ModFlags & Modifiers.ABSTRACT) != 0 && Parent.TypeBuilder.IsClass && IsExposedFromAssembly () && Parent.IsClsComplianceRequired ()) {
3651                                         Report.Warning (3011, 1, Location, "`{0}': only CLS-compliant members can be abstract", GetSignatureForError ());
3652                                 }
3653                                 return false;
3654                         }
3655
3656                         if (GenericMethod != null)
3657                                 GenericMethod.VerifyClsCompliance ();
3658
3659                         return true;
3660                 }
3661
3662                 public override bool IsUsed 
3663                 {
3664                         get { return IsExplicitImpl || base.IsUsed; }
3665                 }
3666
3667         }
3668
3669         public abstract class MethodOrOperator : MethodCore, IMethodData
3670         {
3671                 public MethodBuilder MethodBuilder;
3672                 ReturnParameter return_attributes;
3673                 ListDictionary declarative_security;
3674                 protected MethodData MethodData;
3675
3676                 static string[] attribute_targets = new string [] { "method", "return" };
3677
3678                 protected MethodOrOperator (DeclSpace parent, GenericMethod generic, FullNamedExpression type, int mod,
3679                                 int allowed_mod, MemberName name,
3680                                 Attributes attrs, Parameters parameters)
3681                         : base (parent, generic, type, mod, allowed_mod, name,
3682                                         attrs, parameters)
3683                 {
3684                 }
3685
3686                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
3687                 {
3688                         if (a.Target == AttributeTargets.ReturnValue) {
3689                                 if (return_attributes == null)
3690                                         return_attributes = new ReturnParameter (MethodBuilder, Location);
3691
3692                                 return_attributes.ApplyAttributeBuilder (a, cb);
3693                                 return;
3694                         }
3695
3696                         if (a.IsInternalMethodImplAttribute) {
3697                                 is_external_implementation = true;
3698                         }
3699
3700                         if (a.Type == TypeManager.dllimport_type) {
3701                                 const int extern_static = Modifiers.EXTERN | Modifiers.STATIC;
3702                                 if ((ModFlags & extern_static) != extern_static) {
3703                                         Report.Error (601, a.Location, "The DllImport attribute must be specified on a method marked `static' and `extern'");
3704                                 }
3705                                 is_external_implementation = true;
3706                         }
3707
3708                         if (a.IsValidSecurityAttribute ()) {
3709                                 if (declarative_security == null)
3710                                         declarative_security = new ListDictionary ();
3711                                 a.ExtractSecurityPermissionSet (declarative_security);
3712                                 return;
3713                         }
3714
3715                         if (MethodBuilder != null)
3716                                 MethodBuilder.SetCustomAttribute (cb);
3717                 }
3718
3719                 public override AttributeTargets AttributeTargets {
3720                         get {
3721                                 return AttributeTargets.Method; 
3722                         }
3723                 }
3724
3725                 protected override bool CheckForDuplications ()
3726                 {
3727                         string name = GetFullName (MemberName);
3728                         if (MemberName.IsGeneric)
3729                                 name = MemberName.MakeName (name, MemberName.TypeArguments);
3730
3731                         return Parent.MemberCache.CheckExistingMembersOverloads (this, name, Parameters);
3732                 }
3733
3734                 public virtual EmitContext CreateEmitContext (DeclSpace tc, ILGenerator ig)
3735                 {
3736                         return new EmitContext (
3737                                 this, tc, this.ds, Location, ig, MemberType, ModFlags, false);
3738                 }
3739
3740                 protected override bool ResolveMemberType ()
3741                 {
3742 #if GMCS_SOURCE
3743                         if (GenericMethod != null) {
3744                                 MethodBuilder = Parent.TypeBuilder.DefineMethod (GetFullName (MemberName), flags);
3745                                 if (!GenericMethod.Define (MethodBuilder))
3746                                         return false;
3747                         }
3748 #endif
3749
3750                         return base.ResolveMemberType ();
3751                 }
3752
3753                 public override bool Define ()
3754                 {
3755                         if (!base.Define ())
3756                                 return false;
3757
3758                         if (!CheckBase ())
3759                                 return false;
3760
3761                         if (block != null && block.IsIterator && !(Parent is IteratorStorey)) {
3762                                 //
3763                                 // Current method is turned into automatically generated
3764                                 // wrapper which creates an instance of iterator
3765                                 //
3766                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
3767                                 ModFlags |= Modifiers.DEBUGGER_HIDDEN;
3768                         }
3769
3770                         if (IsPartialDefinition) {
3771                                 caching_flags &= ~Flags.Excluded_Undetected;
3772                                 caching_flags |= Flags.Excluded;
3773                                 // Add to member cache only when a partial method implementation is not there
3774                                 if ((caching_flags & Flags.MethodOverloadsExist) == 0) {
3775                                         MethodBase mb = new PartialMethodDefinitionInfo (this);
3776                                         Parent.MemberCache.AddMember (mb, this);
3777                                         TypeManager.AddMethod (mb, this);
3778                                 }
3779
3780                                 return true;
3781                         }
3782
3783                         MethodData = new MethodData (
3784                                 this, ModFlags, flags, this, MethodBuilder, GenericMethod, base_method);
3785
3786                         if (!MethodData.Define (Parent.PartialContainer, GetFullName (MemberName)))
3787                                 return false;
3788                                         
3789                         MethodBuilder = MethodData.MethodBuilder;
3790
3791 #if GMCS_SOURCE                                         
3792                         if (MethodBuilder.IsGenericMethod)
3793                                 Parent.MemberCache.AddGenericMember (MethodBuilder, this);
3794 #endif                  
3795                         
3796                         Parent.MemberCache.AddMember (MethodBuilder, this);
3797
3798                         return true;
3799                 }
3800
3801                 protected override void DoMemberTypeIndependentChecks ()
3802                 {
3803                         base.DoMemberTypeIndependentChecks ();
3804
3805                         CheckAbstractAndExtern (block != null);
3806
3807                         if ((ModFlags & Modifiers.PARTIAL) != 0) {
3808                                 for (int i = 0; i < Parameters.Count; ++i) {
3809                                         if (Parameters.FixedParameters[i].ModFlags == Parameter.Modifier.OUT) {
3810                                                 Report.Error (752, Location, "`{0}': A partial method parameters cannot use `out' modifier",
3811                                                         GetSignatureForError ());
3812                                                 break;
3813                                         }
3814                                 }
3815                         }
3816                 }
3817
3818                 protected override void DoMemberTypeDependentChecks ()
3819                 {
3820                         base.DoMemberTypeDependentChecks ();
3821
3822                         if (!TypeManager.IsGenericParameter (MemberType)) {
3823                                 if (MemberType.IsAbstract && MemberType.IsSealed) {
3824                                         Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
3825                                 }
3826                         }
3827                 }
3828
3829                 public override void Emit ()
3830                 {
3831 #if GMCS_SOURCE                 
3832                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
3833                                 MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
3834                         if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
3835                                 MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
3836 #endif
3837                         if (OptAttributes != null)
3838                                 OptAttributes.Emit ();
3839
3840                         if (declarative_security != null) {
3841                                 foreach (DictionaryEntry de in declarative_security) {
3842                                         MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
3843                                 }
3844                         }
3845
3846                         base.Emit ();
3847                 }
3848
3849                 protected void Error_ConditionalAttributeIsNotValid ()
3850                 {
3851                         Report.Error (577, Location,
3852                                 "Conditional not valid on `{0}' because it is a constructor, destructor, operator or explicit interface implementation",
3853                                 GetSignatureForError ());
3854                 }
3855
3856                 public bool IsPartialDefinition {
3857                         get {
3858                                 return (ModFlags & Modifiers.PARTIAL) != 0 && Block == null;
3859                         }
3860                 }
3861
3862                 public bool IsPartialImplementation {
3863                         get {
3864                                 return (ModFlags & Modifiers.PARTIAL) != 0 && Block != null;
3865                         }
3866                 }
3867
3868                 public override string[] ValidAttributeTargets {
3869                         get {
3870                                 return attribute_targets;
3871                         }
3872                 }
3873
3874                 #region IMethodData Members
3875
3876                 public CallingConventions CallingConventions {
3877                         get {
3878                                 CallingConventions cc = Parameters.CallingConvention;
3879                                 if (!IsInterface)
3880                                         if ((ModFlags & Modifiers.STATIC) == 0)
3881                                                 cc |= CallingConventions.HasThis;
3882
3883                                 // FIXME: How is `ExplicitThis' used in C#?
3884                         
3885                                 return cc;
3886                         }
3887                 }
3888
3889                 public Type ReturnType {
3890                         get {
3891                                 return MemberType;
3892                         }
3893                 }
3894
3895                 public MemberName MethodName {
3896                         get {
3897                                 return MemberName;
3898                         }
3899                 }
3900
3901                 protected override bool CheckBase ()
3902                 {
3903                         if (!base.CheckBase ())
3904                                 return false;
3905
3906                         // TODO: Destructor should derive from MethodCore
3907                         if (base_method != null && (ModFlags & Modifiers.OVERRIDE) != 0 && Name == "Finalize" &&
3908                                 base_method.DeclaringType == TypeManager.object_type && !(this is Destructor)) {
3909                                 Report.Error (249, Location, "Do not override object.Finalize. Instead, provide a destructor");
3910                                 return false;
3911                         }
3912
3913                         return true;
3914                 }
3915
3916                 /// <summary>
3917                 /// Returns true if method has conditional attribute and the conditions is not defined (method is excluded).
3918                 /// </summary>
3919                 public bool IsExcluded () {
3920                         if ((caching_flags & Flags.Excluded_Undetected) == 0)
3921                                 return (caching_flags & Flags.Excluded) != 0;
3922
3923                         caching_flags &= ~Flags.Excluded_Undetected;
3924
3925                         if (base_method == null) {
3926                                 if (OptAttributes == null)
3927                                         return false;
3928
3929                                 if (TypeManager.conditional_attribute_type == null)
3930                                         return false;
3931
3932                                 Attribute[] attrs = OptAttributes.SearchMulti (TypeManager.conditional_attribute_type);
3933
3934                                 if (attrs == null)
3935                                         return false;
3936
3937                                 foreach (Attribute a in attrs) {
3938                                         string condition = a.GetConditionalAttributeValue ();
3939                                         if (condition == null)
3940                                                 return false;
3941
3942                                         if (Location.CompilationUnit.IsConditionalDefined (condition))
3943                                                 return false;
3944                                 }
3945
3946                                 caching_flags |= Flags.Excluded;
3947                                 return true;
3948                         }
3949
3950                         IMethodData md = TypeManager.GetMethod (TypeManager.DropGenericMethodArguments (base_method));
3951                         if (md == null) {
3952                                 if (AttributeTester.IsConditionalMethodExcluded (base_method, Location)) {
3953                                         caching_flags |= Flags.Excluded;
3954                                         return true;
3955                                 }
3956                                 return false;
3957                         }
3958
3959                         if (md.IsExcluded ()) {
3960                                 caching_flags |= Flags.Excluded;
3961                                 return true;
3962                         }
3963                         return false;
3964                 }
3965
3966                 GenericMethod IMethodData.GenericMethod {
3967                         get {
3968                                 return GenericMethod;
3969                         }
3970                 }
3971
3972                 public virtual void EmitExtraSymbolInfo (SourceMethod source)
3973                 { }
3974
3975                 #endregion
3976
3977         }
3978
3979         public class SourceMethod : IMethodDef
3980         {
3981                 MethodBase method;
3982                 SourceMethodBuilder builder;
3983
3984                 protected SourceMethod (DeclSpace parent, MethodBase method, ICompileUnit file)
3985                 {
3986                         this.method = method;
3987                         
3988                         builder = SymbolWriter.OpenMethod (file, parent.NamespaceEntry.SymbolFileID, this);
3989                 }
3990
3991                 public string Name {
3992                         get { return method.Name; }
3993                 }
3994
3995                 public int Token {
3996                         get {
3997                                 if (method is MethodBuilder)
3998                                         return ((MethodBuilder) method).GetToken ().Token;
3999                                 else if (method is ConstructorBuilder)
4000                                         return ((ConstructorBuilder) method).GetToken ().Token;
4001                                 else
4002                                         throw new NotSupportedException ();
4003                         }
4004                 }
4005
4006                 public void CloseMethod ()
4007                 {
4008                         SymbolWriter.CloseMethod ();
4009                 }
4010
4011                 public void SetRealMethodName (string name)
4012                 {
4013                         if (builder != null)
4014                                 builder.SetRealMethodName (name);
4015                 }
4016
4017                 public static SourceMethod Create (DeclSpace parent, MethodBase method, Block block)
4018                 {
4019                         if (!SymbolWriter.HasSymbolWriter)
4020                                 return null;
4021                         if (block == null)
4022                                 return null;
4023
4024                         Location start_loc = block.StartLocation;
4025                         if (start_loc.IsNull)
4026                                 return null;
4027
4028                         ICompileUnit compile_unit = start_loc.CompilationUnit;
4029                         if (compile_unit == null)
4030                                 return null;
4031
4032                         return new SourceMethod (parent, method, compile_unit);
4033                 }
4034         }
4035
4036         public class Method : MethodOrOperator {
4037
4038                 /// <summary>
4039                 ///   Modifiers allowed in a class declaration
4040                 /// </summary>
4041                 const int AllowedModifiers =
4042                         Modifiers.NEW |
4043                         Modifiers.PUBLIC |
4044                         Modifiers.PROTECTED |
4045                         Modifiers.INTERNAL |
4046                         Modifiers.PRIVATE |
4047                         Modifiers.STATIC |
4048                         Modifiers.VIRTUAL |
4049                         Modifiers.SEALED |
4050                         Modifiers.OVERRIDE |
4051                         Modifiers.ABSTRACT |
4052                         Modifiers.UNSAFE |
4053                         Modifiers.EXTERN;
4054
4055                 const int AllowedInterfaceModifiers =
4056                         Modifiers.NEW | Modifiers.UNSAFE;
4057
4058                 public Method (DeclSpace parent, GenericMethod generic,
4059                                FullNamedExpression return_type, int mod,
4060                                MemberName name, Parameters parameters, Attributes attrs)
4061                         : base (parent, generic, return_type, mod,
4062                                 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
4063                                 name, attrs, parameters)
4064                 {
4065                 }
4066
4067                 protected Method (DeclSpace parent, FullNamedExpression return_type, int mod, int amod,
4068                                         MemberName name, Parameters parameters, Attributes attrs)
4069                         : base (parent, null, return_type, mod, amod, name, attrs, parameters)
4070                 {
4071                 }
4072                 
4073                 public override string GetSignatureForError()
4074                 {
4075                         return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4076                 }
4077
4078                 void Error_DuplicateEntryPoint (MethodInfo b, Location location)
4079                 {
4080                         Report.Error (17, location,
4081                                 "Program `{0}' has more than one entry point defined: `{1}'",
4082                                 CodeGen.FileName, TypeManager.CSharpSignature(b));
4083                 }
4084
4085                 bool IsEntryPoint ()
4086                 {
4087                         if (ReturnType != TypeManager.void_type &&
4088                                 ReturnType != TypeManager.int32_type)
4089                                 return false;
4090
4091                         if (Parameters.Count == 0)
4092                                 return true;
4093
4094                         if (Parameters.Count > 1)
4095                                 return false;
4096
4097                         Type t = Parameters.Types [0];
4098                         return t.IsArray && t.GetArrayRank () == 1 &&
4099                                         TypeManager.GetElementType (t) == TypeManager.string_type &&
4100                                         (Parameters[0].ModFlags & ~Parameter.Modifier.PARAMS) == Parameter.Modifier.NONE;
4101                 }
4102
4103                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4104                 {
4105                         if (a.Type == TypeManager.conditional_attribute_type) {
4106                                 if (IsExplicitImpl) {
4107                                         Error_ConditionalAttributeIsNotValid ();
4108                                         return;
4109                                 }
4110
4111                                 if (ReturnType != TypeManager.void_type) {
4112                                         Report.Error (578, Location, "Conditional not valid on `{0}' because its return type is not void", GetSignatureForError ());
4113                                         return;
4114                                 }
4115
4116                                 if ((ModFlags & Modifiers.OVERRIDE) != 0) {
4117                                         Report.Error (243, Location, "Conditional not valid on `{0}' because it is an override method", GetSignatureForError ());
4118                                         return;
4119                                 }
4120
4121                                 if (IsInterface) {
4122                                         Report.Error (582, Location, "Conditional not valid on interface members");
4123                                         return;
4124                                 }
4125
4126                                 if (MethodData.implementing != null) {
4127                                         Report.SymbolRelatedToPreviousError (MethodData.implementing.DeclaringType);
4128                                         Report.Error (629, Location, "Conditional member `{0}' cannot implement interface member `{1}'",
4129                                                 GetSignatureForError (), TypeManager.CSharpSignature (MethodData.implementing));
4130                                         return;
4131                                 }
4132
4133                                 for (int i = 0; i < Parameters.Count; ++i) {
4134                                         if (Parameters.FixedParameters [i].ModFlags == Parameter.Modifier.OUT) {
4135                                                 Report.Error (685, Location, "Conditional method `{0}' cannot have an out parameter", GetSignatureForError ());
4136                                                 return;
4137                                         }
4138                                 }
4139                         }
4140
4141                         if (a.Type == TypeManager.extension_attribute_type) {
4142                                 a.Error_MisusedExtensionAttribute ();
4143                                 return;
4144                         }
4145
4146                         base.ApplyAttributeBuilder (a, cb);
4147                 }
4148
4149                 protected override bool CheckForDuplications ()
4150                 {
4151                         if (!base.CheckForDuplications ())
4152                                 return false;
4153
4154                         ArrayList ar = Parent.PartialContainer.Properties;
4155                         if (ar != null) {
4156                                 for (int i = 0; i < ar.Count; ++i) {
4157                                         PropertyBase pb = (PropertyBase) ar [i];
4158                                         if (pb.AreAccessorsDuplicateImplementation (this))
4159                                                 return false;
4160                                 }
4161                         }
4162
4163                         ar = Parent.PartialContainer.Indexers;
4164                         if (ar != null) {
4165                                 for (int i = 0; i < ar.Count; ++i) {
4166                                         PropertyBase pb = (PropertyBase) ar [i];
4167                                         if (pb.AreAccessorsDuplicateImplementation (this))
4168                                                 return false;
4169                                 }
4170                         }
4171
4172                         return true;
4173                 }
4174
4175                 //
4176                 // Creates the type
4177                 //
4178                 public override bool Define ()
4179                 {
4180                         if (!base.Define ())
4181                                 return false;
4182
4183                         if (RootContext.StdLib && TypeManager.IsSpecialType (ReturnType)) {
4184                                 Error1599 (Location, ReturnType);
4185                                 return false;
4186                         }
4187
4188                         if (ReturnType == TypeManager.void_type && Parameters.Count == 0 && 
4189                                 Name == "Finalize" && !(this is Destructor)) {
4190                                 Report.Warning (465, 1, Location, "Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?");
4191                         }
4192
4193                         if (base_method != null && (ModFlags & Modifiers.NEW) == 0) {
4194                                 if (Parameters.Count == 1 && ParameterTypes [0] == TypeManager.object_type && Name == "Equals")
4195                                         Parent.PartialContainer.Mark_HasEquals ();
4196                                 else if (Parameters.IsEmpty && Name == "GetHashCode")
4197                                         Parent.PartialContainer.Mark_HasGetHashCode ();
4198                         }
4199
4200                         if ((ModFlags & Modifiers.STATIC) == 0)
4201                                 return true;
4202
4203                         if (Parameters.HasExtensionMethodType) {
4204                                 if (Parent.IsStaticClass && !Parent.IsGeneric) {
4205                                         if (!Parent.IsTopLevel)
4206                                                 Report.Error (1109, Location, "`{0}': Extension methods cannot be defined in a nested class",
4207                                                         GetSignatureForError ());
4208
4209                                         if (TypeManager.extension_attribute_type == null) {
4210                                                 Report.Error (1110, Location,
4211                                                         "`{0}': Extension methods cannot be declared without a reference to System.Core.dll assembly. Add the assembly reference or remove `this' modifer from the first parameter",
4212                                                         GetSignatureForError ());
4213                                         } else if (TypeManager.extension_attribute_attr == null) {
4214                                                 ConstructorInfo ci = TypeManager.GetPredefinedConstructor (
4215                                                         TypeManager.extension_attribute_type, Location, System.Type.EmptyTypes);
4216
4217                                                 if (ci != null)
4218                                                         TypeManager.extension_attribute_attr = new CustomAttributeBuilder (ci, new object [0]);
4219                                         }
4220
4221                                         ModFlags |= Modifiers.METHOD_EXTENSION;
4222                                         Parent.ModFlags |= Modifiers.METHOD_EXTENSION;
4223                                         CodeGen.Assembly.HasExtensionMethods = true;
4224                                 } else {
4225                                         Report.Error (1106, Location, "`{0}': Extension methods must be defined in a non-generic static class",
4226                                                 GetSignatureForError ());
4227                                 }
4228                         }
4229
4230                         //
4231                         // This is used to track the Entry Point,
4232                         //
4233                         if (RootContext.NeedsEntryPoint &&
4234                                 Name == "Main" &&
4235                                 (RootContext.MainClass == null ||
4236                                 RootContext.MainClass == Parent.TypeBuilder.FullName)){
4237                                 if (IsEntryPoint ()) {
4238
4239                                         if (RootContext.EntryPoint == null) {
4240                                                 if (Parent.IsGeneric || MemberName.IsGeneric) {
4241                                                         Report.Warning (402, 4, Location, "`{0}': an entry point cannot be generic or in a generic type",
4242                                                                 GetSignatureForError ());
4243                                                 } else {
4244                                                         IMethodData md = TypeManager.GetMethod (MethodBuilder);
4245                                                         md.SetMemberIsUsed ();
4246
4247                                                         RootContext.EntryPoint = MethodBuilder;
4248                                                         RootContext.EntryPointLocation = Location;
4249                                                 }
4250                                         } else {
4251                                                 Error_DuplicateEntryPoint (RootContext.EntryPoint, RootContext.EntryPointLocation);
4252                                                 Error_DuplicateEntryPoint (MethodBuilder, Location);
4253                                         }
4254                                 } else {
4255                                         Report.Warning (28, 4, Location, "`{0}' has the wrong signature to be an entry point",
4256                                                 GetSignatureForError ());
4257                                 }
4258                         }
4259
4260                         return true;
4261                 }
4262
4263                 //
4264                 // Emits the code
4265                 // 
4266                 public override void Emit ()
4267                 {
4268                         try {
4269                                 Report.Debug (64, "METHOD EMIT", this, MethodBuilder, Location, Block, MethodData);
4270                                 if (IsPartialDefinition) {
4271                                         //
4272                                         // Do attribute checks only when partial implementation does not exist
4273                                         //
4274                                         if (MethodBuilder == null)
4275                                                 base.Emit ();
4276
4277                                         return;
4278                                 }
4279
4280                                 if ((ModFlags & Modifiers.PARTIAL) != 0 && (caching_flags & Flags.PartialDefinitionExists) == 0)
4281                                         Report.Error (759, Location, "A partial method `{0}' implementation is missing a partial method declaration",
4282                                                 GetSignatureForError ());
4283
4284                                 MethodData.Emit (Parent);
4285                                 base.Emit ();
4286                                 
4287 #if GMCS_SOURCE                         
4288                                 if ((ModFlags & Modifiers.METHOD_EXTENSION) != 0)
4289                                         MethodBuilder.SetCustomAttribute (TypeManager.extension_attribute_attr);
4290 #endif
4291
4292                                 Block = null;
4293                                 MethodData = null;
4294                         } catch {
4295                                 Console.WriteLine ("Internal compiler error at {0}: exception caught while emitting {1}",
4296                                                    Location, MethodBuilder);
4297                                 throw;
4298                         }
4299                 }
4300
4301                 public override bool EnableOverloadChecks (MemberCore overload)
4302                 {
4303                         // TODO: It can be deleted when members will be defined in correct order
4304                         if (overload is Operator)
4305                                 return overload.EnableOverloadChecks (this);
4306
4307                         if (overload is Indexer)
4308                                 return false;
4309
4310                         return base.EnableOverloadChecks (overload);
4311                 }
4312
4313                 public static void Error1599 (Location loc, Type t)
4314                 {
4315                         Report.Error (1599, loc, "Method or delegate cannot return type `{0}'", TypeManager.CSharpName (t));
4316                 }
4317
4318                 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4319                 {
4320                         MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindMemberToOverride (
4321                                 Parent.TypeBuilder, Name, Parameters, GenericMethod, false);
4322
4323                         if (mi == null)
4324                                 return null;
4325
4326                         if (mi.IsSpecialName)
4327                                 return null;
4328
4329                         base_ret_type = TypeManager.TypeToCoreType (mi.ReturnType);
4330                         return mi;
4331                 }
4332
4333                 public void SetPartialDefinition (Method methodDefinition)
4334                 {
4335                         caching_flags |= Flags.PartialDefinitionExists;
4336                         methodDefinition.MethodBuilder = MethodBuilder;
4337                         if (methodDefinition.attributes == null)
4338                                 return;
4339
4340                         if (attributes == null) {
4341                                 attributes = methodDefinition.attributes;
4342                         } else {
4343                                 attributes.Attrs.AddRange (methodDefinition.attributes.Attrs);
4344                         }
4345                 }
4346
4347                 protected override bool VerifyClsCompliance ()
4348                 {
4349                         if (!base.VerifyClsCompliance ())
4350                                 return false;
4351
4352                         if (ParameterInfo.Count > 0) {
4353                                 ArrayList al = (ArrayList)Parent.PartialContainer.MemberCache.Members [Name];
4354                                 if (al.Count > 1)
4355                                         MemberCache.VerifyClsParameterConflict (al, this, MethodBuilder);
4356                         }
4357
4358                         return true;
4359                 }
4360         }
4361
4362         public abstract class ConstructorInitializer : ExpressionStatement
4363         {
4364                 ArrayList argument_list;
4365                 MethodGroupExpr base_constructor_group;
4366                 
4367                 public ConstructorInitializer (ArrayList argument_list, Location loc)
4368                 {
4369                         this.argument_list = argument_list;
4370                         this.loc = loc;
4371                 }
4372
4373                 public ArrayList Arguments {
4374                         get {
4375                                 return argument_list;
4376                         }
4377                 }
4378
4379                 public override Expression CreateExpressionTree (EmitContext ec)
4380                 {
4381                         throw new NotSupportedException ("ET");
4382                 }
4383
4384                 public bool Resolve (ConstructorBuilder caller_builder, EmitContext ec)
4385                 {
4386                         if (argument_list != null){
4387                                 foreach (Argument a in argument_list){
4388                                         if (!a.Resolve (ec, loc))
4389                                                 return false;
4390                                 }
4391                         }
4392
4393                         if (this is ConstructorBaseInitializer) {
4394                                 if (ec.ContainerType.BaseType == null)
4395                                         return true;
4396
4397                                 type = ec.ContainerType.BaseType;
4398                                 if (ec.ContainerType.IsValueType) {
4399                                         Report.Error (522, loc,
4400                                                 "`{0}': Struct constructors cannot call base constructors", TypeManager.CSharpSignature (caller_builder));
4401                                         return false;
4402                                 }
4403                         } else {
4404                                 //
4405                                 // It is legal to have "this" initializers that take no arguments
4406                                 // in structs, they are just no-ops.
4407                                 //
4408                                 // struct D { public D (int a) : this () {}
4409                                 //
4410                                 if (ec.ContainerType.IsValueType && argument_list == null)
4411                                         return true;
4412                                 
4413                                 type = ec.ContainerType;
4414                         }
4415
4416                         base_constructor_group = MemberLookupFinal (
4417                                 ec, null, type, ConstructorBuilder.ConstructorName, MemberTypes.Constructor,
4418                                 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
4419                                 loc) as MethodGroupExpr;
4420                         
4421                         if (base_constructor_group == null)
4422                                 return false;
4423                         
4424                         base_constructor_group = base_constructor_group.OverloadResolve (
4425                                 ec, ref argument_list, false, loc);
4426                         
4427                         if (base_constructor_group == null)
4428                                 return false;
4429                         
4430                         ConstructorInfo base_ctor = (ConstructorInfo)base_constructor_group;
4431                         
4432                         if (base_ctor == caller_builder){
4433                                 Report.Error (516, loc, "Constructor `{0}' cannot call itself", TypeManager.CSharpSignature (caller_builder));
4434                         }
4435                                                 
4436                         return true;
4437                 }
4438
4439                 public override Expression DoResolve (EmitContext ec)
4440                 {
4441                         throw new NotSupportedException ();
4442                 }
4443
4444                 public override void Emit (EmitContext ec)
4445                 {
4446                         // It can be null for static initializers
4447                         if (base_constructor_group == null)
4448                                 return;
4449                         
4450                         ec.Mark (loc);
4451                         if (!ec.IsStatic)
4452                                 base_constructor_group.InstanceExpression = ec.GetThis (loc);
4453                         
4454                         base_constructor_group.EmitCall (ec, argument_list);
4455                 }
4456
4457                 public override void EmitStatement (EmitContext ec)
4458                 {
4459                         Emit (ec);
4460                 }
4461         }
4462
4463         public class ConstructorBaseInitializer : ConstructorInitializer {
4464                 public ConstructorBaseInitializer (ArrayList argument_list, Location l) :
4465                         base (argument_list, l)
4466                 {
4467                 }
4468         }
4469
4470         class GeneratedBaseInitializer: ConstructorBaseInitializer {
4471                 public GeneratedBaseInitializer (Location loc):
4472                         base (null, loc)
4473                 {
4474                 }
4475         }
4476
4477         public class ConstructorThisInitializer : ConstructorInitializer {
4478                 public ConstructorThisInitializer (ArrayList argument_list, Location l) :
4479                         base (argument_list, l)
4480                 {
4481                 }
4482         }
4483         
4484         public class Constructor : MethodCore, IMethodData {
4485                 public ConstructorBuilder ConstructorBuilder;
4486                 public ConstructorInitializer Initializer;
4487                 ListDictionary declarative_security;
4488                 bool has_compliant_args;
4489
4490                 // <summary>
4491                 //   Modifiers allowed for a constructor.
4492                 // </summary>
4493                 public const int AllowedModifiers =
4494                         Modifiers.PUBLIC |
4495                         Modifiers.PROTECTED |
4496                         Modifiers.INTERNAL |
4497                         Modifiers.STATIC |
4498                         Modifiers.UNSAFE |
4499                         Modifiers.EXTERN |              
4500                         Modifiers.PRIVATE;
4501
4502                 static readonly string[] attribute_targets = new string [] { "method" };
4503
4504                 //
4505                 // The spec claims that static is not permitted, but
4506                 // my very own code has static constructors.
4507                 //
4508                 public Constructor (DeclSpace parent, string name, int mod, Attributes attrs, Parameters args,
4509                                     ConstructorInitializer init, Location loc)
4510                         : base (parent, null, null, mod, AllowedModifiers,
4511                                 new MemberName (name, loc), attrs, args)
4512                 {
4513                         Initializer = init;
4514                 }
4515
4516                 public bool HasCompliantArgs {
4517                         get { return has_compliant_args; }
4518                 }
4519
4520                 public override AttributeTargets AttributeTargets {
4521                         get { return AttributeTargets.Constructor; }
4522                 }
4523
4524                 //
4525                 // Returns true if this is a default constructor
4526                 //
4527                 public bool IsDefault ()
4528                 {
4529                         if ((ModFlags & Modifiers.STATIC) != 0)
4530                                 return Parameters.IsEmpty;
4531                         
4532                         return Parameters.IsEmpty &&
4533                                         (Initializer is ConstructorBaseInitializer) &&
4534                                         (Initializer.Arguments == null);
4535                 }
4536
4537                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
4538                 {
4539                         if (a.IsValidSecurityAttribute ()) {
4540                                 if (declarative_security == null) {
4541                                         declarative_security = new ListDictionary ();
4542                                 }
4543                                 a.ExtractSecurityPermissionSet (declarative_security);
4544                                 return;
4545                         }
4546
4547                         if (a.IsInternalMethodImplAttribute) {
4548                                 is_external_implementation = true;
4549                         }
4550
4551                         ConstructorBuilder.SetCustomAttribute (cb);
4552                 }
4553
4554                 protected override bool CheckBase ()
4555                 {
4556                         if ((ModFlags & Modifiers.STATIC) != 0) {
4557                                 if (!Parameters.IsEmpty) {
4558                                         Report.Error (132, Location, "`{0}': The static constructor must be parameterless",
4559                                                 GetSignatureForError ());
4560                                         return false;
4561                                 }
4562
4563                                 // the rest can be ignored
4564                                 return true;
4565                         }
4566
4567                         // Check whether arguments were correct.
4568                         if (!DefineParameters (Parameters))
4569                                 return false;
4570
4571                         if ((caching_flags & Flags.MethodOverloadsExist) != 0)
4572                                 Parent.MemberCache.CheckExistingMembersOverloads (this, ConstructorInfo.ConstructorName,
4573                                         Parameters);
4574
4575                         if (Parent.PartialContainer.Kind == Kind.Struct) {
4576                                 if (Parameters.Count == 0) {
4577                                         Report.Error (568, Location, 
4578                                                 "Structs cannot contain explicit parameterless constructors");
4579                                         return false;
4580                                 }
4581                         }
4582
4583                         CheckProtectedModifier ();
4584                         
4585                         return true;
4586                 }
4587                 
4588                 //
4589                 // Creates the ConstructorBuilder
4590                 //
4591                 public override bool Define ()
4592                 {
4593                         if (ConstructorBuilder != null)
4594                                 return true;
4595
4596                         MethodAttributes ca = (MethodAttributes.RTSpecialName |
4597                                                MethodAttributes.SpecialName);
4598                         
4599                         if ((ModFlags & Modifiers.STATIC) != 0) {
4600                                 ca |= MethodAttributes.Static | MethodAttributes.Private;
4601                         } else {
4602                                 ca |= MethodAttributes.HideBySig;
4603
4604                                 if ((ModFlags & Modifiers.PUBLIC) != 0)
4605                                         ca |= MethodAttributes.Public;
4606                                 else if ((ModFlags & Modifiers.PROTECTED) != 0){
4607                                         if ((ModFlags & Modifiers.INTERNAL) != 0)
4608                                                 ca |= MethodAttributes.FamORAssem;
4609                                         else 
4610                                                 ca |= MethodAttributes.Family;
4611                                 } else if ((ModFlags & Modifiers.INTERNAL) != 0)
4612                                         ca |= MethodAttributes.Assembly;
4613                                 else
4614                                         ca |= MethodAttributes.Private;
4615                         }
4616
4617                         if (!CheckAbstractAndExtern (block != null))
4618                                 return false;
4619                         
4620                         // Check if arguments were correct.
4621                         if (!CheckBase ())
4622                                 return false;
4623
4624                         ConstructorBuilder = Parent.TypeBuilder.DefineConstructor (
4625                                 ca, CallingConventions,
4626                                 Parameters.GetEmitTypes ());
4627
4628                         if (Parent.PartialContainer.IsComImport) {
4629                                 if (!IsDefault ()) {
4630                                         Report.Error (669, Location, "`{0}': A class with the ComImport attribute cannot have a user-defined constructor",
4631                                                 Parent.GetSignatureForError ());
4632                                 }
4633                                 ConstructorBuilder.SetImplementationFlags (MethodImplAttributes.InternalCall);
4634                         }
4635                         
4636                         Parent.MemberCache.AddMember (ConstructorBuilder, this);
4637                         TypeManager.AddMethod (ConstructorBuilder, this);
4638                         
4639                         // It's here only to report an error
4640                         if (block != null && block.IsIterator) {
4641                                 member_type = TypeManager.void_type;
4642                                 Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
4643                         }
4644
4645                         return true;
4646                 }
4647
4648                 //
4649                 // Emits the code
4650                 //
4651                 public override void Emit ()
4652                 {
4653                         if ((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0)
4654                                 ConstructorBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
4655
4656                         if (OptAttributes != null)
4657                                 OptAttributes.Emit ();
4658
4659                         base.Emit ();
4660
4661                         EmitContext ec = CreateEmitContext (null, null);
4662
4663                         //
4664                         // If we use a "this (...)" constructor initializer, then
4665                         // do not emit field initializers, they are initialized in the other constructor
4666                         //
4667                         bool emit_field_initializers = ((ModFlags & Modifiers.STATIC) != 0) ||
4668                                 !(Initializer is ConstructorThisInitializer);
4669
4670                         if (emit_field_initializers)
4671                                 Parent.PartialContainer.ResolveFieldInitializers (ec);
4672
4673                         if (block != null) {
4674                                 // If this is a non-static `struct' constructor and doesn't have any
4675                                 // initializer, it must initialize all of the struct's fields.
4676                                 if ((Parent.PartialContainer.Kind == Kind.Struct) &&
4677                                         ((ModFlags & Modifiers.STATIC) == 0) && (Initializer == null))
4678                                         block.AddThisVariable (Parent, Location);
4679
4680                                 if (!block.ResolveMeta (ec, ParameterInfo))
4681                                         block = null;
4682
4683                                 if (block != null && (ModFlags & Modifiers.STATIC) == 0){
4684                                         if (Parent.PartialContainer.Kind == Kind.Class && Initializer == null)
4685                                                 Initializer = new GeneratedBaseInitializer (Location);
4686
4687                                         //
4688                                         // Spec mandates that Initializers will not have `this' access
4689                                         //
4690                                         if (Initializer != null) {
4691                                                 ec.IsStatic = true;
4692                                                 Initializer.Resolve (ConstructorBuilder, ec);
4693                                                 ec.IsStatic = false;
4694                                                 block.AddScopeStatement (new StatementExpression (Initializer));
4695                                         }
4696                                 }
4697                         }
4698
4699                         Parameters.ApplyAttributes (ConstructorBuilder);
4700                         
4701                         SourceMethod source = null;
4702                         if (block == null)
4703                                 ec.OmitDebuggingInfo = true;
4704                         else
4705                                 source = SourceMethod.Create (Parent, ConstructorBuilder, block);
4706
4707                         bool unreachable = false;
4708                         if (block != null) {
4709                                 if (!ec.ResolveTopBlock (null, block, ParameterInfo, this, out unreachable))
4710                                         return;
4711
4712                                 ec.EmitMeta (block);
4713
4714                                 if (Report.Errors > 0)
4715                                         return;
4716
4717                                 ec.EmitResolvedTopBlock (block, unreachable);
4718                         }
4719
4720                         if (source != null)
4721                                 source.CloseMethod ();
4722
4723                         if (declarative_security != null) {
4724                                 foreach (DictionaryEntry de in declarative_security) {
4725                                         ConstructorBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
4726                                 }
4727                         }
4728
4729                         block = null;
4730                 }
4731
4732                 // Is never override
4733                 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
4734                 {
4735                         return null;
4736                 }
4737
4738                 public override string GetSignatureForError()
4739                 {
4740                         return base.GetSignatureForError () + Parameters.GetSignatureForError ();
4741                 }
4742
4743                 public override string[] ValidAttributeTargets {
4744                         get {
4745                                 return attribute_targets;
4746                         }
4747                 }
4748
4749                 protected override bool VerifyClsCompliance ()
4750                 {
4751                         if (!base.VerifyClsCompliance () || !IsExposedFromAssembly ()) {
4752                                 return false;
4753                         }
4754                         
4755                         if (ParameterInfo.Count > 0) {
4756                                 ArrayList al = (ArrayList)Parent.MemberCache.Members [".ctor"];
4757                                 if (al.Count > 2)
4758                                         MemberCache.VerifyClsParameterConflict (al, this, ConstructorBuilder);
4759  
4760                                 if (TypeManager.IsSubclassOf (Parent.TypeBuilder, TypeManager.attribute_type)) {
4761                                         foreach (Type param in Parameters.Types) {
4762                                                 if (param.IsArray) {
4763                                                         return true;
4764                                                 }
4765                                         }
4766                                 }
4767                         }
4768                         has_compliant_args = true;
4769                         return true;
4770                 }
4771
4772                 #region IMethodData Members
4773
4774                 public System.Reflection.CallingConventions CallingConventions {
4775                         get {
4776                                 CallingConventions cc = Parameters.CallingConvention;
4777
4778                                 if (Parent.PartialContainer.Kind == Kind.Class)
4779                                         if ((ModFlags & Modifiers.STATIC) == 0)
4780                                                 cc |= CallingConventions.HasThis;
4781
4782                                 // FIXME: How is `ExplicitThis' used in C#?
4783                         
4784                                 return cc;
4785                         }
4786                 }
4787
4788                 public MemberName MethodName {
4789                         get {
4790                                 return MemberName;
4791                         }
4792                 }
4793
4794                 public Type ReturnType {
4795                         get {
4796                                 return MemberType;
4797                         }
4798                 }
4799
4800                 public EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
4801                 {
4802                         ILGenerator ig_ = ConstructorBuilder.GetILGenerator ();
4803                         EmitContext ec = new EmitContext (this, Parent, Location, ig_, TypeManager.void_type, ModFlags, true);
4804                         ec.CurrentBlock = block;
4805                         return ec;
4806                 }
4807
4808                 public bool IsExcluded()
4809                 {
4810                         return false;
4811                 }
4812
4813                 GenericMethod IMethodData.GenericMethod {
4814                         get {
4815                                 return null;
4816                         }
4817                 }
4818
4819                 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
4820                 { }
4821
4822                 #endregion
4823         }
4824
4825         /// <summary>
4826         /// Interface for MethodData class. Holds links to parent members to avoid member duplication.
4827         /// </summary>
4828         public interface IMethodData
4829         {
4830                 CallingConventions CallingConventions { get; }
4831                 Location Location { get; }
4832                 MemberName MethodName { get; }
4833                 Type ReturnType { get; }
4834                 GenericMethod GenericMethod { get; }
4835                 Parameters ParameterInfo { get; }
4836
4837                 Attributes OptAttributes { get; }
4838                 ToplevelBlock Block { get; set; }
4839
4840                 EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
4841                 ObsoleteAttribute GetObsoleteAttribute ();
4842                 string GetSignatureForError ();
4843                 bool IsExcluded ();
4844                 bool IsClsComplianceRequired ();
4845                 void SetMemberIsUsed ();
4846                 void EmitExtraSymbolInfo (SourceMethod source);
4847         }
4848
4849         //
4850         // Encapsulates most of the Method's state
4851         //
4852         public class MethodData {
4853 #if GMCS_SOURCE
4854                 static FieldInfo methodbuilder_attrs_field;
4855 #endif
4856                 public readonly IMethodData method;
4857
4858                 public readonly GenericMethod GenericMethod;
4859
4860                 //
4861                 // Are we implementing an interface ?
4862                 //
4863                 public MethodInfo implementing;
4864
4865                 //
4866                 // Protected data.
4867                 //
4868                 protected InterfaceMemberBase member;
4869                 protected int modifiers;
4870                 protected MethodAttributes flags;
4871                 protected Type declaring_type;
4872                 protected MethodInfo parent_method;
4873
4874                 MethodBuilder builder = null;
4875                 public MethodBuilder MethodBuilder {
4876                         get {
4877                                 return builder;
4878                         }
4879                 }
4880
4881                 public Type DeclaringType {
4882                         get {
4883                                 return declaring_type;
4884                         }
4885                 }
4886
4887                 public MethodData (InterfaceMemberBase member,
4888                                    int modifiers, MethodAttributes flags, IMethodData method)
4889                 {
4890                         this.member = member;
4891                         this.modifiers = modifiers;
4892                         this.flags = flags;
4893
4894                         this.method = method;
4895                 }
4896
4897                 public MethodData (InterfaceMemberBase member, 
4898                                    int modifiers, MethodAttributes flags, 
4899                                    IMethodData method, MethodBuilder builder,
4900                                    GenericMethod generic, MethodInfo parent_method)
4901                         : this (member, modifiers, flags, method)
4902                 {
4903                         this.builder = builder;
4904                         this.GenericMethod = generic;
4905                         this.parent_method = parent_method;
4906                 }
4907
4908                 public bool Define (DeclSpace parent, string method_full_name)
4909                 {
4910                         string name = method.MethodName.Basename;
4911
4912                         TypeContainer container = parent.PartialContainer;
4913
4914                         PendingImplementation pending = container.PendingImplementations;
4915                         if (pending != null){
4916                                 implementing = pending.IsInterfaceMethod (name, member.InterfaceType, this);
4917
4918                                 if (member.InterfaceType != null){
4919                                         if (implementing == null){
4920                                                 if (member is PropertyBase) {
4921                                                         Report.Error (550, method.Location, "`{0}' is an accessor not found in interface member `{1}{2}'",
4922                                                                       method.GetSignatureForError (), TypeManager.CSharpName (member.InterfaceType),
4923                                                                       member.GetSignatureForError ().Substring (member.GetSignatureForError ().LastIndexOf ('.')));
4924
4925                                                 } else {
4926                                                         Report.Error (539, method.Location,
4927                                                                       "`{0}.{1}' in explicit interface declaration is not a member of interface",
4928                                                                       TypeManager.CSharpName (member.InterfaceType), member.ShortName);
4929                                                 }
4930                                                 return false;
4931                                         }
4932                                         if (implementing.IsSpecialName && !(method is AbstractPropertyEventMethod)) {
4933                                                 Report.SymbolRelatedToPreviousError (implementing);
4934                                                 Report.Error (683, method.Location, "`{0}' explicit method implementation cannot implement `{1}' because it is an accessor",
4935                                                         member.GetSignatureForError (), TypeManager.CSharpSignature (implementing));
4936                                                 return false;
4937                                         }
4938                                 } else {
4939                                         if (implementing != null) {
4940                                                 AbstractPropertyEventMethod prop_method = method as AbstractPropertyEventMethod;
4941                                                 if (prop_method == null) {
4942                                                         if (TypeManager.IsSpecialMethod (implementing)) {
4943                                                                 Report.SymbolRelatedToPreviousError (implementing);
4944                                                                 Report.Error (470, method.Location, "Method `{0}' cannot implement interface accessor `{1}.{2}'",
4945                                                                         method.GetSignatureForError (), TypeManager.CSharpSignature (implementing),
4946                                                                         implementing.Name.StartsWith ("get_") ? "get" : "set");
4947                                                         }
4948                                                 } else if (implementing.DeclaringType.IsInterface) {
4949                                                         if (!implementing.IsSpecialName) {
4950                                                                 Report.SymbolRelatedToPreviousError (implementing);
4951                                                                 Report.Error (686, method.Location, "Accessor `{0}' cannot implement interface member `{1}' for type `{2}'. Use an explicit interface implementation",
4952                                                                         method.GetSignatureForError (), TypeManager.CSharpSignature (implementing), container.GetSignatureForError ());
4953                                                                 return false;
4954                                                         }
4955                                                         PropertyBase.PropertyMethod pm = prop_method as PropertyBase.PropertyMethod;
4956                                                         if (pm != null && pm.HasCustomAccessModifier && (pm.ModFlags & Modifiers.PUBLIC) == 0) {
4957                                                                 Report.SymbolRelatedToPreviousError (implementing);
4958                                                                 Report.Error (277, method.Location, "Accessor `{0}' must be declared public to implement interface member `{1}'",
4959                                                                         method.GetSignatureForError (), TypeManager.CSharpSignature (implementing, true));
4960                                                                 return false;
4961                                                         }
4962                                                 }
4963                                         }
4964                                 }
4965                         }
4966
4967                         //
4968                         // For implicit implementations, make sure we are public, for
4969                         // explicit implementations, make sure we are private.
4970                         //
4971                         if (implementing != null){
4972                                 //
4973                                 // Setting null inside this block will trigger a more
4974                                 // verbose error reporting for missing interface implementations
4975                                 //
4976                                 // The "candidate" function has been flagged already
4977                                 // but it wont get cleared
4978                                 //
4979                                 if (member.IsExplicitImpl){
4980                                         if (method.ParameterInfo.HasParams && !TypeManager.GetParameterData (implementing).HasParams) {
4981                                                 Report.SymbolRelatedToPreviousError (implementing);
4982                                                 Report.Error (466, method.Location, "`{0}': the explicit interface implementation cannot introduce the params modifier",
4983                                                         method.GetSignatureForError ());
4984                                                 return false;
4985                                         }
4986                                 } else {
4987                                         if (implementing.DeclaringType.IsInterface) {
4988                                                 //
4989                                                 // If this is an interface method implementation,
4990                                                 // check for public accessibility
4991                                                 //
4992                                                 if ((flags & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
4993                                                 {
4994                                                         implementing = null;
4995                                                 }
4996                                         } else if ((flags & MethodAttributes.MemberAccessMask) == MethodAttributes.Private){
4997                                                 // We may never be private.
4998                                                 implementing = null;
4999
5000                                         } else if ((modifiers & Modifiers.OVERRIDE) == 0){
5001                                                 //
5002                                                 // We may be protected if we're overriding something.
5003                                                 //
5004                                                 implementing = null;
5005                                         }
5006                                 }
5007                                         
5008                                 //
5009                                 // Static is not allowed
5010                                 //
5011                                 if ((modifiers & Modifiers.STATIC) != 0){
5012                                         implementing = null;
5013                                 }
5014                         }
5015                         
5016                         //
5017                         // If implementing is still valid, set flags
5018                         //
5019                         if (implementing != null){
5020                                 //
5021                                 // When implementing interface methods, set NewSlot
5022                                 // unless, we are overwriting a method.
5023                                 //
5024                                 if (implementing.DeclaringType.IsInterface){
5025                                         if ((modifiers & Modifiers.OVERRIDE) == 0)
5026                                                 flags |= MethodAttributes.NewSlot;
5027                                 }
5028                                 flags |=
5029                                         MethodAttributes.Virtual |
5030                                         MethodAttributes.HideBySig;
5031
5032                                 // Set Final unless we're virtual, abstract or already overriding a method.
5033                                 if ((modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT | Modifiers.OVERRIDE)) == 0)
5034                                         flags |= MethodAttributes.Final;
5035                         }
5036
5037                         DefineMethodBuilder (container, method_full_name, method.ParameterInfo);
5038
5039                         if (builder == null)
5040                                 return false;
5041
5042                         if (container.CurrentType != null)
5043                                 declaring_type = container.CurrentType;
5044                         else
5045                                 declaring_type = container.TypeBuilder;
5046
5047                         if (implementing != null && member.IsExplicitImpl) {
5048                                         container.TypeBuilder.DefineMethodOverride (builder, implementing);
5049                         }
5050
5051                         TypeManager.AddMethod (builder, method);
5052
5053                         if (GenericMethod != null) {
5054                                 bool is_override = member.IsExplicitImpl |
5055                                         ((modifiers & Modifiers.OVERRIDE) != 0);
5056
5057                                 if (implementing != null)
5058                                         parent_method = implementing;
5059
5060                                 EmitContext ec = method.CreateEmitContext (container, null);
5061                                 if (!GenericMethod.DefineType (ec, builder, parent_method, is_override))
5062                                         return false;
5063                         }
5064
5065                         return true;
5066                 }
5067
5068
5069                 /// <summary>
5070                 /// Create the MethodBuilder for the method 
5071                 /// </summary>
5072                 void DefineMethodBuilder (TypeContainer container, string method_name, Parameters param)
5073                 {
5074                         if (builder == null) {
5075                                 builder = container.TypeBuilder.DefineMethod (
5076                                         method_name, flags, method.CallingConventions,
5077                                         method.ReturnType, param.GetEmitTypes ());
5078                                 return;
5079                         }
5080
5081 #if GMCS_SOURCE
5082                         //
5083                         // Generic method has been already defined to resolve method parameters
5084                         // correctly when they use type parameters
5085                         //
5086                         builder.SetParameters (param.GetEmitTypes ());
5087                         builder.SetReturnType (method.ReturnType);
5088
5089                         if (builder.Attributes != flags) {
5090                                 try {
5091                                         if (methodbuilder_attrs_field == null)
5092                                                 methodbuilder_attrs_field = typeof (MethodBuilder).GetField ("attrs", BindingFlags.NonPublic | BindingFlags.Instance);
5093                                         methodbuilder_attrs_field.SetValue (builder, flags);
5094                                 } catch {
5095                                         Report.RuntimeMissingSupport (method.Location, "Generic method MethodAttributes");
5096                                 }
5097                         }
5098 #else
5099                         throw new InternalErrorException ();
5100 #endif
5101                 }
5102
5103                 //
5104                 // Emits the code
5105                 // 
5106                 public void Emit (DeclSpace parent)
5107                 {
5108                         ToplevelBlock block = method.Block;
5109
5110                         EmitContext ec;
5111                         if (block != null)
5112                                 ec = method.CreateEmitContext (parent, builder.GetILGenerator ());
5113                         else
5114                                 ec = method.CreateEmitContext (parent, null);
5115
5116                         method.ParameterInfo.ApplyAttributes (MethodBuilder);
5117
5118                         if (GenericMethod != null)
5119                                 GenericMethod.EmitAttributes ();
5120
5121                         //
5122                         // clear the pending implementation flag
5123                         //
5124                         if (implementing != null)
5125                                 parent.PartialContainer.PendingImplementations.ImplementMethod (method.MethodName.Basename,
5126                                         member.InterfaceType, this, member.IsExplicitImpl);
5127
5128                         SourceMethod source = SourceMethod.Create (parent, MethodBuilder, method.Block);
5129
5130                         //
5131                         // Handle destructors specially
5132                         //
5133                         // FIXME: This code generates buggy code
5134                         //
5135                         if (member is Destructor)
5136                                 EmitDestructor (ec, block);
5137                         else
5138                                 ec.EmitTopBlock (method, block);
5139
5140                         if (source != null) {
5141                                 method.EmitExtraSymbolInfo (source);
5142                                 source.CloseMethod ();
5143                         }
5144                 }
5145
5146                 void EmitDestructor (EmitContext ec, ToplevelBlock block)
5147                 {
5148                         ILGenerator ig = ec.ig;
5149                         
5150                         Label finish = ig.DefineLabel ();
5151
5152                         block.SetDestructor ();
5153                         
5154                         ig.BeginExceptionBlock ();
5155                         ec.ReturnLabel = finish;
5156                         ec.HasReturnLabel = true;
5157                         ec.EmitTopBlock (method, block);
5158                         
5159                         // ig.MarkLabel (finish);
5160                         ig.BeginFinallyBlock ();
5161                         
5162                         if (ec.ContainerType.BaseType != null) {
5163                                 Expression member_lookup = Expression.MemberLookup (
5164                                         ec.ContainerType.BaseType, null, ec.ContainerType.BaseType,
5165                                         "Finalize", MemberTypes.Method, Expression.AllBindingFlags, method.Location);
5166
5167                                 if (member_lookup != null){
5168                                         MethodGroupExpr base_destructor = ((MethodGroupExpr) member_lookup);
5169                                 
5170                                         ig.Emit (OpCodes.Ldarg_0);
5171                                         ig.Emit (OpCodes.Call, (MethodInfo) base_destructor.Methods [0]);
5172                                 }
5173                         }
5174                         
5175                         ig.EndExceptionBlock ();
5176                         //ig.MarkLabel (ec.ReturnLabel);
5177                         ig.Emit (OpCodes.Ret);
5178                 }
5179         }
5180
5181         // TODO: Should derive from MethodCore
5182         public class Destructor : Method
5183         {
5184                 const int AllowedModifiers =
5185                         Modifiers.UNSAFE |
5186                         Modifiers.EXTERN;
5187
5188                 static string[] attribute_targets = new string [] { "method" };
5189
5190                 public Destructor (DeclSpace parent, FullNamedExpression return_type, int mod,
5191                                    string name, Parameters parameters, Attributes attrs,
5192                                    Location l)
5193                         : base (parent, return_type, mod, AllowedModifiers, new MemberName (name, l),
5194                                 parameters, attrs)
5195                 {
5196                         ModFlags &= ~Modifiers.PRIVATE;
5197                         if (!RootContext.StdLib && parent.Name == "System.Object")
5198                                 ModFlags |= Modifiers.PROTECTED | Modifiers.VIRTUAL;
5199                         else
5200                                 ModFlags |= Modifiers.PROTECTED | Modifiers.OVERRIDE;
5201                 }
5202
5203                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
5204                 {
5205                         if (a.Type == TypeManager.conditional_attribute_type) {
5206                                 Error_ConditionalAttributeIsNotValid ();
5207                                 return;
5208                         }
5209
5210                         base.ApplyAttributeBuilder (a, cb);
5211                 }
5212
5213                 public override string GetSignatureForError ()
5214                 {
5215                         return Parent.GetSignatureForError () + ".~" + Parent.MemberName.Name + "()";
5216                 }
5217
5218                 public override string[] ValidAttributeTargets {
5219                         get {
5220                                 return attribute_targets;
5221                         }
5222                 }
5223         }
5224         
5225         public abstract class MemberBase : MemberCore
5226         {
5227                 protected FullNamedExpression type_name;
5228                 protected Type member_type;
5229
5230                 public readonly DeclSpace ds;
5231                 public readonly GenericMethod GenericMethod;
5232
5233                 protected MemberBase (DeclSpace parent, GenericMethod generic,
5234                                       FullNamedExpression type, int mod, int allowed_mod, int def_mod,
5235                                       MemberName name, Attributes attrs)
5236                         : base (parent, name, attrs)
5237                 {
5238                         this.ds = generic != null ? generic : (DeclSpace) parent;
5239                         this.type_name = type;
5240                         ModFlags = Modifiers.Check (allowed_mod, mod, def_mod, Location);
5241                         GenericMethod = generic;
5242                         if (GenericMethod != null)
5243                                 GenericMethod.ModFlags = ModFlags;
5244                 }
5245
5246                 //
5247                 // Main member define entry
5248                 //
5249                 public override bool Define ()
5250                 {
5251                         DoMemberTypeIndependentChecks ();
5252
5253                         //
5254                         // Returns false only when type resolution failed
5255                         //
5256                         if (!ResolveMemberType ())
5257                                 return false;
5258
5259                         DoMemberTypeDependentChecks ();
5260                         return true;
5261                 }
5262
5263                 //
5264                 // Any type_name independent checks
5265                 //
5266                 protected virtual void DoMemberTypeIndependentChecks ()
5267                 {
5268                         if ((Parent.ModFlags & Modifiers.SEALED) != 0 &&
5269                                 (ModFlags & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
5270                                 Report.Error (549, Location, "New virtual member `{0}' is declared in a sealed class `{1}'",
5271                                         GetSignatureForError (), Parent.GetSignatureForError ());
5272                         }
5273                 }
5274
5275                 //
5276                 // Any type_name dependent checks
5277                 //
5278                 protected virtual void DoMemberTypeDependentChecks ()
5279                 {
5280                         // verify accessibility
5281                         if (!IsAccessibleAs (MemberType)) {
5282                                 Report.SymbolRelatedToPreviousError (MemberType);
5283                                 if (this is Property)
5284                                         Report.Error (53, Location,
5285                                                       "Inconsistent accessibility: property type `" +
5286                                                       TypeManager.CSharpName (MemberType) + "' is less " +
5287                                                       "accessible than property `" + GetSignatureForError () + "'");
5288                                 else if (this is Indexer)
5289                                         Report.Error (54, Location,
5290                                                       "Inconsistent accessibility: indexer return type `" +
5291                                                       TypeManager.CSharpName (MemberType) + "' is less " +
5292                                                       "accessible than indexer `" + GetSignatureForError () + "'");
5293                                 else if (this is MethodCore) {
5294                                         if (this is Operator)
5295                                                 Report.Error (56, Location,
5296                                                               "Inconsistent accessibility: return type `" +
5297                                                               TypeManager.CSharpName (MemberType) + "' is less " +
5298                                                               "accessible than operator `" + GetSignatureForError () + "'");
5299                                         else
5300                                                 Report.Error (50, Location,
5301                                                               "Inconsistent accessibility: return type `" +
5302                                                               TypeManager.CSharpName (MemberType) + "' is less " +
5303                                                               "accessible than method `" + GetSignatureForError () + "'");
5304                                 } else {
5305                                         Report.Error (52, Location,
5306                                                       "Inconsistent accessibility: field type `" +
5307                                                       TypeManager.CSharpName (MemberType) + "' is less " +
5308                                                       "accessible than field `" + GetSignatureForError () + "'");
5309                                 }
5310                         }
5311                 }
5312
5313                 protected bool IsTypePermitted ()
5314                 {
5315                         if (TypeManager.IsSpecialType (MemberType)) {
5316                                 Report.Error (610, Location, "Field or property cannot be of type `{0}'", TypeManager.CSharpName (MemberType));
5317                                 return false;
5318                         }
5319                         return true;
5320                 }
5321
5322                 protected virtual bool CheckBase ()
5323                 {
5324                         CheckProtectedModifier ();
5325
5326                         return true;
5327                 }
5328
5329                 public Type MemberType {
5330                         get { return member_type; }
5331                 }
5332
5333                 protected virtual bool ResolveMemberType ()
5334                 {
5335                         if (member_type != null)
5336                                 throw new InternalErrorException ("Multi-resolve");
5337
5338                         IResolveContext rc = GenericMethod == null ? this : (IResolveContext) ds;
5339                         TypeExpr te = type_name.ResolveAsTypeTerminal (rc, false);
5340                         if (te == null)
5341                                 return false;
5342
5343                         //
5344                         // Replace original type name, error reporting can use fully resolved name
5345                         //
5346                         type_name = te;
5347
5348                         member_type = te.Type;
5349                         return true;
5350                 }
5351         }
5352
5353         //
5354         // Abstract class for all fields
5355         //
5356         abstract public class FieldBase : MemberBase {
5357                 public FieldBuilder FieldBuilder;
5358                 public Status status;
5359                 protected Expression initializer;
5360
5361                 [Flags]
5362                 public enum Status : byte {
5363                         HAS_OFFSET = 4          // Used by FieldMember.
5364                 }
5365
5366                 static readonly string[] attribute_targets = new string [] { "field" };
5367
5368                 protected FieldBase (DeclSpace parent, FullNamedExpression type, int mod,
5369                                      int allowed_mod, MemberName name, Attributes attrs)
5370                         : base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
5371                                 name, attrs)
5372                 {
5373                         if ((mod & Modifiers.ABSTRACT) != 0)
5374                                 Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
5375                 }
5376
5377                 public override AttributeTargets AttributeTargets {
5378                         get {
5379                                 return AttributeTargets.Field;
5380                         }
5381                 }
5382
5383                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
5384                 {
5385                         if (a.Type == TypeManager.field_offset_attribute_type) {
5386                                 status |= Status.HAS_OFFSET;
5387
5388                                 if (!Parent.PartialContainer.HasExplicitLayout) {
5389                                         Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
5390                                         return;
5391                                 }
5392
5393                                 if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
5394                                         Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
5395                                         return;
5396                                 }
5397                         }
5398
5399 #if NET_2_0
5400                         if (a.Type == TypeManager.fixed_buffer_attr_type) {
5401                                 Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
5402                                 return;
5403                         }
5404 #endif
5405
5406 #if !NET_2_0
5407                         if (a.Type == TypeManager.marshal_as_attr_type) {
5408                                 UnmanagedMarshal marshal = a.GetMarshal (this);
5409                                 if (marshal != null) {
5410                                         FieldBuilder.SetMarshal (marshal);
5411                                 }
5412                                 return;
5413                         }
5414 #endif
5415                         if ((a.HasSecurityAttribute)) {
5416                                 a.Error_InvalidSecurityParent ();
5417                                 return;
5418                         }
5419
5420                         FieldBuilder.SetCustomAttribute (cb);
5421                 }
5422
5423                 protected override bool CheckBase ()
5424                 {
5425                         if (!base.CheckBase ())
5426                                 return false;
5427  
5428                         MemberInfo conflict_symbol = Parent.PartialContainer.FindBaseMemberWithSameName (Name, false);
5429                         if (conflict_symbol == null) {
5430                                 if ((ModFlags & Modifiers.NEW) != 0) {
5431                                         Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required", GetSignatureForError ());
5432                                 }
5433                                 return true;
5434                         }
5435  
5436                         if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE)) == 0) {
5437                                 Report.SymbolRelatedToPreviousError (conflict_symbol);
5438                                 Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
5439                                         GetSignatureForError (), TypeManager.GetFullNameSignature (conflict_symbol));
5440                         }
5441  
5442                         return true;
5443                 }
5444
5445                 protected override void DoMemberTypeDependentChecks ()
5446                 {
5447                         base.DoMemberTypeDependentChecks ();
5448
5449                         if (TypeManager.IsGenericParameter (MemberType))
5450                                 return;
5451
5452                         if (MemberType.IsSealed && MemberType.IsAbstract) {
5453                                 Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType);
5454                         }
5455
5456                         CheckBase ();
5457                         IsTypePermitted ();
5458                 }
5459
5460                 //
5461                 //   Represents header string for documentation comment.
5462                 //
5463                 public override string DocCommentHeader {
5464                         get { return "F:"; }
5465                 }
5466
5467                 public override void Emit ()
5468                 {
5469 #if GMCS_SOURCE
5470                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
5471                                 FieldBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
5472 #endif
5473
5474                         if (OptAttributes != null) {
5475                                 OptAttributes.Emit ();
5476                         }
5477
5478                         if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
5479                                 Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
5480                         }
5481
5482                         base.Emit ();
5483                 }
5484
5485                 public static void Error_VariableOfStaticClass (Location loc, string variable_name, Type static_class)
5486                 {
5487                         Report.SymbolRelatedToPreviousError (static_class);
5488                         Report.Error (723, loc, "`{0}': cannot declare variables of static types",
5489                                 variable_name);
5490                 }
5491
5492                 public Expression Initializer {
5493                         set {
5494                                 if (value != null) {
5495                                         this.initializer = value;
5496                                 }
5497                         }
5498                 }
5499
5500                 protected virtual bool IsFieldClsCompliant {
5501                         get {
5502                                 if (FieldBuilder == null)
5503                                         return true;
5504
5505                                 return AttributeTester.IsClsCompliant (FieldBuilder.FieldType);
5506                         }
5507                 }
5508
5509                 public override string[] ValidAttributeTargets 
5510                 {
5511                         get {
5512                                 return attribute_targets;
5513                         }
5514                 }
5515
5516                 protected override bool VerifyClsCompliance ()
5517                 {
5518                         if (!base.VerifyClsCompliance ())
5519                                 return false;
5520
5521                         if (!IsFieldClsCompliant) {
5522                                 Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
5523                                         GetSignatureForError ());
5524                         }
5525                         return true;
5526                 }
5527
5528                 public void SetAssigned ()
5529                 {
5530                         caching_flags |= Flags.IsAssigned;
5531                 }
5532         }
5533
5534         interface IFixedBuffer
5535         {
5536                 FieldInfo Element { get; }
5537                 Type ElementType { get; }
5538         }
5539
5540         public class FixedFieldExternal: IFixedBuffer
5541         {
5542                 FieldInfo element_field;
5543
5544                 public FixedFieldExternal (FieldInfo fi)
5545                 {
5546                         element_field = fi.FieldType.GetField (FixedField.FixedElementName);
5547                 }
5548
5549                 #region IFixedField Members
5550
5551                 public FieldInfo Element {
5552                         get {
5553                                 return element_field;
5554                         }
5555                 }
5556
5557                 public Type ElementType {
5558                         get {
5559                                 return element_field.FieldType;
5560                         }
5561                 }
5562
5563                 #endregion
5564         }
5565
5566         /// <summary>
5567         /// Fixed buffer implementation
5568         /// </summary>
5569         public class FixedField : FieldBase, IFixedBuffer
5570         {
5571                 public const string FixedElementName = "FixedElementField";
5572                 static int GlobalCounter = 0;
5573                 static object[] ctor_args = new object[] { (short)LayoutKind.Sequential };
5574                 static FieldInfo[] fi;
5575
5576                 TypeBuilder fixed_buffer_type;
5577                 FieldBuilder element;
5578                 Expression size_expr;
5579
5580                 const int AllowedModifiers =
5581                         Modifiers.NEW |
5582                         Modifiers.PUBLIC |
5583                         Modifiers.PROTECTED |
5584                         Modifiers.INTERNAL |
5585                         Modifiers.PRIVATE;
5586
5587                 public FixedField (DeclSpace parent, FullNamedExpression type, int mod, string name,
5588                         Expression size_expr, Attributes attrs, Location loc):
5589                         base (parent, type, mod, AllowedModifiers, new MemberName (name, loc), attrs)
5590                 {
5591                         if (RootContext.Version < LanguageVersion.ISO_2)
5592                                 Report.FeatureIsNotAvailable (loc, "fixed size buffers");
5593
5594                         this.size_expr = size_expr;
5595                 }
5596
5597                 public override bool Define()
5598                 {
5599                         if (!base.Define ())
5600                                 return false;
5601
5602                         if (!TypeManager.IsPrimitiveType (MemberType)) {
5603                                 Report.Error (1663, Location, "`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
5604                                         GetSignatureForError ());
5605                         }                       
5606                         
5607                         // Create nested fixed buffer container
5608                         string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
5609                         fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name, CodeGen.Module.DefaultCharSetType |
5610                                 TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type);
5611                         
5612                         element = fixed_buffer_type.DefineField (FixedElementName, MemberType, FieldAttributes.Public);
5613                         RootContext.RegisterCompilerGeneratedType (fixed_buffer_type);
5614                         
5615                         FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, Modifiers.FieldAttr (ModFlags));
5616                         Parent.MemberCache.AddMember (FieldBuilder, this);
5617                         TypeManager.RegisterFieldBase (FieldBuilder, this);
5618
5619                         return true;
5620                 }
5621
5622                 protected override void DoMemberTypeIndependentChecks ()
5623                 {
5624                         base.DoMemberTypeIndependentChecks ();
5625
5626                         if (!Parent.IsInUnsafeScope)
5627                                 Expression.UnsafeError (Location);
5628
5629                         if (Parent.PartialContainer.Kind != Kind.Struct) {
5630                                 Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
5631                                         GetSignatureForError ());
5632                         }
5633                 }
5634
5635                 public override void Emit()
5636                 {
5637                         EmitContext ec = new EmitContext (this, Parent, Location, null, TypeManager.void_type, ModFlags);
5638                         Constant c = size_expr.ResolveAsConstant (ec, this);
5639                         if (c == null)
5640                                 return;
5641                         
5642                         IntConstant buffer_size_const = c.ImplicitConversionRequired (ec, TypeManager.int32_type, Location) as IntConstant;
5643                         if (buffer_size_const == null)
5644                                 return;
5645
5646                         int buffer_size = buffer_size_const.Value;
5647
5648                         if (buffer_size <= 0) {
5649                                 Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
5650                                 return;
5651                         }
5652
5653                         int type_size = Expression.GetTypeSize (MemberType);
5654
5655                         if (buffer_size > int.MaxValue / type_size) {
5656                                 Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
5657                                         GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
5658                                 return;
5659                         }
5660
5661                         buffer_size *= type_size;
5662                         EmitFieldSize (buffer_size);
5663
5664 #if GMCS_SOURCE
5665                         //
5666                         // Emit compiler generated fixed buffer type attribute
5667                         //
5668                         CustomAttributeBuilder cab = TypeManager.unsafe_value_type_attr;
5669                         if (cab == null) {
5670                                 Type attr_type = TypeManager.CoreLookupType (
5671                                         "System.Runtime.CompilerServices", "UnsafeValueTypeAttribute", Kind.Class, true);
5672
5673                                 if (attr_type != null) {
5674                                         ConstructorInfo ci = TypeManager.GetPredefinedConstructor (attr_type, Location);
5675                                         if (ci != null) {
5676                                                 cab = new CustomAttributeBuilder (ci, new object [0]);
5677                                                 TypeManager.unsafe_value_type_attr = cab;
5678                                         }
5679                                 }
5680                         }
5681
5682                         if (cab != null)
5683                                 fixed_buffer_type.SetCustomAttribute (cab);
5684 #endif
5685                         base.Emit ();
5686                 }
5687
5688                 void EmitFieldSize (int buffer_size)
5689                 {
5690                         if (TypeManager.struct_layout_attribute_type == null) {
5691                                 TypeManager.struct_layout_attribute_type = TypeManager.CoreLookupType (
5692                                         "System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, true);
5693
5694                                 if (TypeManager.struct_layout_attribute_type == null)
5695                                         return;
5696                         }
5697
5698                         if (fi == null)
5699                                 fi = new FieldInfo [] { TypeManager.struct_layout_attribute_type.GetField ("Size") };
5700
5701                         object [] fi_val = new object [] { buffer_size };
5702
5703                         if (TypeManager.struct_layout_attribute_ctor == null) {
5704                                 TypeManager.struct_layout_attribute_ctor = TypeManager.GetPredefinedConstructor (
5705                                         TypeManager.struct_layout_attribute_type, Location, TypeManager.short_type);
5706                                 if (TypeManager.struct_layout_attribute_ctor == null)
5707                                         return;
5708                         }
5709
5710                         CustomAttributeBuilder cab = new CustomAttributeBuilder (TypeManager.struct_layout_attribute_ctor,
5711                                 ctor_args, fi, fi_val);
5712                         fixed_buffer_type.SetCustomAttribute (cab);
5713                         
5714                         //
5715                         // Don't emit FixedBufferAttribute attribute for private types
5716                         //
5717                         if ((ModFlags & Modifiers.PRIVATE) != 0)
5718                                 return; 
5719
5720                         if (TypeManager.fixed_buffer_attr_ctor == null) {
5721                                 if (TypeManager.fixed_buffer_attr_type == null) {
5722                                         TypeManager.fixed_buffer_attr_type = TypeManager.CoreLookupType (
5723                                                 "System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, true);
5724
5725                                         if (TypeManager.fixed_buffer_attr_type == null)
5726                                                 return;
5727                                 }
5728
5729                                 TypeManager.fixed_buffer_attr_ctor = TypeManager.GetPredefinedConstructor (TypeManager.fixed_buffer_attr_type,
5730                                         Location, TypeManager.type_type, TypeManager.int32_type);
5731                                 
5732                                 if (TypeManager.fixed_buffer_attr_ctor == null)
5733                                         return;
5734                         }
5735
5736                         cab = new CustomAttributeBuilder (TypeManager.fixed_buffer_attr_ctor, new object [] { MemberType, buffer_size });
5737                         FieldBuilder.SetCustomAttribute (cab);
5738                 }
5739
5740                 protected override bool IsFieldClsCompliant {
5741                         get {
5742                                 return false;
5743                         }
5744                 }
5745
5746                 public void SetCharSet (TypeAttributes ta)
5747                 {
5748                         TypeAttributes cta = fixed_buffer_type.Attributes;
5749                         if ((cta & TypeAttributes.UnicodeClass) != (ta & TypeAttributes.UnicodeClass))
5750                                 SetTypeBuilderCharSet ((cta & ~TypeAttributes.AutoClass) | TypeAttributes.UnicodeClass);
5751                         else if ((cta & TypeAttributes.AutoClass) != (ta & TypeAttributes.AutoClass))
5752                                 SetTypeBuilderCharSet ((cta & ~TypeAttributes.UnicodeClass) | TypeAttributes.AutoClass);
5753                         else if (cta == 0 && ta != 0)
5754                                 SetTypeBuilderCharSet (cta & ~(TypeAttributes.UnicodeClass | TypeAttributes.AutoClass));
5755                 }
5756
5757                 void SetTypeBuilderCharSet (TypeAttributes ta)
5758                 {
5759                         MethodInfo mi = typeof (TypeBuilder).GetMethod ("SetCharSet", BindingFlags.Instance | BindingFlags.NonPublic);
5760                         if (mi == null) {
5761                                 Report.RuntimeMissingSupport (Location, "TypeBuilder::SetCharSet");
5762                         } else {
5763                                 mi.Invoke (fixed_buffer_type, new object [] { ta });
5764                         }
5765                 }
5766
5767                 #region IFixedField Members
5768
5769                 public FieldInfo Element {
5770                         get {
5771                                 return element;
5772                         }
5773                 }
5774
5775                 public Type ElementType {
5776                         get {
5777                                 return MemberType;
5778                         }
5779                 }
5780
5781                 #endregion
5782         }
5783
5784         //
5785         // The Field class is used to represents class/struct fields during parsing.
5786         //
5787         public class Field : FieldBase {
5788                 // <summary>
5789                 //   Modifiers allowed in a class declaration
5790                 // </summary>
5791                 const int AllowedModifiers =
5792                         Modifiers.NEW |
5793                         Modifiers.PUBLIC |
5794                         Modifiers.PROTECTED |
5795                         Modifiers.INTERNAL |
5796                         Modifiers.PRIVATE |
5797                         Modifiers.STATIC |
5798                         Modifiers.VOLATILE |
5799                         Modifiers.UNSAFE |
5800                         Modifiers.READONLY;
5801
5802                 public Field (DeclSpace parent, FullNamedExpression type, int mod, MemberName name,
5803                               Attributes attrs)
5804                         : base (parent, type, mod, AllowedModifiers, name, attrs)
5805                 {
5806                 }
5807
5808                 bool CanBeVolatile ()
5809                 {
5810                         if (TypeManager.IsReferenceType (MemberType))
5811                                 return true;
5812
5813                         if (MemberType.IsEnum)
5814                                 return true;
5815
5816                         if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
5817                                 MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
5818                                 MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
5819                                 MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
5820                                 MemberType == TypeManager.float_type)
5821                                 return true;
5822
5823                         return false;
5824                 }
5825
5826                 bool CheckStructLayout (Type type, bool isStatic)
5827                 {
5828                         if (TypeManager.IsBuiltinType (type))
5829                                 return true;
5830
5831                         if (isStatic) {
5832                                 if (!TypeManager.IsValueType (type) || TypeManager.IsEqual (type, Parent.TypeBuilder))
5833                                         return true;
5834                         }
5835
5836                         if (!TypeManager.IsEqual (TypeManager.DropGenericTypeArguments (type), Parent.TypeBuilder)) {
5837                                 if (!TypeManager.IsGenericType (type))
5838                                         return true;
5839
5840                                 foreach (Type t in TypeManager.GetTypeArguments (type)) {
5841                                         if (!CheckStructLayout (t, false))
5842                                                 return false;
5843                                 }
5844                                 return true;
5845                         }
5846                         
5847                         Report.Error (523, Location,
5848                                 "Struct member `{0}' of type `{1}' causes a cycle in the struct layout",
5849                                 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5850                         return false;
5851                 }
5852
5853                 public override bool Define ()
5854                 {
5855                         if (!base.Define ())
5856                                 return false;
5857
5858                         try {
5859 #if GMCS_SOURCE
5860                                 Type[] required_modifier = null;
5861                                 if ((ModFlags & Modifiers.VOLATILE) != 0) {
5862                                         if (TypeManager.isvolatile_type == null)
5863                                                 TypeManager.isvolatile_type = TypeManager.CoreLookupType (
5864                                                         "System.Runtime.CompilerServices", "IsVolatile", Kind.Class, true);
5865
5866                                         if (TypeManager.isvolatile_type != null)
5867                                                 required_modifier = new Type [] { TypeManager.isvolatile_type };
5868                                 }
5869
5870                                 FieldBuilder = Parent.TypeBuilder.DefineField (
5871                                         Name, MemberType, required_modifier, null, Modifiers.FieldAttr (ModFlags));
5872 #else
5873                                 FieldBuilder = Parent.TypeBuilder.DefineField (
5874                                         Name, MemberType, Modifiers.FieldAttr (ModFlags));
5875 #endif
5876                                 Parent.MemberCache.AddMember (FieldBuilder, this);
5877                                 TypeManager.RegisterFieldBase (FieldBuilder, this);
5878                         }
5879                         catch (ArgumentException) {
5880                                 Report.RuntimeMissingSupport (Location, "`void' or `void*' field type");
5881                                 return false;
5882                         }
5883
5884                         if (initializer != null) {
5885                                 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
5886                                         new FieldInitializer (FieldBuilder, initializer, this));
5887                         } else {
5888                                 if (Parent.PartialContainer.Kind == Kind.Struct)
5889                                         CheckStructLayout (member_type, (ModFlags & Modifiers.STATIC) != 0);
5890                         }
5891
5892                         return true;
5893                 }
5894
5895                 protected override void DoMemberTypeDependentChecks ()
5896                 {
5897                         base.DoMemberTypeDependentChecks ();
5898
5899                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
5900                                 if (!CanBeVolatile ()) {
5901                                         Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
5902                                                 GetSignatureForError (), TypeManager.CSharpName (MemberType));
5903                                 }
5904
5905                                 if ((ModFlags & Modifiers.READONLY) != 0) {
5906                                         Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
5907                                                 GetSignatureForError ());
5908                                 }
5909                         }
5910                 }
5911
5912                 public override string GetSignatureForError ()
5913                 {
5914                         string s = base.GetSignatureForError ();
5915                         if ((ModFlags & Modifiers.BACKING_FIELD) == 0)
5916                                 return s;
5917
5918                         // Undecorate name mangling
5919                         int l = s.LastIndexOf ('>');
5920                         return s.Substring (0, l).Remove (s.LastIndexOf ('<'), 1);
5921                 }
5922
5923                 protected override bool VerifyClsCompliance ()
5924                 {
5925                         if (!base.VerifyClsCompliance ())
5926                                 return false;
5927
5928                         if ((ModFlags & Modifiers.VOLATILE) != 0) {
5929                                 Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
5930                         }
5931
5932                         return true;
5933                 }
5934         }
5935
5936         //
5937         // `set' and `get' accessors are represented with an Accessor.
5938         // 
5939         public class Accessor {
5940                 //
5941                 // Null if the accessor is empty, or a Block if not
5942                 //
5943                 public const int AllowedModifiers = 
5944                         Modifiers.PUBLIC |
5945                         Modifiers.PROTECTED |
5946                         Modifiers.INTERNAL |
5947                         Modifiers.PRIVATE;
5948                 
5949                 public ToplevelBlock Block;
5950                 public Attributes Attributes;
5951                 public Location Location;
5952                 public int ModFlags;
5953                 public Parameters Parameters;
5954                 
5955                 public Accessor (ToplevelBlock b, int mod, Attributes attrs, Parameters p, Location loc)
5956                 {
5957                         Block = b;
5958                         Attributes = attrs;
5959                         Location = loc;
5960                         Parameters = p;
5961                         ModFlags = Modifiers.Check (AllowedModifiers, mod, 0, loc);
5962                 }
5963         }
5964
5965         // Ooouh Martin, templates are missing here.
5966         // When it will be possible move here a lot of child code and template method type.
5967         public abstract class AbstractPropertyEventMethod : MemberCore, IMethodData {
5968                 protected MethodData method_data;
5969                 protected ToplevelBlock block;
5970                 protected ListDictionary declarative_security;
5971
5972                 // The accessor are created event if they are not wanted.
5973                 // But we need them because their names are reserved.
5974                 // Field says whether accessor will be emited or not
5975                 public readonly bool IsDummy;
5976
5977                 protected readonly string prefix;
5978
5979                 ReturnParameter return_attributes;
5980
5981                 public AbstractPropertyEventMethod (PropertyBasedMember member, string prefix)
5982                         : base (member.Parent, SetupName (prefix, member, member.Location), null)
5983                 {
5984                         this.prefix = prefix;
5985                         IsDummy = true;
5986                 }
5987
5988                 public AbstractPropertyEventMethod (InterfaceMemberBase member, Accessor accessor,
5989                                                     string prefix)
5990                         : base (member.Parent, SetupName (prefix, member, accessor.Location),
5991                                 accessor.Attributes)
5992                 {
5993                         this.prefix = prefix;
5994                         this.block = accessor.Block;
5995                 }
5996
5997                 static MemberName SetupName (string prefix, InterfaceMemberBase member, Location loc)
5998                 {
5999                         return new MemberName (member.MemberName.Left, prefix + member.ShortName, loc);
6000                 }
6001
6002                 public void UpdateName (InterfaceMemberBase member)
6003                 {
6004                         SetMemberName (SetupName (prefix, member, Location));
6005                 }
6006
6007                 #region IMethodData Members
6008
6009                 public ToplevelBlock Block {
6010                         get {
6011                                 return block;
6012                         }
6013
6014                         set {
6015                                 block = value;
6016                         }
6017                 }
6018
6019                 public CallingConventions CallingConventions {
6020                         get {
6021                                 return CallingConventions.Standard;
6022                         }
6023                 }
6024
6025                 public bool IsExcluded ()
6026                 {
6027                         return false;
6028                 }
6029
6030                 GenericMethod IMethodData.GenericMethod {
6031                         get {
6032                                 return null;
6033                         }
6034                 }
6035
6036                 public MemberName MethodName {
6037                         get {
6038                                 return MemberName;
6039                         }
6040                 }
6041
6042                 public Type[] ParameterTypes { 
6043                         get {
6044                                 return ParameterInfo.Types;
6045                         }
6046                 }
6047
6048                 public abstract Parameters ParameterInfo { get ; }
6049                 public abstract Type ReturnType { get; }
6050                 public abstract EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig);
6051
6052                 #endregion
6053
6054                 public override void ApplyAttributeBuilder(Attribute a, CustomAttributeBuilder cb)
6055                 {
6056                         if (a.Type == TypeManager.cls_compliant_attribute_type || a.Type == TypeManager.obsolete_attribute_type ||
6057                                         a.Type == TypeManager.conditional_attribute_type) {
6058                                 Report.Error (1667, a.Location,
6059                                         "Attribute `{0}' is not valid on property or event accessors. It is valid on `{1}' declarations only",
6060                                         TypeManager.CSharpName (a.Type), a.GetValidTargets ());
6061                                 return;
6062                         }
6063
6064                         if (a.IsValidSecurityAttribute ()) {
6065                                 if (declarative_security == null)
6066                                         declarative_security = new ListDictionary ();
6067                                 a.ExtractSecurityPermissionSet (declarative_security);
6068                                 return;
6069                         }
6070
6071                         if (a.Target == AttributeTargets.Method) {
6072                                 method_data.MethodBuilder.SetCustomAttribute (cb);
6073                                 return;
6074                         }
6075
6076                         if (a.Target == AttributeTargets.ReturnValue) {
6077                                 if (return_attributes == null)
6078                                         return_attributes = new ReturnParameter (method_data.MethodBuilder, Location);
6079
6080                                 return_attributes.ApplyAttributeBuilder (a, cb);
6081                                 return;
6082                         }
6083
6084                         ApplyToExtraTarget (a, cb);
6085                 }
6086
6087                 virtual protected void ApplyToExtraTarget (Attribute a, CustomAttributeBuilder cb)
6088                 {
6089                         throw new NotSupportedException ("You forgot to define special attribute target handling");
6090                 }
6091
6092                 // It is not supported for the accessors
6093                 public sealed override bool Define()
6094                 {
6095                         throw new NotSupportedException ();
6096                 }
6097
6098                 public void Emit (DeclSpace parent)
6099                 {
6100                         EmitMethod (parent);
6101
6102 #if GMCS_SOURCE                 
6103                         if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
6104                                 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetCompilerGeneratedAttribute (Location));
6105                         if (((ModFlags & Modifiers.DEBUGGER_HIDDEN) != 0))
6106                                 method_data.MethodBuilder.SetCustomAttribute (TypeManager.GetDebuggerHiddenAttribute (Location));
6107 #endif                  
6108                         if (OptAttributes != null)
6109                                 OptAttributes.Emit ();
6110
6111                         if (declarative_security != null) {
6112                                 foreach (DictionaryEntry de in declarative_security) {
6113                                         method_data.MethodBuilder.AddDeclarativeSecurity ((SecurityAction)de.Key, (PermissionSet)de.Value);
6114                                 }
6115                         }
6116
6117                         block = null;
6118                 }
6119
6120                 protected virtual void EmitMethod (DeclSpace parent)
6121                 {
6122                         method_data.Emit (parent);
6123                 }
6124
6125                 public override bool EnableOverloadChecks (MemberCore overload)
6126                 {
6127                         // This can only happen with indexers and it will
6128                         // be catched as indexer difference
6129                         if (overload is AbstractPropertyEventMethod)
6130                                 return true;
6131
6132                         if (overload is MethodCore) {
6133                                 caching_flags |= Flags.MethodOverloadsExist;
6134                                 return true;
6135                         }
6136                         return false;
6137                 }
6138
6139                 public override bool IsClsComplianceRequired()
6140                 {
6141                         return false;
6142                 }
6143
6144                 public bool IsDuplicateImplementation (MethodCore method)
6145                 {
6146                         if (!MemberName.Equals (method.MemberName))
6147                                 return false;
6148
6149                         Type[] param_types = method.ParameterTypes;
6150
6151                         if (param_types == null || param_types.Length != ParameterTypes.Length)
6152                                 return false;
6153
6154                         for (int i = 0; i < param_types.Length; i++)
6155                                 if (param_types [i] != ParameterTypes [i])
6156                                         return false;
6157
6158                         Report.SymbolRelatedToPreviousError (method);
6159                         Report.Error (82, Location, "A member `{0}' is already reserved",
6160                                 method.GetSignatureForError ());
6161                         return true;
6162                 }
6163
6164                 public override bool IsUsed
6165                 {
6166                         get {
6167                                 if (IsDummy)
6168                                         return false;
6169
6170                                 return base.IsUsed;
6171                         }
6172                 }
6173
6174                 //
6175                 //   Represents header string for documentation comment.
6176                 //
6177                 public override string DocCommentHeader {
6178                         get { throw new InvalidOperationException ("Unexpected attempt to get doc comment from " + this.GetType () + "."); }
6179                 }
6180
6181                 void IMethodData.EmitExtraSymbolInfo (SourceMethod source)
6182                 { }
6183         }
6184
6185         //
6186         // Properties and Indexers both generate PropertyBuilders, we use this to share 
6187         // their common bits.
6188         //
6189         abstract public class PropertyBase : PropertyBasedMember {
6190
6191                 public class GetMethod : PropertyMethod
6192                 {
6193                         static string[] attribute_targets = new string [] { "method", "return" };
6194
6195                         public GetMethod (PropertyBase method):
6196                                 base (method, "get_")
6197                         {
6198                         }
6199
6200                         public GetMethod (PropertyBase method, Accessor accessor):
6201                                 base (method, accessor, "get_")
6202                         {
6203                         }
6204
6205                         public override MethodBuilder Define (DeclSpace parent)
6206                         {
6207                                 base.Define (parent);
6208
6209                                 if (IsDummy)
6210                                         return null;
6211                                 
6212                                 method_data = new MethodData (method, ModFlags, flags, this);
6213
6214                                 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6215                                         return null;
6216
6217                                 return method_data.MethodBuilder;
6218                         }
6219
6220                         public override Type ReturnType {
6221                                 get {
6222                                         return method.MemberType;
6223                                 }
6224                         }
6225
6226                         public override Parameters ParameterInfo {
6227                                 get {
6228                                         return Parameters.EmptyReadOnlyParameters;
6229                                 }
6230                         }
6231
6232                         public override string[] ValidAttributeTargets {
6233                                 get {
6234                                         return attribute_targets;
6235                                 }
6236                         }
6237                 }
6238
6239                 public class SetMethod : PropertyMethod {
6240
6241                         static string[] attribute_targets = new string [] { "method", "param", "return" };
6242                         ImplicitParameter param_attr;
6243                         protected Parameters parameters;
6244
6245                         public SetMethod (PropertyBase method) :
6246                                 base (method, "set_")
6247                         {
6248                                 parameters = new Parameters (
6249                                         new Parameter (method.type_name, "value", Parameter.Modifier.NONE, null, Location));
6250                         }
6251
6252                         public SetMethod (PropertyBase method, Accessor accessor):
6253                                 base (method, accessor, "set_")
6254                         {
6255                                 this.parameters = accessor.Parameters;
6256                         }
6257
6258                         protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
6259                         {
6260                                 if (a.Target == AttributeTargets.Parameter) {
6261                                         if (param_attr == null)
6262                                                 param_attr = new ImplicitParameter (method_data.MethodBuilder);
6263
6264                                         param_attr.ApplyAttributeBuilder (a, cb);
6265                                         return;
6266                                 }
6267
6268                                 base.ApplyAttributeBuilder (a, cb);
6269                         }
6270
6271                         public override Parameters ParameterInfo {
6272                             get {
6273                                 return parameters;
6274                             }
6275                         }
6276
6277                         public override MethodBuilder Define (DeclSpace parent)
6278                         {
6279                                 parameters.Resolve (ResolveContext);
6280                                 base.Define (parent);
6281
6282                                 if (IsDummy)
6283                                         return null;
6284
6285                                 method_data = new MethodData (method, ModFlags, flags, this);
6286
6287                                 if (!method_data.Define (parent, method.GetFullName (MemberName)))
6288                                         return null;
6289
6290                                 return method_data.MethodBuilder;
6291                         }
6292
6293                         public override Type ReturnType {
6294                                 get {
6295                                         return TypeManager.void_type;
6296                                 }
6297                         }
6298
6299                         public override string[] ValidAttributeTargets {
6300                                 get {
6301                                         return attribute_targets;
6302                                 }
6303                         }
6304                 }
6305
6306                 static string[] attribute_targets = new string [] { "property" };
6307
6308                 public abstract class PropertyMethod : AbstractPropertyEventMethod
6309                 {
6310                         protected readonly PropertyBase method;
6311                         protected MethodAttributes flags;
6312
6313                         public PropertyMethod (PropertyBase method, string prefix)
6314                                 : base (method, prefix)
6315                         {
6316                                 this.method = method;
6317                                 this.ModFlags = method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE);                                
6318                         }
6319
6320                         public PropertyMethod (PropertyBase method, Accessor accessor,
6321                                                string prefix)
6322                                 : base (method, accessor, prefix)
6323                         {
6324                                 this.method = method;
6325                                 this.ModFlags = accessor.ModFlags | (method.ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE));
6326
6327                                 if (accessor.ModFlags != 0 && RootContext.Version == LanguageVersion.ISO_1) {
6328                                         Report.FeatureIsNotAvailable (Location, "access modifiers on properties");
6329                                 }
6330                         }
6331
6332                         public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6333                         {
6334                                 if (a.IsInternalMethodImplAttribute) {
6335                                         method.is_external_implementation = true;
6336                                 }
6337
6338                                 base.ApplyAttributeBuilder (a, cb);
6339                         }
6340
6341                         public override AttributeTargets AttributeTargets {
6342                                 get {
6343                                         return AttributeTargets.Method;
6344                                 }
6345                         }
6346
6347                         public override bool IsClsComplianceRequired ()
6348                         {
6349                                 return method.IsClsComplianceRequired ();
6350                         }
6351
6352                         public virtual MethodBuilder Define (DeclSpace parent)
6353                         {
6354                                 CheckForDuplications ();
6355
6356                                 if (IsDummy) {
6357                                         if (method.InterfaceType != null && parent.PartialContainer.PendingImplementations != null) {
6358                                                 MethodInfo mi = parent.PartialContainer.PendingImplementations.IsInterfaceMethod (
6359                                                         MethodName.Name, method.InterfaceType, new MethodData (method, ModFlags, flags, this));
6360                                                 if (mi != null) {
6361                                                         Report.SymbolRelatedToPreviousError (mi);
6362                                                         Report.Error (551, Location, "Explicit interface implementation `{0}' is missing accessor `{1}'",
6363                                                                 method.GetSignatureForError (), TypeManager.CSharpSignature (mi, true));
6364                                                 }
6365                                         }
6366                                         return null;
6367                                 }
6368
6369                                 TypeContainer container = parent.PartialContainer;
6370
6371                                 //
6372                                 // Check for custom access modifier
6373                                 //
6374                                 if ((ModFlags & Modifiers.Accessibility) == 0) {
6375                                         ModFlags |= method.ModFlags;
6376                                         flags = method.flags;
6377                                 } else {
6378                                         if (container.Kind == Kind.Interface)
6379                                                 Report.Error (275, Location, "`{0}': accessibility modifiers may not be used on accessors in an interface",
6380                                                         GetSignatureForError ());
6381
6382                                         if ((method.ModFlags & Modifiers.ABSTRACT) != 0 && (ModFlags & Modifiers.PRIVATE) != 0) {
6383                                                 Report.Error (442, Location, "`{0}': abstract properties cannot have private accessors", GetSignatureForError ());
6384                                         }
6385
6386                                         CheckModifiers (ModFlags);
6387                                         ModFlags |= (method.ModFlags & (~Modifiers.Accessibility));
6388                                         ModFlags |= Modifiers.PROPERTY_CUSTOM;
6389                                         flags = Modifiers.MethodAttr (ModFlags);
6390                                         flags |= (method.flags & (~MethodAttributes.MemberAccessMask));
6391                                 }
6392
6393                                 CheckAbstractAndExtern (block != null);
6394
6395                                 if (block != null && block.IsIterator)
6396                                         Iterator.CreateIterator (this, Parent.PartialContainer, ModFlags);
6397
6398                                 return null;
6399                         }
6400
6401                         public bool HasCustomAccessModifier {
6402                                 get {
6403                                         return (ModFlags & Modifiers.PROPERTY_CUSTOM) != 0;
6404                                 }
6405                         }
6406
6407                         public PropertyBase Property {
6408                                 get {
6409                                         return method;
6410                                 }
6411                         }
6412
6413                         public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
6414                         {
6415                                 return new EmitContext (this,
6416                                         ds, method.ds, method.Location, ig, ReturnType,
6417                                         method.ModFlags, false);
6418                         }
6419
6420                         public override ObsoleteAttribute GetObsoleteAttribute ()
6421                         {
6422                                 return method.GetObsoleteAttribute ();
6423                         }
6424
6425                         public override string GetSignatureForError()
6426                         {
6427                                 return method.GetSignatureForError () + '.' + prefix.Substring (0, 3);
6428                         }
6429                         
6430                         void CheckModifiers (int modflags)
6431                         {
6432                                 modflags &= Modifiers.Accessibility;
6433                                 int flags = 0;
6434                                 int mflags = method.ModFlags & Modifiers.Accessibility;
6435
6436                                 if ((mflags & Modifiers.PUBLIC) != 0) {
6437                                         flags |= Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE;
6438                                 }
6439                                 else if ((mflags & Modifiers.PROTECTED) != 0) {
6440                                         if ((mflags & Modifiers.INTERNAL) != 0)
6441                                                 flags |= Modifiers.PROTECTED | Modifiers.INTERNAL;
6442
6443                                         flags |= Modifiers.PRIVATE;
6444                                 }
6445                                 else if ((mflags & Modifiers.INTERNAL) != 0)
6446                                         flags |= Modifiers.PRIVATE;
6447
6448                                 if ((mflags == modflags) || (modflags & (~flags)) != 0) {
6449                                         Report.Error (273, Location,
6450                                                 "The accessibility modifier of the `{0}' accessor must be more restrictive than the modifier of the property or indexer `{1}'",
6451                                                 GetSignatureForError (), method.GetSignatureForError ());
6452                                 }
6453                         }
6454
6455                         protected bool CheckForDuplications ()
6456                         {
6457                                 if ((caching_flags & Flags.MethodOverloadsExist) == 0)
6458                                         return true;
6459
6460                                 return Parent.MemberCache.CheckExistingMembersOverloads (this, Name, ParameterInfo);
6461                         }
6462                 }
6463
6464                 public PropertyMethod Get, Set;
6465                 public PropertyBuilder PropertyBuilder;
6466                 public MethodBuilder GetBuilder, SetBuilder;
6467
6468                 protected bool define_set_first = false;
6469
6470                 public PropertyBase (DeclSpace parent, FullNamedExpression type, int mod_flags,
6471                                      int allowed_mod, MemberName name,
6472                                      Attributes attrs, bool define_set_first)
6473                         : base (parent, null, type, mod_flags, allowed_mod, name, attrs)
6474                 {
6475                          this.define_set_first = define_set_first;
6476                 }
6477
6478                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
6479                 {
6480                         if (a.HasSecurityAttribute) {
6481                                 a.Error_InvalidSecurityParent ();
6482                                 return;
6483                         }
6484
6485                         PropertyBuilder.SetCustomAttribute (cb);
6486                 }
6487
6488                 public override AttributeTargets AttributeTargets {
6489                         get {
6490                                 return AttributeTargets.Property;
6491                         }
6492                 }
6493
6494                 protected override void DoMemberTypeDependentChecks ()
6495                 {
6496                         base.DoMemberTypeDependentChecks ();
6497
6498                         IsTypePermitted ();
6499 #if MS_COMPATIBLE
6500                         if (MemberType.IsGenericParameter)
6501                                 return;
6502 #endif
6503
6504                         if ((MemberType.Attributes & Class.StaticClassAttribute) == Class.StaticClassAttribute) {
6505                                 Report.Error (722, Location, Error722, TypeManager.CSharpName (MemberType));
6506                         }
6507                 }
6508
6509                 protected override void DoMemberTypeIndependentChecks ()
6510                 {
6511                         base.DoMemberTypeIndependentChecks ();
6512
6513                         //
6514                         // Accessors modifiers check
6515                         //
6516                         if ((Get.ModFlags & Modifiers.Accessibility) != 0 &&
6517                                 (Set.ModFlags & Modifiers.Accessibility) != 0) {
6518                                 Report.Error (274, Location, "`{0}': Cannot specify accessibility modifiers for both accessors of the property or indexer",
6519                                                 GetSignatureForError ());
6520                         }
6521
6522                         if ((ModFlags & Modifiers.OVERRIDE) == 0 && 
6523                                 (Get.IsDummy && (Set.ModFlags & Modifiers.Accessibility) != 0) ||
6524                                 (Set.IsDummy && (Get.ModFlags & Modifiers.Accessibility) != 0)) {
6525                                 Report.Error (276, Location, 
6526                                               "`{0}': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor",
6527                                               GetSignatureForError ());
6528                         }
6529                 }
6530
6531                 bool DefineGet ()
6532                 {
6533                         GetBuilder = Get.Define (Parent);
6534                         return (Get.IsDummy) ? true : GetBuilder != null;
6535                 }
6536
6537                 bool DefineSet (bool define)
6538                 {
6539                         if (!define)
6540                                 return true;
6541
6542                         SetBuilder = Set.Define (Parent);
6543                         return (Set.IsDummy) ? true : SetBuilder != null;
6544                 }
6545
6546                 protected bool DefineAccessors ()
6547                 {
6548                         return DefineSet (define_set_first) &&
6549                                 DefineGet () &&
6550                                 DefineSet (!define_set_first);
6551                 }
6552
6553                 protected abstract PropertyInfo ResolveBaseProperty ();
6554
6555                 // TODO: rename to Resolve......
6556                 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
6557                 {
6558                         PropertyInfo base_property = ResolveBaseProperty ();
6559                         if (base_property == null)
6560                                 return null;
6561
6562                         base_ret_type = base_property.PropertyType;
6563                         MethodInfo get_accessor = base_property.GetGetMethod (true);
6564                         MethodInfo set_accessor = base_property.GetSetMethod (true);
6565                         MethodAttributes get_accessor_access = 0, set_accessor_access = 0;
6566
6567                         //
6568                         // Check base property accessors conflict
6569                         //
6570                         if ((ModFlags & (Modifiers.OVERRIDE | Modifiers.NEW)) == Modifiers.OVERRIDE) {
6571                                 if (get_accessor == null) {
6572                                         if (Get != null && !Get.IsDummy) {
6573                                                 Report.SymbolRelatedToPreviousError (base_property);
6574                                                 Report.Error (545, Location,
6575                                                         "`{0}.get': cannot override because `{1}' does not have an overridable get accessor",
6576                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6577                                         }
6578                                 } else {
6579                                         get_accessor_access = get_accessor.Attributes & MethodAttributes.MemberAccessMask;
6580
6581                                         if (!Get.IsDummy && !CheckAccessModifiers (
6582                                                 Modifiers.MethodAttr (Get.ModFlags) & MethodAttributes.MemberAccessMask, get_accessor_access, get_accessor))
6583                                                 Error_CannotChangeAccessModifiers (Get.Location, get_accessor, get_accessor_access, ".get");
6584                                 }
6585
6586                                 if (set_accessor == null) {
6587                                         if (Set != null && !Set.IsDummy) {
6588                                                 Report.SymbolRelatedToPreviousError (base_property);
6589                                                 Report.Error (546, Location,
6590                                                         "`{0}.set': cannot override because `{1}' does not have an overridable set accessor",
6591                                                         GetSignatureForError (), TypeManager.GetFullNameSignature (base_property));
6592                                         }
6593                                 } else {
6594                                         set_accessor_access = set_accessor.Attributes & MethodAttributes.MemberAccessMask;
6595
6596                                         if (!Set.IsDummy && !CheckAccessModifiers (
6597                                                 Modifiers.MethodAttr (Set.ModFlags) & MethodAttributes.MemberAccessMask, set_accessor_access, set_accessor))
6598                                                 Error_CannotChangeAccessModifiers (Set.Location, set_accessor, set_accessor_access, ".set");
6599                                 }
6600                         }
6601
6602                         // When one accessor does not exist and property hides base one
6603                         // we need to propagate this upwards
6604                         if (set_accessor == null)
6605                                 set_accessor = get_accessor;
6606
6607                         //
6608                         // Get the less restrictive access
6609                         //
6610                         return get_accessor_access > set_accessor_access ? get_accessor : set_accessor;
6611                 }
6612
6613                 public override void Emit ()
6614                 {
6615                         //
6616                         // The PropertyBuilder can be null for explicit implementations, in that
6617                         // case, we do not actually emit the ".property", so there is nowhere to
6618                         // put the attribute
6619                         //
6620                         if (PropertyBuilder != null && OptAttributes != null)
6621                                 OptAttributes.Emit ();
6622
6623                         if (!Get.IsDummy)
6624                                 Get.Emit (Parent);
6625
6626                         if (!Set.IsDummy)
6627                                 Set.Emit (Parent);
6628
6629                         base.Emit ();
6630                 }
6631
6632                 /// <summary>
6633                 /// Tests whether accessors are not in collision with some method (CS0111)
6634                 /// </summary>
6635                 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
6636                 {
6637                         return Get.IsDuplicateImplementation (mc) || Set.IsDuplicateImplementation (mc);
6638                 }
6639
6640                 public override bool IsUsed
6641                 {
6642                         get {
6643                                 if (IsExplicitImpl)
6644                                         return true;
6645
6646                                 return Get.IsUsed | Set.IsUsed;
6647                         }
6648                 }
6649
6650                 protected override void SetMemberName (MemberName new_name)
6651                 {
6652                         base.SetMemberName (new_name);
6653
6654                         Get.UpdateName (this);
6655                         Set.UpdateName (this);
6656                 }
6657
6658                 public override string[] ValidAttributeTargets {
6659                         get {
6660                                 return attribute_targets;
6661                         }
6662                 }
6663
6664                 //
6665                 //   Represents header string for documentation comment.
6666                 //
6667                 public override string DocCommentHeader {
6668                         get { return "P:"; }
6669                 }
6670         }
6671                         
6672         public class Property : PropertyBase {
6673                 const int AllowedModifiers =
6674                         Modifiers.NEW |
6675                         Modifiers.PUBLIC |
6676                         Modifiers.PROTECTED |
6677                         Modifiers.INTERNAL |
6678                         Modifiers.PRIVATE |
6679                         Modifiers.STATIC |
6680                         Modifiers.SEALED |
6681                         Modifiers.OVERRIDE |
6682                         Modifiers.ABSTRACT |
6683                         Modifiers.UNSAFE |
6684                         Modifiers.EXTERN |
6685                         Modifiers.VIRTUAL;
6686
6687                 const int AllowedInterfaceModifiers =
6688                         Modifiers.NEW;
6689
6690                 void CreateAutomaticProperty (Block block, Accessor get_block, Accessor set_block)
6691                 {
6692                         // Make the field
6693                         Field field = new Field (
6694                                 Parent, type_name,
6695                                 Modifiers.BACKING_FIELD | Modifiers.PRIVATE | (ModFlags & (Modifiers.STATIC | Modifiers.UNSAFE)),
6696                             new MemberName ("<" + Name + ">k__BackingField", Location), null);
6697                         ((TypeContainer)Parent).PartialContainer.AddField (field);
6698
6699                         // Make get block
6700                         get_block.Block = new ToplevelBlock (block, Parameters.EmptyReadOnlyParameters, Location);
6701                         Return r = new Return (new SimpleName(field.Name, Location), Location);
6702                         get_block.Block.AddStatement (r);
6703                         get_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6704
6705                         // Make set block
6706                         set_block.Block = new ToplevelBlock (block, set_block.Parameters, Location);
6707                         Assign a = new SimpleAssign (new SimpleName (field.Name, Location), new SimpleName ("value", Location));
6708                         set_block.Block.AddStatement (new StatementExpression(a));
6709                         set_block.ModFlags |= Modifiers.COMPILER_GENERATED;
6710                 }
6711
6712                 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6713                                  MemberName name, Attributes attrs, Accessor get_block,
6714                                  Accessor set_block, bool define_set_first)
6715                         : this (parent, type, mod, name, attrs, get_block, set_block,
6716                                 define_set_first, null)
6717                 {
6718                 }
6719                 
6720                 public Property (DeclSpace parent, FullNamedExpression type, int mod,
6721                                  MemberName name, Attributes attrs, Accessor get_block,
6722                                  Accessor set_block, bool define_set_first, Block current_block)
6723                         : base (parent, type, mod,
6724                                 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
6725                                 name, attrs, define_set_first)
6726                 {
6727                         if (!IsInterface && (mod & (Modifiers.ABSTRACT | Modifiers.EXTERN)) == 0 &&
6728                                 get_block != null && get_block.Block == null &&
6729                                 set_block != null && set_block.Block == null) {
6730                                 if (RootContext.Version <= LanguageVersion.ISO_2)
6731                                         Report.FeatureIsNotAvailable (Location, "automatically implemented properties");
6732                                 
6733                                 CreateAutomaticProperty (current_block, get_block, set_block);
6734                         }
6735
6736                         if (get_block == null)
6737                                 Get = new GetMethod (this);
6738                         else
6739                                 Get = new GetMethod (this, get_block);
6740
6741                         if (set_block == null)
6742                                 Set = new SetMethod (this);
6743                         else
6744                                 Set = new SetMethod (this, set_block);
6745                 }
6746
6747                 public override bool Define ()
6748                 {
6749                         if (!base.Define ())
6750                                 return false;
6751
6752                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
6753
6754                         if (!DefineAccessors ())
6755                                 return false;
6756
6757                         if (!CheckBase ())
6758                                 return false;
6759
6760                         // FIXME - PropertyAttributes.HasDefault ?
6761
6762                         PropertyBuilder = Parent.TypeBuilder.DefineProperty (
6763                                 GetFullName (MemberName), PropertyAttributes.None, MemberType, null);
6764
6765                         if (!Get.IsDummy) {
6766                                 PropertyBuilder.SetGetMethod (GetBuilder);
6767                                 Parent.MemberCache.AddMember (GetBuilder, Get);
6768                         }
6769
6770                         if (!Set.IsDummy) {
6771                                 PropertyBuilder.SetSetMethod (SetBuilder);
6772                                 Parent.MemberCache.AddMember (SetBuilder, Set);
6773                         }
6774                         
6775                         TypeManager.RegisterProperty (PropertyBuilder, this);
6776                         Parent.MemberCache.AddMember (PropertyBuilder, this);
6777                         return true;
6778                 }
6779
6780                 public override void Emit ()
6781                 {
6782                         if (((Set.ModFlags | Get.ModFlags) & (Modifiers.STATIC | Modifiers.COMPILER_GENERATED)) == Modifiers.COMPILER_GENERATED && Parent.PartialContainer.HasExplicitLayout) {
6783                                 Report.Error (842, Location,
6784                                         "Automatically implemented property `{0}' cannot be used inside a type with an explicit StructLayout attribute",
6785                                         GetSignatureForError ());
6786                         }
6787
6788                         base.Emit ();
6789                 }
6790
6791                 protected override PropertyInfo ResolveBaseProperty ()
6792                 {
6793                         return Parent.PartialContainer.BaseCache.FindMemberToOverride (
6794                                 Parent.TypeBuilder, Name, Parameters.EmptyReadOnlyParameters, null, true) as PropertyInfo;
6795                 }
6796         }
6797
6798         /// </summary>
6799         ///  Gigantic workaround  for lameness in SRE follows :
6800         ///  This class derives from EventInfo and attempts to basically
6801         ///  wrap around the EventBuilder so that FindMembers can quickly
6802         ///  return this in it search for members
6803         /// </summary>
6804         public class MyEventBuilder : EventInfo {
6805                 
6806                 //
6807                 // We use this to "point" to our Builder which is
6808                 // not really a MemberInfo
6809                 //
6810                 EventBuilder MyBuilder;
6811                 
6812                 //
6813                 // We "catch" and wrap these methods
6814                 //
6815                 MethodInfo raise, remove, add;
6816
6817                 EventAttributes attributes;
6818                 Type declaring_type, reflected_type, event_type;
6819                 string name;
6820
6821                 Event my_event;
6822
6823                 public MyEventBuilder (Event ev, TypeBuilder type_builder, string name, EventAttributes event_attr, Type event_type)
6824                 {
6825                         MyBuilder = type_builder.DefineEvent (name, event_attr, event_type);
6826
6827                         // And now store the values in our own fields.
6828                         
6829                         declaring_type = type_builder;
6830
6831                         reflected_type = type_builder;
6832                         
6833                         attributes = event_attr;
6834                         this.name = name;
6835                         my_event = ev;
6836                         this.event_type = event_type;
6837                 }
6838                 
6839                 //
6840                 // Methods that you have to override.  Note that you only need 
6841                 // to "implement" the variants that take the argument (those are
6842                 // the "abstract" methods, the others (GetAddMethod()) are 
6843                 // regular.
6844                 //
6845                 public override MethodInfo GetAddMethod (bool nonPublic)
6846                 {
6847                         return add;
6848                 }
6849                 
6850                 public override MethodInfo GetRemoveMethod (bool nonPublic)
6851                 {
6852                         return remove;
6853                 }
6854                 
6855                 public override MethodInfo GetRaiseMethod (bool nonPublic)
6856                 {
6857                         return raise;
6858                 }
6859                 
6860                 //
6861                 // These methods make "MyEventInfo" look like a Builder
6862                 //
6863                 public void SetRaiseMethod (MethodBuilder raiseMethod)
6864                 {
6865                         raise = raiseMethod;
6866                         MyBuilder.SetRaiseMethod (raiseMethod);
6867                 }
6868
6869                 public void SetRemoveOnMethod (MethodBuilder removeMethod)
6870                 {
6871                         remove = removeMethod;
6872                         MyBuilder.SetRemoveOnMethod (removeMethod);
6873                 }
6874
6875                 public void SetAddOnMethod (MethodBuilder addMethod)
6876                 {
6877                         add = addMethod;
6878                         MyBuilder.SetAddOnMethod (addMethod);
6879                 }
6880
6881                 public void SetCustomAttribute (CustomAttributeBuilder cb)
6882                 {
6883                         MyBuilder.SetCustomAttribute (cb);
6884                 }
6885                 
6886                 public override object [] GetCustomAttributes (bool inherit)
6887                 {
6888                         // FIXME : There's nothing which can be seemingly done here because
6889                         // we have no way of getting at the custom attribute objects of the
6890                         // EventBuilder !
6891                         return null;
6892                 }
6893
6894                 public override object [] GetCustomAttributes (Type t, bool inherit)
6895                 {
6896                         // FIXME : Same here !
6897                         return null;
6898                 }
6899
6900                 public override bool IsDefined (Type t, bool b)
6901                 {
6902                         return true;
6903                 }
6904
6905                 public override EventAttributes Attributes {
6906                         get {
6907                                 return attributes;
6908                         }
6909                 }
6910
6911                 public override string Name {
6912                         get {
6913                                 return name;
6914                         }
6915                 }
6916
6917                 public override Type DeclaringType {
6918                         get {
6919                                 return declaring_type;
6920                         }
6921                 }
6922
6923                 public override Type ReflectedType {
6924                         get {
6925                                 return reflected_type;
6926                         }
6927                 }
6928
6929                 public Type EventType {
6930                         get {
6931                                 return event_type;
6932                         }
6933                 }
6934                 
6935                 public void SetUsed ()
6936                 {
6937                         if (my_event != null) {
6938 //                              my_event.SetAssigned ();
6939                                 my_event.SetMemberIsUsed ();
6940                         }
6941                 }
6942         }
6943         
6944         /// <summary>
6945         /// For case when event is declared like property (with add and remove accessors).
6946         /// </summary>
6947         public class EventProperty: Event {
6948                 abstract class AEventPropertyAccessor : AEventAccessor
6949                 {
6950                         protected AEventPropertyAccessor (Event method, Accessor accessor, string prefix):
6951                                 base (method, accessor, prefix)
6952                         {
6953                         }
6954
6955                         public override MethodBuilder Define (DeclSpace ds)
6956                         {
6957                                 CheckAbstractAndExtern (block != null);
6958                                 return base.Define (ds);
6959                         }
6960                         
6961                         public override string GetSignatureForError ()
6962                         {
6963                                 return method.GetSignatureForError () + "." + prefix.Substring (0, prefix.Length - 1);
6964                         }
6965                 }
6966
6967                 sealed class AddDelegateMethod: AEventPropertyAccessor
6968                 {
6969                         public AddDelegateMethod (Event method, Accessor accessor):
6970                                 base (method, accessor, "add_")
6971                         {
6972                         }
6973
6974                         protected override MethodInfo DelegateMethodInfo {
6975                                 get {
6976                                         return TypeManager.delegate_combine_delegate_delegate;
6977                                 }
6978                         }
6979                 }
6980
6981                 sealed class RemoveDelegateMethod: AEventPropertyAccessor
6982                 {
6983                         public RemoveDelegateMethod (Event method, Accessor accessor):
6984                                 base (method, accessor, "remove_")
6985                         {
6986                         }
6987
6988                         protected override MethodInfo DelegateMethodInfo {
6989                                 get {
6990                                         return TypeManager.delegate_remove_delegate_delegate;
6991                                 }
6992                         }
6993                 }
6994
6995
6996                 static readonly string[] attribute_targets = new string [] { "event" }; // "property" target was disabled for 2.0 version
6997
6998                 public EventProperty (DeclSpace parent, FullNamedExpression type, int mod_flags,
6999                                       MemberName name,
7000                                       Attributes attrs, Accessor add, Accessor remove)
7001                         : base (parent, type, mod_flags, name, attrs)
7002                 {
7003                         Add = new AddDelegateMethod (this, add);
7004                         Remove = new RemoveDelegateMethod (this, remove);
7005                 }
7006
7007                 public override bool Define()
7008                 {
7009                         if (!base.Define ())
7010                                 return false;
7011
7012                         SetMemberIsUsed ();
7013                         return true;
7014                 }
7015
7016                 public override string[] ValidAttributeTargets {
7017                         get {
7018                                 return attribute_targets;
7019                         }
7020                 }
7021         }
7022
7023         /// <summary>
7024         /// Event is declared like field.
7025         /// </summary>
7026         public class EventField : Event {
7027                 abstract class EventFieldAccessor : AEventAccessor
7028                 {
7029                         protected EventFieldAccessor (Event method, string prefix)
7030                                 : base (method, prefix)
7031                         {
7032                         }
7033
7034                         protected override void EmitMethod(DeclSpace parent)
7035                         {
7036                                 if (method_data.implementing != null)
7037                                         parent.PartialContainer.PendingImplementations.ImplementMethod (
7038                                                 Name, method.InterfaceType, method_data, method.IsExplicitImpl);
7039                                 
7040                                 if ((method.ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7041                                         return;
7042
7043                                 MethodBuilder mb = method_data.MethodBuilder;
7044                                 ILGenerator ig = mb.GetILGenerator ();
7045
7046                                 // TODO: because we cannot use generics yet
7047                                 FieldInfo field_info = ((EventField)method).FieldBuilder;
7048
7049                                 if (parent is Class) {
7050                                         mb.SetImplementationFlags (mb.GetMethodImplementationFlags () | MethodImplAttributes.Synchronized);
7051                                 }
7052                                 
7053                                 if ((method.ModFlags & Modifiers.STATIC) != 0) {
7054                                         ig.Emit (OpCodes.Ldsfld, field_info);
7055                                         ig.Emit (OpCodes.Ldarg_0);
7056                                         ig.Emit (OpCodes.Call, DelegateMethodInfo);
7057                                         ig.Emit (OpCodes.Castclass, method.MemberType);
7058                                         ig.Emit (OpCodes.Stsfld, field_info);
7059                                 } else {
7060                                         ig.Emit (OpCodes.Ldarg_0);
7061                                         ig.Emit (OpCodes.Ldarg_0);
7062                                         ig.Emit (OpCodes.Ldfld, field_info);
7063                                         ig.Emit (OpCodes.Ldarg_1);
7064                                         ig.Emit (OpCodes.Call, DelegateMethodInfo);
7065                                         ig.Emit (OpCodes.Castclass, method.MemberType);
7066                                         ig.Emit (OpCodes.Stfld, field_info);
7067                                 }
7068                                 ig.Emit (OpCodes.Ret);
7069                         }
7070                 }
7071
7072                 sealed class AddDelegateMethod: EventFieldAccessor
7073                 {
7074                         public AddDelegateMethod (Event method):
7075                                 base (method, "add_")
7076                         {
7077                         }
7078
7079                         protected override MethodInfo DelegateMethodInfo {
7080                                 get {
7081                                         return TypeManager.delegate_combine_delegate_delegate;
7082                                 }
7083                         }
7084                 }
7085
7086                 sealed class RemoveDelegateMethod: EventFieldAccessor
7087                 {
7088                         public RemoveDelegateMethod (Event method):
7089                                 base (method, "remove_")
7090                         {
7091                         }
7092
7093                         protected override MethodInfo DelegateMethodInfo {
7094                                 get {
7095                                         return TypeManager.delegate_remove_delegate_delegate;
7096                                 }
7097                         }
7098                 }
7099
7100
7101                 static readonly string[] attribute_targets = new string [] { "event", "field", "method" };
7102                 static readonly string[] attribute_targets_interface = new string[] { "event", "method" };
7103
7104                 public FieldBuilder FieldBuilder;
7105                 public Expression Initializer;
7106
7107                 public EventField (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7108                         : base (parent, type, mod_flags, name, attrs)
7109                 {
7110                         Add = new AddDelegateMethod (this);
7111                         Remove = new RemoveDelegateMethod (this);
7112                 }
7113
7114                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7115                 {
7116                         if (a.Target == AttributeTargets.Field) {
7117                                 FieldBuilder.SetCustomAttribute (cb);
7118                                 return;
7119                         }
7120
7121                         if (a.Target == AttributeTargets.Method) {
7122                                 int errors = Report.Errors;
7123                                 Add.ApplyAttributeBuilder (a, cb);
7124                                 if (errors == Report.Errors)
7125                                         Remove.ApplyAttributeBuilder (a, cb);
7126                                 return;
7127                         }
7128
7129                         base.ApplyAttributeBuilder (a, cb);
7130                 }
7131
7132                 public override bool Define()
7133                 {
7134                         if (!base.Define ())
7135                                 return false;
7136
7137                         if (IsInterface)
7138                                 return true;
7139
7140                         // FIXME: We are unable to detect whether generic event is used because
7141                         // we are using FieldExpr instead of EventExpr for event access in that
7142                         // case.  When this issue will be fixed this hack can be removed.
7143                         if (TypeManager.IsGenericType (MemberType))
7144                                 SetMemberIsUsed();
7145
7146                         if (Add.IsInterfaceImplementation)
7147                                 SetMemberIsUsed ();
7148
7149                         FieldBuilder = Parent.TypeBuilder.DefineField (
7150                                 Name, MemberType,
7151                                 FieldAttributes.Private | ((ModFlags & Modifiers.STATIC) != 0 ? FieldAttributes.Static : 0));
7152                         TypeManager.RegisterEventField (EventBuilder, this);
7153
7154                         if (Initializer != null) {
7155                                 if (((ModFlags & Modifiers.ABSTRACT) != 0)) {
7156                                         Report.Error (74, Location, "`{0}': abstract event cannot have an initializer",
7157                                                 GetSignatureForError ());
7158                                         return false;
7159                                 }
7160
7161                                 ((TypeContainer) Parent).RegisterFieldForInitialization (this,
7162                                         new FieldInitializer (FieldBuilder, Initializer, this));
7163                         }
7164
7165                         return true;
7166                 }
7167
7168                 public override string[] ValidAttributeTargets 
7169                 {
7170                         get {
7171                                 return IsInterface ? attribute_targets_interface : attribute_targets;
7172                         }
7173                 }
7174         }
7175
7176         public abstract class Event : PropertyBasedMember {
7177                 public abstract class AEventAccessor : AbstractPropertyEventMethod
7178                 {
7179                         protected readonly Event method;
7180                         ImplicitParameter param_attr;
7181
7182                         static readonly string[] attribute_targets = new string [] { "method", "param", "return" };
7183
7184                         protected AEventAccessor (Event method, string prefix)
7185                                 : base (method, prefix)
7186                         {
7187                                 this.method = method;
7188                                 this.ModFlags = method.ModFlags;
7189                         }
7190
7191                         protected AEventAccessor (Event method, Accessor accessor, string prefix)
7192                                 : base (method, accessor, prefix)
7193                         {
7194                                 this.method = method;
7195                                 this.ModFlags = method.ModFlags;
7196                         }
7197
7198                         public bool IsInterfaceImplementation {
7199                                 get { return method_data.implementing != null; }
7200                         }
7201
7202                         public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7203                         {
7204                                 if (a.IsInternalMethodImplAttribute) {
7205                                         method.is_external_implementation = true;
7206                                 }
7207
7208                                 base.ApplyAttributeBuilder (a, cb);
7209                         }
7210
7211                         protected override void ApplyToExtraTarget(Attribute a, CustomAttributeBuilder cb)
7212                         {
7213                                 if (a.Target == AttributeTargets.Parameter) {
7214                                         if (param_attr == null)
7215                                                 param_attr = new ImplicitParameter (method_data.MethodBuilder);
7216
7217                                         param_attr.ApplyAttributeBuilder (a, cb);
7218                                         return;
7219                                 }
7220
7221                                 base.ApplyAttributeBuilder (a, cb);
7222                         }
7223
7224                         public override AttributeTargets AttributeTargets {
7225                                 get {
7226                                         return AttributeTargets.Method;
7227                                 }
7228                         }
7229
7230                         public override bool IsClsComplianceRequired ()
7231                         {
7232                                 return method.IsClsComplianceRequired ();
7233                         }
7234
7235                         public virtual MethodBuilder Define (DeclSpace parent)
7236                         {
7237                                 method_data = new MethodData (method, method.ModFlags,
7238                                         method.flags | MethodAttributes.HideBySig | MethodAttributes.SpecialName, this);
7239
7240                                 if (!method_data.Define (parent, method.GetFullName (MemberName)))
7241                                         return null;
7242
7243                                 MethodBuilder mb = method_data.MethodBuilder;
7244                                 ParameterInfo.ApplyAttributes (mb);
7245                                 return mb;
7246                         }
7247
7248                         protected abstract MethodInfo DelegateMethodInfo { get; }
7249
7250                         public override Type ReturnType {
7251                                 get {
7252                                         return TypeManager.void_type;
7253                                 }
7254                         }
7255
7256                         public override EmitContext CreateEmitContext (DeclSpace ds, ILGenerator ig)
7257                         {
7258                                 return new EmitContext (
7259                                         this, method.Parent, Location, ig, ReturnType,
7260                                         method.ModFlags, false);
7261                         }
7262
7263                         public override ObsoleteAttribute GetObsoleteAttribute ()
7264                         {
7265                                 return method.GetObsoleteAttribute ();
7266                         }
7267
7268                         public override string[] ValidAttributeTargets {
7269                                 get {
7270                                         return attribute_targets;
7271                                 }
7272                         }
7273
7274                         public override Parameters ParameterInfo {
7275                                 get {
7276                                         return method.parameters;
7277                                 }
7278                         }
7279                 }
7280
7281
7282                 const int AllowedModifiers =
7283                         Modifiers.NEW |
7284                         Modifiers.PUBLIC |
7285                         Modifiers.PROTECTED |
7286                         Modifiers.INTERNAL |
7287                         Modifiers.PRIVATE |
7288                         Modifiers.STATIC |
7289                         Modifiers.VIRTUAL |
7290                         Modifiers.SEALED |
7291                         Modifiers.OVERRIDE |
7292                         Modifiers.UNSAFE |
7293                         Modifiers.ABSTRACT |
7294                         Modifiers.EXTERN;
7295
7296                 const int AllowedInterfaceModifiers =
7297                         Modifiers.NEW;
7298
7299                 public AEventAccessor Add, Remove;
7300                 public MyEventBuilder     EventBuilder;
7301                 public MethodBuilder AddBuilder, RemoveBuilder;
7302
7303                 Parameters parameters;
7304
7305                 protected Event (DeclSpace parent, FullNamedExpression type, int mod_flags, MemberName name, Attributes attrs)
7306                         : base (parent, null, type, mod_flags,
7307                                 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7308                                 name, attrs)
7309                 {
7310                 }
7311
7312                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
7313                 {
7314                         if ((a.HasSecurityAttribute)) {
7315                                 a.Error_InvalidSecurityParent ();
7316                                 return;
7317                         }
7318                         
7319                         EventBuilder.SetCustomAttribute (cb);
7320                 }
7321
7322                 public bool AreAccessorsDuplicateImplementation (MethodCore mc)
7323                 {
7324                         return Add.IsDuplicateImplementation (mc) || Remove.IsDuplicateImplementation (mc);
7325                 }
7326
7327                 public override AttributeTargets AttributeTargets {
7328                         get {
7329                                 return AttributeTargets.Event;
7330                         }
7331                 }
7332
7333                 public override bool Define ()
7334                 {
7335                         if (!base.Define ())
7336                                 return false;
7337
7338                         if (!TypeManager.IsDelegateType (MemberType)) {
7339                                 Report.Error (66, Location, "`{0}': event must be of a delegate type", GetSignatureForError ());
7340                         }
7341
7342                         parameters = Parameters.CreateFullyResolved (
7343                                 new Parameter (null, "value", Parameter.Modifier.NONE, null, Location), MemberType);
7344
7345                         if (!CheckBase ())
7346                                 return false;
7347
7348                         if (TypeManager.delegate_combine_delegate_delegate == null) {
7349                                 TypeManager.delegate_combine_delegate_delegate = TypeManager.GetPredefinedMethod (
7350                                         TypeManager.delegate_type, "Combine", Location,
7351                                         TypeManager.delegate_type, TypeManager.delegate_type);
7352                         }
7353                         if (TypeManager.delegate_remove_delegate_delegate == null) {
7354                                 TypeManager.delegate_remove_delegate_delegate = TypeManager.GetPredefinedMethod (
7355                                         TypeManager.delegate_type, "Remove", Location,
7356                                         TypeManager.delegate_type, TypeManager.delegate_type);
7357                         }
7358
7359                         //
7360                         // Now define the accessors
7361                         //
7362
7363                         AddBuilder = Add.Define (Parent);
7364                         if (AddBuilder == null)
7365                                 return false;
7366
7367                         RemoveBuilder = Remove.Define (Parent);
7368                         if (RemoveBuilder == null)
7369                                 return false;
7370
7371                         EventBuilder = new MyEventBuilder (this, Parent.TypeBuilder, Name, EventAttributes.None, MemberType);                                           
7372                         EventBuilder.SetAddOnMethod (AddBuilder);
7373                         EventBuilder.SetRemoveOnMethod (RemoveBuilder);
7374
7375                         Parent.MemberCache.AddMember (EventBuilder, this);
7376                         Parent.MemberCache.AddMember (AddBuilder, Add);
7377                         Parent.MemberCache.AddMember (RemoveBuilder, Remove);
7378                         
7379                         return true;
7380                 }
7381
7382                 public override void Emit ()
7383                 {
7384                         if (OptAttributes != null) {
7385                                 OptAttributes.Emit ();
7386                         }
7387
7388                         Add.Emit (Parent);
7389                         Remove.Emit (Parent);
7390
7391                         base.Emit ();
7392                 }
7393
7394                 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7395                 {
7396                         MethodInfo mi = (MethodInfo) Parent.PartialContainer.BaseCache.FindBaseEvent (
7397                                 Parent.TypeBuilder, Name);
7398
7399                         if (mi == null)
7400                                 return null;
7401
7402                         AParametersCollection pd = TypeManager.GetParameterData (mi);
7403                         base_ret_type = pd.Types [0];
7404                         return mi;
7405                 }
7406
7407                 //
7408                 //   Represents header string for documentation comment.
7409                 //
7410                 public override string DocCommentHeader {
7411                         get { return "E:"; }
7412                 }
7413         }
7414
7415  
7416         public class Indexer : PropertyBase
7417         {
7418                 public class GetIndexerMethod : GetMethod
7419                 {
7420                         Parameters parameters;
7421
7422                         public GetIndexerMethod (Indexer method):
7423                                 base (method)
7424                         {
7425                                 this.parameters = method.parameters;
7426                         }
7427
7428                         public GetIndexerMethod (PropertyBase method, Accessor accessor):
7429                                 base (method, accessor)
7430                         {
7431                                 parameters = accessor.Parameters;
7432                         }
7433
7434                         public override MethodBuilder Define (DeclSpace parent)
7435                         {
7436                                 parameters.Resolve (ResolveContext);
7437                                 return base.Define (parent);
7438                         }
7439                         
7440                         public override bool EnableOverloadChecks (MemberCore overload)
7441                         {
7442                                 if (base.EnableOverloadChecks (overload)) {
7443                                         overload.caching_flags |= Flags.MethodOverloadsExist;
7444                                         return true;
7445                                 }
7446
7447                                 return false;
7448                         }                       
7449
7450                         public override Parameters ParameterInfo {
7451                                 get {
7452                                         return parameters;
7453                                 }
7454                         }
7455                 }
7456
7457                 public class SetIndexerMethod: SetMethod
7458                 {
7459                         public SetIndexerMethod (Indexer method):
7460                                 base (method)
7461                         {
7462                                 parameters = Parameters.MergeGenerated (method.parameters, false, parameters [0], null);
7463                         }
7464
7465                         public SetIndexerMethod (PropertyBase method, Accessor accessor):
7466                                 base (method, accessor)
7467                         {
7468                                 parameters = method.Get.IsDummy ? accessor.Parameters : accessor.Parameters.Clone ();                   
7469                         }
7470
7471                         public override bool EnableOverloadChecks (MemberCore overload)
7472                         {
7473                                 if (base.EnableOverloadChecks (overload)) {
7474                                         overload.caching_flags |= Flags.MethodOverloadsExist;
7475                                         return true;
7476                                 }
7477
7478                                 return false;
7479                         }
7480                 }
7481
7482                 const int AllowedModifiers =
7483                         Modifiers.NEW |
7484                         Modifiers.PUBLIC |
7485                         Modifiers.PROTECTED |
7486                         Modifiers.INTERNAL |
7487                         Modifiers.PRIVATE |
7488                         Modifiers.VIRTUAL |
7489                         Modifiers.SEALED |
7490                         Modifiers.OVERRIDE |
7491                         Modifiers.UNSAFE |
7492                         Modifiers.EXTERN |
7493                         Modifiers.ABSTRACT;
7494
7495                 const int AllowedInterfaceModifiers =
7496                         Modifiers.NEW;
7497
7498                 public readonly Parameters parameters;
7499
7500                 public Indexer (DeclSpace parent, FullNamedExpression type, MemberName name, int mod,
7501                                 Parameters parameters, Attributes attrs,
7502                                 Accessor get_block, Accessor set_block, bool define_set_first)
7503                         : base (parent, type, mod,
7504                                 parent.PartialContainer.Kind == Kind.Interface ? AllowedInterfaceModifiers : AllowedModifiers,
7505                                 name, attrs, define_set_first)
7506                 {
7507                         this.parameters = parameters;
7508
7509                         if (get_block == null)
7510                                 Get = new GetIndexerMethod (this);
7511                         else
7512                                 Get = new GetIndexerMethod (this, get_block);
7513
7514                         if (set_block == null)
7515                                 Set = new SetIndexerMethod (this);
7516                         else
7517                                 Set = new SetIndexerMethod (this, set_block);
7518                 }
7519
7520                 protected override bool CheckForDuplications ()
7521                 {
7522                         return Parent.MemberCache.CheckExistingMembersOverloads (this, GetFullName (MemberName), parameters);
7523                 }
7524                 
7525                 public override bool Define ()
7526                 {
7527                         if (!base.Define ())
7528                                 return false;
7529
7530                         if (!DefineParameters (parameters))
7531                                 return false;
7532
7533                         if (OptAttributes != null && TypeManager.indexer_name_type != null) {
7534                                 Attribute indexer_attr = OptAttributes.Search (TypeManager.indexer_name_type);
7535                                 if (indexer_attr != null) {
7536                                         // Remove the attribute from the list because it is not emitted
7537                                         OptAttributes.Attrs.Remove (indexer_attr);
7538
7539                                         string name = indexer_attr.GetIndexerAttributeValue ();
7540                                         if (name == null)
7541                                                 return false;
7542
7543                                         ShortName = name;
7544
7545                                         if (IsExplicitImpl) {
7546                                                 Report.Error (415, indexer_attr.Location,
7547                                                               "The `IndexerName' attribute is valid only on an " +
7548                                                               "indexer that is not an explicit interface member declaration");
7549                                                 return false;
7550                                         }
7551
7552                                         if ((ModFlags & Modifiers.OVERRIDE) != 0) {
7553                                                 Report.Error (609, indexer_attr.Location,
7554                                                               "Cannot set the `IndexerName' attribute on an indexer marked override");
7555                                                 return false;
7556                                         }
7557                                 }
7558                         }
7559
7560                         if (InterfaceType != null) {
7561                                 string base_IndexerName = TypeManager.IndexerPropertyName (InterfaceType);
7562                                 if (base_IndexerName != Name)
7563                                         ShortName = base_IndexerName;
7564                         }
7565
7566                         if (!Parent.PartialContainer.AddMember (this) ||
7567                                 !Parent.PartialContainer.AddMember (Get) || !Parent.PartialContainer.AddMember (Set))
7568                                 return false;
7569
7570                         flags |= MethodAttributes.HideBySig | MethodAttributes.SpecialName;
7571                         
7572                         if (!DefineAccessors ())
7573                                 return false;
7574
7575                         if (!CheckBase ())
7576                                 return false;
7577
7578                         //
7579                         // Now name the parameters
7580                         //
7581                         PropertyBuilder = Parent.TypeBuilder.DefineProperty (
7582                                 GetFullName (MemberName), PropertyAttributes.None, MemberType, parameters.GetEmitTypes ());
7583
7584                         if (!Get.IsDummy) {
7585                                 PropertyBuilder.SetGetMethod (GetBuilder);
7586                                 Parent.MemberCache.AddMember (GetBuilder, Get);
7587                         }
7588
7589                         if (!Set.IsDummy) {
7590                                 PropertyBuilder.SetSetMethod (SetBuilder);
7591                                 Parent.MemberCache.AddMember (SetBuilder, Set);
7592                         }
7593                                 
7594                         TypeManager.RegisterIndexer (PropertyBuilder, parameters);
7595                         Parent.MemberCache.AddMember (PropertyBuilder, this);
7596                         return true;
7597                 }
7598
7599                 public override bool EnableOverloadChecks (MemberCore overload)
7600                 {
7601                         if (overload is Indexer) {
7602                                 caching_flags |= Flags.MethodOverloadsExist;
7603                                 return true;
7604                         }
7605
7606                         return base.EnableOverloadChecks (overload);
7607                 }
7608
7609                 public override string GetDocCommentName (DeclSpace ds)
7610                 {
7611                         return DocUtil.GetMethodDocCommentName (this, parameters, ds);
7612                 }
7613
7614                 public override string GetSignatureForError ()
7615                 {
7616                         StringBuilder sb = new StringBuilder (Parent.GetSignatureForError ());
7617                         if (MemberName.Left != null) {
7618                                 sb.Append ('.');
7619                                 sb.Append (MemberName.Left.GetSignatureForError ());
7620                         }
7621
7622                         sb.Append (".this");
7623                         sb.Append (parameters.GetSignatureForError ().Replace ('(', '[').Replace (')', ']'));
7624                         return sb.ToString ();
7625                 }
7626
7627                 protected override PropertyInfo ResolveBaseProperty ()
7628                 {
7629                         return Parent.PartialContainer.BaseCache.FindMemberToOverride (
7630                                 Parent.TypeBuilder, Name, parameters, null, true) as PropertyInfo;
7631                 }
7632
7633                 protected override bool VerifyClsCompliance ()
7634                 {
7635                         if (!base.VerifyClsCompliance ())
7636                                 return false;
7637
7638                         parameters.VerifyClsCompliance ();
7639                         return true;
7640                 }
7641         }
7642
7643         public class Operator : MethodOrOperator {
7644
7645                 const int AllowedModifiers =
7646                         Modifiers.PUBLIC |
7647                         Modifiers.UNSAFE |
7648                         Modifiers.EXTERN |
7649                         Modifiers.STATIC;
7650
7651                 public enum OpType : byte {
7652
7653                         // Unary operators
7654                         LogicalNot,
7655                         OnesComplement,
7656                         Increment,
7657                         Decrement,
7658                         True,
7659                         False,
7660
7661                         // Unary and Binary operators
7662                         Addition,
7663                         Subtraction,
7664
7665                         UnaryPlus,
7666                         UnaryNegation,
7667                         
7668                         // Binary operators
7669                         Multiply,
7670                         Division,
7671                         Modulus,
7672                         BitwiseAnd,
7673                         BitwiseOr,
7674                         ExclusiveOr,
7675                         LeftShift,
7676                         RightShift,
7677                         Equality,
7678                         Inequality,
7679                         GreaterThan,
7680                         LessThan,
7681                         GreaterThanOrEqual,
7682                         LessThanOrEqual,
7683
7684                         // Implicit and Explicit
7685                         Implicit,
7686                         Explicit,
7687
7688                         // Just because of enum
7689                         TOP
7690                 };
7691
7692                 public readonly OpType OperatorType;
7693
7694                 static readonly string [] [] names;
7695
7696                 static Operator ()
7697                 {
7698                         names = new string[(int)OpType.TOP][];
7699                         names [(int) OpType.LogicalNot] = new string [] { "!", "op_LogicalNot" };
7700                         names [(int) OpType.OnesComplement] = new string [] { "~", "op_OnesComplement" };
7701                         names [(int) OpType.Increment] = new string [] { "++", "op_Increment" };
7702                         names [(int) OpType.Decrement] = new string [] { "--", "op_Decrement" };
7703                         names [(int) OpType.True] = new string [] { "true", "op_True" };
7704                         names [(int) OpType.False] = new string [] { "false", "op_False" };
7705                         names [(int) OpType.Addition] = new string [] { "+", "op_Addition" };
7706                         names [(int) OpType.Subtraction] = new string [] { "-", "op_Subtraction" };
7707                         names [(int) OpType.UnaryPlus] = new string [] { "+", "op_UnaryPlus" };
7708                         names [(int) OpType.UnaryNegation] = new string [] { "-", "op_UnaryNegation" };
7709                         names [(int) OpType.Multiply] = new string [] { "*", "op_Multiply" };
7710                         names [(int) OpType.Division] = new string [] { "/", "op_Division" };
7711                         names [(int) OpType.Modulus] = new string [] { "%", "op_Modulus" };
7712                         names [(int) OpType.BitwiseAnd] = new string [] { "&", "op_BitwiseAnd" };
7713                         names [(int) OpType.BitwiseOr] = new string [] { "|", "op_BitwiseOr" };
7714                         names [(int) OpType.ExclusiveOr] = new string [] { "^", "op_ExclusiveOr" };
7715                         names [(int) OpType.LeftShift] = new string [] { "<<", "op_LeftShift" };
7716                         names [(int) OpType.RightShift] = new string [] { ">>", "op_RightShift" };
7717                         names [(int) OpType.Equality] = new string [] { "==", "op_Equality" };
7718                         names [(int) OpType.Inequality] = new string [] { "!=", "op_Inequality" };
7719                         names [(int) OpType.GreaterThan] = new string [] { ">", "op_GreaterThan" };
7720                         names [(int) OpType.LessThan] = new string [] { "<", "op_LessThan" };
7721                         names [(int) OpType.GreaterThanOrEqual] = new string [] { ">=", "op_GreaterThanOrEqual" };
7722                         names [(int) OpType.LessThanOrEqual] = new string [] { "<=", "op_LessThanOrEqual" };
7723                         names [(int) OpType.Implicit] = new string [] { "implicit", "op_Implicit" };
7724                         names [(int) OpType.Explicit] = new string [] { "explicit", "op_Explicit" };
7725                 }
7726                 
7727                 public Operator (DeclSpace parent, OpType type, FullNamedExpression ret_type,
7728                                  int mod_flags, Parameters parameters,
7729                                  ToplevelBlock block, Attributes attrs, Location loc)
7730                         : base (parent, null, ret_type, mod_flags, AllowedModifiers,
7731                                 new MemberName (GetMetadataName (type), loc), attrs, parameters)
7732                 {
7733                         OperatorType = type;
7734                         Block = block;
7735                 }
7736
7737                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb) 
7738                 {
7739                         if (a.Type == TypeManager.conditional_attribute_type) {
7740                                 Error_ConditionalAttributeIsNotValid ();
7741                                 return;
7742                         }
7743
7744                         base.ApplyAttributeBuilder (a, cb);
7745                 }
7746                 
7747                 public override bool Define ()
7748                 {
7749                         const int RequiredModifiers = Modifiers.PUBLIC | Modifiers.STATIC;
7750                         if ((ModFlags & RequiredModifiers) != RequiredModifiers){
7751                                 Report.Error (558, Location, "User-defined operator `{0}' must be declared static and public", GetSignatureForError ());
7752                         }
7753
7754                         if (!base.Define ())
7755                                 return false;
7756
7757                         // imlicit and explicit operator of same types are not allowed
7758                         if (OperatorType == OpType.Explicit)
7759                                 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Implicit), Parameters);
7760                         else if (OperatorType == OpType.Implicit)
7761                                 Parent.MemberCache.CheckExistingMembersOverloads (this, GetMetadataName (OpType.Explicit), Parameters);
7762
7763                         Type declaring_type = MethodData.DeclaringType;
7764                         Type return_type = MemberType;
7765                         Type first_arg_type = ParameterTypes [0];
7766                         
7767                         Type first_arg_type_unwrap = first_arg_type;
7768                         if (TypeManager.IsNullableType (first_arg_type))
7769                                 first_arg_type_unwrap = TypeManager.GetTypeArguments (first_arg_type) [0];
7770                         
7771                         Type return_type_unwrap = return_type;
7772                         if (TypeManager.IsNullableType (return_type))
7773                                 return_type_unwrap = TypeManager.GetTypeArguments (return_type) [0];                    
7774
7775                         //
7776                         // Rules for conversion operators
7777                         //
7778                         if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7779                                 if (first_arg_type_unwrap == return_type_unwrap && first_arg_type_unwrap == declaring_type){
7780                                         Report.Error (555, Location,
7781                                                 "User-defined operator cannot take an object of the enclosing type and convert to an object of the enclosing type");
7782                                         return false;
7783                                 }
7784                                 
7785                                 Type conv_type;
7786                                 if (TypeManager.IsEqual (declaring_type, return_type) || declaring_type == return_type_unwrap) {
7787                                         conv_type = first_arg_type;
7788                                 } else if (TypeManager.IsEqual (declaring_type, first_arg_type) || declaring_type == first_arg_type_unwrap) {
7789                                         conv_type = return_type;
7790                                 } else {
7791                                         Report.Error (556, Location, 
7792                                                 "User-defined conversion must convert to or from the enclosing type");
7793                                         return false;
7794                                 }
7795
7796                                 //
7797                                 // Because IsInterface and IsClass are not supported
7798                                 //
7799                                 if (!TypeManager.IsGenericParameter (conv_type)) {
7800                                         if (conv_type.IsInterface) {
7801                                                 Report.Error (552, Location, "User-defined conversion `{0}' cannot convert to or from an interface type",
7802                                                         GetSignatureForError ());
7803                                                 return false;
7804                                         }
7805
7806                                         if (conv_type.IsClass) {
7807                                                 if (TypeManager.IsSubclassOf (declaring_type, conv_type)) {
7808                                                         Report.Error (553, Location, "User-defined conversion `{0}' cannot convert to or from a base class",
7809                                                                 GetSignatureForError ());
7810                                                         return false;
7811                                                 }
7812
7813                                                 if (TypeManager.IsSubclassOf (conv_type, declaring_type)) {
7814                                                         Report.Error (554, Location, "User-defined conversion `{0}' cannot convert to or from a derived class",
7815                                                                 GetSignatureForError ());
7816                                                         return false;
7817                                                 }
7818                                         }
7819                                 }
7820                         } else if (OperatorType == OpType.LeftShift || OperatorType == OpType.RightShift) {
7821                                 if (first_arg_type != declaring_type || Parameters.Types [1] != TypeManager.int32_type) {
7822                                         Report.Error (564, Location, "Overloaded shift operator must have the type of the first operand be the containing type, and the type of the second operand must be int");
7823                                         return false;
7824                                 }
7825                         } else if (Parameters.Count == 1) {
7826                                 // Checks for Unary operators
7827
7828                                 if (OperatorType == OpType.Increment || OperatorType == OpType.Decrement) {
7829                                         if (return_type != declaring_type && !TypeManager.IsSubclassOf (return_type, declaring_type)) {
7830                                                 Report.Error (448, Location,
7831                                                         "The return type for ++ or -- operator must be the containing type or derived from the containing type");
7832                                                 return false;
7833                                         }
7834                                         if (first_arg_type != declaring_type) {
7835                                                 Report.Error (
7836                                                         559, Location, "The parameter type for ++ or -- operator must be the containing type");
7837                                                 return false;
7838                                         }
7839                                 }
7840                                 
7841                                 if (!TypeManager.IsEqual (first_arg_type_unwrap, declaring_type)){
7842                                         Report.Error (562, Location,
7843                                                 "The parameter type of a unary operator must be the containing type");
7844                                         return false;
7845                                 }
7846                                 
7847                                 if (OperatorType == OpType.True || OperatorType == OpType.False) {
7848                                         if (return_type != TypeManager.bool_type){
7849                                                 Report.Error (
7850                                                         215, Location,
7851                                                         "The return type of operator True or False " +
7852                                                         "must be bool");
7853                                                 return false;
7854                                         }
7855                                 }
7856                                 
7857                         } else {
7858                                 // Checks for Binary operators
7859                                 
7860                                 if (first_arg_type != declaring_type &&
7861                                     Parameters.Types [1] != declaring_type){
7862                                         Report.Error (
7863                                                 563, Location,
7864                                                 "One of the parameters of a binary operator must " +
7865                                                 "be the containing type");
7866                                         return false;
7867                                 }
7868                         }
7869
7870                         return true;
7871                 }
7872
7873                 protected override bool ResolveMemberType ()
7874                 {
7875                         if (!base.ResolveMemberType ())
7876                                 return false;
7877
7878                         flags |= MethodAttributes.SpecialName | MethodAttributes.HideBySig;
7879                         return true;
7880                 }
7881                 
7882                 public override void Emit ()
7883                 {
7884                         base.Emit ();
7885
7886                         Parameters.ApplyAttributes (MethodBuilder);
7887
7888                         //
7889                         // abstract or extern methods have no bodies
7890                         //
7891                         if ((ModFlags & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
7892                                 return;
7893                         
7894                         EmitContext ec;
7895                         if ((flags & MethodAttributes.PinvokeImpl) == 0)
7896                                 ec = CreateEmitContext (Parent, MethodBuilder.GetILGenerator ());
7897                         else
7898                                 ec = CreateEmitContext (Parent, null);
7899                         
7900                         SourceMethod source = SourceMethod.Create (Parent, MethodBuilder, Block);
7901                         ec.EmitTopBlock (this, Block);
7902
7903                         if (source != null)
7904                                 source.CloseMethod ();
7905
7906                         Block = null;
7907                 }
7908
7909                 // Operator cannot be override
7910                 protected override MethodInfo FindOutBaseMethod (ref Type base_ret_type)
7911                 {
7912                         return null;
7913                 }
7914
7915                 public static string GetName (OpType ot)
7916                 {
7917                         return names [(int) ot] [0];
7918                 }
7919
7920                 public static string GetName (string metadata_name)
7921                 {
7922                         for (int i = 0; i < names.Length; ++i) {
7923                                 if (names [i] [1] == metadata_name)
7924                                         return names [i] [0];
7925                         }
7926                         return null;
7927                 }
7928
7929                 public static string GetMetadataName (OpType ot)
7930                 {
7931                         return names [(int) ot] [1];
7932                 }
7933
7934                 public static string GetMetadataName (string name)
7935                 {
7936                         for (int i = 0; i < names.Length; ++i) {
7937                                 if (names [i] [0] == name)
7938                                         return names [i] [1];
7939                         }
7940                         return null;
7941                 }
7942
7943                 public OpType GetMatchingOperator ()
7944                 {
7945                         switch (OperatorType) {
7946                         case OpType.Equality:
7947                                 return OpType.Inequality;
7948                         case OpType.Inequality:
7949                                 return OpType.Equality;
7950                         case OpType.True:
7951                                 return OpType.False;
7952                         case OpType.False:
7953                                 return OpType.True;
7954                         case OpType.GreaterThan:
7955                                 return OpType.LessThan;
7956                         case OpType.LessThan:
7957                                 return OpType.GreaterThan;
7958                         case OpType.GreaterThanOrEqual:
7959                                 return OpType.LessThanOrEqual;
7960                         case OpType.LessThanOrEqual:
7961                                 return OpType.GreaterThanOrEqual;
7962                         default:
7963                                 return OpType.TOP;
7964                         }
7965                 }
7966
7967                 public override string GetSignatureForError ()
7968                 {
7969                         StringBuilder sb = new StringBuilder ();
7970                         if (OperatorType == OpType.Implicit || OperatorType == OpType.Explicit) {
7971                                 sb.AppendFormat ("{0}.{1} operator {2}",
7972                                         Parent.GetSignatureForError (), GetName (OperatorType), type_name.GetSignatureForError ());
7973                         }
7974                         else {
7975                                 sb.AppendFormat ("{0}.operator {1}", Parent.GetSignatureForError (), GetName (OperatorType));
7976                         }
7977
7978                         sb.Append (Parameters.GetSignatureForError ());
7979                         return sb.ToString ();
7980                 }
7981         }
7982
7983         //
7984         // This is used to compare method signatures
7985         //
7986         struct MethodSignature {
7987                 public string Name;
7988                 public Type RetType;
7989                 public Type [] Parameters;
7990                 
7991                 /// <summary>
7992                 ///    This delegate is used to extract methods which have the
7993                 ///    same signature as the argument
7994                 /// </summary>
7995                 public static MemberFilter method_signature_filter = new MemberFilter (MemberSignatureCompare);
7996                 
7997                 public MethodSignature (string name, Type ret_type, Type [] parameters)
7998                 {
7999                         Name = name;
8000                         RetType = ret_type;
8001
8002                         if (parameters == null)
8003                                 Parameters = Type.EmptyTypes;
8004                         else
8005                                 Parameters = parameters;
8006                 }
8007
8008                 public override string ToString ()
8009                 {
8010                         string pars = "";
8011                         if (Parameters.Length != 0){
8012                                 System.Text.StringBuilder sb = new System.Text.StringBuilder ();
8013                                 for (int i = 0; i < Parameters.Length; i++){
8014                                         sb.Append (Parameters [i]);
8015                                         if (i+1 < Parameters.Length)
8016                                                 sb.Append (", ");
8017                                 }
8018                                 pars = sb.ToString ();
8019                         }
8020
8021                         return String.Format ("{0} {1} ({2})", RetType, Name, pars);
8022                 }
8023                 
8024                 public override int GetHashCode ()
8025                 {
8026                         return Name.GetHashCode ();
8027                 }
8028
8029                 public override bool Equals (Object o)
8030                 {
8031                         MethodSignature other = (MethodSignature) o;
8032
8033                         if (other.Name != Name)
8034                                 return false;
8035
8036                         if (other.RetType != RetType)
8037                                 return false;
8038                         
8039                         if (Parameters == null){
8040                                 if (other.Parameters == null)
8041                                         return true;
8042                                 return false;
8043                         }
8044
8045                         if (other.Parameters == null)
8046                                 return false;
8047                         
8048                         int c = Parameters.Length;
8049                         if (other.Parameters.Length != c)
8050                                 return false;
8051
8052                         for (int i = 0; i < c; i++)
8053                                 if (other.Parameters [i] != Parameters [i])
8054                                         return false;
8055
8056                         return true;
8057                 }
8058
8059                 static bool MemberSignatureCompare (MemberInfo m, object filter_criteria)
8060                 {
8061                         MethodSignature sig = (MethodSignature) filter_criteria;
8062
8063                         if (m.Name != sig.Name)
8064                                 return false;
8065
8066                         Type ReturnType;
8067                         MethodInfo mi = m as MethodInfo;
8068                         PropertyInfo pi = m as PropertyInfo;
8069
8070                         if (mi != null)
8071                                 ReturnType = mi.ReturnType;
8072                         else if (pi != null)
8073                                 ReturnType = pi.PropertyType;
8074                         else
8075                                 return false;
8076
8077                         //
8078                         // we use sig.RetType == null to mean `do not check the
8079                         // method return value.  
8080                         //
8081                         if (sig.RetType != null) {
8082                                 if (!TypeManager.IsEqual (ReturnType, sig.RetType))
8083                                         return false;
8084                         }
8085
8086                         Type [] args;
8087                         if (mi != null)
8088                                 args = TypeManager.GetParameterData (mi).Types;
8089                         else
8090                                 args = TypeManager.GetParameterData (pi).Types;
8091                         Type [] sigp = sig.Parameters;
8092
8093                         if (args.Length != sigp.Length)
8094                                 return false;
8095
8096                         for (int i = args.Length - 1; i >= 0; i--)
8097                                 if (!TypeManager.IsEqual (args [i], sigp [i]))
8098                                         return false;
8099
8100                         return true;
8101                 }
8102         }
8103 }
8104