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