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