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