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