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