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