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