9d564c596611616a05f573430f3de7cb4d81a4cc
[mono.git] / mcs / gmcs / decl.cs
1 //
2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Marek Safar (marek.safar@seznam.cz)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // (C) 2004 Novell, Inc
11 //
12 // TODO: Move the method verification stuff from the class.cs and interface.cs here
13 //
14
15 using System;
16 using System.Text;
17 using System.Collections;
18 using System.Globalization;
19 using System.Reflection.Emit;
20 using System.Reflection;
21 using System.Xml;
22
23 namespace Mono.CSharp {
24
25         public class MemberName {
26                 public readonly string Name;
27                 public readonly TypeArguments TypeArguments;
28
29                 public readonly MemberName Left;
30                 public readonly Location Location;
31
32                 public static readonly MemberName Null = new MemberName ("", Location.Null);
33
34                 bool is_double_colon;
35
36                 private MemberName (MemberName left, string name, bool is_double_colon,
37                                     TypeArguments args, Location loc)
38                 {
39                         this.Name = name;
40                         this.Location = loc;
41                         this.is_double_colon = is_double_colon;
42                         this.TypeArguments = args;
43                         this.Left = left;
44                 }
45
46                 public MemberName (string name, TypeArguments args, Location loc)
47                         : this (name, loc)
48                 {
49                         this.TypeArguments = args;
50                 }
51
52                 public MemberName (string name, Location loc)
53                 {
54                         this.Name = name;
55                         this.Location = loc;
56                 }
57
58                 public MemberName (MemberName left, string name, Location loc)
59                         : this (name, loc)
60                 {
61                         this.Left = left;
62                 }
63
64                 public MemberName (MemberName left, string name, TypeArguments args, Location loc)
65                         : this (name, args, loc)
66                 {
67                         this.Left = left;
68                 }
69
70                 public MemberName (string alias, string name, Location loc)
71                         : this (new MemberName (alias, loc), name, true, null, loc)
72                 {
73                 }
74
75                 public MemberName (MemberName left, MemberName right)
76                         : this (left, right, right.Location)
77                 {
78                 }
79
80                 public MemberName (MemberName left, MemberName right, Location loc)
81                         : this (null, right.Name, false, right.TypeArguments, loc)
82                 {
83                         if (right.is_double_colon)
84                                 throw new InternalErrorException ("Cannot append double_colon member name");
85                         this.Left = (right.Left == null) ? left : new MemberName (left, right.Left);
86                 }
87
88                 static readonly char [] dot_array = { '.' };
89
90                 public static MemberName FromDotted (string name, Location loc)
91                 {
92                         string [] elements = name.Split (dot_array);
93                         int count = elements.Length;
94                         int i = 0;
95                         MemberName n = new MemberName (elements [i++], loc);
96                         while (i < count)
97                                 n = new MemberName (n, elements [i++], loc);
98                         return n;
99                 }
100
101                 public string GetName ()
102                 {
103                         string connect = is_double_colon ? "::" : ".";
104                         if (Left != null)
105                                 return Left.GetName () + connect + Name;
106                         else
107                                 return Name;
108                 }
109
110                 public bool IsGeneric {
111                         get {
112                                 if (TypeArguments != null)
113                                         return true;
114                                 else if (Left != null)
115                                         return Left.IsGeneric;
116                                 else
117                                         return false;
118                         }
119                 }
120
121                 public string GetName (bool is_generic)
122                 {
123                         string name = is_generic ? Basename : Name;
124                         string connect = is_double_colon ? "::" : ".";
125                         if (Left != null)
126                                 return Left.GetName (is_generic) + connect + name;
127                         else
128                                 return name;
129                 }
130
131                 public int CountTypeArguments {
132                         get {
133                                 if (TypeArguments == null)
134                                         return 0;
135                                 else
136                                         return TypeArguments.Count;
137                         }
138                 }
139
140                 public string MethodName {
141                         get {
142                                 string connect = is_double_colon ? "::" : ".";
143                                 if (Left != null)
144                                         return Left.FullName + connect + Name;
145                                 else
146                                         return Name;
147                         }
148                 }
149
150                 public static string MakeName (string name, TypeArguments args)
151                 {
152                         if (args == null)
153                                 return name;
154                         else
155                                 return name + "`" + args.Count;
156                 }
157
158                 public static string MakeName (string name, int count)
159                 {
160                         return name + "`" + count;
161                 }
162
163                 public string GetTypeName ()
164                 {
165                         string connect = is_double_colon ? "::" : ".";
166                         if (Left != null)
167                                 return Left.GetTypeName () + connect +
168                                         MakeName (Name, TypeArguments);
169                         else
170                                 return MakeName (Name, TypeArguments);
171                 }
172
173                 protected bool IsUnbound {
174                         get {
175                                 if ((Left != null) && Left.IsUnbound)
176                                         return true;
177                                 else if (TypeArguments == null)
178                                         return false;
179                                 else
180                                         return TypeArguments.IsUnbound;
181                         }
182                 }
183
184                 protected bool CheckUnbound (Location loc)
185                 {
186                         if ((Left != null) && !Left.CheckUnbound (loc))
187                                 return false;
188                         if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
189                                 Report.Error (1031, loc, "Type expected");
190                                 return false;
191                         }
192
193                         return true;
194                 }
195
196                 public Expression GetTypeExpression ()
197                 {
198                         if (IsUnbound) {
199                                 if (!CheckUnbound (Location))
200                                         return null;
201
202                                 return new UnboundTypeExpression (this, Location);
203                         }
204
205                         if (Left == null) {
206                                 if (TypeArguments != null)
207                                         return new SimpleName (Basename, TypeArguments, Location);
208                                 else
209                                         return new SimpleName (Name, Location);
210                         }
211
212                         if (is_double_colon) {
213                                 if (Left.Left != null)
214                                         throw new InternalErrorException ("The left side of a :: should be an identifier");
215                                 return new QualifiedAliasMember (Left.Name, Name, Location);
216                         }
217
218                         Expression lexpr = Left.GetTypeExpression ();
219                         return new MemberAccess (lexpr, Name, TypeArguments, Location);
220                 }
221
222                 public MemberName Clone ()
223                 {
224                         MemberName left_clone = Left == null ? null : Left.Clone ();
225                         return new MemberName (left_clone, Name, is_double_colon, TypeArguments, Location);
226                 }
227
228                 public string Basename {
229                         get {
230                                 if (TypeArguments != null)
231                                         return MakeName (Name, TypeArguments);
232                                 else
233                                         return Name;
234                         }
235                 }
236
237                 public string FullName {
238                         get {
239                                 if (TypeArguments != null)
240                                         return Name + "<" + TypeArguments + ">";
241                                 else
242                                         return Name;
243                         }
244                 }
245
246                 public override string ToString ()
247                 {
248                         string connect = is_double_colon ? "::" : ".";
249                         if (Left != null)
250                                 return Left.FullName + connect + FullName;
251                         else
252                                 return FullName;
253                 }
254
255                 public override bool Equals (object other)
256                 {
257                         return Equals (other as MemberName);
258                 }
259
260                 public bool Equals (MemberName other)
261                 {
262                         if (this == other)
263                                 return true;
264                         if (other == null || Name != other.Name)
265                                 return false;
266                         if (is_double_colon != other.is_double_colon)
267                                 return false;
268
269                         if ((TypeArguments != null) &&
270                             (other.TypeArguments == null || TypeArguments.Count != other.TypeArguments.Count))
271                                 return false;
272
273                         if ((TypeArguments == null) && (other.TypeArguments != null))
274                                 return false;
275
276                         if (Left == null)
277                                 return other.Left == null;
278
279                         return Left.Equals (other.Left);
280                 }
281
282                 public override int GetHashCode ()
283                 {
284                         int hash = Name.GetHashCode ();
285                         for (MemberName n = Left; n != null; n = n.Left)
286                                 hash ^= n.Name.GetHashCode ();
287                         if (is_double_colon)
288                                 hash ^= 0xbadc01d;
289
290                         if (TypeArguments != null)
291                                 hash ^= TypeArguments.Count << 5;
292
293                         return hash & 0x7FFFFFFF;
294                 }
295         }
296
297         /// <summary>
298         ///   Base representation for members.  This is used to keep track
299         ///   of Name, Location and Modifier flags, and handling Attributes.
300         /// </summary>
301         public abstract class MemberCore : Attributable, IResolveContext {
302                 /// <summary>
303                 ///   Public name
304                 /// </summary>
305
306                 protected string cached_name;
307                 public string Name {
308                         get {
309                                 if (cached_name == null)
310                                         cached_name = MemberName.GetName (!(this is GenericMethod) && !(this is Method));
311                                 return cached_name;
312                         }
313                 }
314
315                 // Is not readonly because of IndexerName attribute
316                 private MemberName member_name;
317                 public MemberName MemberName {
318                         get { return member_name; }
319                 }
320
321                 /// <summary>
322                 ///   Modifier flags that the user specified in the source code
323                 /// </summary>
324                 public int ModFlags;
325
326                 public /*readonly*/ DeclSpace Parent;
327
328                 /// <summary>
329                 ///   Location where this declaration happens
330                 /// </summary>
331                 public Location Location {
332                         get { return member_name.Location; }
333                 }
334
335                 /// <summary>
336                 ///   XML documentation comment
337                 /// </summary>
338                 public string DocComment;
339
340                 /// <summary>
341                 ///   Represents header string for documentation comment 
342                 ///   for each member types.
343                 /// </summary>
344                 public abstract string DocCommentHeader { get; }
345
346                 [Flags]
347                 public enum Flags {
348                         Obsolete_Undetected = 1,                // Obsolete attribute has not been detected yet
349                         Obsolete = 1 << 1,                      // Type has obsolete attribute
350                         ClsCompliance_Undetected = 1 << 2,      // CLS Compliance has not been detected yet
351                         ClsCompliant = 1 << 3,                  // Type is CLS Compliant
352                         CloseTypeCreated = 1 << 4,              // Tracks whether we have Closed the type
353                         HasCompliantAttribute_Undetected = 1 << 5,      // Presence of CLSCompliantAttribute has not been detected
354                         HasClsCompliantAttribute = 1 << 6,                      // Type has CLSCompliantAttribute
355                         ClsCompliantAttributeTrue = 1 << 7,                     // Type has CLSCompliant (true)
356                         Excluded_Undetected = 1 << 8,           // Conditional attribute has not been detected yet
357                         Excluded = 1 << 9,                                      // Method is conditional
358                         TestMethodDuplication = 1 << 10,                // Test for duplication must be performed
359                         IsUsed = 1 << 11,
360                         IsAssigned = 1 << 12                            // Field is assigned
361                 }
362
363                 /// <summary>
364                 ///   MemberCore flags at first detected then cached
365                 /// </summary>
366                 internal Flags caching_flags;
367
368                 public MemberCore (DeclSpace parent, MemberName name, Attributes attrs)
369                         : base (attrs)
370                 {
371                         if (parent is PartialContainer && !(this is PartialContainer))
372                                 throw new InternalErrorException ("A PartialContainer cannot be the direct parent of a member");
373
374                         Parent = parent;
375                         member_name = name;
376                         caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
377                 }
378
379                 protected virtual void SetMemberName (MemberName new_name)
380                 {
381                         member_name = new_name;
382                         cached_name = null;
383                 }
384
385                 public abstract bool Define ();
386
387                 // 
388                 // Returns full member name for error message
389                 //
390                 public virtual string GetSignatureForError ()
391                 {
392                         if (Parent == null || Parent.Parent == null)
393                                 return Name;
394
395                         return String.Concat (Parent.GetSignatureForError (), '.', Name);
396                 }
397
398                 /// <summary>
399                 /// Base Emit method. This is also entry point for CLS-Compliant verification.
400                 /// </summary>
401                 public virtual void Emit ()
402                 {
403                         if (!RootContext.VerifyClsCompliance)
404                                 return;
405
406                         VerifyClsCompliance (Parent);
407                 }
408
409                 public virtual EmitContext EmitContext {
410                         get { return Parent.EmitContext; }
411                 }
412
413                 public bool InUnsafe {
414                         get { return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext; }
415                 }
416
417                 public virtual bool IsUsed {
418                         get { return (caching_flags & Flags.IsUsed) != 0; }
419                 }
420
421                 public void SetMemberIsUsed ()
422                 {
423                         caching_flags |= Flags.IsUsed;
424                 }
425
426                 // 
427                 // Whehter is it ok to use an unsafe pointer in this type container
428                 //
429                 public bool UnsafeOK (DeclSpace parent)
430                 {
431                         //
432                         // First check if this MemberCore modifier flags has unsafe set
433                         //
434                         if ((ModFlags & Modifiers.UNSAFE) != 0)
435                                 return true;
436
437                         if (parent.UnsafeContext)
438                                 return true;
439
440                         Expression.UnsafeError (Location);
441                         return false;
442                 }
443
444                 /// <summary>
445                 /// Returns instance of ObsoleteAttribute for this MemberCore
446                 /// </summary>
447                 public virtual ObsoleteAttribute GetObsoleteAttribute ()
448                 {
449                         // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
450                         if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
451                                 return null;
452                         }
453
454                         caching_flags &= ~Flags.Obsolete_Undetected;
455
456                         if (OptAttributes == null)
457                                 return null;
458
459                         Attribute obsolete_attr = OptAttributes.Search (
460                                 TypeManager.obsolete_attribute_type);
461                         if (obsolete_attr == null)
462                                 return null;
463
464                         ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute ();
465                         if (obsolete == null)
466                                 return null;
467
468                         caching_flags |= Flags.Obsolete;
469                         return obsolete;
470                 }
471
472                 /// <summary>
473                 /// Checks for ObsoleteAttribute presence. It's used for testing of all non-types elements
474                 /// </summary>
475                 public virtual void CheckObsoleteness (Location loc)
476                 {
477                         if (Parent != null)
478                                 Parent.CheckObsoleteness (loc);
479
480                         ObsoleteAttribute oa = GetObsoleteAttribute ();
481                         if (oa == null) {
482                                 return;
483                         }
484
485                         AttributeTester.Report_ObsoleteMessage (oa, GetSignatureForError (), loc);
486                 }
487
488                 protected void CheckObsoleteType (Expression type)
489                 {
490                         ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type.Type);
491                         if (obsolete_attr == null)
492                                 return;
493
494                         if (GetObsoleteAttribute () != null || Parent.GetObsoleteAttribute () != null)
495                                 return;
496
497                         AttributeTester.Report_ObsoleteMessage (obsolete_attr, TypeManager.CSharpName (type.Type), type.Location);
498                 }
499
500                 /// <summary>
501                 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
502                 /// </summary>
503                 public override bool IsClsComplianceRequired ()
504                 {
505                         if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
506                                 return (caching_flags & Flags.ClsCompliant) != 0;
507
508                         if (GetClsCompliantAttributeValue (Parent) && IsExposedFromAssembly (Parent)) {
509                                 caching_flags &= ~Flags.ClsCompliance_Undetected;
510                                 caching_flags |= Flags.ClsCompliant;
511                                 return true;
512                         }
513
514                         caching_flags &= ~Flags.ClsCompliance_Undetected;
515                         return false;
516                 }
517
518                 /// <summary>
519                 /// Returns true when MemberCore is exposed from assembly.
520                 /// </summary>
521                 public bool IsExposedFromAssembly (DeclSpace ds)
522                 {
523                         if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
524                                 return false;
525                         
526                         DeclSpace parentContainer = ds;
527                         while (parentContainer != null && parentContainer.ModFlags != 0) {
528                                 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
529                                         return false;
530                                 parentContainer = parentContainer.Parent;
531                         }
532                         return true;
533                 }
534
535                 /// <summary>
536                 /// Resolve CLSCompliantAttribute value or gets cached value.
537                 /// </summary>
538                 bool GetClsCompliantAttributeValue (DeclSpace ds)
539                 {
540                         if (OptAttributes != null) {
541                                 Attribute cls_attribute = OptAttributes.Search (
542                                         TypeManager.cls_compliant_attribute_type);
543                                 if (cls_attribute != null) {
544                                         caching_flags |= Flags.HasClsCompliantAttribute;
545                                         return cls_attribute.GetClsCompliantAttributeValue ();
546                                 }
547                         }
548                         return ds.GetClsCompliantAttributeValue ();
549                 }
550
551                 /// <summary>
552                 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
553                 /// </summary>
554                 protected bool HasClsCompliantAttribute {
555                         get {
556                                 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
557                         }
558                 }
559
560                 /// <summary>
561                 /// It helps to handle error 102 & 111 detection
562                 /// </summary>
563                 public virtual bool MarkForDuplicationCheck ()
564                 {
565                         return false;
566                 }
567
568                 /// <summary>
569                 /// The main virtual method for CLS-Compliant verifications.
570                 /// The method returns true if member is CLS-Compliant and false if member is not
571                 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
572                 /// and add their extra verifications.
573                 /// </summary>
574                 protected virtual bool VerifyClsCompliance (DeclSpace ds)
575                 {
576                         if (!IsClsComplianceRequired ()) {
577                                 if (HasClsCompliantAttribute && RootContext.WarningLevel >= 2) {
578                                         if (!IsExposedFromAssembly (ds))
579                                                 Report.Warning (3019, 2, Location, "CLS compliance checking will not be performed on `{0}' because it is not visible from outside this assembly", GetSignatureForError ());
580                                         if (!CodeGen.Assembly.IsClsCompliant)
581                                                 Report.Warning (3021, 2, Location, "`{0}' does not need a CLSCompliant attribute because the assembly is not marked as CLS-compliant", GetSignatureForError ());
582                                 }
583                                 return false;
584                         }
585
586                         if (!CodeGen.Assembly.IsClsCompliant) {
587                                 if (HasClsCompliantAttribute) {
588                                         Report.Error (3014, Location,
589                                                 "`{0}' cannot be marked as CLS-compliant because the assembly is not marked as CLS-compliant",
590                                                 GetSignatureForError ());
591                                 }
592                                 return false;
593                         }
594
595                         if (member_name.Name [0] == '_') {
596                                 Report.Error (3008, Location, "Identifier `{0}' is not CLS-compliant", GetSignatureForError () );
597                         }
598                         return true;
599                 }
600
601                 //
602                 // Raised (and passed an XmlElement that contains the comment)
603                 // when GenerateDocComment is writing documentation expectedly.
604                 //
605                 internal virtual void OnGenerateDocComment (DeclSpace ds, XmlElement intermediateNode)
606                 {
607                 }
608
609                 //
610                 // Returns a string that represents the signature for this 
611                 // member which should be used in XML documentation.
612                 //
613                 public virtual string GetDocCommentName (DeclSpace ds)
614                 {
615                         if (ds == null || this is DeclSpace)
616                                 return DocCommentHeader + Name;
617                         else
618                                 return String.Concat (DocCommentHeader, ds.Name, ".", Name);
619                 }
620
621                 //
622                 // Generates xml doc comments (if any), and if required,
623                 // handle warning report.
624                 //
625                 internal virtual void GenerateDocComment (DeclSpace ds)
626                 {
627                         DocUtil.GenerateDocComment (this, ds);
628                 }
629
630                 public override IResolveContext ResolveContext {
631                         get {
632                                 return this;
633                         }
634                 }
635
636                 #region IResolveContext Members
637
638                 public virtual DeclSpace DeclContainer {
639                         get {
640                                 return Parent;
641                         }
642                 }
643
644                 public bool IsInObsoleteScope {
645                         get {
646                                 if (GetObsoleteAttribute () != null)
647                                         return true;
648
649                                 return Parent == null ? false : Parent.IsInObsoleteScope;
650                         }
651                 }
652
653                 public bool IsInUnsafeScope {
654                         get {
655                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
656                                         return true;
657
658                                 return Parent == null ? false : Parent.IsInUnsafeScope;
659                         }
660                 }
661
662                 #endregion
663         }
664
665         /// <summary>
666         ///   Base class for structs, classes, enumerations and interfaces.  
667         /// </summary>
668         /// <remarks>
669         ///   They all create new declaration spaces.  This
670         ///   provides the common foundation for managing those name
671         ///   spaces.
672         /// </remarks>
673         public abstract class DeclSpace : MemberCore {
674                 /// <summary>
675                 ///   This points to the actual definition that is being
676                 ///   created with System.Reflection.Emit
677                 /// </summary>
678                 public TypeBuilder TypeBuilder;
679
680                 /// <summary>
681                 ///   If we are a generic type, this is the type we are
682                 ///   currently defining.  We need to lookup members on this
683                 ///   instead of the TypeBuilder.
684                 /// </summary>
685                 public Type CurrentType;
686
687                 //
688                 // This is the namespace in which this typecontainer
689                 // was declared.  We use this to resolve names.
690                 //
691                 public NamespaceEntry NamespaceEntry;
692
693                 private Hashtable Cache = new Hashtable ();
694                 
695                 public readonly string Basename;
696                 
697                 protected Hashtable defined_names;
698
699                 readonly bool is_generic;
700                 readonly int count_type_params;
701                 readonly int count_current_type_params;
702
703                 // The emit context for toplevel objects.
704                 protected EmitContext ec;
705                 
706                 public override EmitContext EmitContext {
707                         get { return ec; }
708                 }
709
710                 //
711                 // Whether we are Generic
712                 //
713                 public bool IsGeneric {
714                         get {
715                                 if (is_generic)
716                                         return true;
717                                 else if (Parent != null)
718                                         return Parent.IsGeneric;
719                                 else
720                                         return false;
721                         }
722                 }
723
724                 static string[] attribute_targets = new string [] { "type" };
725
726                 public DeclSpace (NamespaceEntry ns, DeclSpace parent, MemberName name,
727                                   Attributes attrs)
728                         : base (parent, name, attrs)
729                 {
730                         NamespaceEntry = ns;
731                         Basename = name.Basename;
732                         defined_names = new Hashtable ();
733                         if (name.TypeArguments != null) {
734                                 is_generic = true;
735                                 count_type_params = count_current_type_params = name.TypeArguments.Count;
736                         }
737                         if (parent != null)
738                                 count_type_params += parent.count_type_params;
739                 }
740
741                 public override DeclSpace DeclContainer {
742                         get {
743                                 return this;
744                         }
745                 }
746
747                 /// <summary>
748                 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
749                 /// </summary>
750                 protected bool AddToContainer (MemberCore symbol, string name)
751                 {
752                         if (name == MemberName.Name && !(this is Interface) && !(this is Enum)) {
753                                 if (symbol is TypeParameter)
754                                         Report.Error (694, symbol.Location,
755                                                       "Type parameter `{0}' has same name as " +
756                                                       "containing type, or method", name);
757                                 else {
758                                         Report.SymbolRelatedToPreviousError (this);
759                                         Report.Error (542,  symbol.Location,
760                                                       "`{0}': member names cannot be the same " +
761                                                       "as their enclosing type",
762                                                       symbol.GetSignatureForError ());
763                                         return false;
764                                 }
765                         }
766
767                         MemberCore mc = (MemberCore) defined_names [name];
768
769                         if (mc == null) {
770                                 defined_names.Add (name, symbol);
771                                 return true;
772                         }
773
774                         if (symbol.MarkForDuplicationCheck () && mc.MarkForDuplicationCheck ())
775                                 return true;
776
777                         Report.SymbolRelatedToPreviousError (mc);
778                         if (symbol is PartialContainer || mc is PartialContainer) {
779                                 Report.Error (260, symbol.Location,
780                                         "Missing partial modifier on declaration of type `{0}'. Another partial declaration of this type exists",
781                                         name);
782                                 return false;
783                         }
784
785                         if (this is RootTypes) {
786                                 Report.Error (101, symbol.Location, 
787                                         "The namespace `{0}' already contains a definition for `{1}'",
788                                         ((DeclSpace)symbol).NamespaceEntry.GetSignatureForError (), symbol.MemberName.Name);
789                         } else if (symbol is TypeParameter) {
790                                 Report.Error (692, symbol.Location,
791                                               "Duplicate type parameter `{0}'", name);
792                         } else {
793                                 Report.Error (102, symbol.Location,
794                                               "The type `{0}' already contains a definition for `{1}'",
795                                               GetSignatureForError (), symbol.MemberName.Name);
796                         }
797
798                         return false;
799                 }
800
801                 /// <summary>
802                 ///   Returns the MemberCore associated with a given name in the declaration
803                 ///   space. It doesn't return method based symbols !!
804                 /// </summary>
805                 /// 
806                 public MemberCore GetDefinition (string name)
807                 {
808                         return (MemberCore)defined_names [name];
809                 }
810
811                 // 
812                 // root_types contains all the types.  All TopLevel types
813                 // hence have a parent that points to `root_types', that is
814                 // why there is a non-obvious test down here.
815                 //
816                 public bool IsTopLevel {
817                         get { return (Parent != null && Parent.Parent == null); }
818                 }
819
820                 public virtual void CloseType ()
821                 {
822                         if ((caching_flags & Flags.CloseTypeCreated) == 0){
823                                 try {
824                                         TypeBuilder.CreateType ();
825                                 } catch {
826                                         //
827                                         // The try/catch is needed because
828                                         // nested enumerations fail to load when they
829                                         // are defined.
830                                         //
831                                         // Even if this is the right order (enumerations
832                                         // declared after types).
833                                         //
834                                         // Note that this still creates the type and
835                                         // it is possible to save it
836                                 }
837                                 caching_flags |= Flags.CloseTypeCreated;
838                         }
839                 }
840
841                 protected virtual TypeAttributes TypeAttr {
842                         get { return CodeGen.Module.DefaultCharSetType; }
843                 }
844
845                 /// <remarks>
846                 ///  Should be overriten by the appropriate declaration space
847                 /// </remarks>
848                 public abstract TypeBuilder DefineType ();
849                 
850                 /// <summary>
851                 ///   Define all members, but don't apply any attributes or do anything which may
852                 ///   access not-yet-defined classes.  This method also creates the MemberCache.
853                 /// </summary>
854                 public virtual bool DefineMembers ()
855                 {
856                         if (((ModFlags & Modifiers.NEW) != 0) && IsTopLevel) {
857                                 Report.Error (1530, Location, "Keyword `new' is not allowed on namespace elements");
858                                 return false;
859                         }
860                         return true;
861                 }
862
863                 public override string GetSignatureForError ()
864                 {
865                         if (IsGeneric) {
866                                 return SimpleName.RemoveGenericArity (Name) + TypeParameter.GetSignatureForError (CurrentTypeParameters);
867                         }
868                         // Parent.GetSignatureForError
869                         return Name;
870                 }
871
872                 //
873                 // Whether this is an `unsafe context'
874                 //
875                 public bool UnsafeContext {
876                         get {
877                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
878                                         return true;
879                                 if (Parent != null)
880                                         return Parent.UnsafeContext;
881                                 return false;
882                         }
883                 }
884
885                 EmitContext type_resolve_ec;
886                 protected EmitContext TypeResolveEmitContext {
887                         get {
888                                 if (type_resolve_ec == null) {
889                                         // FIXME: I think this should really be one of:
890                                         //
891                                         // a. type_resolve_ec = Parent.EmitContext;
892                                         // b. type_resolve_ec = new EmitContext (Parent, Parent, loc, null, null, ModFlags, false);
893                                         //
894                                         // However, if Parent == RootContext.Tree.Types, its NamespaceEntry will be null.
895                                         //
896                                         type_resolve_ec = new EmitContext (Parent, this, Location.Null, null, null, ModFlags, false);
897                                 }
898                                 return type_resolve_ec;
899                         }
900                 }
901
902                 // <summary>
903                 //    Resolves the expression `e' for a type, and will recursively define
904                 //    types.  This should only be used for resolving base types.
905                 // </summary>
906                 protected TypeExpr ResolveBaseTypeExpr (Expression e, bool silent, Location loc)
907                 {
908                         TypeResolveEmitContext.loc = loc;
909                         TypeResolveEmitContext.ResolvingTypeTree = true;
910                         if (this is GenericMethod)
911                                 TypeResolveEmitContext.ContainerType = Parent.TypeBuilder;
912                         return e.ResolveAsTypeTerminal (TypeResolveEmitContext, silent);
913                 }
914                 
915                 public bool CheckAccessLevel (Type check_type) 
916                 {
917                         TypeBuilder tb;
918                         if ((this is GenericMethod) || (this is Iterator))
919                                 tb = Parent.TypeBuilder;
920                         else
921                                 tb = TypeBuilder;
922
923                         check_type = TypeManager.DropGenericTypeArguments (check_type);
924                         if (check_type == tb)
925                                 return true;
926
927                         if (TypeBuilder == null)
928                                 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
929                                 //        However, this is invoked again later -- so safe to return true.
930                                 //        May also be null when resolving top-level attributes.
931                                 return true;
932
933                         if (check_type.IsGenericParameter)
934                                 return true; // FIXME
935                         
936                         TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
937                         
938                         //
939                         // Broken Microsoft runtime, return public for arrays, no matter what 
940                         // the accessibility is for their underlying class, and they return 
941                         // NonPublic visibility for pointers
942                         //
943                         if (check_type.IsArray || check_type.IsPointer)
944                                 return CheckAccessLevel (TypeManager.GetElementType (check_type));
945
946                         switch (check_attr){
947                         case TypeAttributes.Public:
948                                 return true;
949
950                         case TypeAttributes.NotPublic:
951
952                                 if (TypeBuilder == null)
953                                         // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
954                                         //        However, this is invoked again later -- so safe to return true.
955                                         //        May also be null when resolving top-level attributes.
956                                         return true;
957                                 //
958                                 // This test should probably use the declaringtype.
959                                 //
960                                 return check_type.Assembly == TypeBuilder.Assembly ||
961                                         TypeManager.IsFriendAssembly (check_type.Assembly);
962
963                         case TypeAttributes.NestedPublic:
964                                 return true;
965
966                         case TypeAttributes.NestedPrivate:
967                                 return NestedAccessible (tb, check_type);
968
969                         case TypeAttributes.NestedFamily:
970                                 //
971                                 // Only accessible to methods in current type or any subtypes
972                                 //
973                                 return FamilyAccessible (tb, check_type);
974
975                         case TypeAttributes.NestedFamANDAssem:
976                                 return ((check_type.Assembly == tb.Assembly) || 
977                                                 TypeManager.IsFriendAssembly (check_type.Assembly)) && 
978                                         FamilyAccessible (tb, check_type);
979
980                         case TypeAttributes.NestedFamORAssem:
981                                 return (check_type.Assembly == tb.Assembly) ||
982                                         FamilyAccessible (tb, check_type) ||
983                                         TypeManager.IsFriendAssembly (check_type.Assembly);
984
985                         case TypeAttributes.NestedAssembly:
986                                 return check_type.Assembly == tb.Assembly ||
987                                         TypeManager.IsFriendAssembly (check_type.Assembly);
988                         }
989
990                         Console.WriteLine ("HERE: " + check_attr);
991                         return false;
992
993                 }
994
995                 protected bool NestedAccessible (Type tb, Type check_type)
996                 {
997                         Type declaring = check_type.DeclaringType;
998                         return TypeBuilder == declaring ||
999                                 TypeManager.IsNestedChildOf (TypeBuilder, declaring);
1000                 }
1001
1002                 protected bool FamilyAccessible (Type tb, Type check_type)
1003                 {
1004                         Type declaring = check_type.DeclaringType;
1005                         return TypeManager.IsNestedFamilyAccessible (TypeBuilder, declaring);
1006                 }
1007
1008                 // Access level of a type.
1009                 const int X = 1;
1010                 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
1011                         // Public    Assembly   Protected
1012                         Protected           = (0 << 0) | (0 << 1) | (X << 2),
1013                         Public              = (X << 0) | (X << 1) | (X << 2),
1014                         Private             = (0 << 0) | (0 << 1) | (0 << 2),
1015                         Internal            = (0 << 0) | (X << 1) | (0 << 2),
1016                         ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
1017                 }
1018
1019                 static AccessLevel GetAccessLevelFromModifiers (int flags)
1020                 {
1021                         if ((flags & Modifiers.INTERNAL) != 0) {
1022
1023                                 if ((flags & Modifiers.PROTECTED) != 0)
1024                                         return AccessLevel.ProtectedOrInternal;
1025                                 else
1026                                         return AccessLevel.Internal;
1027
1028                         } else if ((flags & Modifiers.PROTECTED) != 0)
1029                                 return AccessLevel.Protected;
1030                         else if ((flags & Modifiers.PRIVATE) != 0)
1031                                 return AccessLevel.Private;
1032                         else
1033                                 return AccessLevel.Public;
1034                 }
1035
1036                 // What is the effective access level of this?
1037                 // TODO: Cache this?
1038                 AccessLevel EffectiveAccessLevel {
1039                         get {
1040                                 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
1041                                 if (!IsTopLevel && (Parent != null))
1042                                         return myAccess & Parent.EffectiveAccessLevel;
1043                                 return myAccess;
1044                         }
1045                 }
1046
1047                 // Return the access level for type `t'
1048                 static AccessLevel TypeEffectiveAccessLevel (Type t)
1049                 {
1050                         if (t.IsPublic)
1051                                 return AccessLevel.Public;
1052                         if (t.IsNestedPrivate)
1053                                 return AccessLevel.Private;
1054                         if (t.IsNotPublic)
1055                                 return AccessLevel.Internal;
1056
1057                         // By now, it must be nested
1058                         AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
1059
1060                         if (t.IsNestedPublic)
1061                                 return parentLevel;
1062                         if (t.IsNestedAssembly)
1063                                 return parentLevel & AccessLevel.Internal;
1064                         if (t.IsNestedFamily)
1065                                 return parentLevel & AccessLevel.Protected;
1066                         if (t.IsNestedFamORAssem)
1067                                 return parentLevel & AccessLevel.ProtectedOrInternal;
1068                         if (t.IsNestedFamANDAssem)
1069                                 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
1070
1071                         // nested private is taken care of
1072
1073                         throw new Exception ("I give up, what are you?");
1074                 }
1075
1076                 //
1077                 // This answers `is the type P, as accessible as a member M which has the
1078                 // accessability @flags which is declared as a nested member of the type T, this declspace'
1079                 //
1080                 public bool AsAccessible (Type p, int flags)
1081                 {
1082                         if (p.IsGenericParameter)
1083                                 return true; // FIXME
1084
1085                         //
1086                         // 1) if M is private, its accessability is the same as this declspace.
1087                         // we already know that P is accessible to T before this method, so we
1088                         // may return true.
1089                         //
1090
1091                         if ((flags & Modifiers.PRIVATE) != 0)
1092                                 return true;
1093
1094                         while (p.IsArray || p.IsPointer || p.IsByRef)
1095                                 p = TypeManager.GetElementType (p);
1096
1097                         AccessLevel pAccess = TypeEffectiveAccessLevel (p);
1098                         AccessLevel mAccess = this.EffectiveAccessLevel &
1099                                 GetAccessLevelFromModifiers (flags);
1100
1101                         // for every place from which we can access M, we must
1102                         // be able to access P as well. So, we want
1103                         // For every bit in M and P, M_i -> P_1 == true
1104                         // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
1105
1106                         return ~ (~ mAccess | pAccess) == 0;
1107                 }
1108
1109                 //
1110                 // Return the nested type with name @name.  Ensures that the nested type
1111                 // is defined if necessary.  Do _not_ use this when you have a MemberCache handy.
1112                 //
1113                 public virtual Type FindNestedType (string name)
1114                 {
1115                         return null;
1116                 }
1117
1118                 private Type LookupNestedTypeInHierarchy (string name)
1119                 {
1120                         // if the member cache has been created, lets use it.
1121                         // the member cache is MUCH faster.
1122                         if (MemberCache != null)
1123                                 return MemberCache.FindNestedType (name);
1124
1125                         // no member cache. Do it the hard way -- reflection
1126                         Type t = null;
1127                         for (Type current_type = TypeBuilder;
1128                              current_type != null && current_type != TypeManager.object_type;
1129                              current_type = current_type.BaseType) {
1130                                 current_type = TypeManager.DropGenericTypeArguments (current_type);
1131                                 if (current_type is TypeBuilder) {
1132                                         DeclSpace decl = this;
1133                                         if (current_type != TypeBuilder)
1134                                                 decl = TypeManager.LookupDeclSpace (current_type);
1135                                         t = decl.FindNestedType (name);
1136                                 } else {
1137                                         t = TypeManager.GetNestedType (current_type, name);
1138                                 }
1139
1140                                 if (t != null && CheckAccessLevel (t))
1141                                         return t;
1142                         }
1143
1144                         return null;
1145                 }
1146
1147                 //
1148                 // Public function used to locate types.
1149                 //
1150                 // Set 'ignore_cs0104' to true if you want to ignore cs0104 errors.
1151                 //
1152                 // Returns: Type or null if they type can not be found.
1153                 //
1154                 public FullNamedExpression LookupType (string name, Location loc, bool ignore_cs0104)
1155                 {
1156                         if (this is PartialContainer)
1157                                 throw new InternalErrorException ("Should not get here");
1158
1159                         if (Cache.Contains (name))
1160                                 return (FullNamedExpression) Cache [name];
1161
1162                         FullNamedExpression e;
1163                         Type t = LookupNestedTypeInHierarchy (name);
1164                         if (t != null)
1165                                 e = new TypeExpression (t, Location.Null);
1166                         else if (Parent != null && Parent != RootContext.Tree.Types)
1167                                 e = Parent.LookupType (name, loc, ignore_cs0104);
1168                         else
1169                                 e = NamespaceEntry.LookupNamespaceOrType (this, name, loc, ignore_cs0104);
1170
1171                         Cache [name] = e;
1172                         return e;
1173                 }
1174
1175                 /// <remarks>
1176                 ///   This function is broken and not what you're looking for.  It should only
1177                 ///   be used while the type is still being created since it doesn't use the cache
1178                 ///   and relies on the filter doing the member name check.
1179                 /// </remarks>
1180                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1181                                                         MemberFilter filter, object criteria);
1182
1183                 /// <remarks>
1184                 ///   If we have a MemberCache, return it.  This property may return null if the
1185                 ///   class doesn't have a member cache or while it's still being created.
1186                 /// </remarks>
1187                 public abstract MemberCache MemberCache {
1188                         get;
1189                 }
1190
1191                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1192                 {
1193                         if (a.Type == TypeManager.required_attr_type) {
1194                                 Report.Error (1608, a.Location, "The RequiredAttribute attribute is not permitted on C# types");
1195                                 return;
1196                         }
1197                         TypeBuilder.SetCustomAttribute (cb);
1198                 }
1199
1200                 /// <summary>
1201                 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1202                 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1203                 /// </summary>
1204                 public bool GetClsCompliantAttributeValue ()
1205                 {
1206                         if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1207                                 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1208
1209                         caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1210
1211                         if (OptAttributes != null) {
1212                                 Attribute cls_attribute = OptAttributes.Search (TypeManager.cls_compliant_attribute_type);
1213                                 if (cls_attribute != null) {
1214                                         caching_flags |= Flags.HasClsCompliantAttribute;
1215                                         if (cls_attribute.GetClsCompliantAttributeValue ()) {
1216                                                 caching_flags |= Flags.ClsCompliantAttributeTrue;
1217                                                 return true;
1218                                         }
1219                                         return false;
1220                                 }
1221                         }
1222
1223                         if (Parent == null) {
1224                                 if (CodeGen.Assembly.IsClsCompliant) {
1225                                         caching_flags |= Flags.ClsCompliantAttributeTrue;
1226                                         return true;
1227                                 }
1228                                 return false;
1229                         }
1230
1231                         if (Parent.GetClsCompliantAttributeValue ()) {
1232                                 caching_flags |= Flags.ClsCompliantAttributeTrue;
1233                                 return true;
1234                         }
1235                         return false;
1236                 }
1237
1238                 //
1239                 // Extensions for generics
1240                 //
1241                 TypeParameter[] type_params;
1242                 TypeParameter[] type_param_list;
1243
1244                 protected string GetInstantiationName ()
1245                 {
1246                         StringBuilder sb = new StringBuilder (Name);
1247                         sb.Append ("<");
1248                         for (int i = 0; i < type_param_list.Length; i++) {
1249                                 if (i > 0)
1250                                         sb.Append (",");
1251                                 sb.Append (type_param_list [i].Name);
1252                         }
1253                         sb.Append (">");
1254                         return sb.ToString ();
1255                 }
1256
1257                 bool check_type_parameter (ArrayList list, int start, string name)
1258                 {
1259                         for (int i = 0; i < start; i++) {
1260                                 TypeParameter param = (TypeParameter) list [i];
1261
1262                                 if (param.Name != name)
1263                                         continue;
1264
1265                                 Report.Warning (693, 3, Location,
1266                                         "Type parameter `{0}' has same name as type parameter from outer type `{1}'",
1267                                         name, Parent.GetInstantiationName ());
1268
1269                                 return false;
1270                         }
1271
1272                         return true;
1273                 }
1274
1275                 TypeParameter[] initialize_type_params ()
1276                 {
1277                         if (type_param_list != null)
1278                                 return type_param_list;
1279
1280                         DeclSpace the_parent = Parent;
1281                         if (this is GenericMethod)
1282                                 the_parent = null;
1283
1284                         int start = 0;
1285                         TypeParameter[] parent_params = null;
1286                         if ((the_parent != null) && the_parent.IsGeneric) {
1287                                 parent_params = the_parent.initialize_type_params ();
1288                                 start = parent_params != null ? parent_params.Length : 0;
1289                         }
1290
1291                         ArrayList list = new ArrayList ();
1292                         if (parent_params != null)
1293                                 list.AddRange (parent_params);
1294
1295                         int count = type_params != null ? type_params.Length : 0;
1296                         for (int i = 0; i < count; i++) {
1297                                 TypeParameter param = type_params [i];
1298                                 check_type_parameter (list, start, param.Name);
1299                                 list.Add (param);
1300                         }
1301
1302                         type_param_list = new TypeParameter [list.Count];
1303                         list.CopyTo (type_param_list, 0);
1304                         return type_param_list;
1305                 }
1306
1307                 public virtual void SetParameterInfo (ArrayList constraints_list)
1308                 {
1309                         if (!is_generic) {
1310                                 if (constraints_list != null) {
1311                                         Report.Error (
1312                                                 80, Location, "Constraints are not allowed " +
1313                                                 "on non-generic declarations");
1314                                 }
1315
1316                                 return;
1317                         }
1318
1319                         TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
1320                         type_params = new TypeParameter [names.Length];
1321
1322                         //
1323                         // Register all the names
1324                         //
1325                         for (int i = 0; i < type_params.Length; i++) {
1326                                 TypeParameterName name = names [i];
1327
1328                                 Constraints constraints = null;
1329                                 if (constraints_list != null) {
1330                                         foreach (Constraints constraint in constraints_list) {
1331                                                 if (constraint == null)
1332                                                         continue;
1333                                                 if (constraint.TypeParameter == name.Name) {
1334                                                         constraints = constraint;
1335                                                         break;
1336                                                 }
1337                                         }
1338                                 }
1339
1340                                 type_params [i] = new TypeParameter (
1341                                         Parent, this, name.Name, constraints, name.OptAttributes,
1342                                         Location);
1343
1344                                 AddToContainer (type_params [i], name.Name);
1345                         }
1346                 }
1347
1348                 public TypeParameter[] TypeParameters {
1349                         get {
1350                                 if (!IsGeneric)
1351                                         throw new InvalidOperationException ();
1352                                 if (type_param_list == null)
1353                                         initialize_type_params ();
1354
1355                                 return type_param_list;
1356                         }
1357                 }
1358
1359                 public TypeParameter[] CurrentTypeParameters {
1360                         get {
1361                                 if (!IsGeneric)
1362                                         throw new InvalidOperationException ();
1363                                 if (type_params != null)
1364                                         return type_params;
1365                                 else
1366                                         return new TypeParameter [0];
1367                         }
1368                 }
1369
1370                 public int CountTypeParameters {
1371                         get {
1372                                 return count_type_params;
1373                         }
1374                 }
1375
1376                 public int CountCurrentTypeParameters {
1377                         get {
1378                                 return count_current_type_params;
1379                         }
1380                 }
1381
1382                 public TypeParameterExpr LookupGeneric (string name, Location loc)
1383                 {
1384                         if (!IsGeneric)
1385                                 return null;
1386
1387                         foreach (TypeParameter type_param in CurrentTypeParameters) {
1388                                 if (type_param.Name != name)
1389                                         continue;
1390
1391                                 return new TypeParameterExpr (type_param, loc);
1392                         }
1393
1394                         if (Parent != null)
1395                                 return Parent.LookupGeneric (name, loc);
1396
1397                         return null;
1398                 }
1399
1400                 public override string[] ValidAttributeTargets {
1401                         get { return attribute_targets; }
1402                 }
1403
1404                 protected override bool VerifyClsCompliance (DeclSpace ds)
1405                 {
1406                         if (!base.VerifyClsCompliance (ds)) {
1407                                 return false;
1408                         }
1409
1410                         IDictionary cache = TypeManager.AllClsTopLevelTypes;
1411                         string lcase = Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1412                         if (!cache.Contains (lcase)) {
1413                                 cache.Add (lcase, this);
1414                                 return true;
1415                         }
1416
1417                         object val = cache [lcase];
1418                         if (val == null) {
1419                                 Type t = AttributeTester.GetImportedIgnoreCaseClsType (lcase);
1420                                 if (t == null)
1421                                         return true;
1422                                 Report.SymbolRelatedToPreviousError (t);
1423                         }
1424                         else {
1425                                 if (val is PartialContainer)
1426                                         return true;
1427
1428                                 Report.SymbolRelatedToPreviousError ((DeclSpace)val);
1429                         }
1430                         Report.Warning (3005, 1, Location, "Identifier `{0}' differing only in case is not CLS-compliant", GetSignatureForError ());
1431                         return true;
1432                 }
1433         }
1434
1435         /// <summary>
1436         ///   This is a readonly list of MemberInfo's.      
1437         /// </summary>
1438         public class MemberList : IList {
1439                 public readonly IList List;
1440                 int count;
1441
1442                 /// <summary>
1443                 ///   Create a new MemberList from the given IList.
1444                 /// </summary>
1445                 public MemberList (IList list)
1446                 {
1447                         if (list != null)
1448                                 this.List = list;
1449                         else
1450                                 this.List = new ArrayList ();
1451                         count = List.Count;
1452                 }
1453
1454                 /// <summary>
1455                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
1456                 /// </summary>
1457                 public MemberList (IList first, IList second)
1458                 {
1459                         ArrayList list = new ArrayList ();
1460                         list.AddRange (first);
1461                         list.AddRange (second);
1462                         count = list.Count;
1463                         List = list;
1464                 }
1465
1466                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1467
1468                 /// <summary>
1469                 ///   Cast the MemberList into a MemberInfo[] array.
1470                 /// </summary>
1471                 /// <remarks>
1472                 ///   This is an expensive operation, only use it if it's really necessary.
1473                 /// </remarks>
1474                 public static explicit operator MemberInfo [] (MemberList list)
1475                 {
1476                         Timer.StartTimer (TimerType.MiscTimer);
1477                         MemberInfo [] result = new MemberInfo [list.Count];
1478                         list.CopyTo (result, 0);
1479                         Timer.StopTimer (TimerType.MiscTimer);
1480                         return result;
1481                 }
1482
1483                 // ICollection
1484
1485                 public int Count {
1486                         get {
1487                                 return count;
1488                         }
1489                 }
1490
1491                 public bool IsSynchronized {
1492                         get {
1493                                 return List.IsSynchronized;
1494                         }
1495                 }
1496
1497                 public object SyncRoot {
1498                         get {
1499                                 return List.SyncRoot;
1500                         }
1501                 }
1502
1503                 public void CopyTo (Array array, int index)
1504                 {
1505                         List.CopyTo (array, index);
1506                 }
1507
1508                 // IEnumerable
1509
1510                 public IEnumerator GetEnumerator ()
1511                 {
1512                         return List.GetEnumerator ();
1513                 }
1514
1515                 // IList
1516
1517                 public bool IsFixedSize {
1518                         get {
1519                                 return true;
1520                         }
1521                 }
1522
1523                 public bool IsReadOnly {
1524                         get {
1525                                 return true;
1526                         }
1527                 }
1528
1529                 object IList.this [int index] {
1530                         get {
1531                                 return List [index];
1532                         }
1533
1534                         set {
1535                                 throw new NotSupportedException ();
1536                         }
1537                 }
1538
1539                 // FIXME: try to find out whether we can avoid the cast in this indexer.
1540                 public MemberInfo this [int index] {
1541                         get {
1542                                 return (MemberInfo) List [index];
1543                         }
1544                 }
1545
1546                 public int Add (object value)
1547                 {
1548                         throw new NotSupportedException ();
1549                 }
1550
1551                 public void Clear ()
1552                 {
1553                         throw new NotSupportedException ();
1554                 }
1555
1556                 public bool Contains (object value)
1557                 {
1558                         return List.Contains (value);
1559                 }
1560
1561                 public int IndexOf (object value)
1562                 {
1563                         return List.IndexOf (value);
1564                 }
1565
1566                 public void Insert (int index, object value)
1567                 {
1568                         throw new NotSupportedException ();
1569                 }
1570
1571                 public void Remove (object value)
1572                 {
1573                         throw new NotSupportedException ();
1574                 }
1575
1576                 public void RemoveAt (int index)
1577                 {
1578                         throw new NotSupportedException ();
1579                 }
1580         }
1581
1582         /// <summary>
1583         ///   This interface is used to get all members of a class when creating the
1584         ///   member cache.  It must be implemented by all DeclSpace derivatives which
1585         ///   want to support the member cache and by TypeHandle to get caching of
1586         ///   non-dynamic types.
1587         /// </summary>
1588         public interface IMemberContainer {
1589                 /// <summary>
1590                 ///   The name of the IMemberContainer.  This is only used for
1591                 ///   debugging purposes.
1592                 /// </summary>
1593                 string Name {
1594                         get;
1595                 }
1596
1597                 /// <summary>
1598                 ///   The type of this IMemberContainer.
1599                 /// </summary>
1600                 Type Type {
1601                         get;
1602                 }
1603
1604                 /// <summary>
1605                 ///   Returns the IMemberContainer of the base class or null if this
1606                 ///   is an interface or TypeManger.object_type.
1607                 ///   This is used when creating the member cache for a class to get all
1608                 ///   members from the base class.
1609                 /// </summary>
1610                 MemberCache BaseCache {
1611                         get;
1612                 }
1613
1614                 /// <summary>
1615                 ///   Whether this is an interface.
1616                 /// </summary>
1617                 bool IsInterface {
1618                         get;
1619                 }
1620
1621                 /// <summary>
1622                 ///   Returns all members of this class with the corresponding MemberTypes
1623                 ///   and BindingFlags.
1624                 /// </summary>
1625                 /// <remarks>
1626                 ///   When implementing this method, make sure not to return any inherited
1627                 ///   members and check the MemberTypes and BindingFlags properly.
1628                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
1629                 ///   get the BindingFlags (static/non-static,public/non-public) in the
1630                 ///   MemberInfo class, but the cache needs this information.  That's why
1631                 ///   this method is called multiple times with different BindingFlags.
1632                 /// </remarks>
1633                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1634
1635                 /// <summary>
1636                 ///   Return the container's member cache.
1637                 /// </summary>
1638                 MemberCache MemberCache {
1639                         get;
1640                 }
1641         }
1642
1643         /// <summary>
1644         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
1645         ///   member lookups.  It has a member name based hash table; it maps each member
1646         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
1647         ///   and the BindingFlags that were initially used to get it.  The cache contains
1648         ///   all members of the current class and all inherited members.  If this cache is
1649         ///   for an interface types, it also contains all inherited members.
1650         ///
1651         ///   There are two ways to get a MemberCache:
1652         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
1653         ///     use the DeclSpace.MemberCache property.
1654         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1655         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
1656         /// </summary>
1657         public class MemberCache {
1658                 public readonly IMemberContainer Container;
1659                 protected Hashtable member_hash;
1660                 protected Hashtable method_hash;
1661
1662                 /// <summary>
1663                 ///   Create a new MemberCache for the given IMemberContainer `container'.
1664                 /// </summary>
1665                 public MemberCache (IMemberContainer container)
1666                 {
1667                         this.Container = container;
1668
1669                         Timer.IncrementCounter (CounterType.MemberCache);
1670                         Timer.StartTimer (TimerType.CacheInit);
1671
1672                         // If we have a base class (we have a base class unless we're
1673                         // TypeManager.object_type), we deep-copy its MemberCache here.
1674                         if (Container.BaseCache != null)
1675                                 member_hash = SetupCache (Container.BaseCache);
1676                         else
1677                                 member_hash = new Hashtable ();
1678
1679                         // If this is neither a dynamic type nor an interface, create a special
1680                         // method cache with all declared and inherited methods.
1681                         Type type = container.Type;
1682                         if (!(type is TypeBuilder) && !type.IsInterface &&
1683                             // !(type.IsGenericType && (type.GetGenericTypeDefinition () is TypeBuilder)) &&
1684                             !type.IsGenericType &&
1685                             (Container.BaseCache == null || Container.BaseCache.method_hash != null)) {
1686                                 method_hash = new Hashtable ();
1687                                 AddMethods (type);
1688                         }
1689
1690                         // Add all members from the current class.
1691                         AddMembers (Container);
1692
1693                         Timer.StopTimer (TimerType.CacheInit);
1694                 }
1695
1696                 public MemberCache (Type[] ifaces)
1697                 {
1698                         //
1699                         // The members of this cache all belong to other caches.  
1700                         // So, 'Container' will not be used.
1701                         //
1702                         this.Container = null;
1703
1704                         member_hash = new Hashtable ();
1705                         if (ifaces == null)
1706                                 return;
1707
1708                         foreach (Type itype in ifaces)
1709                                 AddCacheContents (TypeManager.LookupMemberCache (itype));
1710                 }
1711
1712                 /// <summary>
1713                 ///   Bootstrap this member cache by doing a deep-copy of our base.
1714                 /// </summary>
1715                 Hashtable SetupCache (MemberCache base_class)
1716                 {
1717                         Hashtable hash = new Hashtable ();
1718
1719                         if (base_class == null)
1720                                 return hash;
1721
1722                         IDictionaryEnumerator it = base_class.member_hash.GetEnumerator ();
1723                         while (it.MoveNext ()) {
1724                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1725                          }
1726                                 
1727                         return hash;
1728                 }
1729
1730                 /// <summary>
1731                 ///   Add the contents of `cache' to the member_hash.
1732                 /// </summary>
1733                 void AddCacheContents (MemberCache cache)
1734                 {
1735                         IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1736                         while (it.MoveNext ()) {
1737                                 ArrayList list = (ArrayList) member_hash [it.Key];
1738                                 if (list == null)
1739                                         member_hash [it.Key] = list = new ArrayList ();
1740
1741                                 ArrayList entries = (ArrayList) it.Value;
1742                                 for (int i = entries.Count-1; i >= 0; i--) {
1743                                         CacheEntry entry = (CacheEntry) entries [i];
1744
1745                                         if (entry.Container != cache.Container)
1746                                                 break;
1747                                         list.Add (entry);
1748                                 }
1749                         }
1750                 }
1751
1752                 /// <summary>
1753                 ///   Add all members from class `container' to the cache.
1754                 /// </summary>
1755                 void AddMembers (IMemberContainer container)
1756                 {
1757                         // We need to call AddMembers() with a single member type at a time
1758                         // to get the member type part of CacheEntry.EntryType right.
1759                         if (!container.IsInterface) {
1760                                 AddMembers (MemberTypes.Constructor, container);
1761                                 AddMembers (MemberTypes.Field, container);
1762                         }
1763                         AddMembers (MemberTypes.Method, container);
1764                         AddMembers (MemberTypes.Property, container);
1765                         AddMembers (MemberTypes.Event, container);
1766                         // Nested types are returned by both Static and Instance searches.
1767                         AddMembers (MemberTypes.NestedType,
1768                                     BindingFlags.Static | BindingFlags.Public, container);
1769                         AddMembers (MemberTypes.NestedType,
1770                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1771                 }
1772
1773                 void AddMembers (MemberTypes mt, IMemberContainer container)
1774                 {
1775                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1776                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1777                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1778                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1779                 }
1780
1781                 /// <summary>
1782                 ///   Add all members from class `container' with the requested MemberTypes and
1783                 ///   BindingFlags to the cache.  This method is called multiple times with different
1784                 ///   MemberTypes and BindingFlags.
1785                 /// </summary>
1786                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1787                 {
1788                         MemberList members = container.GetMembers (mt, bf);
1789
1790                         foreach (MemberInfo member in members) {
1791                                 string name = member.Name;
1792
1793                                 int pos = name.IndexOf ('<');
1794                                 if (pos > 0)
1795                                         name = name.Substring (0, pos);
1796
1797                                 // We use a name-based hash table of ArrayList's.
1798                                 ArrayList list = (ArrayList) member_hash [name];
1799                                 if (list == null) {
1800                                         list = new ArrayList ();
1801                                         member_hash.Add (name, list);
1802                                 }
1803
1804                                 // When this method is called for the current class, the list will
1805                                 // already contain all inherited members from our base classes.
1806                                 // We cannot add new members in front of the list since this'd be an
1807                                 // expensive operation, that's why the list is sorted in reverse order
1808                                 // (ie. members from the current class are coming last).
1809                                 list.Add (new CacheEntry (container, member, mt, bf));
1810                         }
1811                 }
1812
1813                 /// <summary>
1814                 ///   Add all declared and inherited methods from class `type' to the method cache.
1815                 /// </summary>
1816                 void AddMethods (Type type)
1817                 {
1818                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1819                                     BindingFlags.FlattenHierarchy, type);
1820                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1821                                     BindingFlags.FlattenHierarchy, type);
1822                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1823                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1824                 }
1825
1826                 static ArrayList overrides = new ArrayList ();
1827
1828                 void AddMethods (BindingFlags bf, Type type)
1829                 {
1830                         MethodBase [] members = type.GetMethods (bf);
1831
1832                         Array.Reverse (members);
1833
1834                         foreach (MethodBase member in members) {
1835                                 string name = member.Name;
1836
1837                                 // We use a name-based hash table of ArrayList's.
1838                                 ArrayList list = (ArrayList) method_hash [name];
1839                                 if (list == null) {
1840                                         list = new ArrayList ();
1841                                         method_hash.Add (name, list);
1842                                 }
1843
1844                                 MethodInfo curr = (MethodInfo) member;
1845                                 while (curr.IsVirtual && (curr.Attributes & MethodAttributes.NewSlot) == 0) {
1846                                         MethodInfo base_method = curr.GetBaseDefinition ();
1847
1848                                         if (base_method == curr)
1849                                                 // Not every virtual function needs to have a NewSlot flag.
1850                                                 break;
1851
1852                                         overrides.Add (curr);
1853                                         list.Add (new CacheEntry (null, base_method, MemberTypes.Method, bf));
1854                                         curr = base_method;
1855                                 }
1856
1857                                 if (overrides.Count > 0) {
1858                                         for (int i = 0; i < overrides.Count; ++i)
1859                                                 TypeManager.RegisterOverride ((MethodBase) overrides [i], curr);
1860                                         overrides.Clear ();
1861                                 }
1862
1863                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1864                                 // sorted so we need to do this check for every member.
1865                                 BindingFlags new_bf = bf;
1866                                 if (member.DeclaringType == type)
1867                                         new_bf |= BindingFlags.DeclaredOnly;
1868
1869                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1870                         }
1871                 }
1872
1873                 /// <summary>
1874                 ///   Compute and return a appropriate `EntryType' magic number for the given
1875                 ///   MemberTypes and BindingFlags.
1876                 /// </summary>
1877                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1878                 {
1879                         EntryType type = EntryType.None;
1880
1881                         if ((mt & MemberTypes.Constructor) != 0)
1882                                 type |= EntryType.Constructor;
1883                         if ((mt & MemberTypes.Event) != 0)
1884                                 type |= EntryType.Event;
1885                         if ((mt & MemberTypes.Field) != 0)
1886                                 type |= EntryType.Field;
1887                         if ((mt & MemberTypes.Method) != 0)
1888                                 type |= EntryType.Method;
1889                         if ((mt & MemberTypes.Property) != 0)
1890                                 type |= EntryType.Property;
1891                         // Nested types are returned by static and instance searches.
1892                         if ((mt & MemberTypes.NestedType) != 0)
1893                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1894
1895                         if ((bf & BindingFlags.Instance) != 0)
1896                                 type |= EntryType.Instance;
1897                         if ((bf & BindingFlags.Static) != 0)
1898                                 type |= EntryType.Static;
1899                         if ((bf & BindingFlags.Public) != 0)
1900                                 type |= EntryType.Public;
1901                         if ((bf & BindingFlags.NonPublic) != 0)
1902                                 type |= EntryType.NonPublic;
1903                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1904                                 type |= EntryType.Declared;
1905
1906                         return type;
1907                 }
1908
1909                 /// <summary>
1910                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1911                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1912                 ///   single member types.
1913                 /// </summary>
1914                 public static bool IsSingleMemberType (MemberTypes mt)
1915                 {
1916                         switch (mt) {
1917                         case MemberTypes.Constructor:
1918                         case MemberTypes.Event:
1919                         case MemberTypes.Field:
1920                         case MemberTypes.Method:
1921                         case MemberTypes.Property:
1922                         case MemberTypes.NestedType:
1923                                 return true;
1924
1925                         default:
1926                                 return false;
1927                         }
1928                 }
1929
1930                 /// <summary>
1931                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1932                 ///   number to speed up the searching process.
1933                 /// </summary>
1934                 [Flags]
1935                 protected enum EntryType {
1936                         None            = 0x000,
1937
1938                         Instance        = 0x001,
1939                         Static          = 0x002,
1940                         MaskStatic      = Instance|Static,
1941
1942                         Public          = 0x004,
1943                         NonPublic       = 0x008,
1944                         MaskProtection  = Public|NonPublic,
1945
1946                         Declared        = 0x010,
1947
1948                         Constructor     = 0x020,
1949                         Event           = 0x040,
1950                         Field           = 0x080,
1951                         Method          = 0x100,
1952                         Property        = 0x200,
1953                         NestedType      = 0x400,
1954
1955                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1956                 }
1957
1958                 protected class CacheEntry {
1959                         public readonly IMemberContainer Container;
1960                         public readonly EntryType EntryType;
1961                         public readonly MemberInfo Member;
1962
1963                         public CacheEntry (IMemberContainer container, MemberInfo member,
1964                                            MemberTypes mt, BindingFlags bf)
1965                         {
1966                                 this.Container = container;
1967                                 this.Member = member;
1968                                 this.EntryType = GetEntryType (mt, bf);
1969                         }
1970
1971                         public override string ToString ()
1972                         {
1973                                 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1974                                                       EntryType, Member);
1975                         }
1976                 }
1977
1978                 /// <summary>
1979                 ///   This is called each time we're walking up one level in the class hierarchy
1980                 ///   and checks whether we can abort the search since we've already found what
1981                 ///   we were looking for.
1982                 /// </summary>
1983                 protected bool DoneSearching (ArrayList list)
1984                 {
1985                         //
1986                         // We've found exactly one member in the current class and it's not
1987                         // a method or constructor.
1988                         //
1989                         if (list.Count == 1 && !(list [0] is MethodBase))
1990                                 return true;
1991
1992                         //
1993                         // Multiple properties: we query those just to find out the indexer
1994                         // name
1995                         //
1996                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1997                                 return true;
1998
1999                         return false;
2000                 }
2001
2002                 /// <summary>
2003                 ///   Looks up members with name `name'.  If you provide an optional
2004                 ///   filter function, it'll only be called with members matching the
2005                 ///   requested member name.
2006                 ///
2007                 ///   This method will try to use the cache to do the lookup if possible.
2008                 ///
2009                 ///   Unlike other FindMembers implementations, this method will always
2010                 ///   check all inherited members - even when called on an interface type.
2011                 ///
2012                 ///   If you know that you're only looking for methods, you should use
2013                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
2014                 ///   When doing a method-only search, it'll try to use a special method
2015                 ///   cache (unless it's a dynamic type or an interface) and the returned
2016                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
2017                 ///   The lookup process will automatically restart itself in method-only
2018                 ///   search mode if it discovers that it's about to return methods.
2019                 /// </summary>
2020                 ArrayList global = new ArrayList ();
2021                 bool using_global = false;
2022                 
2023                 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2024                 
2025                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2026                                                   MemberFilter filter, object criteria)
2027                 {
2028                         if (using_global)
2029                                 throw new Exception ();
2030                         
2031                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2032                         bool method_search = mt == MemberTypes.Method;
2033                         // If we have a method cache and we aren't already doing a method-only search,
2034                         // then we restart a method search if the first match is a method.
2035                         bool do_method_search = !method_search && (method_hash != null);
2036
2037                         ArrayList applicable;
2038
2039                         // If this is a method-only search, we try to use the method cache if
2040                         // possible; a lookup in the method cache will return a MemberInfo with
2041                         // the correct ReflectedType for inherited methods.
2042                         
2043                         if (method_search && (method_hash != null))
2044                                 applicable = (ArrayList) method_hash [name];
2045                         else
2046                                 applicable = (ArrayList) member_hash [name];
2047
2048                         if (applicable == null)
2049                                 return emptyMemberInfo;
2050
2051                         //
2052                         // 32  slots gives 53 rss/54 size
2053                         // 2/4 slots gives 55 rss
2054                         //
2055                         // Strange: from 25,000 calls, only 1,800
2056                         // are above 2.  Why does this impact it?
2057                         //
2058                         global.Clear ();
2059                         using_global = true;
2060
2061                         Timer.StartTimer (TimerType.CachedLookup);
2062
2063                         EntryType type = GetEntryType (mt, bf);
2064
2065                         IMemberContainer current = Container;
2066
2067
2068                         // `applicable' is a list of all members with the given member name `name'
2069                         // in the current class and all its base classes.  The list is sorted in
2070                         // reverse order due to the way how the cache is initialy created (to speed
2071                         // things up, we're doing a deep-copy of our base).
2072
2073                         for (int i = applicable.Count-1; i >= 0; i--) {
2074                                 CacheEntry entry = (CacheEntry) applicable [i];
2075
2076                                 // This happens each time we're walking one level up in the class
2077                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
2078                                 // the first time this happens (this may already happen in the first
2079                                 // iteration of this loop if there are no members with the name we're
2080                                 // looking for in the current class).
2081                                 if (entry.Container != current) {
2082                                         if (declared_only || DoneSearching (global))
2083                                                 break;
2084
2085                                         current = entry.Container;
2086                                 }
2087
2088                                 // Is the member of the correct type ?
2089                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2090                                         continue;
2091
2092                                 // Is the member static/non-static ?
2093                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2094                                         continue;
2095
2096                                 // Apply the filter to it.
2097                                 if (filter (entry.Member, criteria)) {
2098                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2099                                                 do_method_search = false;
2100                                         global.Add (entry.Member);
2101                                 }
2102                         }
2103
2104                         Timer.StopTimer (TimerType.CachedLookup);
2105
2106                         // If we have a method cache and we aren't already doing a method-only
2107                         // search, we restart in method-only search mode if the first match is
2108                         // a method.  This ensures that we return a MemberInfo with the correct
2109                         // ReflectedType for inherited methods.
2110                         if (do_method_search && (global.Count > 0)){
2111                                 using_global = false;
2112
2113                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2114                         }
2115
2116                         using_global = false;
2117                         MemberInfo [] copy = new MemberInfo [global.Count];
2118                         global.CopyTo (copy);
2119                         return copy;
2120                 }
2121                 
2122                 // find the nested type @name in @this.
2123                 public Type FindNestedType (string name)
2124                 {
2125                         ArrayList applicable = (ArrayList) member_hash [name];
2126                         if (applicable == null)
2127                                 return null;
2128                         
2129                         for (int i = applicable.Count-1; i >= 0; i--) {
2130                                 CacheEntry entry = (CacheEntry) applicable [i];
2131                                 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
2132                                         return (Type) entry.Member;
2133                         }
2134                         
2135                         return null;
2136                 }
2137                 
2138                 //
2139                 // This finds the method or property for us to override. invocationType is the type where
2140                 // the override is going to be declared, name is the name of the method/property, and
2141                 // paramTypes is the parameters, if any to the method or property
2142                 //
2143                 // Because the MemberCache holds members from this class and all the base classes,
2144                 // we can avoid tons of reflection stuff.
2145                 //
2146                 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, GenericMethod genericMethod, bool is_property)
2147                 {
2148                         ArrayList applicable;
2149                         if (method_hash != null && !is_property)
2150                                 applicable = (ArrayList) method_hash [name];
2151                         else
2152                                 applicable = (ArrayList) member_hash [name];
2153                         
2154                         if (applicable == null)
2155                                 return null;
2156                         //
2157                         // Walk the chain of methods, starting from the top.
2158                         //
2159                         for (int i = applicable.Count - 1; i >= 0; i--) {
2160                                 CacheEntry entry = (CacheEntry) applicable [i];
2161                                 
2162                                 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2163                                         continue;
2164
2165                                 PropertyInfo pi = null;
2166                                 MethodInfo mi = null;
2167                                 FieldInfo fi = null;
2168                                 Type [] cmpAttrs = null;
2169                                 
2170                                 if (is_property) {
2171                                         if ((entry.EntryType & EntryType.Field) != 0) {
2172                                                 fi = (FieldInfo)entry.Member;
2173
2174                                                 // TODO: For this case we ignore member type
2175                                                 //fb = TypeManager.GetField (fi);
2176                                                 //cmpAttrs = new Type[] { fb.MemberType };
2177                                         } else {
2178                                                 pi = (PropertyInfo) entry.Member;
2179                                                 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2180                                         }
2181                                 } else {
2182                                         mi = (MethodInfo) entry.Member;
2183                                         cmpAttrs = TypeManager.GetParameterData (mi).Types;
2184                                 }
2185
2186                                 if (fi != null) {
2187                                         // TODO: Almost duplicate !
2188                                         // Check visibility
2189                                         switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2190                                                 case FieldAttributes.Private:
2191                                                         //
2192                                                         // A private method is Ok if we are a nested subtype.
2193                                                         // The spec actually is not very clear about this, see bug 52458.
2194                                                         //
2195                                                         if (invocationType != entry.Container.Type &
2196                                                                 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2197                                                                 continue;
2198
2199                                                         break;
2200                                                 case FieldAttributes.FamANDAssem:
2201                                                 case FieldAttributes.Assembly:
2202                                                         //
2203                                                         // Check for assembly methods
2204                                                         //
2205                                                         if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2206                                                                 continue;
2207                                                         break;
2208                                         }
2209                                         return entry.Member;
2210                                 }
2211
2212                                 //
2213                                 // Check the arguments
2214                                 //
2215                                 if (cmpAttrs.Length != paramTypes.Length)
2216                                         continue;
2217
2218                                 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2219                                         if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2220                                                 goto next;
2221                                 }
2222
2223                                 //
2224                                 // check generic arguments for methods
2225                                 //
2226                                 if (mi != null) {
2227                                         Type [] cmpGenArgs = mi.GetGenericArguments ();
2228                                         if (genericMethod != null && cmpGenArgs.Length > 0) {
2229                                                 if (genericMethod.TypeParameters.Length != cmpGenArgs.Length)
2230                                                         goto next;
2231                                         }
2232                                         else if (! (genericMethod == null && cmpGenArgs.Length == 0))
2233                                                 goto next;
2234                                 }
2235
2236                                 //
2237                                 // get one of the methods because this has the visibility info.
2238                                 //
2239                                 if (is_property) {
2240                                         mi = pi.GetGetMethod (true);
2241                                         if (mi == null)
2242                                                 mi = pi.GetSetMethod (true);
2243                                 }
2244                                 
2245                                 //
2246                                 // Check visibility
2247                                 //
2248                                 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2249                                 case MethodAttributes.Private:
2250                                         //
2251                                         // A private method is Ok if we are a nested subtype.
2252                                         // The spec actually is not very clear about this, see bug 52458.
2253                                         //
2254                                         if (invocationType.Equals (entry.Container.Type) ||
2255                                             TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2256                                                 return entry.Member;
2257                                         
2258                                         break;
2259                                 case MethodAttributes.FamANDAssem:
2260                                 case MethodAttributes.Assembly:
2261                                         //
2262                                         // Check for assembly methods
2263                                         //
2264                                         if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2265                                                 return entry.Member;
2266                                         
2267                                         break;
2268                                 default:
2269                                         //
2270                                         // A protected method is ok, because we are overriding.
2271                                         // public is always ok.
2272                                         //
2273                                         return entry.Member;
2274                                 }
2275                         next:
2276                                 ;
2277                         }
2278                         
2279                         return null;
2280                 }
2281
2282                 /// <summary>
2283                 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2284                 /// We handle two cases. The first is for types without parameters (events, field, properties).
2285                 /// The second are methods, indexers and this is why ignore_complex_types is here.
2286                 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2287                 /// </summary>
2288                 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2289                 {
2290                         ArrayList applicable = null;
2291  
2292                         if (method_hash != null)
2293                                 applicable = (ArrayList) method_hash [name];
2294  
2295                         if (applicable != null) {
2296                                 for (int i = applicable.Count - 1; i >= 0; i--) {
2297                                         CacheEntry entry = (CacheEntry) applicable [i];
2298                                         if ((entry.EntryType & EntryType.Public) != 0)
2299                                                 return entry.Member;
2300                                 }
2301                         }
2302  
2303                         if (member_hash == null)
2304                                 return null;
2305                         applicable = (ArrayList) member_hash [name];
2306                         
2307                         if (applicable != null) {
2308                                 for (int i = applicable.Count - 1; i >= 0; i--) {
2309                                         CacheEntry entry = (CacheEntry) applicable [i];
2310                                         if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2311                                                 if (ignore_complex_types) {
2312                                                         if ((entry.EntryType & EntryType.Method) != 0)
2313                                                                 continue;
2314  
2315                                                         // Does exist easier way how to detect indexer ?
2316                                                         if ((entry.EntryType & EntryType.Property) != 0) {
2317                                                                 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2318                                                                 if (arg_types.Length > 0)
2319                                                                         continue;
2320                                                         }
2321                                                 }
2322                                                 return entry.Member;
2323                                         }
2324                                 }
2325                         }
2326                         return null;
2327                 }
2328
2329                 Hashtable locase_table;
2330  
2331                 /// <summary>
2332                 /// Builds low-case table for CLS Compliance test
2333                 /// </summary>
2334                 public Hashtable GetPublicMembers ()
2335                 {
2336                         if (locase_table != null)
2337                                 return locase_table;
2338  
2339                         locase_table = new Hashtable ();
2340                         foreach (DictionaryEntry entry in member_hash) {
2341                                 ArrayList members = (ArrayList)entry.Value;
2342                                 for (int ii = 0; ii < members.Count; ++ii) {
2343                                         CacheEntry member_entry = (CacheEntry) members [ii];
2344  
2345                                         if ((member_entry.EntryType & EntryType.Public) == 0)
2346                                                 continue;
2347  
2348                                         // TODO: Does anyone know easier way how to detect that member is internal ?
2349                                         switch (member_entry.EntryType & EntryType.MaskType) {
2350                                                 case EntryType.Constructor:
2351                                                         continue;
2352  
2353                                                 case EntryType.Field:
2354                                                         if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2355                                                                 continue;
2356                                                         break;
2357  
2358                                                 case EntryType.Method:
2359                                                         if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2360                                                                 continue;
2361                                                         break;
2362  
2363                                                 case EntryType.Property:
2364                                                         PropertyInfo pi = (PropertyInfo)member_entry.Member;
2365                                                         if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2366                                                                 continue;
2367                                                         break;
2368  
2369                                                 case EntryType.Event:
2370                                                         EventInfo ei = (EventInfo)member_entry.Member;
2371                                                         MethodInfo mi = ei.GetAddMethod ();
2372                                                         if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2373                                                                 continue;
2374                                                         break;
2375                                         }
2376                                         string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2377                                         locase_table [lcase] = member_entry.Member;
2378                                         break;
2379                                 }
2380                         }
2381                         return locase_table;
2382                 }
2383  
2384                 public Hashtable Members {
2385                         get {
2386                                 return member_hash;
2387                         }
2388                 }
2389  
2390                 /// <summary>
2391                 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2392                 /// </summary>
2393                 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2394                 {
2395                         EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2396  
2397                         for (int i = 0; i < al.Count; ++i) {
2398                                 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2399                 
2400                                 // skip itself
2401                                 if (entry.Member == this_builder)
2402                                         continue;
2403                 
2404                                 if ((entry.EntryType & tested_type) != tested_type)
2405                                         continue;
2406                 
2407                                 MethodBase method_to_compare = (MethodBase)entry.Member;
2408                                 AttributeTester.Result result = AttributeTester.AreOverloadedMethodParamsClsCompliant (
2409                                         method.ParameterTypes, TypeManager.GetParameterData (method_to_compare).Types);
2410
2411                                 if (result == AttributeTester.Result.Ok)
2412                                         continue;
2413
2414                                 IMethodData md = TypeManager.GetMethod (method_to_compare);
2415
2416                                 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2417                                 // However it is exactly what csc does.
2418                                 if (md != null && !md.IsClsComplianceRequired ())
2419                                         continue;
2420                 
2421                                 Report.SymbolRelatedToPreviousError (entry.Member);
2422                                 switch (result) {
2423                                         case AttributeTester.Result.RefOutArrayError:
2424                                                 Report.Error (3006, method.Location, "Overloaded method `{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
2425                                                 continue;
2426                                         case AttributeTester.Result.ArrayArrayError:
2427                                                 Report.Error (3007, method.Location, "Overloaded method `{0}' differing only by unnamed array types is not CLS-compliant", method.GetSignatureForError ());
2428                                                 continue;
2429                                 }
2430
2431                                 throw new NotImplementedException (result.ToString ());
2432                         }
2433                 }
2434         }
2435 }