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