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