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