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