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