2004-05-29 Gonzalo Paniagua Javier <gonzalo@ximian.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 //
6 // Licensed under the terms of the GNU GPL
7 //
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
9 //
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
11 //
12
13 using System;
14 using System.Collections;
15 using System.Globalization;
16 using System.Reflection.Emit;
17 using System.Reflection;
18
19 namespace Mono.CSharp {
20
21         /// <summary>
22         ///   Base representation for members.  This is used to keep track
23         ///   of Name, Location and Modifier flags, and handling Attributes.
24         /// </summary>
25         public abstract class MemberCore : Attributable {
26                 /// <summary>
27                 ///   Public name
28                 /// </summary>
29                 public string Name;
30
31                 /// <summary>
32                 ///   Modifier flags that the user specified in the source code
33                 /// </summary>
34                 public int ModFlags;
35
36                 /// <summary>
37                 ///   Location where this declaration happens
38                 /// </summary>
39                 public readonly Location Location;
40
41                 [Flags]
42                 public enum Flags {
43                         Obsolete_Undetected = 1,                // Obsolete attribute has not been detected yet
44                         Obsolete = 1 << 1,                      // Type has obsolete attribute
45                         ClsCompliance_Undetected = 1 << 2,      // CLS Compliance has not been detected yet
46                         ClsCompliant = 1 << 3,                  // Type is CLS Compliant
47                         CloseTypeCreated = 1 << 4,              // Tracks whether we have Closed the type
48                         HasCompliantAttribute_Undetected = 1 << 5,      // Presence of CLSCompliantAttribute has not been detected
49                         HasClsCompliantAttribute = 1 << 6,                      // Type has CLSCompliantAttribute
50                         ClsCompliantAttributeTrue = 1 << 7,                     // Type has CLSCompliant (true)
51                 }
52
53                 /// <summary>
54                 ///   MemberCore flags at first detected then cached
55                 /// </summary>
56                 protected Flags caching_flags;
57
58                 public MemberCore (string name, Attributes attrs, Location loc)
59                         : base (attrs)
60                 {
61                         Name = name;
62                         Location = loc;
63                         caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected;
64                 }
65
66                 public abstract bool Define (TypeContainer parent);
67
68                 // 
69                 // Returns full member name for error message
70                 //
71                 public virtual string GetSignatureForError ()
72                 {
73                         return Name;
74                 }
75
76                 /// <summary>
77                 /// Base Emit method. This is also entry point for CLS-Compliant verification.
78                 /// </summary>
79                 public virtual void Emit (TypeContainer container)
80                 {
81                         if (!RootContext.VerifyClsCompliance)
82                                 return;
83
84                         VerifyClsCompliance (container);
85                 }
86
87                 // 
88                 // Whehter is it ok to use an unsafe pointer in this type container
89                 //
90                 public bool UnsafeOK (DeclSpace parent)
91                 {
92                         //
93                         // First check if this MemberCore modifier flags has unsafe set
94                         //
95                         if ((ModFlags & Modifiers.UNSAFE) != 0)
96                                 return true;
97
98                         if (parent.UnsafeContext)
99                                 return true;
100
101                         Expression.UnsafeError (Location);
102                         return false;
103                 }
104
105                 /// <summary>
106                 /// Returns instance of ObsoleteAttribute for this MemberCore
107                 /// </summary>
108                 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
109                 {
110                         // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
111                         if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
112                                 return null;
113                         }
114
115                         caching_flags &= ~Flags.Obsolete_Undetected;
116
117                         if (OptAttributes == null)
118                                 return null;
119
120                         // TODO: remove this allocation
121                         EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
122                                 null, null, ds.ModFlags, false);
123
124                         Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
125                         if (obsolete_attr == null)
126                                 return null;
127
128                         ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
129                         if (obsolete == null)
130                                 return null;
131
132                         caching_flags |= Flags.Obsolete;
133                         return obsolete;
134                 }
135
136                 /// <summary>
137                 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
138                 /// </summary>
139                 public override bool IsClsCompliaceRequired (DeclSpace container)
140                 {
141                         if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
142                                 return (caching_flags & Flags.ClsCompliant) != 0;
143
144                         if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
145                                 caching_flags &= ~Flags.ClsCompliance_Undetected;
146                                 caching_flags |= Flags.ClsCompliant;
147                                 return true;
148                         }
149
150                         caching_flags &= ~Flags.ClsCompliance_Undetected;
151                         return false;
152                 }
153
154                 /// <summary>
155                 /// Returns true when MemberCore is exposed from assembly.
156                 /// </summary>
157                 protected bool IsExposedFromAssembly (DeclSpace ds)
158                 {
159                         if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
160                                 return false;
161                         
162                         DeclSpace parentContainer = ds;
163                         while (parentContainer != null && parentContainer.ModFlags != 0) {
164                                 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
165                                         return false;
166                                 parentContainer = parentContainer.Parent;
167                         }
168                         return true;
169                 }
170
171                 /// <summary>
172                 /// Resolve CLSCompliantAttribute value or gets cached value.
173                 /// </summary>
174                 bool GetClsCompliantAttributeValue (DeclSpace ds)
175                 {
176                         if (OptAttributes != null) {
177                                 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
178                                                                   null, null, ds.ModFlags, false);
179                                 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
180                                 if (cls_attribute != null) {
181                                         caching_flags |= Flags.HasClsCompliantAttribute;
182                                         return cls_attribute.GetClsCompliantAttributeValue (ds);
183                                 }
184                         }
185                         return ds.GetClsCompliantAttributeValue ();
186                 }
187
188                 /// <summary>
189                 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
190                 /// </summary>
191                 protected bool HasClsCompliantAttribute {
192                         get {
193                                 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
194                         }
195                 }
196
197                 /// <summary>
198                 /// This method is used to testing error 3005 (Method or parameter name collision).
199                 /// </summary>
200                 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
201
202                 /// <summary>
203                 /// Common helper method for identifier and parameters CLS-Compliant testing.
204                 /// When return false error 3005 is reported. True means no violation.
205                 /// And error 3006 tests are peformed here because of speed.
206                 /// </summary>
207                 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
208                 {
209                         MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property, 
210                                 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
211                 
212                         if (ml.Count < 2)
213                                 return true;
214
215                         bool error3006 = false;
216                         for (int i = 0; i < ml.Count; ++i) {
217                                 MemberInfo mi = ml [i];
218                                 if (name == mi.Name) {
219                                         MethodBase method = mi as MethodBase;
220                                         if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
221                                                 continue;
222
223                                         if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
224                                                 error3006 = false;
225                                                 continue;
226                                         }
227
228                                         error3006 = true;
229                                 }
230
231                                 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
232                                 // because BindingFlags.Public returns internal types too
233                                 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
234
235                                 // Type is external, we can get attribute directly
236                                 if (temp_ds == null) {
237                                         object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
238                                         if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
239                                                 continue;
240                                 } else {
241                                         string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
242
243                                         MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
244                                         if (!mc.IsClsCompliaceRequired (ds))
245                                                 continue;
246                                 }
247
248                                 for (int ii = 0; ii < ml.Count; ++ii) {
249                                         mi = ml [ii];
250                                         if (name == mi.Name)
251                                                 continue;
252                                         Report.SymbolRelatedToPreviousError (mi);
253                                 }
254
255                                 if (error3006)
256                                         Report.Error_T (3006, Location, GetSignatureForError ());
257
258                                 return error3006;
259
260                         }
261                         return true;
262                 }
263
264                 /// <summary>
265                 /// The main virtual method for CLS-Compliant verifications.
266                 /// The method returns true if member is CLS-Compliant and false if member is not
267                 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
268                 /// and add their extra verifications.
269                 /// </summary>
270                 protected virtual bool VerifyClsCompliance (DeclSpace ds)
271                 {
272                         if (!IsClsCompliaceRequired (ds)) {
273                                 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
274                                         Report.Warning_T (3019, Location, GetSignatureForError ());
275                                 }
276                                 return false;
277                         }
278
279                         if (!CodeGen.Assembly.IsClsCompliant) {
280                                 if (HasClsCompliantAttribute) {
281                                         Report.Error_T (3014, Location, GetSignatureForError ());
282                                 }
283                         }
284
285                         int index = Name.LastIndexOf ('.');
286                         if (Name [index > 0 ? index + 1 : 0] == '_') {
287                                 Report.Error_T (3008, Location, GetSignatureForError () );
288                         }
289
290                         if (!IsIdentifierClsCompliant (ds)) {
291                                 Report.Error_T (3005, Location, GetSignatureForError ());
292                         }
293
294                         return true;
295                 }
296
297         }
298
299         /// <summary>
300         ///   Base class for structs, classes, enumerations and interfaces.  
301         /// </summary>
302         /// <remarks>
303         ///   They all create new declaration spaces.  This
304         ///   provides the common foundation for managing those name
305         ///   spaces.
306         /// </remarks>
307         public abstract class DeclSpace : MemberCore {
308                 /// <summary>
309                 ///   this points to the actual definition that is being
310                 ///   created with System.Reflection.Emit
311                 /// </summary>
312                 public TypeBuilder TypeBuilder;
313
314                 //
315                 // This is the namespace in which this typecontainer
316                 // was declared.  We use this to resolve names.
317                 //
318                 public NamespaceEntry NamespaceEntry;
319
320                 public Hashtable Cache = new Hashtable ();
321                 
322                 public string Basename;
323                 
324                 /// <summary>
325                 ///   defined_names is used for toplevel objects
326                 /// </summary>
327                 protected Hashtable defined_names;
328
329                 TypeContainer parent;           
330
331                 static string[] attribute_targets = new string [] { "type" };
332
333                 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
334                         : base (name, attrs, l)
335                 {
336                         NamespaceEntry = ns;
337                         Basename = name.Substring (1 + name.LastIndexOf ('.'));
338                         defined_names = new Hashtable ();
339                         this.parent = parent;
340                 }
341
342                 public void RecordDecl ()
343                 {
344                         if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
345                                 NamespaceEntry.DefineName (Basename, this);
346                 }
347
348                 /// <summary>
349                 ///   The result value from adding an declaration into
350                 ///   a struct or a class
351                 /// </summary>
352                 public enum AdditionResult {
353                         /// <summary>
354                         /// The declaration has been successfully
355                         /// added to the declation space.
356                         /// </summary>
357                         Success,
358
359                         /// <summary>
360                         ///   The symbol has already been defined.
361                         /// </summary>
362                         NameExists,
363
364                         /// <summary>
365                         ///   Returned if the declation being added to the
366                         ///   name space clashes with its container name.
367                         ///
368                         ///   The only exceptions for this are constructors
369                         ///   and static constructors
370                         /// </summary>
371                         EnclosingClash,
372
373                         /// <summary>
374                         ///   Returned if a constructor was created (because syntactically
375                         ///   it looked like a constructor) but was not (because the name
376                         ///   of the method is not the same as the container class
377                         /// </summary>
378                         NotAConstructor,
379
380                         /// <summary>
381                         ///   This is only used by static constructors to emit the
382                         ///   error 111, but this error for other things really
383                         ///   happens at another level for other functions.
384                         /// </summary>
385                         MethodExists,
386
387                         /// <summary>
388                         ///   Some other error.
389                         /// </summary>
390                         Error
391                 }
392
393                 /// <summary>
394                 ///   Returns a status code based purely on the name
395                 ///   of the member being added
396                 /// </summary>
397                 protected AdditionResult IsValid (string basename, string name)
398                 {
399                         if (basename == Basename)
400                                 return AdditionResult.EnclosingClash;
401
402                         if (defined_names.Contains (name))
403                                 return AdditionResult.NameExists;
404
405                         return AdditionResult.Success;
406                 }
407
408                 public static int length;
409                 public static int small;
410                 
411                 /// <summary>
412                 ///   Introduce @name into this declaration space and
413                 ///   associates it with the object @o.  Note that for
414                 ///   methods this will just point to the first method. o
415                 /// </summary>
416                 public void DefineName (string name, object o)
417                 {
418                         defined_names.Add (name, o);
419
420 #if DEBUGME
421                         int p = name.LastIndexOf ('.');
422                         int l = name.Length;
423                         length += l;
424                         small += l -p;
425 #endif
426                 }
427
428                 /// <summary>
429                 ///   Returns the object associated with a given name in the declaration
430                 ///   space.  This is the inverse operation of `DefineName'
431                 /// </summary>
432                 public object GetDefinition (string name)
433                 {
434                         return defined_names [name];
435                 }
436                 
437                 bool in_transit = false;
438                 
439                 /// <summary>
440                 ///   This function is used to catch recursive definitions
441                 ///   in declarations.
442                 /// </summary>
443                 public bool InTransit {
444                         get {
445                                 return in_transit;
446                         }
447
448                         set {
449                                 in_transit = value;
450                         }
451                 }
452
453                 public TypeContainer Parent {
454                         get {
455                                 return parent;
456                         }
457                 }
458
459                 /// <summary>
460                 ///   Looks up the alias for the name
461                 /// </summary>
462                 public string LookupAlias (string name)
463                 {
464                         if (NamespaceEntry != null)
465                                 return NamespaceEntry.LookupAlias (name);
466                         else
467                                 return null;
468                 }
469                 
470                 // 
471                 // root_types contains all the types.  All TopLevel types
472                 // hence have a parent that points to `root_types', that is
473                 // why there is a non-obvious test down here.
474                 //
475                 public bool IsTopLevel {
476                         get {
477                                 if (parent != null){
478                                         if (parent.parent == null)
479                                                 return true;
480                                 }
481                                 return false;
482                         }
483                 }
484
485                 public virtual void CloseType ()
486                 {
487                         if ((caching_flags & Flags.CloseTypeCreated) == 0){
488                                 try {
489                                         TypeBuilder.CreateType ();
490                                 } catch {
491                                         //
492                                         // The try/catch is needed because
493                                         // nested enumerations fail to load when they
494                                         // are defined.
495                                         //
496                                         // Even if this is the right order (enumerations
497                                         // declared after types).
498                                         //
499                                         // Note that this still creates the type and
500                                         // it is possible to save it
501                                 }
502                                 caching_flags |= Flags.CloseTypeCreated;
503                         }
504                 }
505
506                 /// <remarks>
507                 ///  Should be overriten by the appropriate declaration space
508                 /// </remarks>
509                 public abstract TypeBuilder DefineType ();
510                 
511                 /// <summary>
512                 ///   Define all members, but don't apply any attributes or do anything which may
513                 ///   access not-yet-defined classes.  This method also creates the MemberCache.
514                 /// </summary>
515                 public abstract bool DefineMembers (TypeContainer parent);
516
517                 //
518                 // Whether this is an `unsafe context'
519                 //
520                 public bool UnsafeContext {
521                         get {
522                                 if ((ModFlags & Modifiers.UNSAFE) != 0)
523                                         return true;
524                                 if (parent != null)
525                                         return parent.UnsafeContext;
526                                 return false;
527                         }
528                 }
529
530                 public static string MakeFQN (string nsn, string name)
531                 {
532                         if (nsn == "")
533                                 return name;
534                         return String.Concat (nsn, ".", name);
535                 }
536
537                 EmitContext type_resolve_ec;
538                 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
539                 {
540                         type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
541                         type_resolve_ec.ResolvingTypeTree = true;
542
543                         return type_resolve_ec;
544                 }
545
546                 // <summary>
547                 //    Looks up the type, as parsed into the expression `e' 
548                 // </summary>
549                 public Type ResolveType (Expression e, bool silent, Location loc)
550                 {
551                         if (type_resolve_ec == null)
552                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
553                         type_resolve_ec.loc = loc;
554                         type_resolve_ec.ContainerType = TypeBuilder;
555
556                         int errors = Report.Errors;
557                         TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
558                         
559                         if (d == null || d.eclass != ExprClass.Type){
560                                 if (!silent && errors == Report.Errors){
561                                         Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
562                                 }
563                                 return null;
564                         }
565
566                         if (!d.CheckAccessLevel (this)) {
567                                 Report.Error_T (122, loc, d.Name);
568                                 return null;
569                         }
570
571                         return d.Type;
572                 }
573
574                 // <summary>
575                 //    Resolves the expression `e' for a type, and will recursively define
576                 //    types. 
577                 // </summary>
578                 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
579                 {
580                         if (type_resolve_ec == null)
581                                 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
582                         type_resolve_ec.loc = loc;
583                         type_resolve_ec.ContainerType = TypeBuilder;
584
585                         TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
586                          
587                         if (d == null || d.eclass != ExprClass.Type){
588                                 if (!silent){
589                                         Report.Error (246, loc, "Cannot find type `"+ e +"'");
590                                 }
591                                 return null;
592                         }
593
594                         return d;
595                 }
596                 
597                 public bool CheckAccessLevel (Type check_type) 
598                 {
599                         if (check_type == TypeBuilder)
600                                 return true;
601                         
602                         TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
603                         
604                         //
605                         // Broken Microsoft runtime, return public for arrays, no matter what 
606                         // the accessibility is for their underlying class, and they return 
607                         // NonPublic visibility for pointers
608                         //
609                         if (check_type.IsArray || check_type.IsPointer)
610                                 return CheckAccessLevel (TypeManager.GetElementType (check_type));
611
612                         switch (check_attr){
613                         case TypeAttributes.Public:
614                                 return true;
615
616                         case TypeAttributes.NotPublic:
617
618                                 // In same cases is null.
619                                 if (TypeBuilder == null)
620                                         return true;
621
622                                 //
623                                 // This test should probably use the declaringtype.
624                                 //
625                                 return check_type.Assembly == TypeBuilder.Assembly;
626                                 
627                         case TypeAttributes.NestedPublic:
628                                 return true;
629
630                         case TypeAttributes.NestedPrivate:
631                                 string check_type_name = check_type.FullName;
632                                 string type_name = TypeBuilder.FullName;
633                                 
634                                 int cio = check_type_name.LastIndexOf ('+');
635                                 string container = check_type_name.Substring (0, cio);
636
637                                 //
638                                 // Check if the check_type is a nested class of the current type
639                                 //
640                                 if (check_type_name.StartsWith (type_name + "+")){
641                                         return true;
642                                 }
643                                 
644                                 if (type_name.StartsWith (container)){
645                                         return true;
646                                 }
647
648                                 return false;
649
650                         case TypeAttributes.NestedFamily:
651                                 //
652                                 // Only accessible to methods in current type or any subtypes
653                                 //
654                                 return FamilyAccessible (check_type);
655
656                         case TypeAttributes.NestedFamANDAssem:
657                                 return (check_type.Assembly == TypeBuilder.Assembly) &&
658                                         FamilyAccessible (check_type);
659
660                         case TypeAttributes.NestedFamORAssem:
661                                 return (check_type.Assembly == TypeBuilder.Assembly) ||
662                                         FamilyAccessible (check_type);
663
664                         case TypeAttributes.NestedAssembly:
665                                 return check_type.Assembly == TypeBuilder.Assembly;
666                         }
667
668                         Console.WriteLine ("HERE: " + check_attr);
669                         return false;
670
671                 }
672
673                 protected bool FamilyAccessible (Type check_type)
674                 {
675                         Type declaring = check_type.DeclaringType;
676                         if (TypeBuilder.IsSubclassOf (declaring))
677                                 return true;
678
679                         string check_type_name = check_type.FullName;
680                         
681                         int cio = check_type_name.LastIndexOf ('+');
682                         string container = check_type_name.Substring (0, cio);
683                         
684                         //
685                         // Check if the check_type is a nested class of the current type
686                         //
687                         if (check_type_name.StartsWith (container + "+"))
688                                 return true;
689
690                         return false;
691                 }
692
693                 // Access level of a type.
694                 const int X = 1;
695                 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
696                                             // Public    Assembly   Protected
697                         Protected           = (0 << 0) | (0 << 1) | (X << 2),
698                         Public              = (X << 0) | (X << 1) | (X << 2),
699                         Private             = (0 << 0) | (0 << 1) | (0 << 2),
700                         Internal            = (0 << 0) | (X << 1) | (0 << 2),
701                         ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
702                 }
703                 
704                 static AccessLevel GetAccessLevelFromModifiers (int flags)
705                 {
706                         if ((flags & Modifiers.INTERNAL) != 0) {
707                                 
708                                 if ((flags & Modifiers.PROTECTED) != 0)
709                                         return AccessLevel.ProtectedOrInternal;
710                                 else
711                                         return AccessLevel.Internal;
712                                 
713                         } else if ((flags & Modifiers.PROTECTED) != 0)
714                                 return AccessLevel.Protected;
715                         
716                         else if ((flags & Modifiers.PRIVATE) != 0)
717                                 return AccessLevel.Private;
718                         
719                         else
720                                 return AccessLevel.Public;
721                 }
722
723                 // What is the effective access level of this?
724                 // TODO: Cache this?
725                 AccessLevel EffectiveAccessLevel {
726                         get {
727                                 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
728                                 if (!IsTopLevel && (Parent != null))
729                                         return myAccess & Parent.EffectiveAccessLevel;
730                                 else
731                                         return myAccess;
732                         }
733                 }
734
735                 // Return the access level for type `t'
736                 static AccessLevel TypeEffectiveAccessLevel (Type t)
737                 {
738                         if (t.IsPublic)
739                                 return AccessLevel.Public;              
740                         if (t.IsNestedPrivate)
741                                 return AccessLevel.Private;
742                         if (t.IsNotPublic)
743                                 return AccessLevel.Internal;
744                         
745                         // By now, it must be nested
746                         AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
747                         
748                         if (t.IsNestedPublic)
749                                 return parentLevel;
750                         if (t.IsNestedAssembly)
751                                 return parentLevel & AccessLevel.Internal;
752                         if (t.IsNestedFamily)
753                                 return parentLevel & AccessLevel.Protected;
754                         if (t.IsNestedFamORAssem)
755                                 return parentLevel & AccessLevel.ProtectedOrInternal;
756                         if (t.IsNestedFamANDAssem)
757                                 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
758                         
759                         // nested private is taken care of
760                         
761                         throw new Exception ("I give up, what are you?");
762                 }
763
764                 //
765                 // This answers `is the type P, as accessible as a member M which has the
766                 // accessability @flags which is declared as a nested member of the type T, this declspace'
767                 //
768                 public bool AsAccessible (Type p, int flags)
769                 {
770                         //
771                         // 1) if M is private, its accessability is the same as this declspace.
772                         // we already know that P is accessible to T before this method, so we
773                         // may return true.
774                         //
775                         
776                         if ((flags & Modifiers.PRIVATE) != 0)
777                                 return true;
778                         
779                         while (p.IsArray || p.IsPointer || p.IsByRef)
780                                 p = TypeManager.GetElementType (p);
781                         
782                         AccessLevel pAccess = TypeEffectiveAccessLevel (p);
783                         AccessLevel mAccess = this.EffectiveAccessLevel &
784                                 GetAccessLevelFromModifiers (flags);
785                         
786                         // for every place from which we can access M, we must
787                         // be able to access P as well. So, we want
788                         // For every bit in M and P, M_i -> P_1 == true
789                         // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
790                         
791                         return ~ (~ mAccess | pAccess) == 0;
792                 }
793                 
794                 static DoubleHash dh = new DoubleHash (1000);
795
796                 Type DefineTypeAndParents (DeclSpace tc)
797                 {
798                         DeclSpace container = tc.Parent;
799
800                         if (container.TypeBuilder == null && container.Name != "")
801                                 DefineTypeAndParents (container);
802
803                         return tc.DefineType ();
804                 }
805                 
806                 Type LookupInterfaceOrClass (string ns, string name, out bool error)
807                 {
808                         DeclSpace parent;
809                         Type t;
810                         object r;
811                         
812                         error = false;
813
814                         if (dh.Lookup (ns, name, out r))
815                                 return (Type) r;
816                         else {
817                                 if (ns != ""){
818                                         if (Namespace.IsNamespace (ns)){
819                                                 string fullname = (ns != "") ? ns + "." + name : name;
820                                                 t = TypeManager.LookupType (fullname);
821                                         } else
822                                                 t = null;
823                                 } else
824                                         t = TypeManager.LookupType (name);
825                         }
826                         
827                         if (t != null) {
828                                 dh.Insert (ns, name, t);
829                                 return t;
830                         }
831
832                         //
833                         // In case we are fed a composite name, normalize it.
834                         //
835                         int p = name.LastIndexOf ('.');
836                         if (p != -1){
837                                 ns = MakeFQN (ns, name.Substring (0, p));
838                                 name = name.Substring (p+1);
839                         }
840                         
841                         parent = RootContext.Tree.LookupByNamespace (ns, name);
842                         if (parent == null) {
843                                 dh.Insert (ns, name, null);
844                                 return null;
845                         }
846
847                         t = DefineTypeAndParents (parent);
848                         if (t == null){
849                                 error = true;
850                                 return null;
851                         }
852                         
853                         dh.Insert (ns, name, t);
854                         return t;
855                 }
856
857                 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
858                 {
859                         Report.Error (104, loc,
860                                       String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
861                                                      t1.FullName, t2.FullName));
862                 }
863
864                 /// <summary>
865                 ///   GetType is used to resolve type names at the DeclSpace level.
866                 ///   Use this to lookup class/struct bases, interface bases or 
867                 ///   delegate type references
868                 /// </summary>
869                 ///
870                 /// <remarks>
871                 ///   Contrast this to LookupType which is used inside method bodies to 
872                 ///   lookup types that have already been defined.  GetType is used
873                 ///   during the tree resolution process and potentially define
874                 ///   recursively the type
875                 /// </remarks>
876                 public Type FindType (Location loc, string name)
877                 {
878                         Type t;
879                         bool error;
880
881                         //
882                         // For the case the type we are looking for is nested within this one
883                         // or is in any base class
884                         //
885                         DeclSpace containing_ds = this;
886
887                         while (containing_ds != null){
888                                 Type container_type = containing_ds.TypeBuilder;
889                                 Type current_type = container_type;
890
891                                 while (current_type != null && current_type != TypeManager.object_type) {
892                                         string pre = current_type.FullName;
893
894                                         t = LookupInterfaceOrClass (pre, name, out error);
895                                         if (error)
896                                                 return null;
897                                 
898                                         if ((t != null) && containing_ds.CheckAccessLevel (t))
899                                                 return t;
900
901                                         current_type = current_type.BaseType;
902                                 }
903                                 containing_ds = containing_ds.Parent;
904                         }
905
906                         //
907                         // Attempt to lookup the class on our namespace and all it's implicit parents
908                         //
909                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
910                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
911                                 if (error)
912                                         return null;
913                                 
914                                 if (t != null) 
915                                         return t;
916                         }
917                         
918                         //
919                         // Attempt to do a direct unqualified lookup
920                         //
921                         t = LookupInterfaceOrClass ("", name, out error);
922                         if (error)
923                                 return null;
924                         
925                         if (t != null)
926                                 return t;
927                         
928                         //
929                         // Attempt to lookup the class on any of the `using'
930                         // namespaces
931                         //
932
933                         for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
934
935                                 t = LookupInterfaceOrClass (ns.FullName, name, out error);
936                                 if (error)
937                                         return null;
938
939                                 if (t != null)
940                                         return t;
941
942                                 if (name.IndexOf ('.') > 0)
943                                         continue;
944
945                                 string alias_value = ns.LookupAlias (name);
946                                 if (alias_value != null) {
947                                         t = LookupInterfaceOrClass ("", alias_value, out error);
948                                         if (error)
949                                                 return null;
950
951                                         if (t != null)
952                                                 return t;
953                                 }
954
955                                 //
956                                 // Now check the using clause list
957                                 //
958                                 Type match = null;
959                                 foreach (Namespace using_ns in ns.GetUsingTable ()) {
960                                         match = LookupInterfaceOrClass (using_ns.Name, name, out error);
961                                         if (error)
962                                                 return null;
963
964                                         if (match != null){
965                                                 if (t != null){
966                                                         if (CheckAccessLevel (match)) {
967                                                                 Error_AmbiguousTypeReference (loc, name, t, match);
968                                                                 return null;
969                                                         }
970                                                         continue;
971                                                 }
972                                                 
973                                                 t = match;
974                                         }
975                                 }
976                                 if (t != null)
977                                         return t;
978                         }
979
980                         //Report.Error (246, Location, "Can not find type `"+name+"'");
981                         return null;
982                 }
983
984                 /// <remarks>
985                 ///   This function is broken and not what you're looking for.  It should only
986                 ///   be used while the type is still being created since it doesn't use the cache
987                 ///   and relies on the filter doing the member name check.
988                 /// </remarks>
989                 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
990                                                         MemberFilter filter, object criteria);
991
992                 /// <remarks>
993                 ///   If we have a MemberCache, return it.  This property may return null if the
994                 ///   class doesn't have a member cache or while it's still being created.
995                 /// </remarks>
996                 public abstract MemberCache MemberCache {
997                         get;
998                 }
999
1000                 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1001                 {
1002                         try {
1003                                 TypeBuilder.SetCustomAttribute (cb);
1004                         } catch (System.ArgumentException e) {
1005                                 Report.Warning (-21, a.Location,
1006                                                 "The CharSet named property on StructLayout\n"+
1007                                                 "\tdoes not work correctly on Microsoft.NET\n"+
1008                                                 "\tYou might want to remove the CharSet declaration\n"+
1009                                                 "\tor compile using the Mono runtime instead of the\n"+
1010                                                 "\tMicrosoft .NET runtime\n"+
1011                                                 "\tThe runtime gave the error: " + e);
1012                         }
1013                 }
1014
1015                 /// <summary>
1016                 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1017                 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1018                 /// </summary>
1019                 public bool GetClsCompliantAttributeValue ()
1020                 {
1021                         if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1022                                 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1023
1024                         caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1025
1026                         if (OptAttributes != null) {
1027                                 EmitContext ec = new EmitContext (parent, this, Location,
1028                                                                   null, null, ModFlags, false);
1029                                 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1030                                 if (cls_attribute != null) {
1031                                         caching_flags |= Flags.HasClsCompliantAttribute;
1032                                         if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1033                                                 caching_flags |= Flags.ClsCompliantAttributeTrue;
1034                                                 return true;
1035                                         }
1036                                         return false;
1037                                 }
1038                         }
1039
1040                         if (parent == null) {
1041                                 if (CodeGen.Assembly.IsClsCompliant) {
1042                                         caching_flags |= Flags.ClsCompliantAttributeTrue;
1043                                         return true;
1044                                 }
1045                                 return false;
1046                         }
1047
1048                         if (parent.GetClsCompliantAttributeValue ()) {
1049                                 caching_flags |= Flags.ClsCompliantAttributeTrue;
1050                                 return true;
1051                         }
1052                         return false;
1053                 }
1054
1055
1056                 // Tests container name for CLS-Compliant name (differing only in case)
1057                 // Possible optimalization: search in same namespace only
1058                 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1059                 {
1060                         int l = Name.Length;
1061
1062                         if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1063                                 // Seek through all imported types
1064                                 foreach (string type_name in TypeManager.all_imported_types.Keys) 
1065                                 {
1066                                         if (l != type_name.Length)
1067                                                 continue;
1068
1069                                         if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 && 
1070                                                 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1071                                                 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1072                                                 return false;
1073                                 }
1074                         }
1075                         }
1076
1077                         // Seek through generated types
1078                         foreach (string name in RootContext.Tree.Decls.Keys) {
1079                                 if (l != name.Length)
1080                                         continue;
1081
1082                                 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) { 
1083
1084                                         if (Name == name)
1085                                                 continue;
1086                                         
1087                                         DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1088                                         if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1089                                                 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1090                                                 return false;
1091                                         }
1092                                 }
1093                         }
1094
1095                         return true;
1096                 }
1097
1098                 protected override string[] ValidAttributeTargets {
1099                         get {
1100                                 return attribute_targets;
1101                         }
1102                 }
1103         }
1104
1105         /// <summary>
1106         ///   This is a readonly list of MemberInfo's.      
1107         /// </summary>
1108         public class MemberList : IList {
1109                 public readonly IList List;
1110                 int count;
1111
1112                 /// <summary>
1113                 ///   Create a new MemberList from the given IList.
1114                 /// </summary>
1115                 public MemberList (IList list)
1116                 {
1117                         if (list != null)
1118                                 this.List = list;
1119                         else
1120                                 this.List = new ArrayList ();
1121                         count = List.Count;
1122                 }
1123
1124                 /// <summary>
1125                 ///   Concatenate the ILists `first' and `second' to a new MemberList.
1126                 /// </summary>
1127                 public MemberList (IList first, IList second)
1128                 {
1129                         ArrayList list = new ArrayList ();
1130                         list.AddRange (first);
1131                         list.AddRange (second);
1132                         count = list.Count;
1133                         List = list;
1134                 }
1135
1136                 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1137
1138                 /// <summary>
1139                 ///   Cast the MemberList into a MemberInfo[] array.
1140                 /// </summary>
1141                 /// <remarks>
1142                 ///   This is an expensive operation, only use it if it's really necessary.
1143                 /// </remarks>
1144                 public static explicit operator MemberInfo [] (MemberList list)
1145                 {
1146                         Timer.StartTimer (TimerType.MiscTimer);
1147                         MemberInfo [] result = new MemberInfo [list.Count];
1148                         list.CopyTo (result, 0);
1149                         Timer.StopTimer (TimerType.MiscTimer);
1150                         return result;
1151                 }
1152
1153                 // ICollection
1154
1155                 public int Count {
1156                         get {
1157                                 return count;
1158                         }
1159                 }
1160
1161                 public bool IsSynchronized {
1162                         get {
1163                                 return List.IsSynchronized;
1164                         }
1165                 }
1166
1167                 public object SyncRoot {
1168                         get {
1169                                 return List.SyncRoot;
1170                         }
1171                 }
1172
1173                 public void CopyTo (Array array, int index)
1174                 {
1175                         List.CopyTo (array, index);
1176                 }
1177
1178                 // IEnumerable
1179
1180                 public IEnumerator GetEnumerator ()
1181                 {
1182                         return List.GetEnumerator ();
1183                 }
1184
1185                 // IList
1186
1187                 public bool IsFixedSize {
1188                         get {
1189                                 return true;
1190                         }
1191                 }
1192
1193                 public bool IsReadOnly {
1194                         get {
1195                                 return true;
1196                         }
1197                 }
1198
1199                 object IList.this [int index] {
1200                         get {
1201                                 return List [index];
1202                         }
1203
1204                         set {
1205                                 throw new NotSupportedException ();
1206                         }
1207                 }
1208
1209                 // FIXME: try to find out whether we can avoid the cast in this indexer.
1210                 public MemberInfo this [int index] {
1211                         get {
1212                                 return (MemberInfo) List [index];
1213                         }
1214                 }
1215
1216                 public int Add (object value)
1217                 {
1218                         throw new NotSupportedException ();
1219                 }
1220
1221                 public void Clear ()
1222                 {
1223                         throw new NotSupportedException ();
1224                 }
1225
1226                 public bool Contains (object value)
1227                 {
1228                         return List.Contains (value);
1229                 }
1230
1231                 public int IndexOf (object value)
1232                 {
1233                         return List.IndexOf (value);
1234                 }
1235
1236                 public void Insert (int index, object value)
1237                 {
1238                         throw new NotSupportedException ();
1239                 }
1240
1241                 public void Remove (object value)
1242                 {
1243                         throw new NotSupportedException ();
1244                 }
1245
1246                 public void RemoveAt (int index)
1247                 {
1248                         throw new NotSupportedException ();
1249                 }
1250         }
1251
1252         /// <summary>
1253         ///   This interface is used to get all members of a class when creating the
1254         ///   member cache.  It must be implemented by all DeclSpace derivatives which
1255         ///   want to support the member cache and by TypeHandle to get caching of
1256         ///   non-dynamic types.
1257         /// </summary>
1258         public interface IMemberContainer {
1259                 /// <summary>
1260                 ///   The name of the IMemberContainer.  This is only used for
1261                 ///   debugging purposes.
1262                 /// </summary>
1263                 string Name {
1264                         get;
1265                 }
1266
1267                 /// <summary>
1268                 ///   The type of this IMemberContainer.
1269                 /// </summary>
1270                 Type Type {
1271                         get;
1272                 }
1273
1274                 /// <summary>
1275                 ///   Returns the IMemberContainer of the parent class or null if this
1276                 ///   is an interface or TypeManger.object_type.
1277                 ///   This is used when creating the member cache for a class to get all
1278                 ///   members from the parent class.
1279                 /// </summary>
1280                 IMemberContainer Parent {
1281                         get;
1282                 }
1283
1284                 /// <summary>
1285                 ///   Whether this is an interface.
1286                 /// </summary>
1287                 bool IsInterface {
1288                         get;
1289                 }
1290
1291                 /// <summary>
1292                 ///   Returns all members of this class with the corresponding MemberTypes
1293                 ///   and BindingFlags.
1294                 /// </summary>
1295                 /// <remarks>
1296                 ///   When implementing this method, make sure not to return any inherited
1297                 ///   members and check the MemberTypes and BindingFlags properly.
1298                 ///   Unfortunately, System.Reflection is lame and doesn't provide a way to
1299                 ///   get the BindingFlags (static/non-static,public/non-public) in the
1300                 ///   MemberInfo class, but the cache needs this information.  That's why
1301                 ///   this method is called multiple times with different BindingFlags.
1302                 /// </remarks>
1303                 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1304
1305                 /// <summary>
1306                 ///   Return the container's member cache.
1307                 /// </summary>
1308                 MemberCache MemberCache {
1309                         get;
1310                 }
1311         }
1312
1313         /// <summary>
1314         ///   The MemberCache is used by dynamic and non-dynamic types to speed up
1315         ///   member lookups.  It has a member name based hash table; it maps each member
1316         ///   name to a list of CacheEntry objects.  Each CacheEntry contains a MemberInfo
1317         ///   and the BindingFlags that were initially used to get it.  The cache contains
1318         ///   all members of the current class and all inherited members.  If this cache is
1319         ///   for an interface types, it also contains all inherited members.
1320         ///
1321         ///   There are two ways to get a MemberCache:
1322         ///   * if this is a dynamic type, lookup the corresponding DeclSpace and then
1323         ///     use the DeclSpace.MemberCache property.
1324         ///   * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1325         ///     TypeHandle instance for the type and then use TypeHandle.MemberCache.
1326         /// </summary>
1327         public class MemberCache {
1328                 public readonly IMemberContainer Container;
1329                 protected Hashtable member_hash;
1330                 protected Hashtable method_hash;
1331                 
1332                 /// <summary>
1333                 ///   Create a new MemberCache for the given IMemberContainer `container'.
1334                 /// </summary>
1335                 public MemberCache (IMemberContainer container)
1336                 {
1337                         this.Container = container;
1338
1339                         Timer.IncrementCounter (CounterType.MemberCache);
1340                         Timer.StartTimer (TimerType.CacheInit);
1341
1342                         
1343
1344                         // If we have a parent class (we have a parent class unless we're
1345                         // TypeManager.object_type), we deep-copy its MemberCache here.
1346                         if (Container.IsInterface) {
1347                                 MemberCache parent;
1348                                 
1349                                 if (Container.Parent != null)
1350                                         parent = Container.Parent.MemberCache;
1351                                 else
1352                                         parent = TypeHandle.ObjectType.MemberCache;
1353                                 member_hash = SetupCacheForInterface (parent);
1354                         } else if (Container.Parent != null)
1355                                 member_hash = SetupCache (Container.Parent.MemberCache);
1356                         else
1357                                 member_hash = new Hashtable ();
1358
1359                         // If this is neither a dynamic type nor an interface, create a special
1360                         // method cache with all declared and inherited methods.
1361                         Type type = container.Type;
1362                         if (!(type is TypeBuilder) && !type.IsInterface) {
1363                                 method_hash = new Hashtable ();
1364                                 AddMethods (type);
1365                         }
1366
1367                         // Add all members from the current class.
1368                         AddMembers (Container);
1369
1370                         Timer.StopTimer (TimerType.CacheInit);
1371                 }
1372
1373                 /// <summary>
1374                 ///   Bootstrap this member cache by doing a deep-copy of our parent.
1375                 /// </summary>
1376                 Hashtable SetupCache (MemberCache parent)
1377                 {
1378                         Hashtable hash = new Hashtable ();
1379
1380                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1381                         while (it.MoveNext ()) {
1382                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1383                         }
1384                                 
1385                         return hash;
1386                 }
1387
1388
1389                 /// <summary>
1390                 ///   Add the contents of `new_hash' to `hash'.
1391                 /// </summary>
1392                 void AddHashtable (Hashtable hash, MemberCache cache)
1393                 {
1394                         Hashtable new_hash = cache.member_hash;
1395                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
1396                         while (it.MoveNext ()) {
1397                                 ArrayList list = (ArrayList) hash [it.Key];
1398                                 if (list == null)
1399                                         hash [it.Key] = list = new ArrayList ();
1400
1401                                 foreach (CacheEntry entry in (ArrayList) it.Value) {
1402                                         if (entry.Container != cache.Container)
1403                                                 break;
1404                                         list.Add (entry);
1405                                 }
1406                         }
1407                 }
1408
1409                 /// <summary>
1410                 ///   Bootstrap the member cache for an interface type.
1411                 ///   Type.GetMembers() won't return any inherited members for interface types,
1412                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
1413                 /// </summary>
1414                 Hashtable SetupCacheForInterface (MemberCache parent)
1415                 {
1416                         Hashtable hash = SetupCache (parent);
1417                         TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1418
1419                         foreach (TypeExpr iface in ifaces) {
1420                                 Type itype = iface.Type;
1421
1422                                 IMemberContainer iface_container =
1423                                         TypeManager.LookupMemberContainer (itype);
1424
1425                                 MemberCache iface_cache = iface_container.MemberCache;
1426
1427                                 AddHashtable (hash, iface_cache);
1428                         }
1429
1430                         return hash;
1431                 }
1432
1433                 /// <summary>
1434                 ///   Add all members from class `container' to the cache.
1435                 /// </summary>
1436                 void AddMembers (IMemberContainer container)
1437                 {
1438                         // We need to call AddMembers() with a single member type at a time
1439                         // to get the member type part of CacheEntry.EntryType right.
1440                         AddMembers (MemberTypes.Constructor, container);
1441                         AddMembers (MemberTypes.Field, container);
1442                         AddMembers (MemberTypes.Method, container);
1443                         AddMembers (MemberTypes.Property, container);
1444                         AddMembers (MemberTypes.Event, container);
1445                         // Nested types are returned by both Static and Instance searches.
1446                         AddMembers (MemberTypes.NestedType,
1447                                     BindingFlags.Static | BindingFlags.Public, container);
1448                         AddMembers (MemberTypes.NestedType,
1449                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1450                 }
1451
1452                 void AddMembers (MemberTypes mt, IMemberContainer container)
1453                 {
1454                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1455                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1456                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1457                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1458                 }
1459
1460                 /// <summary>
1461                 ///   Add all members from class `container' with the requested MemberTypes and
1462                 ///   BindingFlags to the cache.  This method is called multiple times with different
1463                 ///   MemberTypes and BindingFlags.
1464                 /// </summary>
1465                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1466                 {
1467                         MemberList members = container.GetMembers (mt, bf);
1468
1469                         foreach (MemberInfo member in members) {
1470                                 string name = member.Name;
1471
1472                                 // We use a name-based hash table of ArrayList's.
1473                                 ArrayList list = (ArrayList) member_hash [name];
1474                                 if (list == null) {
1475                                         list = new ArrayList ();
1476                                         member_hash.Add (name, list);
1477                                 }
1478
1479                                 // When this method is called for the current class, the list will
1480                                 // already contain all inherited members from our parent classes.
1481                                 // We cannot add new members in front of the list since this'd be an
1482                                 // expensive operation, that's why the list is sorted in reverse order
1483                                 // (ie. members from the current class are coming last).
1484                                 list.Add (new CacheEntry (container, member, mt, bf));
1485                         }
1486                 }
1487
1488                 /// <summary>
1489                 ///   Add all declared and inherited methods from class `type' to the method cache.
1490                 /// </summary>
1491                 void AddMethods (Type type)
1492                 {
1493                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1494                                     BindingFlags.FlattenHierarchy, type);
1495                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1496                                     BindingFlags.FlattenHierarchy, type);
1497                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1498                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1499                 }
1500
1501                 void AddMethods (BindingFlags bf, Type type)
1502                 {
1503                         MemberInfo [] members = type.GetMethods (bf);
1504
1505                         Array.Reverse (members);
1506                         
1507                         foreach (MethodBase member in members) {
1508                                 string name = member.Name;
1509
1510                                 // Varargs methods aren't allowed in C# code.
1511                                 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1512                                         continue;
1513
1514                                 // We use a name-based hash table of ArrayList's.
1515                                 ArrayList list = (ArrayList) method_hash [name];
1516                                 if (list == null) {
1517                                         list = new ArrayList ();
1518                                         method_hash.Add (name, list);
1519                                 }
1520
1521                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1522                                 // sorted so we need to do this check for every member.
1523                                 BindingFlags new_bf = bf;
1524                                 if (member.DeclaringType == type)
1525                                         new_bf |= BindingFlags.DeclaredOnly;
1526
1527                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1528                         }
1529
1530                         
1531                 }
1532
1533                 /// <summary>
1534                 ///   Compute and return a appropriate `EntryType' magic number for the given
1535                 ///   MemberTypes and BindingFlags.
1536                 /// </summary>
1537                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1538                 {
1539                         EntryType type = EntryType.None;
1540
1541                         if ((mt & MemberTypes.Constructor) != 0)
1542                                 type |= EntryType.Constructor;
1543                         if ((mt & MemberTypes.Event) != 0)
1544                                 type |= EntryType.Event;
1545                         if ((mt & MemberTypes.Field) != 0)
1546                                 type |= EntryType.Field;
1547                         if ((mt & MemberTypes.Method) != 0)
1548                                 type |= EntryType.Method;
1549                         if ((mt & MemberTypes.Property) != 0)
1550                                 type |= EntryType.Property;
1551                         // Nested types are returned by static and instance searches.
1552                         if ((mt & MemberTypes.NestedType) != 0)
1553                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1554
1555                         if ((bf & BindingFlags.Instance) != 0)
1556                                 type |= EntryType.Instance;
1557                         if ((bf & BindingFlags.Static) != 0)
1558                                 type |= EntryType.Static;
1559                         if ((bf & BindingFlags.Public) != 0)
1560                                 type |= EntryType.Public;
1561                         if ((bf & BindingFlags.NonPublic) != 0)
1562                                 type |= EntryType.NonPublic;
1563                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1564                                 type |= EntryType.Declared;
1565
1566                         return type;
1567                 }
1568
1569                 /// <summary>
1570                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1571                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1572                 ///   single member types.
1573                 /// </summary>
1574                 public static bool IsSingleMemberType (MemberTypes mt)
1575                 {
1576                         switch (mt) {
1577                         case MemberTypes.Constructor:
1578                         case MemberTypes.Event:
1579                         case MemberTypes.Field:
1580                         case MemberTypes.Method:
1581                         case MemberTypes.Property:
1582                         case MemberTypes.NestedType:
1583                                 return true;
1584
1585                         default:
1586                                 return false;
1587                         }
1588                 }
1589
1590                 /// <summary>
1591                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1592                 ///   number to speed up the searching process.
1593                 /// </summary>
1594                 [Flags]
1595                 protected enum EntryType {
1596                         None            = 0x000,
1597
1598                         Instance        = 0x001,
1599                         Static          = 0x002,
1600                         MaskStatic      = Instance|Static,
1601
1602                         Public          = 0x004,
1603                         NonPublic       = 0x008,
1604                         MaskProtection  = Public|NonPublic,
1605
1606                         Declared        = 0x010,
1607
1608                         Constructor     = 0x020,
1609                         Event           = 0x040,
1610                         Field           = 0x080,
1611                         Method          = 0x100,
1612                         Property        = 0x200,
1613                         NestedType      = 0x400,
1614
1615                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1616                 }
1617
1618                 protected struct CacheEntry {
1619                         public readonly IMemberContainer Container;
1620                         public readonly EntryType EntryType;
1621                         public readonly MemberInfo Member;
1622
1623                         public CacheEntry (IMemberContainer container, MemberInfo member,
1624                                            MemberTypes mt, BindingFlags bf)
1625                         {
1626                                 this.Container = container;
1627                                 this.Member = member;
1628                                 this.EntryType = GetEntryType (mt, bf);
1629                         }
1630                 }
1631
1632                 /// <summary>
1633                 ///   This is called each time we're walking up one level in the class hierarchy
1634                 ///   and checks whether we can abort the search since we've already found what
1635                 ///   we were looking for.
1636                 /// </summary>
1637                 protected bool DoneSearching (ArrayList list)
1638                 {
1639                         //
1640                         // We've found exactly one member in the current class and it's not
1641                         // a method or constructor.
1642                         //
1643                         if (list.Count == 1 && !(list [0] is MethodBase))
1644                                 return true;
1645
1646                         //
1647                         // Multiple properties: we query those just to find out the indexer
1648                         // name
1649                         //
1650                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1651                                 return true;
1652
1653                         return false;
1654                 }
1655
1656                 /// <summary>
1657                 ///   Looks up members with name `name'.  If you provide an optional
1658                 ///   filter function, it'll only be called with members matching the
1659                 ///   requested member name.
1660                 ///
1661                 ///   This method will try to use the cache to do the lookup if possible.
1662                 ///
1663                 ///   Unlike other FindMembers implementations, this method will always
1664                 ///   check all inherited members - even when called on an interface type.
1665                 ///
1666                 ///   If you know that you're only looking for methods, you should use
1667                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1668                 ///   When doing a method-only search, it'll try to use a special method
1669                 ///   cache (unless it's a dynamic type or an interface) and the returned
1670                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1671                 ///   The lookup process will automatically restart itself in method-only
1672                 ///   search mode if it discovers that it's about to return methods.
1673                 /// </summary>
1674                 ArrayList global = new ArrayList ();
1675                 bool using_global = false;
1676                 
1677                 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1678                 
1679                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1680                                                MemberFilter filter, object criteria)
1681                 {
1682                         if (using_global)
1683                                 throw new Exception ();
1684                         
1685                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1686                         bool method_search = mt == MemberTypes.Method;
1687                         // If we have a method cache and we aren't already doing a method-only search,
1688                         // then we restart a method search if the first match is a method.
1689                         bool do_method_search = !method_search && (method_hash != null);
1690
1691                         ArrayList applicable;
1692
1693                         // If this is a method-only search, we try to use the method cache if
1694                         // possible; a lookup in the method cache will return a MemberInfo with
1695                         // the correct ReflectedType for inherited methods.
1696                         
1697                         if (method_search && (method_hash != null))
1698                                 applicable = (ArrayList) method_hash [name];
1699                         else
1700                                 applicable = (ArrayList) member_hash [name];
1701
1702                         if (applicable == null)
1703                                 return emptyMemberInfo;
1704
1705                         //
1706                         // 32  slots gives 53 rss/54 size
1707                         // 2/4 slots gives 55 rss
1708                         //
1709                         // Strange: from 25,000 calls, only 1,800
1710                         // are above 2.  Why does this impact it?
1711                         //
1712                         global.Clear ();
1713                         using_global = true;
1714
1715                         Timer.StartTimer (TimerType.CachedLookup);
1716
1717                         EntryType type = GetEntryType (mt, bf);
1718
1719                         IMemberContainer current = Container;
1720
1721
1722                         // `applicable' is a list of all members with the given member name `name'
1723                         // in the current class and all its parent classes.  The list is sorted in
1724                         // reverse order due to the way how the cache is initialy created (to speed
1725                         // things up, we're doing a deep-copy of our parent).
1726
1727                         for (int i = applicable.Count-1; i >= 0; i--) {
1728                                 CacheEntry entry = (CacheEntry) applicable [i];
1729
1730                                 // This happens each time we're walking one level up in the class
1731                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1732                                 // the first time this happens (this may already happen in the first
1733                                 // iteration of this loop if there are no members with the name we're
1734                                 // looking for in the current class).
1735                                 if (entry.Container != current) {
1736                                         if (declared_only || DoneSearching (global))
1737                                                 break;
1738
1739                                         current = entry.Container;
1740                                 }
1741
1742                                 // Is the member of the correct type ?
1743                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1744                                         continue;
1745
1746                                 // Is the member static/non-static ?
1747                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1748                                         continue;
1749
1750                                 // Apply the filter to it.
1751                                 if (filter (entry.Member, criteria)) {
1752                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1753                                                 do_method_search = false;
1754                                         global.Add (entry.Member);
1755                                 }
1756                         }
1757
1758                         Timer.StopTimer (TimerType.CachedLookup);
1759
1760                         // If we have a method cache and we aren't already doing a method-only
1761                         // search, we restart in method-only search mode if the first match is
1762                         // a method.  This ensures that we return a MemberInfo with the correct
1763                         // ReflectedType for inherited methods.
1764                         if (do_method_search && (global.Count > 0)){
1765                                 using_global = false;
1766
1767                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1768                         }
1769
1770                         using_global = false;
1771                         MemberInfo [] copy = new MemberInfo [global.Count];
1772                         global.CopyTo (copy);
1773                         return copy;
1774                 }
1775                 
1776                 //
1777                 // This finds the method or property for us to override. invocationType is the type where
1778                 // the override is going to be declared, name is the name of the method/property, and
1779                 // paramTypes is the parameters, if any to the method or property
1780                 //
1781                 // Because the MemberCache holds members from this class and all the base classes,
1782                 // we can avoid tons of reflection stuff.
1783                 //
1784                 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1785                 {
1786                         ArrayList applicable;
1787                         if (method_hash != null && !is_property)
1788                                 applicable = (ArrayList) method_hash [name];
1789                         else
1790                                 applicable = (ArrayList) member_hash [name];
1791                         
1792                         if (applicable == null)
1793                                 return null;
1794                         //
1795                         // Walk the chain of methods, starting from the top.
1796                         //
1797                         for (int i = applicable.Count - 1; i >= 0; i--) {
1798                                 CacheEntry entry = (CacheEntry) applicable [i];
1799                                 
1800                                 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1801                                         continue;
1802
1803                                 PropertyInfo pi = null;
1804                                 MethodInfo mi = null;
1805                                 FieldInfo fi = null;
1806                                 Type [] cmpAttrs = null;
1807                                 
1808                                 if (is_property) {
1809                                         if ((entry.EntryType & EntryType.Field) != 0) {
1810                                                 fi = (FieldInfo)entry.Member;
1811
1812                                                 // TODO: For this case we ignore member type
1813                                                 //fb = TypeManager.GetField (fi);
1814                                                 //cmpAttrs = new Type[] { fb.MemberType };
1815                                         } else {
1816                                                 pi = (PropertyInfo) entry.Member;
1817                                                 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1818                                         }
1819                                 } else {
1820                                         mi = (MethodInfo) entry.Member;
1821                                         cmpAttrs = TypeManager.GetArgumentTypes (mi);
1822                                 }
1823
1824                                 if (fi != null) {
1825                                         // TODO: Almost duplicate !
1826                                         // Check visibility
1827                                         switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1828                                                 case FieldAttributes.Private:
1829                                                         //
1830                                                         // A private method is Ok if we are a nested subtype.
1831                                                         // The spec actually is not very clear about this, see bug 52458.
1832                                                         //
1833                                                         if (invocationType != entry.Container.Type &
1834                                                                 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1835                                                                 continue;
1836
1837                                                         break;
1838                                                 case FieldAttributes.FamANDAssem:
1839                                                 case FieldAttributes.Assembly:
1840                                                         //
1841                                                         // Check for assembly methods
1842                                                         //
1843                                                         if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1844                                                                 continue;
1845                                                         break;
1846                                         }
1847                                         return entry.Member;
1848                                 }
1849
1850                                 //
1851                                 // Check the arguments
1852                                 //
1853                                 if (cmpAttrs.Length != paramTypes.Length)
1854                                         continue;
1855         
1856                                 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1857                                         if (paramTypes [j] != cmpAttrs [j])
1858                                                 goto next;
1859                                 
1860                                 //
1861                                 // get one of the methods because this has the visibility info.
1862                                 //
1863                                 if (is_property) {
1864                                         mi = pi.GetGetMethod (true);
1865                                         if (mi == null)
1866                                                 mi = pi.GetSetMethod (true);
1867                                 }
1868                                 
1869                                 //
1870                                 // Check visibility
1871                                 //
1872                                 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1873                                 case MethodAttributes.Private:
1874                                         //
1875                                         // A private method is Ok if we are a nested subtype.
1876                                         // The spec actually is not very clear about this, see bug 52458.
1877                                         //
1878                                         if (invocationType == entry.Container.Type ||
1879                                             TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1880                                                 return entry.Member;
1881                                         
1882                                         break;
1883                                 case MethodAttributes.FamANDAssem:
1884                                 case MethodAttributes.Assembly:
1885                                         //
1886                                         // Check for assembly methods
1887                                         //
1888                                         if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1889                                                 return entry.Member;
1890                                         
1891                                         break;
1892                                 default:
1893                                         //
1894                                         // A protected method is ok, because we are overriding.
1895                                         // public is always ok.
1896                                         //
1897                                         return entry.Member;
1898                                 }
1899                         next:
1900                                 ;
1901                         }
1902                         
1903                         return null;
1904                 }
1905         }
1906 }