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