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