2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 // Marek Safar (marek.safar@seznam.cz)
7 // Licensed under the terms of the GNU GPL
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
11 // TODO: Move the method verification stuff from the class.cs and interface.cs here
16 using System.Collections;
17 using System.Globalization;
18 using System.Reflection.Emit;
19 using System.Reflection;
21 namespace Mono.CSharp {
23 public class MemberName {
25 public readonly TypeArguments TypeArguments;
27 public readonly MemberName Left;
29 public static readonly MemberName Null = new MemberName ("");
31 public MemberName (string name)
36 public MemberName (string name, TypeArguments args)
39 this.TypeArguments = args;
42 public MemberName (MemberName left, string name, TypeArguments args)
48 public MemberName (MemberName left, MemberName right)
49 : this (left, right.Name, right.TypeArguments)
53 public string GetName ()
56 return Left.GetName () + "." + Name;
61 public bool IsGeneric {
63 if (TypeArguments != null)
65 else if (Left != null)
66 return Left.IsGeneric;
72 public string GetName (bool is_generic)
74 string name = is_generic ? Basename : Name;
76 return Left.GetName (is_generic) + "." + name;
81 public int CountTypeArguments {
83 if (TypeArguments == null)
86 return TypeArguments.Count;
90 public string GetMethodName ()
93 return Left.GetFullName () + "." + Name;
98 public string GetFullName ()
101 if (TypeArguments != null)
102 full_name = Name + "<" + TypeArguments + ">";
106 return Left.GetFullName () + "." + full_name;
111 public static string MakeName (string name, TypeArguments args)
116 return name + "`" + args.Count;
119 public static string MakeName (string name, int count)
121 return name + "`" + count;
124 public string GetTypeName ()
128 return Left.GetTypeName () + "." +
129 MakeName (Name, TypeArguments);
131 return MakeName (Name, TypeArguments);
134 protected bool IsUnbound {
136 if ((Left != null) && Left.IsUnbound)
138 else if (TypeArguments == null)
141 return TypeArguments.IsUnbound;
145 protected bool CheckUnbound (Location loc)
147 if ((Left != null) && !Left.CheckUnbound (loc))
149 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
150 Report.Error (1031, loc, "Type expected");
157 public Expression GetTypeExpression (Location loc)
160 if (!CheckUnbound (loc))
163 return new UnboundTypeExpression (GetTypeName ());
167 Expression lexpr = Left.GetTypeExpression (loc);
169 return new MemberAccess (lexpr, Name, TypeArguments, loc);
171 if (TypeArguments != null)
172 return new ConstructedType (Name, TypeArguments, loc);
174 return new SimpleName (Name, loc);
178 public MemberName Clone ()
181 return new MemberName (Left.Clone (), Name, TypeArguments);
183 return new MemberName (Name, TypeArguments);
186 public string Basename {
188 if (TypeArguments != null)
189 return MakeName (Name, TypeArguments);
195 public override string ToString ()
198 if (TypeArguments != null)
199 full_name = Name + "<" + TypeArguments + ">";
204 return Left + "." + full_name;
211 /// Base representation for members. This is used to keep track
212 /// of Name, Location and Modifier flags, and handling Attributes.
214 public abstract class MemberCore : Attributable {
220 return MemberName.GetName (!(this is GenericMethod) && !(this is Method));
224 public readonly MemberName MemberName;
227 /// Modifier flags that the user specified in the source code
231 public readonly TypeContainer Parent;
234 /// Location where this declaration happens
236 public readonly Location Location;
240 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
241 Obsolete = 1 << 1, // Type has obsolete attribute
242 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
243 ClsCompliant = 1 << 3, // Type is CLS Compliant
244 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
245 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
246 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
247 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
248 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
249 Excluded = 1 << 9, // Method is conditional
250 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
254 /// MemberCore flags at first detected then cached
256 internal Flags caching_flags;
258 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
265 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
269 /// Tests presence of ObsoleteAttribute and report proper error
271 protected void CheckUsageOfObsoleteAttribute (Type type)
276 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
277 if (obsolete_attr == null)
280 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
283 public abstract bool Define ();
286 // Returns full member name for error message
288 public virtual string GetSignatureForError ()
294 /// Use this method when MethodBuilder is null
296 public virtual string GetSignatureForError (TypeContainer tc)
302 /// Base Emit method. This is also entry point for CLS-Compliant verification.
304 public virtual void Emit ()
306 VerifyObsoleteAttribute ();
308 if (!RootContext.VerifyClsCompliance)
311 VerifyClsCompliance (Parent);
315 // Whehter is it ok to use an unsafe pointer in this type container
317 public bool UnsafeOK (DeclSpace parent)
320 // First check if this MemberCore modifier flags has unsafe set
322 if ((ModFlags & Modifiers.UNSAFE) != 0)
325 if (parent.UnsafeContext)
328 Expression.UnsafeError (Location);
333 /// Returns instance of ObsoleteAttribute for this MemberCore
335 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
337 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
338 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
342 caching_flags &= ~Flags.Obsolete_Undetected;
344 if (OptAttributes == null)
347 // TODO: remove this allocation
348 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
349 null, null, ds.ModFlags, false);
351 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
352 if (obsolete_attr == null)
355 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
356 if (obsolete == null)
359 caching_flags |= Flags.Obsolete;
364 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
366 public override bool IsClsCompliaceRequired (DeclSpace container)
368 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
369 return (caching_flags & Flags.ClsCompliant) != 0;
371 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
372 caching_flags &= ~Flags.ClsCompliance_Undetected;
373 caching_flags |= Flags.ClsCompliant;
377 caching_flags &= ~Flags.ClsCompliance_Undetected;
382 /// Returns true when MemberCore is exposed from assembly.
384 protected bool IsExposedFromAssembly (DeclSpace ds)
386 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
389 DeclSpace parentContainer = ds;
390 while (parentContainer != null && parentContainer.ModFlags != 0) {
391 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
393 parentContainer = parentContainer.Parent;
399 /// Resolve CLSCompliantAttribute value or gets cached value.
401 bool GetClsCompliantAttributeValue (DeclSpace ds)
403 if (OptAttributes != null) {
404 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
405 null, null, ds.ModFlags, false);
406 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
407 if (cls_attribute != null) {
408 caching_flags |= Flags.HasClsCompliantAttribute;
409 return cls_attribute.GetClsCompliantAttributeValue (ds);
412 return ds.GetClsCompliantAttributeValue ();
416 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
418 protected bool HasClsCompliantAttribute {
420 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
425 /// The main virtual method for CLS-Compliant verifications.
426 /// The method returns true if member is CLS-Compliant and false if member is not
427 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
428 /// and add their extra verifications.
430 protected virtual bool VerifyClsCompliance (DeclSpace ds)
432 if (!IsClsCompliaceRequired (ds)) {
433 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
434 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
439 if (!CodeGen.Assembly.IsClsCompliant) {
440 if (HasClsCompliantAttribute) {
441 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
446 int index = Name.LastIndexOf ('.');
447 if (Name [index > 0 ? index + 1 : 0] == '_') {
448 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
453 protected abstract void VerifyObsoleteAttribute ();
458 /// Base class for structs, classes, enumerations and interfaces.
461 /// They all create new declaration spaces. This
462 /// provides the common foundation for managing those name
465 public abstract class DeclSpace : MemberCore, IAlias {
467 /// This points to the actual definition that is being
468 /// created with System.Reflection.Emit
470 public TypeBuilder TypeBuilder;
473 /// If we are a generic type, this is the type we are
474 /// currently defining. We need to lookup members on this
475 /// instead of the TypeBuilder.
477 public TypeExpr CurrentType;
480 // This is the namespace in which this typecontainer
481 // was declared. We use this to resolve names.
483 public NamespaceEntry NamespaceEntry;
485 public Hashtable Cache = new Hashtable ();
487 public string Basename;
489 protected Hashtable defined_names;
491 readonly bool is_generic;
492 readonly int count_type_params;
495 // Whether we are Generic
497 public bool IsGeneric {
501 else if (Parent != null)
502 return Parent.IsGeneric;
508 static string[] attribute_targets = new string [] { "type" };
510 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
511 Attributes attrs, Location l)
512 : base (parent, name, attrs, l)
515 Basename = name.Name;
516 defined_names = new Hashtable ();
517 if (name.TypeArguments != null) {
519 count_type_params = name.TypeArguments.Count;
522 count_type_params += parent.count_type_params;
526 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
528 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
530 if (basename == Basename) {
531 Report.SymbolRelatedToPreviousError (this);
532 Report.Error (542, "'{0}': member names cannot be the same as their enclosing type", symbol.Location, symbol.GetSignatureForError ());
536 MemberCore mc = (MemberCore)defined_names [fullname];
538 if (is_method && (mc is MethodCore || mc is IMethodData)) {
539 symbol.caching_flags |= Flags.TestMethodDuplication;
540 mc.caching_flags |= Flags.TestMethodDuplication;
545 Report.SymbolRelatedToPreviousError (mc);
546 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
550 defined_names.Add (fullname, symbol);
554 public void RecordDecl ()
556 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
557 NamespaceEntry.DefineName (MemberName.Basename, this);
561 /// Returns the MemberCore associated with a given name in the declaration
562 /// space. It doesn't return method based symbols !!
565 public MemberCore GetDefinition (string name)
567 return (MemberCore)defined_names [name];
570 bool in_transit = false;
573 /// This function is used to catch recursive definitions
576 public bool InTransit {
587 /// Looks up the alias for the name
589 public IAlias LookupAlias (string name)
591 if (NamespaceEntry != null)
592 return NamespaceEntry.LookupAlias (name);
598 // root_types contains all the types. All TopLevel types
599 // hence have a parent that points to `root_types', that is
600 // why there is a non-obvious test down here.
602 public bool IsTopLevel {
605 if (Parent.Parent == null)
612 public virtual void CloseType ()
614 if ((caching_flags & Flags.CloseTypeCreated) == 0){
616 TypeBuilder.CreateType ();
619 // The try/catch is needed because
620 // nested enumerations fail to load when they
623 // Even if this is the right order (enumerations
624 // declared after types).
626 // Note that this still creates the type and
627 // it is possible to save it
629 caching_flags |= Flags.CloseTypeCreated;
634 /// Should be overriten by the appropriate declaration space
636 public abstract TypeBuilder DefineType ();
639 /// Define all members, but don't apply any attributes or do anything which may
640 /// access not-yet-defined classes. This method also creates the MemberCache.
642 public abstract bool DefineMembers (TypeContainer parent);
645 // Whether this is an `unsafe context'
647 public bool UnsafeContext {
649 if ((ModFlags & Modifiers.UNSAFE) != 0)
652 return Parent.UnsafeContext;
657 public static string MakeFQN (string nsn, string name)
661 return String.Concat (nsn, ".", name);
664 EmitContext type_resolve_ec;
665 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
667 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
668 type_resolve_ec.ResolvingTypeTree = true;
670 return type_resolve_ec;
674 // Looks up the type, as parsed into the expression `e'
676 public Type ResolveType (Expression e, bool silent, Location loc)
678 TypeExpr d = ResolveTypeExpr (e, silent, loc);
682 return ResolveType (d, loc);
685 public Type ResolveType (TypeExpr d, Location loc)
687 if (!d.CheckAccessLevel (this)) {
688 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", d.Name);
692 Type t = d.ResolveType (type_resolve_ec);
696 if (d is UnboundTypeExpression)
699 TypeContainer tc = TypeManager.LookupTypeContainer (t);
700 if ((tc != null) && tc.IsGeneric) {
702 int tnum = TypeManager.GetNumberOfTypeArguments (t);
703 Report.Error (305, loc,
704 "Using the generic type `{0}' " +
705 "requires {1} type arguments",
706 TypeManager.GetFullName (t), tnum);
710 ConstructedType ctype = new ConstructedType (
711 t, TypeParameters, loc);
713 t = ctype.ResolveType (type_resolve_ec);
720 // Resolves the expression `e' for a type, and will recursively define
723 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
725 if (type_resolve_ec == null)
726 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
727 type_resolve_ec.loc = loc;
728 if (this is GenericMethod)
729 type_resolve_ec.ContainerType = Parent.TypeBuilder;
731 type_resolve_ec.ContainerType = TypeBuilder;
733 int errors = Report.Errors;
735 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
737 if ((d != null) && (d.eclass == ExprClass.Type))
740 if (silent || (Report.Errors != errors))
743 if (e is SimpleName){
744 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
745 d = s.ResolveAsTypeTerminal (type_resolve_ec);
747 if ((d == null) || (d.Type == null)) {
748 Report.Error (246, loc, "Cannot find type `{0}'", e);
752 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
755 Report.Error (308, loc,
756 "The non-generic type `{0}' cannot " +
757 "be used with type arguments.",
758 TypeManager.CSharpName (d.Type));
762 Report.Error (305, loc,
763 "Using the generic type `{0}' " +
764 "requires {1} type arguments",
765 TypeManager.GetFullName (d.Type), num_args);
769 Report.Error (246, loc, "Cannot find type `{0}'", e);
773 public bool CheckAccessLevel (Type check_type)
776 if (this is GenericMethod)
777 tb = Parent.TypeBuilder;
781 if (check_type.IsGenericInstance)
782 check_type = check_type.GetGenericTypeDefinition ();
784 if (check_type == tb)
787 if (check_type.IsGenericParameter)
788 return true; // FIXME
790 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
793 // Broken Microsoft runtime, return public for arrays, no matter what
794 // the accessibility is for their underlying class, and they return
795 // NonPublic visibility for pointers
797 if (check_type.IsArray || check_type.IsPointer)
798 return CheckAccessLevel (TypeManager.GetElementType (check_type));
801 case TypeAttributes.Public:
804 case TypeAttributes.NotPublic:
806 // In same cases is null.
807 if (TypeBuilder == null)
811 // This test should probably use the declaringtype.
813 return check_type.Assembly == TypeBuilder.Assembly;
815 case TypeAttributes.NestedPublic:
818 case TypeAttributes.NestedPrivate:
819 string check_type_name = check_type.FullName;
820 string type_name = tb.FullName;
822 int cio = check_type_name.LastIndexOf ('+');
823 string container = check_type_name.Substring (0, cio);
826 // Check if the check_type is a nested class of the current type
828 if (check_type_name.StartsWith (type_name + "+")){
832 if (type_name.StartsWith (container)){
838 case TypeAttributes.NestedFamily:
840 // Only accessible to methods in current type or any subtypes
842 return FamilyAccessible (tb, check_type);
844 case TypeAttributes.NestedFamANDAssem:
845 return (check_type.Assembly == tb.Assembly) &&
846 FamilyAccessible (tb, check_type);
848 case TypeAttributes.NestedFamORAssem:
849 return (check_type.Assembly == tb.Assembly) ||
850 FamilyAccessible (tb, check_type);
852 case TypeAttributes.NestedAssembly:
853 return check_type.Assembly == tb.Assembly;
856 Console.WriteLine ("HERE: " + check_attr);
861 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
863 Type declaring = check_type.DeclaringType;
864 if (tb.IsSubclassOf (declaring))
867 string check_type_name = check_type.FullName;
869 int cio = check_type_name.LastIndexOf ('+');
870 string container = check_type_name.Substring (0, cio);
873 // Check if the check_type is a nested class of the current type
875 if (check_type_name.StartsWith (container + "+"))
881 // Access level of a type.
883 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
884 // Public Assembly Protected
885 Protected = (0 << 0) | (0 << 1) | (X << 2),
886 Public = (X << 0) | (X << 1) | (X << 2),
887 Private = (0 << 0) | (0 << 1) | (0 << 2),
888 Internal = (0 << 0) | (X << 1) | (0 << 2),
889 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
892 static AccessLevel GetAccessLevelFromModifiers (int flags)
894 if ((flags & Modifiers.INTERNAL) != 0) {
896 if ((flags & Modifiers.PROTECTED) != 0)
897 return AccessLevel.ProtectedOrInternal;
899 return AccessLevel.Internal;
901 } else if ((flags & Modifiers.PROTECTED) != 0)
902 return AccessLevel.Protected;
903 else if ((flags & Modifiers.PRIVATE) != 0)
904 return AccessLevel.Private;
906 return AccessLevel.Public;
909 // What is the effective access level of this?
911 AccessLevel EffectiveAccessLevel {
913 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
914 if (!IsTopLevel && (Parent != null))
915 return myAccess & Parent.EffectiveAccessLevel;
920 // Return the access level for type `t'
921 static AccessLevel TypeEffectiveAccessLevel (Type t)
924 return AccessLevel.Public;
925 if (t.IsNestedPrivate)
926 return AccessLevel.Private;
928 return AccessLevel.Internal;
930 // By now, it must be nested
931 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
933 if (t.IsNestedPublic)
935 if (t.IsNestedAssembly)
936 return parentLevel & AccessLevel.Internal;
937 if (t.IsNestedFamily)
938 return parentLevel & AccessLevel.Protected;
939 if (t.IsNestedFamORAssem)
940 return parentLevel & AccessLevel.ProtectedOrInternal;
941 if (t.IsNestedFamANDAssem)
942 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
944 // nested private is taken care of
946 throw new Exception ("I give up, what are you?");
950 // This answers `is the type P, as accessible as a member M which has the
951 // accessability @flags which is declared as a nested member of the type T, this declspace'
953 public bool AsAccessible (Type p, int flags)
955 if (p.IsGenericParameter)
956 return true; // FIXME
959 // 1) if M is private, its accessability is the same as this declspace.
960 // we already know that P is accessible to T before this method, so we
964 if ((flags & Modifiers.PRIVATE) != 0)
967 while (p.IsArray || p.IsPointer || p.IsByRef)
968 p = TypeManager.GetElementType (p);
970 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
971 AccessLevel mAccess = this.EffectiveAccessLevel &
972 GetAccessLevelFromModifiers (flags);
974 // for every place from which we can access M, we must
975 // be able to access P as well. So, we want
976 // For every bit in M and P, M_i -> P_1 == true
977 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
979 return ~ (~ mAccess | pAccess) == 0;
982 static DoubleHash dh = new DoubleHash (1000);
984 Type DefineTypeAndParents (DeclSpace tc)
986 DeclSpace container = tc.Parent;
988 if (container.TypeBuilder == null && container.Name != "")
989 DefineTypeAndParents (container);
991 return tc.DefineType ();
994 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1002 if (dh.Lookup (ns, name, out r))
1006 if (Namespace.IsNamespace (ns)){
1007 string fullname = (ns != "") ? ns + "." + name : name;
1008 t = TypeManager.LookupType (fullname);
1012 t = TypeManager.LookupType (name);
1016 dh.Insert (ns, name, t);
1021 // In case we are fed a composite name, normalize it.
1023 int p = name.LastIndexOf ('.');
1025 ns = MakeFQN (ns, name.Substring (0, p));
1026 name = name.Substring (p+1);
1029 parent = RootContext.Tree.LookupByNamespace (ns, name);
1030 if (parent == null) {
1031 dh.Insert (ns, name, null);
1035 t = DefineTypeAndParents (parent);
1041 dh.Insert (ns, name, t);
1045 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1047 Report.Error (104, loc,
1048 "`{0}' is an ambiguous reference ({1} or {2})",
1052 public Type FindNestedType (Location loc, string name,
1053 out DeclSpace containing_ds)
1058 containing_ds = this;
1059 while (containing_ds != null){
1060 Type container_type = containing_ds.TypeBuilder;
1061 Type current_type = container_type;
1063 while (current_type != null && current_type != TypeManager.object_type) {
1064 string pre = current_type.FullName;
1066 t = LookupInterfaceOrClass (pre, name, out error);
1070 if ((t != null) && containing_ds.CheckAccessLevel (t))
1073 current_type = current_type.BaseType;
1075 containing_ds = containing_ds.Parent;
1082 /// GetType is used to resolve type names at the DeclSpace level.
1083 /// Use this to lookup class/struct bases, interface bases or
1084 /// delegate type references
1088 /// Contrast this to LookupType which is used inside method bodies to
1089 /// lookup types that have already been defined. GetType is used
1090 /// during the tree resolution process and potentially define
1091 /// recursively the type
1093 public Type FindType (Location loc, string name)
1099 // For the case the type we are looking for is nested within this one
1100 // or is in any base class
1102 DeclSpace containing_ds = this;
1104 while (containing_ds != null){
1105 Type container_type = containing_ds.TypeBuilder;
1106 Type current_type = container_type;
1108 while (current_type != null && current_type != TypeManager.object_type) {
1109 string pre = current_type.FullName;
1111 t = LookupInterfaceOrClass (pre, name, out error);
1115 if ((t != null) && containing_ds.CheckAccessLevel (t))
1118 current_type = current_type.BaseType;
1120 containing_ds = containing_ds.Parent;
1124 // Attempt to lookup the class on our namespace and all it's implicit parents
1126 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1127 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1136 // Attempt to do a direct unqualified lookup
1138 t = LookupInterfaceOrClass ("", name, out error);
1146 // Attempt to lookup the class on any of the `using'
1150 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1152 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1159 if (name.IndexOf ('.') > 0)
1162 IAlias alias_value = ns.LookupAlias (name);
1163 if (alias_value != null) {
1164 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1173 // Now check the using clause list
1176 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1177 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1181 if (match != null) {
1183 if (CheckAccessLevel (match)) {
1184 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1197 //Report.Error (246, Location, "Can not find type `"+name+"'");
1202 /// This function is broken and not what you're looking for. It should only
1203 /// be used while the type is still being created since it doesn't use the cache
1204 /// and relies on the filter doing the member name check.
1206 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1207 MemberFilter filter, object criteria);
1210 /// If we have a MemberCache, return it. This property may return null if the
1211 /// class doesn't have a member cache or while it's still being created.
1213 public abstract MemberCache MemberCache {
1217 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1220 TypeBuilder.SetCustomAttribute (cb);
1221 } catch (System.ArgumentException e) {
1222 Report.Warning (-21, a.Location,
1223 "The CharSet named property on StructLayout\n"+
1224 "\tdoes not work correctly on Microsoft.NET\n"+
1225 "\tYou might want to remove the CharSet declaration\n"+
1226 "\tor compile using the Mono runtime instead of the\n"+
1227 "\tMicrosoft .NET runtime\n"+
1228 "\tThe runtime gave the error: " + e);
1233 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1234 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1236 public bool GetClsCompliantAttributeValue ()
1238 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1239 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1241 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1243 if (OptAttributes != null) {
1244 EmitContext ec = new EmitContext (Parent, this, Location,
1245 null, null, ModFlags, false);
1246 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1247 if (cls_attribute != null) {
1248 caching_flags |= Flags.HasClsCompliantAttribute;
1249 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1250 caching_flags |= Flags.ClsCompliantAttributeTrue;
1257 if (Parent == null) {
1258 if (CodeGen.Assembly.IsClsCompliant) {
1259 caching_flags |= Flags.ClsCompliantAttributeTrue;
1265 if (Parent.GetClsCompliantAttributeValue ()) {
1266 caching_flags |= Flags.ClsCompliantAttributeTrue;
1273 // Extensions for generics
1275 TypeParameter[] type_params;
1276 TypeParameter[] type_param_list;
1278 protected string GetInstantiationName ()
1280 StringBuilder sb = new StringBuilder (Name);
1282 for (int i = 0; i < type_param_list.Length; i++) {
1285 sb.Append (type_param_list [i].Name);
1288 return sb.ToString ();
1291 bool check_type_parameter (ArrayList list, int start, string name)
1293 for (int i = 0; i < start; i++) {
1294 TypeParameter param = (TypeParameter) list [i];
1296 if (param.Name != name)
1299 if (RootContext.WarningLevel >= 3)
1302 "Type parameter `{0}' has same name " +
1303 "as type parameter from outer type `{1}'",
1304 name, Parent.GetInstantiationName ());
1312 TypeParameter[] initialize_type_params ()
1314 if (type_param_list != null)
1315 return type_param_list;
1317 DeclSpace the_parent = Parent;
1318 if (this is GenericMethod)
1322 TypeParameter[] parent_params = null;
1323 if ((the_parent != null) && the_parent.IsGeneric) {
1324 parent_params = the_parent.initialize_type_params ();
1325 start = parent_params != null ? parent_params.Length : 0;
1328 ArrayList list = new ArrayList ();
1329 if (parent_params != null)
1330 list.AddRange (parent_params);
1332 int count = type_params != null ? type_params.Length : 0;
1333 for (int i = 0; i < count; i++) {
1334 TypeParameter param = type_params [i];
1335 check_type_parameter (list, start, param.Name);
1339 type_param_list = new TypeParameter [list.Count];
1340 list.CopyTo (type_param_list, 0);
1341 return type_param_list;
1344 public void SetParameterInfo (ArrayList constraints_list)
1347 if (constraints_list != null) {
1349 80, Location, "Contraints are not allowed " +
1350 "on non-generic declarations");
1356 string[] names = MemberName.TypeArguments.GetDeclarations ();
1357 type_params = new TypeParameter [names.Length];
1360 // Register all the names
1362 for (int i = 0; i < type_params.Length; i++) {
1363 string name = names [i];
1365 Constraints constraints = null;
1366 if (constraints_list != null) {
1367 foreach (Constraints constraint in constraints_list) {
1368 if (constraint.TypeParameter == name) {
1369 constraints = constraint;
1375 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1377 string full_name = Name + "." + name;
1378 AddToContainer (type_params [i], false, full_name, name);
1382 public TypeParameter[] TypeParameters {
1385 throw new InvalidOperationException ();
1386 if (type_param_list == null)
1387 initialize_type_params ();
1389 return type_param_list;
1393 protected TypeParameter[] CurrentTypeParameters {
1396 throw new InvalidOperationException ();
1397 if (type_params != null)
1400 return new TypeParameter [0];
1404 public int CountTypeParameters {
1406 return count_type_params;
1410 public TypeParameterExpr LookupGeneric (string name, Location loc)
1415 foreach (TypeParameter type_param in CurrentTypeParameters) {
1416 if (type_param.Name != name)
1419 return new TypeParameterExpr (type_param, loc);
1423 return Parent.LookupGeneric (name, loc);
1428 bool IAlias.IsType {
1429 get { return true; }
1432 string IAlias.Name {
1433 get { return Name; }
1436 TypeExpr IAlias.Type
1439 if (TypeBuilder == null)
1440 throw new InvalidOperationException ();
1442 if (CurrentType != null)
1445 return new TypeExpression (TypeBuilder, Location);
1449 public override string[] ValidAttributeTargets {
1451 return attribute_targets;
1457 /// This is a readonly list of MemberInfo's.
1459 public class MemberList : IList {
1460 public readonly IList List;
1464 /// Create a new MemberList from the given IList.
1466 public MemberList (IList list)
1471 this.List = new ArrayList ();
1476 /// Concatenate the ILists `first' and `second' to a new MemberList.
1478 public MemberList (IList first, IList second)
1480 ArrayList list = new ArrayList ();
1481 list.AddRange (first);
1482 list.AddRange (second);
1487 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1490 /// Cast the MemberList into a MemberInfo[] array.
1493 /// This is an expensive operation, only use it if it's really necessary.
1495 public static explicit operator MemberInfo [] (MemberList list)
1497 Timer.StartTimer (TimerType.MiscTimer);
1498 MemberInfo [] result = new MemberInfo [list.Count];
1499 list.CopyTo (result, 0);
1500 Timer.StopTimer (TimerType.MiscTimer);
1512 public bool IsSynchronized {
1514 return List.IsSynchronized;
1518 public object SyncRoot {
1520 return List.SyncRoot;
1524 public void CopyTo (Array array, int index)
1526 List.CopyTo (array, index);
1531 public IEnumerator GetEnumerator ()
1533 return List.GetEnumerator ();
1538 public bool IsFixedSize {
1544 public bool IsReadOnly {
1550 object IList.this [int index] {
1552 return List [index];
1556 throw new NotSupportedException ();
1560 // FIXME: try to find out whether we can avoid the cast in this indexer.
1561 public MemberInfo this [int index] {
1563 return (MemberInfo) List [index];
1567 public int Add (object value)
1569 throw new NotSupportedException ();
1572 public void Clear ()
1574 throw new NotSupportedException ();
1577 public bool Contains (object value)
1579 return List.Contains (value);
1582 public int IndexOf (object value)
1584 return List.IndexOf (value);
1587 public void Insert (int index, object value)
1589 throw new NotSupportedException ();
1592 public void Remove (object value)
1594 throw new NotSupportedException ();
1597 public void RemoveAt (int index)
1599 throw new NotSupportedException ();
1604 /// This interface is used to get all members of a class when creating the
1605 /// member cache. It must be implemented by all DeclSpace derivatives which
1606 /// want to support the member cache and by TypeHandle to get caching of
1607 /// non-dynamic types.
1609 public interface IMemberContainer {
1611 /// The name of the IMemberContainer. This is only used for
1612 /// debugging purposes.
1619 /// The type of this IMemberContainer.
1626 /// Returns the IMemberContainer of the parent class or null if this
1627 /// is an interface or TypeManger.object_type.
1628 /// This is used when creating the member cache for a class to get all
1629 /// members from the parent class.
1631 IMemberContainer ParentContainer {
1636 /// Whether this is an interface.
1643 /// Returns all members of this class with the corresponding MemberTypes
1644 /// and BindingFlags.
1647 /// When implementing this method, make sure not to return any inherited
1648 /// members and check the MemberTypes and BindingFlags properly.
1649 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1650 /// get the BindingFlags (static/non-static,public/non-public) in the
1651 /// MemberInfo class, but the cache needs this information. That's why
1652 /// this method is called multiple times with different BindingFlags.
1654 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1657 /// Return the container's member cache.
1659 MemberCache MemberCache {
1665 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1666 /// member lookups. It has a member name based hash table; it maps each member
1667 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1668 /// and the BindingFlags that were initially used to get it. The cache contains
1669 /// all members of the current class and all inherited members. If this cache is
1670 /// for an interface types, it also contains all inherited members.
1672 /// There are two ways to get a MemberCache:
1673 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1674 /// use the DeclSpace.MemberCache property.
1675 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1676 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1678 public class MemberCache {
1679 public readonly IMemberContainer Container;
1680 protected Hashtable member_hash;
1681 protected Hashtable method_hash;
1684 /// Create a new MemberCache for the given IMemberContainer `container'.
1686 public MemberCache (IMemberContainer container)
1688 this.Container = container;
1690 Timer.IncrementCounter (CounterType.MemberCache);
1691 Timer.StartTimer (TimerType.CacheInit);
1695 // If we have a parent class (we have a parent class unless we're
1696 // TypeManager.object_type), we deep-copy its MemberCache here.
1697 if (Container.IsInterface) {
1700 if (Container.ParentContainer != null)
1701 parent = Container.ParentContainer.MemberCache;
1703 parent = TypeHandle.ObjectType.MemberCache;
1704 member_hash = SetupCacheForInterface (parent);
1705 } else if (Container.ParentContainer != null)
1706 member_hash = SetupCache (Container.ParentContainer.MemberCache);
1708 member_hash = new Hashtable ();
1710 // If this is neither a dynamic type nor an interface, create a special
1711 // method cache with all declared and inherited methods.
1712 Type type = container.Type;
1713 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1714 method_hash = new Hashtable ();
1718 // Add all members from the current class.
1719 AddMembers (Container);
1721 Timer.StopTimer (TimerType.CacheInit);
1725 /// Bootstrap this member cache by doing a deep-copy of our parent.
1727 Hashtable SetupCache (MemberCache parent)
1729 Hashtable hash = new Hashtable ();
1731 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1732 while (it.MoveNext ()) {
1733 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1741 /// Add the contents of `new_hash' to `hash'.
1743 void AddHashtable (Hashtable hash, MemberCache cache)
1745 Hashtable new_hash = cache.member_hash;
1746 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1747 while (it.MoveNext ()) {
1748 ArrayList list = (ArrayList) hash [it.Key];
1750 hash [it.Key] = list = new ArrayList ();
1752 foreach (CacheEntry entry in (ArrayList) it.Value) {
1753 if (entry.Container != cache.Container)
1761 /// Bootstrap the member cache for an interface type.
1762 /// Type.GetMembers() won't return any inherited members for interface types,
1763 /// so we need to do this manually. Interfaces also inherit from System.Object.
1765 Hashtable SetupCacheForInterface (MemberCache parent)
1767 Hashtable hash = SetupCache (parent);
1768 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1770 foreach (Type itype in ifaces) {
1771 IMemberContainer iface_container =
1772 TypeManager.LookupMemberContainer (itype);
1774 MemberCache iface_cache = iface_container.MemberCache;
1776 AddHashtable (hash, iface_cache);
1783 /// Add all members from class `container' to the cache.
1785 void AddMembers (IMemberContainer container)
1787 // We need to call AddMembers() with a single member type at a time
1788 // to get the member type part of CacheEntry.EntryType right.
1789 AddMembers (MemberTypes.Constructor, container);
1790 AddMembers (MemberTypes.Field, container);
1791 AddMembers (MemberTypes.Method, container);
1792 AddMembers (MemberTypes.Property, container);
1793 AddMembers (MemberTypes.Event, container);
1794 // Nested types are returned by both Static and Instance searches.
1795 AddMembers (MemberTypes.NestedType,
1796 BindingFlags.Static | BindingFlags.Public, container);
1797 AddMembers (MemberTypes.NestedType,
1798 BindingFlags.Static | BindingFlags.NonPublic, container);
1801 void AddMembers (MemberTypes mt, IMemberContainer container)
1803 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1804 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1805 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1806 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1810 /// Add all members from class `container' with the requested MemberTypes and
1811 /// BindingFlags to the cache. This method is called multiple times with different
1812 /// MemberTypes and BindingFlags.
1814 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1816 MemberList members = container.GetMembers (mt, bf);
1818 foreach (MemberInfo member in members) {
1819 string name = member.Name;
1821 int pos = name.IndexOf ('<');
1823 name = name.Substring (0, pos);
1825 // We use a name-based hash table of ArrayList's.
1826 ArrayList list = (ArrayList) member_hash [name];
1828 list = new ArrayList ();
1829 member_hash.Add (name, list);
1832 // When this method is called for the current class, the list will
1833 // already contain all inherited members from our parent classes.
1834 // We cannot add new members in front of the list since this'd be an
1835 // expensive operation, that's why the list is sorted in reverse order
1836 // (ie. members from the current class are coming last).
1837 list.Add (new CacheEntry (container, member, mt, bf));
1842 /// Add all declared and inherited methods from class `type' to the method cache.
1844 void AddMethods (Type type)
1846 AddMethods (BindingFlags.Static | BindingFlags.Public |
1847 BindingFlags.FlattenHierarchy, type);
1848 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1849 BindingFlags.FlattenHierarchy, type);
1850 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1851 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1854 void AddMethods (BindingFlags bf, Type type)
1856 MemberInfo [] members = type.GetMethods (bf);
1858 Array.Reverse (members);
1860 foreach (MethodBase member in members) {
1861 string name = member.Name;
1863 // We use a name-based hash table of ArrayList's.
1864 ArrayList list = (ArrayList) method_hash [name];
1866 list = new ArrayList ();
1867 method_hash.Add (name, list);
1870 // Unfortunately, the elements returned by Type.GetMethods() aren't
1871 // sorted so we need to do this check for every member.
1872 BindingFlags new_bf = bf;
1873 if (member.DeclaringType == type)
1874 new_bf |= BindingFlags.DeclaredOnly;
1876 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1881 /// Compute and return a appropriate `EntryType' magic number for the given
1882 /// MemberTypes and BindingFlags.
1884 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1886 EntryType type = EntryType.None;
1888 if ((mt & MemberTypes.Constructor) != 0)
1889 type |= EntryType.Constructor;
1890 if ((mt & MemberTypes.Event) != 0)
1891 type |= EntryType.Event;
1892 if ((mt & MemberTypes.Field) != 0)
1893 type |= EntryType.Field;
1894 if ((mt & MemberTypes.Method) != 0)
1895 type |= EntryType.Method;
1896 if ((mt & MemberTypes.Property) != 0)
1897 type |= EntryType.Property;
1898 // Nested types are returned by static and instance searches.
1899 if ((mt & MemberTypes.NestedType) != 0)
1900 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1902 if ((bf & BindingFlags.Instance) != 0)
1903 type |= EntryType.Instance;
1904 if ((bf & BindingFlags.Static) != 0)
1905 type |= EntryType.Static;
1906 if ((bf & BindingFlags.Public) != 0)
1907 type |= EntryType.Public;
1908 if ((bf & BindingFlags.NonPublic) != 0)
1909 type |= EntryType.NonPublic;
1910 if ((bf & BindingFlags.DeclaredOnly) != 0)
1911 type |= EntryType.Declared;
1917 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1918 /// denote multiple member types. Returns true if the given flags value denotes a
1919 /// single member types.
1921 public static bool IsSingleMemberType (MemberTypes mt)
1924 case MemberTypes.Constructor:
1925 case MemberTypes.Event:
1926 case MemberTypes.Field:
1927 case MemberTypes.Method:
1928 case MemberTypes.Property:
1929 case MemberTypes.NestedType:
1938 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1939 /// number to speed up the searching process.
1942 protected enum EntryType {
1947 MaskStatic = Instance|Static,
1951 MaskProtection = Public|NonPublic,
1955 Constructor = 0x020,
1962 MaskType = Constructor|Event|Field|Method|Property|NestedType
1965 protected struct CacheEntry {
1966 public readonly IMemberContainer Container;
1967 public readonly EntryType EntryType;
1968 public readonly MemberInfo Member;
1970 public CacheEntry (IMemberContainer container, MemberInfo member,
1971 MemberTypes mt, BindingFlags bf)
1973 this.Container = container;
1974 this.Member = member;
1975 this.EntryType = GetEntryType (mt, bf);
1980 /// This is called each time we're walking up one level in the class hierarchy
1981 /// and checks whether we can abort the search since we've already found what
1982 /// we were looking for.
1984 protected bool DoneSearching (ArrayList list)
1987 // We've found exactly one member in the current class and it's not
1988 // a method or constructor.
1990 if (list.Count == 1 && !(list [0] is MethodBase))
1994 // Multiple properties: we query those just to find out the indexer
1997 if ((list.Count > 0) && (list [0] is PropertyInfo))
2004 /// Looks up members with name `name'. If you provide an optional
2005 /// filter function, it'll only be called with members matching the
2006 /// requested member name.
2008 /// This method will try to use the cache to do the lookup if possible.
2010 /// Unlike other FindMembers implementations, this method will always
2011 /// check all inherited members - even when called on an interface type.
2013 /// If you know that you're only looking for methods, you should use
2014 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2015 /// When doing a method-only search, it'll try to use a special method
2016 /// cache (unless it's a dynamic type or an interface) and the returned
2017 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2018 /// The lookup process will automatically restart itself in method-only
2019 /// search mode if it discovers that it's about to return methods.
2021 ArrayList global = new ArrayList ();
2022 bool using_global = false;
2024 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2026 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2027 MemberFilter filter, object criteria)
2030 throw new Exception ();
2032 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2033 bool method_search = mt == MemberTypes.Method;
2034 // If we have a method cache and we aren't already doing a method-only search,
2035 // then we restart a method search if the first match is a method.
2036 bool do_method_search = !method_search && (method_hash != null);
2038 ArrayList applicable;
2040 // If this is a method-only search, we try to use the method cache if
2041 // possible; a lookup in the method cache will return a MemberInfo with
2042 // the correct ReflectedType for inherited methods.
2044 if (method_search && (method_hash != null))
2045 applicable = (ArrayList) method_hash [name];
2047 applicable = (ArrayList) member_hash [name];
2049 if (applicable == null)
2050 return emptyMemberInfo;
2053 // 32 slots gives 53 rss/54 size
2054 // 2/4 slots gives 55 rss
2056 // Strange: from 25,000 calls, only 1,800
2057 // are above 2. Why does this impact it?
2060 using_global = true;
2062 Timer.StartTimer (TimerType.CachedLookup);
2064 EntryType type = GetEntryType (mt, bf);
2066 IMemberContainer current = Container;
2069 // `applicable' is a list of all members with the given member name `name'
2070 // in the current class and all its parent classes. The list is sorted in
2071 // reverse order due to the way how the cache is initialy created (to speed
2072 // things up, we're doing a deep-copy of our parent).
2074 for (int i = applicable.Count-1; i >= 0; i--) {
2075 CacheEntry entry = (CacheEntry) applicable [i];
2077 // This happens each time we're walking one level up in the class
2078 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2079 // the first time this happens (this may already happen in the first
2080 // iteration of this loop if there are no members with the name we're
2081 // looking for in the current class).
2082 if (entry.Container != current) {
2083 if (declared_only || DoneSearching (global))
2086 current = entry.Container;
2089 // Is the member of the correct type ?
2090 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2093 // Is the member static/non-static ?
2094 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2097 // Apply the filter to it.
2098 if (filter (entry.Member, criteria)) {
2099 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2100 do_method_search = false;
2101 global.Add (entry.Member);
2105 Timer.StopTimer (TimerType.CachedLookup);
2107 // If we have a method cache and we aren't already doing a method-only
2108 // search, we restart in method-only search mode if the first match is
2109 // a method. This ensures that we return a MemberInfo with the correct
2110 // ReflectedType for inherited methods.
2111 if (do_method_search && (global.Count > 0)){
2112 using_global = false;
2114 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2117 using_global = false;
2118 MemberInfo [] copy = new MemberInfo [global.Count];
2119 global.CopyTo (copy);
2124 // This finds the method or property for us to override. invocationType is the type where
2125 // the override is going to be declared, name is the name of the method/property, and
2126 // paramTypes is the parameters, if any to the method or property
2128 // Because the MemberCache holds members from this class and all the base classes,
2129 // we can avoid tons of reflection stuff.
2131 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2133 ArrayList applicable;
2134 if (method_hash != null && !is_property)
2135 applicable = (ArrayList) method_hash [name];
2137 applicable = (ArrayList) member_hash [name];
2139 if (applicable == null)
2142 // Walk the chain of methods, starting from the top.
2144 for (int i = applicable.Count - 1; i >= 0; i--) {
2145 CacheEntry entry = (CacheEntry) applicable [i];
2147 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2150 PropertyInfo pi = null;
2151 MethodInfo mi = null;
2152 FieldInfo fi = null;
2153 Type [] cmpAttrs = null;
2156 if ((entry.EntryType & EntryType.Field) != 0) {
2157 fi = (FieldInfo)entry.Member;
2159 // TODO: For this case we ignore member type
2160 //fb = TypeManager.GetField (fi);
2161 //cmpAttrs = new Type[] { fb.MemberType };
2163 pi = (PropertyInfo) entry.Member;
2164 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2167 mi = (MethodInfo) entry.Member;
2168 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2172 // TODO: Almost duplicate !
2174 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2175 case FieldAttributes.Private:
2177 // A private method is Ok if we are a nested subtype.
2178 // The spec actually is not very clear about this, see bug 52458.
2180 if (invocationType != entry.Container.Type &
2181 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2185 case FieldAttributes.FamANDAssem:
2186 case FieldAttributes.Assembly:
2188 // Check for assembly methods
2190 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2194 return entry.Member;
2198 // Check the arguments
2200 if (cmpAttrs.Length != paramTypes.Length)
2203 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2204 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2209 // get one of the methods because this has the visibility info.
2212 mi = pi.GetGetMethod (true);
2214 mi = pi.GetSetMethod (true);
2220 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2221 case MethodAttributes.Private:
2223 // A private method is Ok if we are a nested subtype.
2224 // The spec actually is not very clear about this, see bug 52458.
2226 if (invocationType.Equals (entry.Container.Type) ||
2227 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2228 return entry.Member;
2231 case MethodAttributes.FamANDAssem:
2232 case MethodAttributes.Assembly:
2234 // Check for assembly methods
2236 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2237 return entry.Member;
2242 // A protected method is ok, because we are overriding.
2243 // public is always ok.
2245 return entry.Member;
2255 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2256 /// We handle two cases. The first is for types without parameters (events, field, properties).
2257 /// The second are methods, indexers and this is why ignore_complex_types is here.
2258 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2260 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2262 ArrayList applicable = null;
2264 if (method_hash != null)
2265 applicable = (ArrayList) method_hash [name];
2267 if (applicable != null) {
2268 for (int i = applicable.Count - 1; i >= 0; i--) {
2269 CacheEntry entry = (CacheEntry) applicable [i];
2270 if ((entry.EntryType & EntryType.Public) != 0)
2271 return entry.Member;
2275 if (member_hash == null)
2277 applicable = (ArrayList) member_hash [name];
2279 if (applicable != null) {
2280 for (int i = applicable.Count - 1; i >= 0; i--) {
2281 CacheEntry entry = (CacheEntry) applicable [i];
2282 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2283 if (ignore_complex_types) {
2284 if ((entry.EntryType & EntryType.Method) != 0)
2287 // Does exist easier way how to detect indexer ?
2288 if ((entry.EntryType & EntryType.Property) != 0) {
2289 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2290 if (arg_types.Length == 1)
2294 return entry.Member;
2301 Hashtable locase_table;
2304 /// Builds low-case table for CLS Compliance test
2306 public Hashtable GetPublicMembers ()
2308 if (locase_table != null)
2309 return locase_table;
2311 locase_table = new Hashtable ();
2312 foreach (DictionaryEntry entry in member_hash) {
2313 ArrayList members = (ArrayList)entry.Value;
2314 for (int ii = 0; ii < members.Count; ++ii) {
2315 CacheEntry member_entry = (CacheEntry) members [ii];
2317 if ((member_entry.EntryType & EntryType.Public) == 0)
2320 // TODO: Does anyone know easier way how to detect that member is internal ?
2321 switch (member_entry.EntryType & EntryType.MaskType) {
2322 case EntryType.Constructor:
2325 case EntryType.Field:
2326 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2330 case EntryType.Method:
2331 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2335 case EntryType.Property:
2336 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2337 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2341 case EntryType.Event:
2342 EventInfo ei = (EventInfo)member_entry.Member;
2343 MethodInfo mi = ei.GetAddMethod ();
2344 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2348 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2349 locase_table [lcase] = member_entry.Member;
2353 return locase_table;
2356 public Hashtable Members {
2363 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2365 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2367 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2369 for (int i = 0; i < al.Count; ++i) {
2370 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2373 if (entry.Member == this_builder)
2376 if ((entry.EntryType & tested_type) != tested_type)
2379 MethodBase method_to_compare = (MethodBase)entry.Member;
2380 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2383 IMethodData md = TypeManager.GetMethod (method_to_compare);
2385 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2386 // However it is exactly what csc does.
2387 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2390 Report.SymbolRelatedToPreviousError (entry.Member);
2391 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());