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