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