2004-10-31 Marek Safar <marek.safar@seznam.cz>
[mono.git] / mcs / mcs / decl.cs
1 //
2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Marek Safar (marek.safar@seznam.cz)
6 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11 // TODO: Move the method verification stuff from the class.cs and interface.cs here
12 //
13
14 using System;
15 using System.Collections;
16 using System.Globalization;
17 using System.Reflection.Emit;
18 using System.Reflection;
19
20 namespace Mono.CSharp {
21
22         public class MemberName {
23                 public string Name;
24                 public readonly MemberName Left;
25
26                 public static readonly MemberName Null = new MemberName ("");
27
28                 public MemberName (string name)
29                 {
30                         this.Name = name;
31                 }
32
33                 public MemberName (MemberName left, string name)
34                         : this (name)
35                 {
36                         this.Left = left;
37                 }
38
39                 public MemberName (MemberName left, MemberName right)
40                         : this (left, right.Name)
41                 {
42                 }
43
44                 public string GetName ()
45                 {
46                         return GetName (false);
47                 }
48
49                 public string GetName (bool is_generic)
50                 {
51                         string name = is_generic ? Basename : Name;
52                         if (Left != null)
53                                 return Left.GetName (is_generic) + "." + name;
54                         else
55                                 return name;
56                 }
57
58                 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 && !(this is Interface)) {
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, bool setup_inherited_interfaces)
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 = null;
1283                                 member_hash = SetupCacheForInterface (parent, setup_inherited_interfaces);
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                         if (parent == null)
1310                                 return hash;
1311
1312                         IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1313                         while (it.MoveNext ()) {
1314                                 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1315                         }
1316                                 
1317                         return hash;
1318                 }
1319
1320
1321                 /// <summary>
1322                 ///   Add the contents of `new_hash' to `hash'.
1323                 /// </summary>
1324                 void AddHashtable (Hashtable hash, MemberCache cache)
1325                 {
1326                         Hashtable new_hash = cache.member_hash;
1327                         IDictionaryEnumerator it = new_hash.GetEnumerator ();
1328                         while (it.MoveNext ()) {
1329                                 ArrayList list = (ArrayList) hash [it.Key];
1330                                 if (list == null)
1331                                         hash [it.Key] = list = new ArrayList ();
1332
1333                                 foreach (CacheEntry entry in (ArrayList) it.Value) {
1334                                         if (entry.Container != cache.Container)
1335                                                 break;
1336                                         list.Add (entry);
1337                                 }
1338                         }
1339                 }
1340
1341                 /// <summary>
1342                 ///   Bootstrap the member cache for an interface type.
1343                 ///   Type.GetMembers() won't return any inherited members for interface types,
1344                 ///   so we need to do this manually.  Interfaces also inherit from System.Object.
1345                 /// </summary>
1346                 Hashtable SetupCacheForInterface (MemberCache parent, bool deep_setup)
1347                 {
1348                         Hashtable hash = SetupCache (parent);
1349
1350                         if (!deep_setup)
1351                                 return hash;
1352
1353                         TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1354
1355                         foreach (TypeExpr iface in ifaces) {
1356                                 Type itype = iface.Type;
1357
1358                                 IMemberContainer iface_container =
1359                                         TypeManager.LookupMemberContainer (itype);
1360
1361                                 MemberCache iface_cache = iface_container.MemberCache;
1362
1363                                 AddHashtable (hash, iface_cache);
1364                         }
1365
1366                         return hash;
1367                 }
1368
1369                 /// <summary>
1370                 ///   Add all members from class `container' to the cache.
1371                 /// </summary>
1372                 void AddMembers (IMemberContainer container)
1373                 {
1374                         // We need to call AddMembers() with a single member type at a time
1375                         // to get the member type part of CacheEntry.EntryType right.
1376                         if (!container.IsInterface) {
1377                                 AddMembers (MemberTypes.Constructor, container);
1378                                 AddMembers (MemberTypes.Field, container);
1379                         }
1380                         AddMembers (MemberTypes.Method, container);
1381                         AddMembers (MemberTypes.Property, container);
1382                         AddMembers (MemberTypes.Event, container);
1383                         // Nested types are returned by both Static and Instance searches.
1384                         AddMembers (MemberTypes.NestedType,
1385                                     BindingFlags.Static | BindingFlags.Public, container);
1386                         AddMembers (MemberTypes.NestedType,
1387                                     BindingFlags.Static | BindingFlags.NonPublic, container);
1388                 }
1389
1390                 void AddMembers (MemberTypes mt, IMemberContainer container)
1391                 {
1392                         AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1393                         AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1394                         AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1395                         AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1396                 }
1397
1398                 /// <summary>
1399                 ///   Add all members from class `container' with the requested MemberTypes and
1400                 ///   BindingFlags to the cache.  This method is called multiple times with different
1401                 ///   MemberTypes and BindingFlags.
1402                 /// </summary>
1403                 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1404                 {
1405                         MemberList members = container.GetMembers (mt, bf);
1406
1407                         foreach (MemberInfo member in members) {
1408                                 string name = member.Name;
1409
1410                                 // We use a name-based hash table of ArrayList's.
1411                                 ArrayList list = (ArrayList) member_hash [name];
1412                                 if (list == null) {
1413                                         list = new ArrayList ();
1414                                         member_hash.Add (name, list);
1415                                 }
1416
1417                                 // When this method is called for the current class, the list will
1418                                 // already contain all inherited members from our parent classes.
1419                                 // We cannot add new members in front of the list since this'd be an
1420                                 // expensive operation, that's why the list is sorted in reverse order
1421                                 // (ie. members from the current class are coming last).
1422                                 list.Add (new CacheEntry (container, member, mt, bf));
1423                         }
1424                 }
1425
1426                 /// <summary>
1427                 ///   Add all declared and inherited methods from class `type' to the method cache.
1428                 /// </summary>
1429                 void AddMethods (Type type)
1430                 {
1431                         AddMethods (BindingFlags.Static | BindingFlags.Public |
1432                                     BindingFlags.FlattenHierarchy, type);
1433                         AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1434                                     BindingFlags.FlattenHierarchy, type);
1435                         AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1436                         AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1437                 }
1438
1439                 void AddMethods (BindingFlags bf, Type type)
1440                 {
1441                         MemberInfo [] members = type.GetMethods (bf);
1442
1443                         Array.Reverse (members);
1444
1445                         foreach (MethodBase member in members) {
1446                                 string name = member.Name;
1447
1448                                 // We use a name-based hash table of ArrayList's.
1449                                 ArrayList list = (ArrayList) method_hash [name];
1450                                 if (list == null) {
1451                                         list = new ArrayList ();
1452                                         method_hash.Add (name, list);
1453                                 }
1454
1455                                 // Unfortunately, the elements returned by Type.GetMethods() aren't
1456                                 // sorted so we need to do this check for every member.
1457                                 BindingFlags new_bf = bf;
1458                                 if (member.DeclaringType == type)
1459                                         new_bf |= BindingFlags.DeclaredOnly;
1460
1461                                 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1462                         }
1463
1464                         
1465                 }
1466
1467                 /// <summary>
1468                 ///   Compute and return a appropriate `EntryType' magic number for the given
1469                 ///   MemberTypes and BindingFlags.
1470                 /// </summary>
1471                 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1472                 {
1473                         EntryType type = EntryType.None;
1474
1475                         if ((mt & MemberTypes.Constructor) != 0)
1476                                 type |= EntryType.Constructor;
1477                         if ((mt & MemberTypes.Event) != 0)
1478                                 type |= EntryType.Event;
1479                         if ((mt & MemberTypes.Field) != 0)
1480                                 type |= EntryType.Field;
1481                         if ((mt & MemberTypes.Method) != 0)
1482                                 type |= EntryType.Method;
1483                         if ((mt & MemberTypes.Property) != 0)
1484                                 type |= EntryType.Property;
1485                         // Nested types are returned by static and instance searches.
1486                         if ((mt & MemberTypes.NestedType) != 0)
1487                                 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1488
1489                         if ((bf & BindingFlags.Instance) != 0)
1490                                 type |= EntryType.Instance;
1491                         if ((bf & BindingFlags.Static) != 0)
1492                                 type |= EntryType.Static;
1493                         if ((bf & BindingFlags.Public) != 0)
1494                                 type |= EntryType.Public;
1495                         if ((bf & BindingFlags.NonPublic) != 0)
1496                                 type |= EntryType.NonPublic;
1497                         if ((bf & BindingFlags.DeclaredOnly) != 0)
1498                                 type |= EntryType.Declared;
1499
1500                         return type;
1501                 }
1502
1503                 /// <summary>
1504                 ///   The `MemberTypes' enumeration type is a [Flags] type which means that it may
1505                 ///   denote multiple member types.  Returns true if the given flags value denotes a
1506                 ///   single member types.
1507                 /// </summary>
1508                 public static bool IsSingleMemberType (MemberTypes mt)
1509                 {
1510                         switch (mt) {
1511                         case MemberTypes.Constructor:
1512                         case MemberTypes.Event:
1513                         case MemberTypes.Field:
1514                         case MemberTypes.Method:
1515                         case MemberTypes.Property:
1516                         case MemberTypes.NestedType:
1517                                 return true;
1518
1519                         default:
1520                                 return false;
1521                         }
1522                 }
1523
1524                 /// <summary>
1525                 ///   We encode the MemberTypes and BindingFlags of each members in a "magic"
1526                 ///   number to speed up the searching process.
1527                 /// </summary>
1528                 [Flags]
1529                 protected internal enum EntryType {
1530                         None            = 0x000,
1531
1532                         Instance        = 0x001,
1533                         Static          = 0x002,
1534                         MaskStatic      = Instance|Static,
1535
1536                         Public          = 0x004,
1537                         NonPublic       = 0x008,
1538                         MaskProtection  = Public|NonPublic,
1539
1540                         Declared        = 0x010,
1541
1542                         Constructor     = 0x020,
1543                         Event           = 0x040,
1544                         Field           = 0x080,
1545                         Method          = 0x100,
1546                         Property        = 0x200,
1547                         NestedType      = 0x400,
1548
1549                         MaskType        = Constructor|Event|Field|Method|Property|NestedType
1550                 }
1551
1552                 protected internal struct CacheEntry {
1553                         public readonly IMemberContainer Container;
1554                         public readonly EntryType EntryType;
1555                         public readonly MemberInfo Member;
1556
1557                         public CacheEntry (IMemberContainer container, MemberInfo member,
1558                                            MemberTypes mt, BindingFlags bf)
1559                         {
1560                                 this.Container = container;
1561                                 this.Member = member;
1562                                 this.EntryType = GetEntryType (mt, bf);
1563                         }
1564                 }
1565
1566                 /// <summary>
1567                 ///   This is called each time we're walking up one level in the class hierarchy
1568                 ///   and checks whether we can abort the search since we've already found what
1569                 ///   we were looking for.
1570                 /// </summary>
1571                 protected bool DoneSearching (ArrayList list)
1572                 {
1573                         //
1574                         // We've found exactly one member in the current class and it's not
1575                         // a method or constructor.
1576                         //
1577                         if (list.Count == 1 && !(list [0] is MethodBase))
1578                                 return true;
1579
1580                         //
1581                         // Multiple properties: we query those just to find out the indexer
1582                         // name
1583                         //
1584                         if ((list.Count > 0) && (list [0] is PropertyInfo))
1585                                 return true;
1586
1587                         return false;
1588                 }
1589
1590                 /// <summary>
1591                 ///   Looks up members with name `name'.  If you provide an optional
1592                 ///   filter function, it'll only be called with members matching the
1593                 ///   requested member name.
1594                 ///
1595                 ///   This method will try to use the cache to do the lookup if possible.
1596                 ///
1597                 ///   Unlike other FindMembers implementations, this method will always
1598                 ///   check all inherited members - even when called on an interface type.
1599                 ///
1600                 ///   If you know that you're only looking for methods, you should use
1601                 ///   MemberTypes.Method alone since this speeds up the lookup a bit.
1602                 ///   When doing a method-only search, it'll try to use a special method
1603                 ///   cache (unless it's a dynamic type or an interface) and the returned
1604                 ///   MemberInfo's will have the correct ReflectedType for inherited methods.
1605                 ///   The lookup process will automatically restart itself in method-only
1606                 ///   search mode if it discovers that it's about to return methods.
1607                 /// </summary>
1608                 ArrayList global = new ArrayList ();
1609                 bool using_global = false;
1610                 
1611                 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1612                 
1613                 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1614                                                   MemberFilter filter, object criteria)
1615                 {
1616                         if (using_global)
1617                                 throw new Exception ();
1618                         
1619                         bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1620                         bool method_search = mt == MemberTypes.Method;
1621                         // If we have a method cache and we aren't already doing a method-only search,
1622                         // then we restart a method search if the first match is a method.
1623                         bool do_method_search = !method_search && (method_hash != null);
1624
1625                         ArrayList applicable;
1626
1627                         // If this is a method-only search, we try to use the method cache if
1628                         // possible; a lookup in the method cache will return a MemberInfo with
1629                         // the correct ReflectedType for inherited methods.
1630                         
1631                         if (method_search && (method_hash != null))
1632                                 applicable = (ArrayList) method_hash [name];
1633                         else
1634                                 applicable = (ArrayList) member_hash [name];
1635
1636                         if (applicable == null)
1637                                 return emptyMemberInfo;
1638
1639                         //
1640                         // 32  slots gives 53 rss/54 size
1641                         // 2/4 slots gives 55 rss
1642                         //
1643                         // Strange: from 25,000 calls, only 1,800
1644                         // are above 2.  Why does this impact it?
1645                         //
1646                         global.Clear ();
1647                         using_global = true;
1648
1649                         Timer.StartTimer (TimerType.CachedLookup);
1650
1651                         EntryType type = GetEntryType (mt, bf);
1652
1653                         IMemberContainer current = Container;
1654
1655
1656                         // `applicable' is a list of all members with the given member name `name'
1657                         // in the current class and all its parent classes.  The list is sorted in
1658                         // reverse order due to the way how the cache is initialy created (to speed
1659                         // things up, we're doing a deep-copy of our parent).
1660
1661                         for (int i = applicable.Count-1; i >= 0; i--) {
1662                                 CacheEntry entry = (CacheEntry) applicable [i];
1663
1664                                 // This happens each time we're walking one level up in the class
1665                                 // hierarchy.  If we're doing a DeclaredOnly search, we must abort
1666                                 // the first time this happens (this may already happen in the first
1667                                 // iteration of this loop if there are no members with the name we're
1668                                 // looking for in the current class).
1669                                 if (entry.Container != current) {
1670                                         if (declared_only || DoneSearching (global))
1671                                                 break;
1672
1673                                         current = entry.Container;
1674                                 }
1675
1676                                 // Is the member of the correct type ?
1677                                 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1678                                         continue;
1679
1680                                 // Is the member static/non-static ?
1681                                 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1682                                         continue;
1683
1684                                 // Apply the filter to it.
1685                                 if (filter (entry.Member, criteria)) {
1686                                         if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1687                                                 do_method_search = false;
1688                                         global.Add (entry.Member);
1689                                 }
1690                         }
1691
1692                         Timer.StopTimer (TimerType.CachedLookup);
1693
1694                         // If we have a method cache and we aren't already doing a method-only
1695                         // search, we restart in method-only search mode if the first match is
1696                         // a method.  This ensures that we return a MemberInfo with the correct
1697                         // ReflectedType for inherited methods.
1698                         if (do_method_search && (global.Count > 0)){
1699                                 using_global = false;
1700
1701                                 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1702                         }
1703
1704                         using_global = false;
1705                         MemberInfo [] copy = new MemberInfo [global.Count];
1706                         global.CopyTo (copy);
1707                         return copy;
1708                 }
1709                 
1710                 // find the nested type @name in @this.
1711                 public Type FindNestedType (string name)
1712                 {
1713                         ArrayList applicable = (ArrayList) member_hash [name];
1714                         if (applicable == null)
1715                                 return null;
1716                         
1717                         for (int i = applicable.Count-1; i >= 0; i--) {
1718                                 CacheEntry entry = (CacheEntry) applicable [i];
1719                                 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
1720                                         return (Type) entry.Member;
1721                         }
1722                         
1723                         return null;
1724                 }
1725                 
1726                 //
1727                 // This finds the method or property for us to override. invocationType is the type where
1728                 // the override is going to be declared, name is the name of the method/property, and
1729                 // paramTypes is the parameters, if any to the method or property
1730                 //
1731                 // Because the MemberCache holds members from this class and all the base classes,
1732                 // we can avoid tons of reflection stuff.
1733                 //
1734                 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1735                 {
1736                         ArrayList applicable;
1737                         if (method_hash != null && !is_property)
1738                                 applicable = (ArrayList) method_hash [name];
1739                         else
1740                                 applicable = (ArrayList) member_hash [name];
1741                         
1742                         if (applicable == null)
1743                                 return null;
1744                         //
1745                         // Walk the chain of methods, starting from the top.
1746                         //
1747                         for (int i = applicable.Count - 1; i >= 0; i--) {
1748                                 CacheEntry entry = (CacheEntry) applicable [i];
1749                                 
1750                                 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1751                                         continue;
1752
1753                                 PropertyInfo pi = null;
1754                                 MethodInfo mi = null;
1755                                 FieldInfo fi = null;
1756                                 Type [] cmpAttrs = null;
1757                                 
1758                                 if (is_property) {
1759                                         if ((entry.EntryType & EntryType.Field) != 0) {
1760                                                 fi = (FieldInfo)entry.Member;
1761
1762                                                 // TODO: For this case we ignore member type
1763                                                 //fb = TypeManager.GetField (fi);
1764                                                 //cmpAttrs = new Type[] { fb.MemberType };
1765                                         } else {
1766                                                 pi = (PropertyInfo) entry.Member;
1767                                                 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1768                                         }
1769                                 } else {
1770                                         mi = (MethodInfo) entry.Member;
1771                                         cmpAttrs = TypeManager.GetArgumentTypes (mi);
1772                                 }
1773
1774                                 if (fi != null) {
1775                                         // TODO: Almost duplicate !
1776                                         // Check visibility
1777                                         switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1778                                                 case FieldAttributes.Private:
1779                                                         //
1780                                                         // A private method is Ok if we are a nested subtype.
1781                                                         // The spec actually is not very clear about this, see bug 52458.
1782                                                         //
1783                                                         if (invocationType != entry.Container.Type &
1784                                                                 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1785                                                                 continue;
1786
1787                                                         break;
1788                                                 case FieldAttributes.FamANDAssem:
1789                                                 case FieldAttributes.Assembly:
1790                                                         //
1791                                                         // Check for assembly methods
1792                                                         //
1793                                                         if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1794                                                                 continue;
1795                                                         break;
1796                                         }
1797                                         return entry.Member;
1798                                 }
1799
1800                                 //
1801                                 // Check the arguments
1802                                 //
1803                                 if (cmpAttrs.Length != paramTypes.Length)
1804                                         continue;
1805         
1806                                 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1807                                         if (paramTypes [j] != cmpAttrs [j])
1808                                                 goto next;
1809                                 
1810                                 //
1811                                 // get one of the methods because this has the visibility info.
1812                                 //
1813                                 if (is_property) {
1814                                         mi = pi.GetGetMethod (true);
1815                                         if (mi == null)
1816                                                 mi = pi.GetSetMethod (true);
1817                                 }
1818                                 
1819                                 //
1820                                 // Check visibility
1821                                 //
1822                                 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1823                                 case MethodAttributes.Private:
1824                                         //
1825                                         // A private method is Ok if we are a nested subtype.
1826                                         // The spec actually is not very clear about this, see bug 52458.
1827                                         //
1828                                         if (invocationType == entry.Container.Type ||
1829                                             TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1830                                                 return entry.Member;
1831                                         
1832                                         break;
1833                                 case MethodAttributes.FamANDAssem:
1834                                 case MethodAttributes.Assembly:
1835                                         //
1836                                         // Check for assembly methods
1837                                         //
1838                                         if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1839                                                 return entry.Member;
1840                                         
1841                                         break;
1842                                 default:
1843                                         //
1844                                         // A protected method is ok, because we are overriding.
1845                                         // public is always ok.
1846                                         //
1847                                         return entry.Member;
1848                                 }
1849                         next:
1850                                 ;
1851                         }
1852                         
1853                         return null;
1854                 }
1855
1856                 /// <summary>
1857                 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
1858                 /// We handle two cases. The first is for types without parameters (events, field, properties).
1859                 /// The second are methods, indexers and this is why ignore_complex_types is here.
1860                 /// The latest param is temporary hack. See DoDefineMembers method for more info.
1861                 /// </summary>
1862                 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
1863                 {
1864                         ArrayList applicable = null;
1865  
1866                         if (method_hash != null)
1867                                 applicable = (ArrayList) method_hash [name];
1868  
1869                         if (applicable != null) {
1870                                 for (int i = applicable.Count - 1; i >= 0; i--) {
1871                                         CacheEntry entry = (CacheEntry) applicable [i];
1872                                         if ((entry.EntryType & EntryType.Public) != 0)
1873                                                 return entry.Member;
1874                                 }
1875                         }
1876  
1877                         if (member_hash == null)
1878                                 return null;
1879                         applicable = (ArrayList) member_hash [name];
1880                         
1881                         if (applicable != null) {
1882                                 for (int i = applicable.Count - 1; i >= 0; i--) {
1883                                         CacheEntry entry = (CacheEntry) applicable [i];
1884                                         if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
1885                                                 if (ignore_complex_types) {
1886                                                         if ((entry.EntryType & EntryType.Method) != 0)
1887                                                                 continue;
1888  
1889                                                         // Does exist easier way how to detect indexer ?
1890                                                         if ((entry.EntryType & EntryType.Property) != 0) {
1891                                                                 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
1892                                                                 if (arg_types.Length > 0)
1893                                                                         continue;
1894                                                         }
1895                                                 }
1896                                                 return entry.Member;
1897                                         }
1898                                 }
1899                         }
1900                         return null;
1901                 }
1902
1903                 Hashtable locase_table;
1904  
1905                 /// <summary>
1906                 /// Builds low-case table for CLS Compliance test
1907                 /// </summary>
1908                 public Hashtable GetPublicMembers ()
1909                 {
1910                         if (locase_table != null)
1911                                 return locase_table;
1912  
1913                         locase_table = new Hashtable ();
1914                         foreach (DictionaryEntry entry in member_hash) {
1915                                 ArrayList members = (ArrayList)entry.Value;
1916                                 for (int ii = 0; ii < members.Count; ++ii) {
1917                                         CacheEntry member_entry = (CacheEntry) members [ii];
1918  
1919                                         if ((member_entry.EntryType & EntryType.Public) == 0)
1920                                                 continue;
1921  
1922                                         // TODO: Does anyone know easier way how to detect that member is internal ?
1923                                         switch (member_entry.EntryType & EntryType.MaskType) {
1924                                                 case EntryType.Constructor:
1925                                                         continue;
1926  
1927                                                 case EntryType.Field:
1928                                                         if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
1929                                                                 continue;
1930                                                         break;
1931  
1932                                                 case EntryType.Method:
1933                                                         if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
1934                                                                 continue;
1935                                                         break;
1936  
1937                                                 case EntryType.Property:
1938                                                         PropertyInfo pi = (PropertyInfo)member_entry.Member;
1939                                                         if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
1940                                                                 continue;
1941                                                         break;
1942  
1943                                                 case EntryType.Event:
1944                                                         EventInfo ei = (EventInfo)member_entry.Member;
1945                                                         MethodInfo mi = ei.GetAddMethod ();
1946                                                         if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
1947                                                                 continue;
1948                                                         break;
1949                                         }
1950                                         string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
1951                                         locase_table [lcase] = member_entry.Member;
1952                                         break;
1953                                 }
1954                         }
1955                         return locase_table;
1956                 }
1957  
1958                 public Hashtable Members {
1959                         get {
1960                                 return member_hash;
1961                         }
1962                 }
1963  
1964                 /// <summary>
1965                 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
1966                 /// </summary>
1967                 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
1968                 {
1969                         EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
1970  
1971                         for (int i = 0; i < al.Count; ++i) {
1972                                 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
1973                 
1974                                 // skip itself
1975                                 if (entry.Member == this_builder)
1976                                         continue;
1977                 
1978                                 if ((entry.EntryType & tested_type) != tested_type)
1979                                         continue;
1980                 
1981                                 MethodBase method_to_compare = (MethodBase)entry.Member;
1982                                 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
1983                                         continue;
1984
1985                                 IMethodData md = TypeManager.GetMethod (method_to_compare);
1986
1987                                 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
1988                                 // However it is exactly what csc does.
1989                                 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
1990                                         continue;
1991                 
1992                                 Report.SymbolRelatedToPreviousError (entry.Member);
1993                                 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());
1994                         }
1995                 }
1996         }
1997 }