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