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