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