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