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