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