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