**** Merged from MCS ****
[mono-project.git] / mcs / mcs / decl.cs
blob87b12ad6069cfa1fa0810ac9a78ede4ad2c7960b
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)
11 // TODO: Move the method verification stuff from the class.cs and interface.cs here
14 using System;
15 using System.Collections;
16 using System.Globalization;
17 using System.Reflection.Emit;
18 using System.Reflection;
20 namespace Mono.CSharp {
22 public class MemberName {
23 public string Name;
24 public readonly MemberName Left;
26 public static readonly MemberName Null = new MemberName ("");
28 public MemberName (string name)
30 this.Name = name;
33 public MemberName (MemberName left, string name)
34 : this (name)
36 this.Left = left;
39 public MemberName (MemberName left, MemberName right)
40 : this (left, right.Name)
44 public string GetName ()
46 return GetName (false);
49 public string GetName (bool is_generic)
51 string name = is_generic ? Basename : Name;
52 if (Left != null)
53 return Left.GetName (is_generic) + "." + name;
54 else
55 return name;
58 ///
59 /// This returns exclusively the name as seen on the source code
60 /// it is not the fully qualifed type after resolution
61 ///
62 public string GetPartialName ()
64 if (Left != null)
65 return Left.GetPartialName () + "." + Name;
66 else
67 return Name;
70 public string GetTypeName ()
72 if (Left != null)
73 return Left.GetTypeName () + "." + Name;
74 else
75 return Name;
78 public Expression GetTypeExpression (Location loc)
80 if (Left != null) {
81 Expression lexpr = Left.GetTypeExpression (loc);
83 return new MemberAccess (lexpr, Name, loc);
84 } else {
85 return new SimpleName (Name, loc);
89 public MemberName Clone ()
91 if (Left != null)
92 return new MemberName (Left.Clone (), Name);
93 else
94 return new MemberName (Name);
97 public string Basename {
98 get {
99 return Name;
103 public override string ToString ()
105 throw new Exception ("This exception is thrown because someone is miss-using\n" +
106 "MemberName.ToString in the compiler. Please report this bug");
111 /// <summary>
112 /// Base representation for members. This is used to keep track
113 /// of Name, Location and Modifier flags, and handling Attributes.
114 /// </summary>
115 public abstract class MemberCore : Attributable {
116 /// <summary>
117 /// Public name
118 /// </summary>
119 public string Name {
120 get {
121 // !(this is GenericMethod) && !(this is Method)
122 return MemberName.GetName (false);
126 public readonly MemberName MemberName;
128 /// <summary>
129 /// Modifier flags that the user specified in the source code
130 /// </summary>
131 public int ModFlags;
133 public readonly TypeContainer Parent;
135 /// <summary>
136 /// Location where this declaration happens
137 /// </summary>
138 public readonly Location Location;
140 [Flags]
141 public enum Flags {
142 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
143 Obsolete = 1 << 1, // Type has obsolete attribute
144 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
145 ClsCompliant = 1 << 3, // Type is CLS Compliant
146 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
147 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
148 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
149 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
150 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
151 Excluded = 1 << 9, // Method is conditional
152 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
155 /// <summary>
156 /// MemberCore flags at first detected then cached
157 /// </summary>
158 internal Flags caching_flags;
160 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
161 Location loc)
162 : base (attrs)
164 Parent = parent;
165 MemberName = name;
166 Location = loc;
167 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
170 /// <summary>
171 /// Tests presence of ObsoleteAttribute and report proper error
172 /// </summary>
173 protected void CheckUsageOfObsoleteAttribute (Type type)
175 if (type == null)
176 return;
178 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
179 if (obsolete_attr == null)
180 return;
182 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
185 public abstract bool Define ();
188 // Returns full member name for error message
190 public virtual string GetSignatureForError ()
192 return Name;
195 /// <summary>
196 /// Use this method when MethodBuilder is null
197 /// </summary>
198 public virtual string GetSignatureForError (TypeContainer tc)
200 return Name;
203 /// <summary>
204 /// Base Emit method. This is also entry point for CLS-Compliant verification.
205 /// </summary>
206 public virtual void Emit ()
208 // Hack with Parent == null is for EnumMember
209 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent) == null))
210 VerifyObsoleteAttribute ();
212 if (!RootContext.VerifyClsCompliance)
213 return;
215 VerifyClsCompliance (Parent);
218 public bool InUnsafe {
219 get {
220 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
225 // Whehter is it ok to use an unsafe pointer in this type container
227 public bool UnsafeOK (DeclSpace parent)
230 // First check if this MemberCore modifier flags has unsafe set
232 if ((ModFlags & Modifiers.UNSAFE) != 0)
233 return true;
235 if (parent.UnsafeContext)
236 return true;
238 Expression.UnsafeError (Location);
239 return false;
242 /// <summary>
243 /// Returns instance of ObsoleteAttribute for this MemberCore
244 /// </summary>
245 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
247 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
248 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
249 return null;
252 caching_flags &= ~Flags.Obsolete_Undetected;
254 if (OptAttributes == null)
255 return null;
257 // TODO: remove this allocation
258 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
259 null, null, ds.ModFlags, false);
261 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
262 if (obsolete_attr == null)
263 return null;
265 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
266 if (obsolete == null)
267 return null;
269 caching_flags |= Flags.Obsolete;
270 return obsolete;
273 /// <summary>
274 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
275 /// </summary>
276 public override bool IsClsCompliaceRequired (DeclSpace container)
278 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
279 return (caching_flags & Flags.ClsCompliant) != 0;
281 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
282 caching_flags &= ~Flags.ClsCompliance_Undetected;
283 caching_flags |= Flags.ClsCompliant;
284 return true;
287 caching_flags &= ~Flags.ClsCompliance_Undetected;
288 return false;
291 /// <summary>
292 /// Returns true when MemberCore is exposed from assembly.
293 /// </summary>
294 protected bool IsExposedFromAssembly (DeclSpace ds)
296 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
297 return false;
299 DeclSpace parentContainer = ds;
300 while (parentContainer != null && parentContainer.ModFlags != 0) {
301 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
302 return false;
303 parentContainer = parentContainer.Parent;
305 return true;
308 /// <summary>
309 /// Resolve CLSCompliantAttribute value or gets cached value.
310 /// </summary>
311 bool GetClsCompliantAttributeValue (DeclSpace ds)
313 if (OptAttributes != null) {
314 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
315 null, null, ds.ModFlags, false);
316 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
317 if (cls_attribute != null) {
318 caching_flags |= Flags.HasClsCompliantAttribute;
319 return cls_attribute.GetClsCompliantAttributeValue (ds);
322 return ds.GetClsCompliantAttributeValue ();
325 /// <summary>
326 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
327 /// </summary>
328 protected bool HasClsCompliantAttribute {
329 get {
330 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
335 /// <summary>
336 /// The main virtual method for CLS-Compliant verifications.
337 /// The method returns true if member is CLS-Compliant and false if member is not
338 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
339 /// and add their extra verifications.
340 /// </summary>
341 protected virtual bool VerifyClsCompliance (DeclSpace ds)
343 if (!IsClsCompliaceRequired (ds)) {
344 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
345 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
347 return false;
350 if (!CodeGen.Assembly.IsClsCompliant) {
351 if (HasClsCompliantAttribute) {
352 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
354 return false;
357 int index = Name.LastIndexOf ('.');
358 if (Name [index > 0 ? index + 1 : 0] == '_') {
359 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
361 return true;
364 protected abstract void VerifyObsoleteAttribute ();
368 /// <summary>
369 /// Base class for structs, classes, enumerations and interfaces.
370 /// </summary>
371 /// <remarks>
372 /// They all create new declaration spaces. This
373 /// provides the common foundation for managing those name
374 /// spaces.
375 /// </remarks>
376 public abstract class DeclSpace : MemberCore {
377 /// <summary>
378 /// this points to the actual definition that is being
379 /// created with System.Reflection.Emit
380 /// </summary>
381 public TypeBuilder TypeBuilder;
384 // This is the namespace in which this typecontainer
385 // was declared. We use this to resolve names.
387 public NamespaceEntry NamespaceEntry;
389 public Hashtable Cache = new Hashtable ();
391 public string Basename;
393 protected Hashtable defined_names;
395 static string[] attribute_targets = new string [] { "type" };
397 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
398 Attributes attrs, Location l)
399 : base (parent, name, attrs, l)
401 NamespaceEntry = ns;
402 Basename = name.Name;
403 defined_names = new Hashtable ();
406 /// <summary>
407 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
408 /// </summary>
409 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
411 if (basename == Basename && !(this is Interface)) {
412 Report.SymbolRelatedToPreviousError (this);
413 Report.Error (542, "'{0}': member names cannot be the same as their enclosing type", symbol.Location, symbol.GetSignatureForError ());
414 return false;
417 MemberCore mc = (MemberCore)defined_names [fullname];
419 if (is_method && (mc is MethodCore || mc is IMethodData)) {
420 symbol.caching_flags |= Flags.TestMethodDuplication;
421 mc.caching_flags |= Flags.TestMethodDuplication;
422 return true;
425 if (mc != null) {
426 Report.SymbolRelatedToPreviousError (mc);
427 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
428 return false;
431 defined_names.Add (fullname, symbol);
432 return true;
435 public void RecordDecl ()
437 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
438 NamespaceEntry.DefineName (MemberName.Basename, this);
441 /// <summary>
442 /// Returns the MemberCore associated with a given name in the declaration
443 /// space. It doesn't return method based symbols !!
444 /// </summary>
445 ///
446 public MemberCore GetDefinition (string name)
448 return (MemberCore)defined_names [name];
451 bool in_transit = false;
453 /// <summary>
454 /// This function is used to catch recursive definitions
455 /// in declarations.
456 /// </summary>
457 public bool InTransit {
458 get {
459 return in_transit;
462 set {
463 in_transit = value;
467 /// <summary>
468 /// Looks up the alias for the name
469 /// </summary>
470 public string LookupAlias (string name)
472 if (NamespaceEntry != null)
473 return NamespaceEntry.LookupAlias (name);
474 else
475 return null;
479 // root_types contains all the types. All TopLevel types
480 // hence have a parent that points to `root_types', that is
481 // why there is a non-obvious test down here.
483 public bool IsTopLevel {
484 get {
485 if (Parent != null){
486 if (Parent.Parent == null)
487 return true;
489 return false;
493 public virtual void CloseType ()
495 if ((caching_flags & Flags.CloseTypeCreated) == 0){
496 try {
497 TypeBuilder.CreateType ();
498 } catch {
500 // The try/catch is needed because
501 // nested enumerations fail to load when they
502 // are defined.
504 // Even if this is the right order (enumerations
505 // declared after types).
507 // Note that this still creates the type and
508 // it is possible to save it
510 caching_flags |= Flags.CloseTypeCreated;
514 /// <remarks>
515 /// Should be overriten by the appropriate declaration space
516 /// </remarks>
517 public abstract TypeBuilder DefineType ();
519 /// <summary>
520 /// Define all members, but don't apply any attributes or do anything which may
521 /// access not-yet-defined classes. This method also creates the MemberCache.
522 /// </summary>
523 public abstract bool DefineMembers (TypeContainer parent);
526 // Whether this is an `unsafe context'
528 public bool UnsafeContext {
529 get {
530 if ((ModFlags & Modifiers.UNSAFE) != 0)
531 return true;
532 if (Parent != null)
533 return Parent.UnsafeContext;
534 return false;
538 public static string MakeFQN (string nsn, string name)
540 if (nsn == "")
541 return name;
542 return String.Concat (nsn, ".", name);
545 EmitContext type_resolve_ec;
546 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
548 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
549 type_resolve_ec.ResolvingTypeTree = true;
551 return type_resolve_ec;
554 // <summary>
555 // Looks up the type, as parsed into the expression `e'.
556 // </summary>
557 //[Obsolete ("This method is going away soon")]
558 public Type ResolveType (Expression e, bool silent, Location loc)
560 TypeExpr d = ResolveTypeExpr (e, silent, loc);
561 return d == null ? null : d.Type;
564 // <summary>
565 // Resolves the expression `e' for a type, and will recursively define
566 // types. This should only be used for resolving base types.
567 // </summary>
568 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
570 if (type_resolve_ec == null)
571 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
572 type_resolve_ec.loc = loc;
573 type_resolve_ec.ContainerType = TypeBuilder;
575 return e.ResolveAsTypeTerminal (type_resolve_ec, silent);
578 public bool CheckAccessLevel (Type check_type)
580 if (check_type == TypeBuilder)
581 return true;
583 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
586 // Broken Microsoft runtime, return public for arrays, no matter what
587 // the accessibility is for their underlying class, and they return
588 // NonPublic visibility for pointers
590 if (check_type.IsArray || check_type.IsPointer)
591 return CheckAccessLevel (TypeManager.GetElementType (check_type));
593 if (TypeBuilder == null)
594 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
595 // However, this is invoked again later -- so safe to return true.
596 // May also be null when resolving top-level attributes.
597 return true;
599 switch (check_attr){
600 case TypeAttributes.Public:
601 return true;
603 case TypeAttributes.NotPublic:
605 // This test should probably use the declaringtype.
607 return check_type.Assembly == TypeBuilder.Assembly;
609 case TypeAttributes.NestedPublic:
610 return true;
612 case TypeAttributes.NestedPrivate:
613 return NestedAccessible (check_type);
615 case TypeAttributes.NestedFamily:
616 return FamilyAccessible (check_type);
618 case TypeAttributes.NestedFamANDAssem:
619 return (check_type.Assembly == TypeBuilder.Assembly) &&
620 FamilyAccessible (check_type);
622 case TypeAttributes.NestedFamORAssem:
623 return (check_type.Assembly == TypeBuilder.Assembly) ||
624 FamilyAccessible (check_type);
626 case TypeAttributes.NestedAssembly:
627 return check_type.Assembly == TypeBuilder.Assembly;
630 Console.WriteLine ("HERE: " + check_attr);
631 return false;
635 protected bool NestedAccessible (Type check_type)
637 string check_type_name = check_type.FullName;
639 // At this point, we already know check_type is a nested class.
640 int cio = check_type_name.LastIndexOf ('+');
642 // Ensure that the string 'container' has a '+' in it to avoid false matches
643 string container = check_type_name.Substring (0, cio + 1);
645 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
646 string type_name = TypeBuilder.FullName + "+";
648 // If the current class is nested inside the container of check_type,
649 // we can access check_type even if it is private or protected.
650 return type_name.StartsWith (container);
653 protected bool FamilyAccessible (Type check_type)
655 Type declaring = check_type.DeclaringType;
656 if (TypeBuilder == declaring ||
657 TypeBuilder.IsSubclassOf (declaring))
658 return true;
660 return NestedAccessible (check_type);
663 // Access level of a type.
664 const int X = 1;
665 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
666 // Public Assembly Protected
667 Protected = (0 << 0) | (0 << 1) | (X << 2),
668 Public = (X << 0) | (X << 1) | (X << 2),
669 Private = (0 << 0) | (0 << 1) | (0 << 2),
670 Internal = (0 << 0) | (X << 1) | (0 << 2),
671 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
674 static AccessLevel GetAccessLevelFromModifiers (int flags)
676 if ((flags & Modifiers.INTERNAL) != 0) {
678 if ((flags & Modifiers.PROTECTED) != 0)
679 return AccessLevel.ProtectedOrInternal;
680 else
681 return AccessLevel.Internal;
683 } else if ((flags & Modifiers.PROTECTED) != 0)
684 return AccessLevel.Protected;
686 else if ((flags & Modifiers.PRIVATE) != 0)
687 return AccessLevel.Private;
689 else
690 return AccessLevel.Public;
693 // What is the effective access level of this?
694 // TODO: Cache this?
695 AccessLevel EffectiveAccessLevel {
696 get {
697 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
698 if (!IsTopLevel && (Parent != null))
699 return myAccess & Parent.EffectiveAccessLevel;
700 else
701 return myAccess;
705 // Return the access level for type `t'
706 static AccessLevel TypeEffectiveAccessLevel (Type t)
708 if (t.IsPublic)
709 return AccessLevel.Public;
710 if (t.IsNestedPrivate)
711 return AccessLevel.Private;
712 if (t.IsNotPublic)
713 return AccessLevel.Internal;
715 // By now, it must be nested
716 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
718 if (t.IsNestedPublic)
719 return parentLevel;
720 if (t.IsNestedAssembly)
721 return parentLevel & AccessLevel.Internal;
722 if (t.IsNestedFamily)
723 return parentLevel & AccessLevel.Protected;
724 if (t.IsNestedFamORAssem)
725 return parentLevel & AccessLevel.ProtectedOrInternal;
726 if (t.IsNestedFamANDAssem)
727 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
729 // nested private is taken care of
731 throw new Exception ("I give up, what are you?");
735 // This answers `is the type P, as accessible as a member M which has the
736 // accessability @flags which is declared as a nested member of the type T, this declspace'
738 public bool AsAccessible (Type p, int flags)
741 // 1) if M is private, its accessability is the same as this declspace.
742 // we already know that P is accessible to T before this method, so we
743 // may return true.
746 if ((flags & Modifiers.PRIVATE) != 0)
747 return true;
749 while (p.IsArray || p.IsPointer || p.IsByRef)
750 p = TypeManager.GetElementType (p);
752 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
753 AccessLevel mAccess = this.EffectiveAccessLevel &
754 GetAccessLevelFromModifiers (flags);
756 // for every place from which we can access M, we must
757 // be able to access P as well. So, we want
758 // For every bit in M and P, M_i -> P_1 == true
759 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
761 return ~ (~ mAccess | pAccess) == 0;
764 static DoubleHash dh = new DoubleHash (1000);
766 Type DefineTypeAndParents (DeclSpace tc)
768 DeclSpace container = tc.Parent;
770 if (container.TypeBuilder == null && container.Name != "")
771 DefineTypeAndParents (container);
773 return tc.DefineType ();
776 Type LookupInterfaceOrClass (string ns, string name, out bool error)
778 DeclSpace parent;
779 Type t;
780 object r;
782 error = false;
783 int p = name.LastIndexOf ('.');
785 if (dh.Lookup (ns, name, out r))
786 return (Type) r;
787 else {
789 // If the type is not a nested type, we do not need `LookupType's processing.
790 // If the @name does not have a `.' in it, this cant be a nested type.
792 if (ns != ""){
793 if (Namespace.IsNamespace (ns)) {
794 if (p != -1)
795 t = TypeManager.LookupType (ns + "." + name);
796 else
797 t = TypeManager.LookupTypeDirect (ns + "." + name);
798 } else
799 t = null;
800 } else if (p != -1)
801 t = TypeManager.LookupType (name);
802 else
803 t = TypeManager.LookupTypeDirect (name);
806 if (t != null) {
807 dh.Insert (ns, name, t);
808 return t;
812 // In case we are fed a composite name, normalize it.
815 if (p != -1){
816 ns = MakeFQN (ns, name.Substring (0, p));
817 name = name.Substring (p+1);
820 parent = RootContext.Tree.LookupByNamespace (ns, name);
821 if (parent == null) {
822 dh.Insert (ns, name, null);
823 return null;
826 t = DefineTypeAndParents (parent);
827 if (t == null){
828 error = true;
829 return null;
832 dh.Insert (ns, name, t);
833 return t;
836 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
838 Report.Error (104, loc,
839 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
840 t1.FullName, t2.FullName));
843 /// <summary>
844 /// GetType is used to resolve type names at the DeclSpace level.
845 /// Use this to lookup class/struct bases, interface bases or
846 /// delegate type references
847 /// </summary>
849 /// <remarks>
850 /// Contrast this to LookupType which is used inside method bodies to
851 /// lookup types that have already been defined. GetType is used
852 /// during the tree resolution process and potentially define
853 /// recursively the type
854 /// </remarks>
855 public Type FindType (Location loc, string name)
857 Type t;
858 bool error;
861 // For the case the type we are looking for is nested within this one
862 // or is in any base class
864 DeclSpace containing_ds = this;
866 while (containing_ds != null){
867 Type container_type = containing_ds.TypeBuilder;
868 Type current_type = container_type;
870 while (current_type != null && current_type != TypeManager.object_type) {
871 string pre = current_type.FullName;
873 t = LookupInterfaceOrClass (pre, name, out error);
874 if (error)
875 return null;
877 if ((t != null) && containing_ds.CheckAccessLevel (t))
878 return t;
880 current_type = current_type.BaseType;
882 containing_ds = containing_ds.Parent;
886 // Attempt to lookup the class on our namespace and all it's implicit parents
888 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
889 t = LookupInterfaceOrClass (ns.FullName, name, out error);
890 if (error)
891 return null;
893 if (t != null)
894 return t;
898 // Attempt to do a direct unqualified lookup
900 t = LookupInterfaceOrClass ("", name, out error);
901 if (error)
902 return null;
904 if (t != null)
905 return t;
908 // Attempt to lookup the class on any of the `using'
909 // namespaces
912 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
914 t = LookupInterfaceOrClass (ns.FullName, name, out error);
915 if (error)
916 return null;
918 if (t != null)
919 return t;
921 if (name.IndexOf ('.') > 0)
922 continue;
924 string alias_value = ns.LookupAlias (name);
925 if (alias_value != null) {
926 t = LookupInterfaceOrClass ("", alias_value, out error);
927 if (error)
928 return null;
930 if (t != null)
931 return t;
935 // Now check the using clause list
937 Type match = null;
938 foreach (Namespace using_ns in ns.GetUsingTable ()) {
939 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
940 if (error)
941 return null;
943 if (match != null){
944 if (t != null){
945 if (CheckAccessLevel (match)) {
946 Error_AmbiguousTypeReference (loc, name, t, match);
947 return null;
949 continue;
952 t = match;
955 if (t != null)
956 return t;
959 //Report.Error (246, Location, "Can not find type `"+name+"'");
960 return null;
963 /// <remarks>
964 /// This function is broken and not what you're looking for. It should only
965 /// be used while the type is still being created since it doesn't use the cache
966 /// and relies on the filter doing the member name check.
967 /// </remarks>
968 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
969 MemberFilter filter, object criteria);
971 /// <remarks>
972 /// If we have a MemberCache, return it. This property may return null if the
973 /// class doesn't have a member cache or while it's still being created.
974 /// </remarks>
975 public abstract MemberCache MemberCache {
976 get;
979 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
981 try {
982 TypeBuilder.SetCustomAttribute (cb);
983 } catch (System.ArgumentException e) {
984 Report.Warning (-21, a.Location,
985 "The CharSet named property on StructLayout\n"+
986 "\tdoes not work correctly on Microsoft.NET\n"+
987 "\tYou might want to remove the CharSet declaration\n"+
988 "\tor compile using the Mono runtime instead of the\n"+
989 "\tMicrosoft .NET runtime\n"+
990 "\tThe runtime gave the error: " + e);
994 /// <summary>
995 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
996 /// If no is attribute exists then return assembly CLSCompliantAttribute.
997 /// </summary>
998 public bool GetClsCompliantAttributeValue ()
1000 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1001 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1003 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1005 if (OptAttributes != null) {
1006 EmitContext ec = new EmitContext (Parent, this, Location,
1007 null, null, ModFlags, false);
1008 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1009 if (cls_attribute != null) {
1010 caching_flags |= Flags.HasClsCompliantAttribute;
1011 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1012 caching_flags |= Flags.ClsCompliantAttributeTrue;
1013 return true;
1015 return false;
1019 if (Parent == null) {
1020 if (CodeGen.Assembly.IsClsCompliant) {
1021 caching_flags |= Flags.ClsCompliantAttributeTrue;
1022 return true;
1024 return false;
1027 if (Parent.GetClsCompliantAttributeValue ()) {
1028 caching_flags |= Flags.ClsCompliantAttributeTrue;
1029 return true;
1031 return false;
1034 public override string[] ValidAttributeTargets {
1035 get {
1036 return attribute_targets;
1041 /// <summary>
1042 /// This is a readonly list of MemberInfo's.
1043 /// </summary>
1044 public class MemberList : IList {
1045 public readonly IList List;
1046 int count;
1048 /// <summary>
1049 /// Create a new MemberList from the given IList.
1050 /// </summary>
1051 public MemberList (IList list)
1053 if (list != null)
1054 this.List = list;
1055 else
1056 this.List = new ArrayList ();
1057 count = List.Count;
1060 /// <summary>
1061 /// Concatenate the ILists `first' and `second' to a new MemberList.
1062 /// </summary>
1063 public MemberList (IList first, IList second)
1065 ArrayList list = new ArrayList ();
1066 list.AddRange (first);
1067 list.AddRange (second);
1068 count = list.Count;
1069 List = list;
1072 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1074 /// <summary>
1075 /// Cast the MemberList into a MemberInfo[] array.
1076 /// </summary>
1077 /// <remarks>
1078 /// This is an expensive operation, only use it if it's really necessary.
1079 /// </remarks>
1080 public static explicit operator MemberInfo [] (MemberList list)
1082 Timer.StartTimer (TimerType.MiscTimer);
1083 MemberInfo [] result = new MemberInfo [list.Count];
1084 list.CopyTo (result, 0);
1085 Timer.StopTimer (TimerType.MiscTimer);
1086 return result;
1089 // ICollection
1091 public int Count {
1092 get {
1093 return count;
1097 public bool IsSynchronized {
1098 get {
1099 return List.IsSynchronized;
1103 public object SyncRoot {
1104 get {
1105 return List.SyncRoot;
1109 public void CopyTo (Array array, int index)
1111 List.CopyTo (array, index);
1114 // IEnumerable
1116 public IEnumerator GetEnumerator ()
1118 return List.GetEnumerator ();
1121 // IList
1123 public bool IsFixedSize {
1124 get {
1125 return true;
1129 public bool IsReadOnly {
1130 get {
1131 return true;
1135 object IList.this [int index] {
1136 get {
1137 return List [index];
1140 set {
1141 throw new NotSupportedException ();
1145 // FIXME: try to find out whether we can avoid the cast in this indexer.
1146 public MemberInfo this [int index] {
1147 get {
1148 return (MemberInfo) List [index];
1152 public int Add (object value)
1154 throw new NotSupportedException ();
1157 public void Clear ()
1159 throw new NotSupportedException ();
1162 public bool Contains (object value)
1164 return List.Contains (value);
1167 public int IndexOf (object value)
1169 return List.IndexOf (value);
1172 public void Insert (int index, object value)
1174 throw new NotSupportedException ();
1177 public void Remove (object value)
1179 throw new NotSupportedException ();
1182 public void RemoveAt (int index)
1184 throw new NotSupportedException ();
1188 /// <summary>
1189 /// This interface is used to get all members of a class when creating the
1190 /// member cache. It must be implemented by all DeclSpace derivatives which
1191 /// want to support the member cache and by TypeHandle to get caching of
1192 /// non-dynamic types.
1193 /// </summary>
1194 public interface IMemberContainer {
1195 /// <summary>
1196 /// The name of the IMemberContainer. This is only used for
1197 /// debugging purposes.
1198 /// </summary>
1199 string Name {
1200 get;
1203 /// <summary>
1204 /// The type of this IMemberContainer.
1205 /// </summary>
1206 Type Type {
1207 get;
1210 /// <summary>
1211 /// Returns the IMemberContainer of the parent class or null if this
1212 /// is an interface or TypeManger.object_type.
1213 /// This is used when creating the member cache for a class to get all
1214 /// members from the parent class.
1215 /// </summary>
1216 IMemberContainer ParentContainer {
1217 get;
1220 /// <summary>
1221 /// Whether this is an interface.
1222 /// </summary>
1223 bool IsInterface {
1224 get;
1227 /// <summary>
1228 /// Returns all members of this class with the corresponding MemberTypes
1229 /// and BindingFlags.
1230 /// </summary>
1231 /// <remarks>
1232 /// When implementing this method, make sure not to return any inherited
1233 /// members and check the MemberTypes and BindingFlags properly.
1234 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1235 /// get the BindingFlags (static/non-static,public/non-public) in the
1236 /// MemberInfo class, but the cache needs this information. That's why
1237 /// this method is called multiple times with different BindingFlags.
1238 /// </remarks>
1239 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1241 /// <summary>
1242 /// Return the container's member cache.
1243 /// </summary>
1244 MemberCache MemberCache {
1245 get;
1249 /// <summary>
1250 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1251 /// member lookups. It has a member name based hash table; it maps each member
1252 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1253 /// and the BindingFlags that were initially used to get it. The cache contains
1254 /// all members of the current class and all inherited members. If this cache is
1255 /// for an interface types, it also contains all inherited members.
1257 /// There are two ways to get a MemberCache:
1258 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1259 /// use the DeclSpace.MemberCache property.
1260 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1261 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1262 /// </summary>
1263 public class MemberCache {
1264 public readonly IMemberContainer Container;
1265 protected Hashtable member_hash;
1266 protected Hashtable method_hash;
1268 /// <summary>
1269 /// Create a new MemberCache for the given IMemberContainer `container'.
1270 /// </summary>
1271 public MemberCache (IMemberContainer container, bool setup_inherited_interfaces)
1273 this.Container = container;
1275 Timer.IncrementCounter (CounterType.MemberCache);
1276 Timer.StartTimer (TimerType.CacheInit);
1280 // If we have a parent class (we have a parent class unless we're
1281 // TypeManager.object_type), we deep-copy its MemberCache here.
1282 if (Container.IsInterface) {
1283 MemberCache parent;
1285 if (Container.ParentContainer != null)
1286 parent = Container.ParentContainer.MemberCache;
1287 else
1288 parent = null;
1289 member_hash = SetupCacheForInterface (parent, setup_inherited_interfaces);
1290 } else if (Container.ParentContainer != null)
1291 member_hash = SetupCache (Container.ParentContainer.MemberCache);
1292 else
1293 member_hash = new Hashtable ();
1295 // If this is neither a dynamic type nor an interface, create a special
1296 // method cache with all declared and inherited methods.
1297 Type type = container.Type;
1298 if (!(type is TypeBuilder) && !type.IsInterface) {
1299 method_hash = new Hashtable ();
1300 AddMethods (type);
1303 // Add all members from the current class.
1304 AddMembers (Container);
1306 Timer.StopTimer (TimerType.CacheInit);
1309 /// <summary>
1310 /// Bootstrap this member cache by doing a deep-copy of our parent.
1311 /// </summary>
1312 Hashtable SetupCache (MemberCache parent)
1314 Hashtable hash = new Hashtable ();
1315 if (parent == null)
1316 return hash;
1318 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1319 while (it.MoveNext ()) {
1320 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1323 return hash;
1327 /// <summary>
1328 /// Add the contents of `new_hash' to `hash'.
1329 /// </summary>
1330 void AddHashtable (Hashtable hash, MemberCache cache)
1332 Hashtable new_hash = cache.member_hash;
1333 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1334 while (it.MoveNext ()) {
1335 ArrayList list = (ArrayList) hash [it.Key];
1336 if (list == null)
1337 hash [it.Key] = list = new ArrayList ();
1339 foreach (CacheEntry entry in (ArrayList) it.Value) {
1340 if (entry.Container != cache.Container)
1341 break;
1342 list.Add (entry);
1347 /// <summary>
1348 /// Bootstrap the member cache for an interface type.
1349 /// Type.GetMembers() won't return any inherited members for interface types,
1350 /// so we need to do this manually. Interfaces also inherit from System.Object.
1351 /// </summary>
1352 Hashtable SetupCacheForInterface (MemberCache parent, bool deep_setup)
1354 Hashtable hash = SetupCache (parent);
1356 if (!deep_setup)
1357 return hash;
1359 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1361 foreach (TypeExpr iface in ifaces) {
1362 Type itype = iface.Type;
1364 IMemberContainer iface_container =
1365 TypeManager.LookupMemberContainer (itype);
1367 MemberCache iface_cache = iface_container.MemberCache;
1369 AddHashtable (hash, iface_cache);
1372 return hash;
1375 /// <summary>
1376 /// Add all members from class `container' to the cache.
1377 /// </summary>
1378 void AddMembers (IMemberContainer container)
1380 // We need to call AddMembers() with a single member type at a time
1381 // to get the member type part of CacheEntry.EntryType right.
1382 if (!container.IsInterface) {
1383 AddMembers (MemberTypes.Constructor, container);
1384 AddMembers (MemberTypes.Field, container);
1386 AddMembers (MemberTypes.Method, container);
1387 AddMembers (MemberTypes.Property, container);
1388 AddMembers (MemberTypes.Event, container);
1389 // Nested types are returned by both Static and Instance searches.
1390 AddMembers (MemberTypes.NestedType,
1391 BindingFlags.Static | BindingFlags.Public, container);
1392 AddMembers (MemberTypes.NestedType,
1393 BindingFlags.Static | BindingFlags.NonPublic, container);
1396 void AddMembers (MemberTypes mt, IMemberContainer container)
1398 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1399 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1400 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1401 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1404 /// <summary>
1405 /// Add all members from class `container' with the requested MemberTypes and
1406 /// BindingFlags to the cache. This method is called multiple times with different
1407 /// MemberTypes and BindingFlags.
1408 /// </summary>
1409 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1411 MemberList members = container.GetMembers (mt, bf);
1413 foreach (MemberInfo member in members) {
1414 string name = member.Name;
1416 // We use a name-based hash table of ArrayList's.
1417 ArrayList list = (ArrayList) member_hash [name];
1418 if (list == null) {
1419 list = new ArrayList ();
1420 member_hash.Add (name, list);
1423 // When this method is called for the current class, the list will
1424 // already contain all inherited members from our parent classes.
1425 // We cannot add new members in front of the list since this'd be an
1426 // expensive operation, that's why the list is sorted in reverse order
1427 // (ie. members from the current class are coming last).
1428 list.Add (new CacheEntry (container, member, mt, bf));
1432 /// <summary>
1433 /// Add all declared and inherited methods from class `type' to the method cache.
1434 /// </summary>
1435 void AddMethods (Type type)
1437 AddMethods (BindingFlags.Static | BindingFlags.Public |
1438 BindingFlags.FlattenHierarchy, type);
1439 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1440 BindingFlags.FlattenHierarchy, type);
1441 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1442 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1445 void AddMethods (BindingFlags bf, Type type)
1447 MemberInfo [] members = type.GetMethods (bf);
1449 Array.Reverse (members);
1451 foreach (MethodBase member in members) {
1452 string name = member.Name;
1454 // We use a name-based hash table of ArrayList's.
1455 ArrayList list = (ArrayList) method_hash [name];
1456 if (list == null) {
1457 list = new ArrayList ();
1458 method_hash.Add (name, list);
1461 // Unfortunately, the elements returned by Type.GetMethods() aren't
1462 // sorted so we need to do this check for every member.
1463 BindingFlags new_bf = bf;
1464 if (member.DeclaringType == type)
1465 new_bf |= BindingFlags.DeclaredOnly;
1467 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1473 /// <summary>
1474 /// Compute and return a appropriate `EntryType' magic number for the given
1475 /// MemberTypes and BindingFlags.
1476 /// </summary>
1477 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1479 EntryType type = EntryType.None;
1481 if ((mt & MemberTypes.Constructor) != 0)
1482 type |= EntryType.Constructor;
1483 if ((mt & MemberTypes.Event) != 0)
1484 type |= EntryType.Event;
1485 if ((mt & MemberTypes.Field) != 0)
1486 type |= EntryType.Field;
1487 if ((mt & MemberTypes.Method) != 0)
1488 type |= EntryType.Method;
1489 if ((mt & MemberTypes.Property) != 0)
1490 type |= EntryType.Property;
1491 // Nested types are returned by static and instance searches.
1492 if ((mt & MemberTypes.NestedType) != 0)
1493 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1495 if ((bf & BindingFlags.Instance) != 0)
1496 type |= EntryType.Instance;
1497 if ((bf & BindingFlags.Static) != 0)
1498 type |= EntryType.Static;
1499 if ((bf & BindingFlags.Public) != 0)
1500 type |= EntryType.Public;
1501 if ((bf & BindingFlags.NonPublic) != 0)
1502 type |= EntryType.NonPublic;
1503 if ((bf & BindingFlags.DeclaredOnly) != 0)
1504 type |= EntryType.Declared;
1506 return type;
1509 /// <summary>
1510 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1511 /// denote multiple member types. Returns true if the given flags value denotes a
1512 /// single member types.
1513 /// </summary>
1514 public static bool IsSingleMemberType (MemberTypes mt)
1516 switch (mt) {
1517 case MemberTypes.Constructor:
1518 case MemberTypes.Event:
1519 case MemberTypes.Field:
1520 case MemberTypes.Method:
1521 case MemberTypes.Property:
1522 case MemberTypes.NestedType:
1523 return true;
1525 default:
1526 return false;
1530 /// <summary>
1531 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1532 /// number to speed up the searching process.
1533 /// </summary>
1534 [Flags]
1535 protected internal enum EntryType {
1536 None = 0x000,
1538 Instance = 0x001,
1539 Static = 0x002,
1540 MaskStatic = Instance|Static,
1542 Public = 0x004,
1543 NonPublic = 0x008,
1544 MaskProtection = Public|NonPublic,
1546 Declared = 0x010,
1548 Constructor = 0x020,
1549 Event = 0x040,
1550 Field = 0x080,
1551 Method = 0x100,
1552 Property = 0x200,
1553 NestedType = 0x400,
1555 MaskType = Constructor|Event|Field|Method|Property|NestedType
1558 protected internal struct CacheEntry {
1559 public readonly IMemberContainer Container;
1560 public readonly EntryType EntryType;
1561 public readonly MemberInfo Member;
1563 public CacheEntry (IMemberContainer container, MemberInfo member,
1564 MemberTypes mt, BindingFlags bf)
1566 this.Container = container;
1567 this.Member = member;
1568 this.EntryType = GetEntryType (mt, bf);
1572 /// <summary>
1573 /// This is called each time we're walking up one level in the class hierarchy
1574 /// and checks whether we can abort the search since we've already found what
1575 /// we were looking for.
1576 /// </summary>
1577 protected bool DoneSearching (ArrayList list)
1580 // We've found exactly one member in the current class and it's not
1581 // a method or constructor.
1583 if (list.Count == 1 && !(list [0] is MethodBase))
1584 return true;
1587 // Multiple properties: we query those just to find out the indexer
1588 // name
1590 if ((list.Count > 0) && (list [0] is PropertyInfo))
1591 return true;
1593 return false;
1596 /// <summary>
1597 /// Looks up members with name `name'. If you provide an optional
1598 /// filter function, it'll only be called with members matching the
1599 /// requested member name.
1601 /// This method will try to use the cache to do the lookup if possible.
1603 /// Unlike other FindMembers implementations, this method will always
1604 /// check all inherited members - even when called on an interface type.
1606 /// If you know that you're only looking for methods, you should use
1607 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1608 /// When doing a method-only search, it'll try to use a special method
1609 /// cache (unless it's a dynamic type or an interface) and the returned
1610 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1611 /// The lookup process will automatically restart itself in method-only
1612 /// search mode if it discovers that it's about to return methods.
1613 /// </summary>
1614 ArrayList global = new ArrayList ();
1615 bool using_global = false;
1617 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1619 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1620 MemberFilter filter, object criteria)
1622 if (using_global)
1623 throw new Exception ();
1625 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1626 bool method_search = mt == MemberTypes.Method;
1627 // If we have a method cache and we aren't already doing a method-only search,
1628 // then we restart a method search if the first match is a method.
1629 bool do_method_search = !method_search && (method_hash != null);
1631 ArrayList applicable;
1633 // If this is a method-only search, we try to use the method cache if
1634 // possible; a lookup in the method cache will return a MemberInfo with
1635 // the correct ReflectedType for inherited methods.
1637 if (method_search && (method_hash != null))
1638 applicable = (ArrayList) method_hash [name];
1639 else
1640 applicable = (ArrayList) member_hash [name];
1642 if (applicable == null)
1643 return emptyMemberInfo;
1646 // 32 slots gives 53 rss/54 size
1647 // 2/4 slots gives 55 rss
1649 // Strange: from 25,000 calls, only 1,800
1650 // are above 2. Why does this impact it?
1652 global.Clear ();
1653 using_global = true;
1655 Timer.StartTimer (TimerType.CachedLookup);
1657 EntryType type = GetEntryType (mt, bf);
1659 IMemberContainer current = Container;
1662 // `applicable' is a list of all members with the given member name `name'
1663 // in the current class and all its parent classes. The list is sorted in
1664 // reverse order due to the way how the cache is initialy created (to speed
1665 // things up, we're doing a deep-copy of our parent).
1667 for (int i = applicable.Count-1; i >= 0; i--) {
1668 CacheEntry entry = (CacheEntry) applicable [i];
1670 // This happens each time we're walking one level up in the class
1671 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1672 // the first time this happens (this may already happen in the first
1673 // iteration of this loop if there are no members with the name we're
1674 // looking for in the current class).
1675 if (entry.Container != current) {
1676 if (declared_only || DoneSearching (global))
1677 break;
1679 current = entry.Container;
1682 // Is the member of the correct type ?
1683 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1684 continue;
1686 // Is the member static/non-static ?
1687 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1688 continue;
1690 // Apply the filter to it.
1691 if (filter (entry.Member, criteria)) {
1692 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1693 do_method_search = false;
1694 global.Add (entry.Member);
1698 Timer.StopTimer (TimerType.CachedLookup);
1700 // If we have a method cache and we aren't already doing a method-only
1701 // search, we restart in method-only search mode if the first match is
1702 // a method. This ensures that we return a MemberInfo with the correct
1703 // ReflectedType for inherited methods.
1704 if (do_method_search && (global.Count > 0)){
1705 using_global = false;
1707 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1710 using_global = false;
1711 MemberInfo [] copy = new MemberInfo [global.Count];
1712 global.CopyTo (copy);
1713 return copy;
1716 // find the nested type @name in @this.
1717 public Type FindNestedType (string name)
1719 ArrayList applicable = (ArrayList) member_hash [name];
1720 if (applicable == null)
1721 return null;
1723 for (int i = applicable.Count-1; i >= 0; i--) {
1724 CacheEntry entry = (CacheEntry) applicable [i];
1725 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
1726 return (Type) entry.Member;
1729 return null;
1733 // This finds the method or property for us to override. invocationType is the type where
1734 // the override is going to be declared, name is the name of the method/property, and
1735 // paramTypes is the parameters, if any to the method or property
1737 // Because the MemberCache holds members from this class and all the base classes,
1738 // we can avoid tons of reflection stuff.
1740 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1742 ArrayList applicable;
1743 if (method_hash != null && !is_property)
1744 applicable = (ArrayList) method_hash [name];
1745 else
1746 applicable = (ArrayList) member_hash [name];
1748 if (applicable == null)
1749 return null;
1751 // Walk the chain of methods, starting from the top.
1753 for (int i = applicable.Count - 1; i >= 0; i--) {
1754 CacheEntry entry = (CacheEntry) applicable [i];
1756 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1757 continue;
1759 PropertyInfo pi = null;
1760 MethodInfo mi = null;
1761 FieldInfo fi = null;
1762 Type [] cmpAttrs = null;
1764 if (is_property) {
1765 if ((entry.EntryType & EntryType.Field) != 0) {
1766 fi = (FieldInfo)entry.Member;
1768 // TODO: For this case we ignore member type
1769 //fb = TypeManager.GetField (fi);
1770 //cmpAttrs = new Type[] { fb.MemberType };
1771 } else {
1772 pi = (PropertyInfo) entry.Member;
1773 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1775 } else {
1776 mi = (MethodInfo) entry.Member;
1777 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1780 if (fi != null) {
1781 // TODO: Almost duplicate !
1782 // Check visibility
1783 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1784 case FieldAttributes.Private:
1786 // A private method is Ok if we are a nested subtype.
1787 // The spec actually is not very clear about this, see bug 52458.
1789 if (invocationType != entry.Container.Type &
1790 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1791 continue;
1793 break;
1794 case FieldAttributes.FamANDAssem:
1795 case FieldAttributes.Assembly:
1797 // Check for assembly methods
1799 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1800 continue;
1801 break;
1803 return entry.Member;
1807 // Check the arguments
1809 if (cmpAttrs.Length != paramTypes.Length)
1810 continue;
1812 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1813 if (paramTypes [j] != cmpAttrs [j])
1814 goto next;
1817 // get one of the methods because this has the visibility info.
1819 if (is_property) {
1820 mi = pi.GetGetMethod (true);
1821 if (mi == null)
1822 mi = pi.GetSetMethod (true);
1826 // Check visibility
1828 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1829 case MethodAttributes.Private:
1831 // A private method is Ok if we are a nested subtype.
1832 // The spec actually is not very clear about this, see bug 52458.
1834 if (invocationType == entry.Container.Type ||
1835 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1836 return entry.Member;
1838 break;
1839 case MethodAttributes.FamANDAssem:
1840 case MethodAttributes.Assembly:
1842 // Check for assembly methods
1844 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1845 return entry.Member;
1847 break;
1848 default:
1850 // A protected method is ok, because we are overriding.
1851 // public is always ok.
1853 return entry.Member;
1855 next:
1859 return null;
1862 /// <summary>
1863 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
1864 /// We handle two cases. The first is for types without parameters (events, field, properties).
1865 /// The second are methods, indexers and this is why ignore_complex_types is here.
1866 /// The latest param is temporary hack. See DoDefineMembers method for more info.
1867 /// </summary>
1868 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
1870 ArrayList applicable = null;
1872 if (method_hash != null)
1873 applicable = (ArrayList) method_hash [name];
1875 if (applicable != null) {
1876 for (int i = applicable.Count - 1; i >= 0; i--) {
1877 CacheEntry entry = (CacheEntry) applicable [i];
1878 if ((entry.EntryType & EntryType.Public) != 0)
1879 return entry.Member;
1883 if (member_hash == null)
1884 return null;
1885 applicable = (ArrayList) member_hash [name];
1887 if (applicable != null) {
1888 for (int i = applicable.Count - 1; i >= 0; i--) {
1889 CacheEntry entry = (CacheEntry) applicable [i];
1890 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
1891 if (ignore_complex_types) {
1892 if ((entry.EntryType & EntryType.Method) != 0)
1893 continue;
1895 // Does exist easier way how to detect indexer ?
1896 if ((entry.EntryType & EntryType.Property) != 0) {
1897 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
1898 if (arg_types.Length > 0)
1899 continue;
1902 return entry.Member;
1906 return null;
1909 Hashtable locase_table;
1911 /// <summary>
1912 /// Builds low-case table for CLS Compliance test
1913 /// </summary>
1914 public Hashtable GetPublicMembers ()
1916 if (locase_table != null)
1917 return locase_table;
1919 locase_table = new Hashtable ();
1920 foreach (DictionaryEntry entry in member_hash) {
1921 ArrayList members = (ArrayList)entry.Value;
1922 for (int ii = 0; ii < members.Count; ++ii) {
1923 CacheEntry member_entry = (CacheEntry) members [ii];
1925 if ((member_entry.EntryType & EntryType.Public) == 0)
1926 continue;
1928 // TODO: Does anyone know easier way how to detect that member is internal ?
1929 switch (member_entry.EntryType & EntryType.MaskType) {
1930 case EntryType.Constructor:
1931 continue;
1933 case EntryType.Field:
1934 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
1935 continue;
1936 break;
1938 case EntryType.Method:
1939 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
1940 continue;
1941 break;
1943 case EntryType.Property:
1944 PropertyInfo pi = (PropertyInfo)member_entry.Member;
1945 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
1946 continue;
1947 break;
1949 case EntryType.Event:
1950 EventInfo ei = (EventInfo)member_entry.Member;
1951 MethodInfo mi = ei.GetAddMethod ();
1952 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
1953 continue;
1954 break;
1956 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
1957 locase_table [lcase] = member_entry.Member;
1958 break;
1961 return locase_table;
1964 public Hashtable Members {
1965 get {
1966 return member_hash;
1970 /// <summary>
1971 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
1972 /// </summary>
1973 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
1975 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
1977 for (int i = 0; i < al.Count; ++i) {
1978 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
1980 // skip itself
1981 if (entry.Member == this_builder)
1982 continue;
1984 if ((entry.EntryType & tested_type) != tested_type)
1985 continue;
1987 MethodBase method_to_compare = (MethodBase)entry.Member;
1988 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
1989 continue;
1991 IMethodData md = TypeManager.GetMethod (method_to_compare);
1993 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
1994 // However it is exactly what csc does.
1995 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
1996 continue;
1998 Report.SymbolRelatedToPreviousError (entry.Member);
1999 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());