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 // Hack with Parent == null is for EnumMember
307 if (Parent == null || (GetObsoleteAttribute (Parent) == null && Parent.GetObsoleteAttribute (Parent.Parent) == null))
308 VerifyObsoleteAttribute ();
310 if (!RootContext.VerifyClsCompliance)
313 VerifyClsCompliance (Parent);
317 // Whehter is it ok to use an unsafe pointer in this type container
319 public bool UnsafeOK (DeclSpace parent)
322 // First check if this MemberCore modifier flags has unsafe set
324 if ((ModFlags & Modifiers.UNSAFE) != 0)
327 if (parent.UnsafeContext)
330 Expression.UnsafeError (Location);
335 /// Returns instance of ObsoleteAttribute for this MemberCore
337 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
339 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
340 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
344 caching_flags &= ~Flags.Obsolete_Undetected;
346 if (OptAttributes == null)
349 // TODO: remove this allocation
350 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
351 null, null, ds.ModFlags, false);
353 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
354 if (obsolete_attr == null)
357 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
358 if (obsolete == null)
361 caching_flags |= Flags.Obsolete;
366 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
368 public override bool IsClsCompliaceRequired (DeclSpace container)
370 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
371 return (caching_flags & Flags.ClsCompliant) != 0;
373 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
374 caching_flags &= ~Flags.ClsCompliance_Undetected;
375 caching_flags |= Flags.ClsCompliant;
379 caching_flags &= ~Flags.ClsCompliance_Undetected;
384 /// Returns true when MemberCore is exposed from assembly.
386 protected bool IsExposedFromAssembly (DeclSpace ds)
388 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
391 DeclSpace parentContainer = ds;
392 while (parentContainer != null && parentContainer.ModFlags != 0) {
393 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
395 parentContainer = parentContainer.Parent;
401 /// Resolve CLSCompliantAttribute value or gets cached value.
403 bool GetClsCompliantAttributeValue (DeclSpace ds)
405 if (OptAttributes != null) {
406 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
407 null, null, ds.ModFlags, false);
408 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
409 if (cls_attribute != null) {
410 caching_flags |= Flags.HasClsCompliantAttribute;
411 return cls_attribute.GetClsCompliantAttributeValue (ds);
414 return ds.GetClsCompliantAttributeValue ();
418 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
420 protected bool HasClsCompliantAttribute {
422 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
427 /// The main virtual method for CLS-Compliant verifications.
428 /// The method returns true if member is CLS-Compliant and false if member is not
429 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
430 /// and add their extra verifications.
432 protected virtual bool VerifyClsCompliance (DeclSpace ds)
434 if (!IsClsCompliaceRequired (ds)) {
435 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
436 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
441 if (!CodeGen.Assembly.IsClsCompliant) {
442 if (HasClsCompliantAttribute) {
443 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
448 int index = Name.LastIndexOf ('.');
449 if (Name [index > 0 ? index + 1 : 0] == '_') {
450 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
455 protected abstract void VerifyObsoleteAttribute ();
460 /// Base class for structs, classes, enumerations and interfaces.
463 /// They all create new declaration spaces. This
464 /// provides the common foundation for managing those name
467 public abstract class DeclSpace : MemberCore, IAlias {
469 /// This points to the actual definition that is being
470 /// created with System.Reflection.Emit
472 public TypeBuilder TypeBuilder;
475 /// If we are a generic type, this is the type we are
476 /// currently defining. We need to lookup members on this
477 /// instead of the TypeBuilder.
479 public TypeExpr CurrentType;
482 // This is the namespace in which this typecontainer
483 // was declared. We use this to resolve names.
485 public NamespaceEntry NamespaceEntry;
487 public Hashtable Cache = new Hashtable ();
489 public string Basename;
491 protected Hashtable defined_names;
493 readonly bool is_generic;
494 readonly int count_type_params;
497 // Whether we are Generic
499 public bool IsGeneric {
503 else if (Parent != null)
504 return Parent.IsGeneric;
510 static string[] attribute_targets = new string [] { "type" };
512 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
513 Attributes attrs, Location l)
514 : base (parent, name, attrs, l)
517 Basename = name.Name;
518 defined_names = new Hashtable ();
519 if (name.TypeArguments != null) {
521 count_type_params = name.TypeArguments.Count;
524 count_type_params += parent.count_type_params;
528 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
530 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
532 if (basename == Basename) {
533 Report.SymbolRelatedToPreviousError (this);
534 Report.Error (542, "'{0}': member names cannot be the same as their enclosing type", symbol.Location, symbol.GetSignatureForError ());
538 MemberCore mc = (MemberCore)defined_names [fullname];
540 if (is_method && (mc is MethodCore || mc is IMethodData)) {
541 symbol.caching_flags |= Flags.TestMethodDuplication;
542 mc.caching_flags |= Flags.TestMethodDuplication;
547 Report.SymbolRelatedToPreviousError (mc);
548 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
552 defined_names.Add (fullname, symbol);
556 public void RecordDecl ()
558 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
559 NamespaceEntry.DefineName (MemberName.Basename, this);
563 /// Returns the MemberCore associated with a given name in the declaration
564 /// space. It doesn't return method based symbols !!
567 public MemberCore GetDefinition (string name)
569 return (MemberCore)defined_names [name];
572 bool in_transit = false;
575 /// This function is used to catch recursive definitions
578 public bool InTransit {
589 /// Looks up the alias for the name
591 public IAlias LookupAlias (string name)
593 if (NamespaceEntry != null)
594 return NamespaceEntry.LookupAlias (name);
600 // root_types contains all the types. All TopLevel types
601 // hence have a parent that points to `root_types', that is
602 // why there is a non-obvious test down here.
604 public bool IsTopLevel {
607 if (Parent.Parent == null)
614 public virtual void CloseType ()
616 if ((caching_flags & Flags.CloseTypeCreated) == 0){
618 TypeBuilder.CreateType ();
621 // The try/catch is needed because
622 // nested enumerations fail to load when they
625 // Even if this is the right order (enumerations
626 // declared after types).
628 // Note that this still creates the type and
629 // it is possible to save it
631 caching_flags |= Flags.CloseTypeCreated;
636 /// Should be overriten by the appropriate declaration space
638 public abstract TypeBuilder DefineType ();
641 /// Define all members, but don't apply any attributes or do anything which may
642 /// access not-yet-defined classes. This method also creates the MemberCache.
644 public abstract bool DefineMembers (TypeContainer parent);
647 // Whether this is an `unsafe context'
649 public bool UnsafeContext {
651 if ((ModFlags & Modifiers.UNSAFE) != 0)
654 return Parent.UnsafeContext;
659 public static string MakeFQN (string nsn, string name)
663 return String.Concat (nsn, ".", name);
666 EmitContext type_resolve_ec;
667 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
669 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
670 type_resolve_ec.ResolvingTypeTree = true;
672 return type_resolve_ec;
676 // Looks up the type, as parsed into the expression `e'
678 public Type ResolveType (Expression e, bool silent, Location loc)
680 TypeExpr d = ResolveTypeExpr (e, silent, loc);
684 return ResolveType (d, loc);
687 public Type ResolveType (TypeExpr d, Location loc)
689 if (!d.CheckAccessLevel (this)) {
690 Report.Error (122, loc, "'{0}' is inaccessible due to its protection level", d.Name);
694 Type t = d.ResolveType (type_resolve_ec);
698 if (d is UnboundTypeExpression)
701 TypeContainer tc = TypeManager.LookupTypeContainer (t);
702 if ((tc != null) && tc.IsGeneric) {
704 int tnum = TypeManager.GetNumberOfTypeArguments (t);
705 Report.Error (305, loc,
706 "Using the generic type `{0}' " +
707 "requires {1} type arguments",
708 TypeManager.GetFullName (t), tnum);
712 ConstructedType ctype = new ConstructedType (
713 t, TypeParameters, loc);
715 t = ctype.ResolveType (type_resolve_ec);
722 // Resolves the expression `e' for a type, and will recursively define
725 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
727 if (type_resolve_ec == null)
728 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
729 type_resolve_ec.loc = loc;
730 if (this is GenericMethod)
731 type_resolve_ec.ContainerType = Parent.TypeBuilder;
733 type_resolve_ec.ContainerType = TypeBuilder;
735 int errors = Report.Errors;
737 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
739 if ((d != null) && (d.eclass == ExprClass.Type))
742 if (silent || (Report.Errors != errors))
745 if (e is SimpleName){
746 SimpleName s = new SimpleName (((SimpleName) e).Name, loc);
747 d = s.ResolveAsTypeTerminal (type_resolve_ec);
749 if ((d == null) || (d.Type == null)) {
750 Report.Error (246, loc, "Cannot find type `{0}'", e);
754 int num_args = TypeManager.GetNumberOfTypeArguments (d.Type);
757 Report.Error (308, loc,
758 "The non-generic type `{0}' cannot " +
759 "be used with type arguments.",
760 TypeManager.CSharpName (d.Type));
764 Report.Error (305, loc,
765 "Using the generic type `{0}' " +
766 "requires {1} type arguments",
767 TypeManager.GetFullName (d.Type), num_args);
771 Report.Error (246, loc, "Cannot find type `{0}'", e);
775 public bool CheckAccessLevel (Type check_type)
778 if (this is GenericMethod)
779 tb = Parent.TypeBuilder;
783 if (check_type.IsGenericInstance)
784 check_type = check_type.GetGenericTypeDefinition ();
786 if (check_type == tb)
789 if (check_type.IsGenericParameter)
790 return true; // FIXME
792 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
795 // Broken Microsoft runtime, return public for arrays, no matter what
796 // the accessibility is for their underlying class, and they return
797 // NonPublic visibility for pointers
799 if (check_type.IsArray || check_type.IsPointer)
800 return CheckAccessLevel (TypeManager.GetElementType (check_type));
803 case TypeAttributes.Public:
806 case TypeAttributes.NotPublic:
808 // In same cases is null.
809 if (TypeBuilder == null)
813 // This test should probably use the declaringtype.
815 return check_type.Assembly == TypeBuilder.Assembly;
817 case TypeAttributes.NestedPublic:
820 case TypeAttributes.NestedPrivate:
821 string check_type_name = check_type.FullName;
822 string type_name = tb.FullName;
824 int cio = check_type_name.LastIndexOf ('+');
825 string container = check_type_name.Substring (0, cio);
828 // Check if the check_type is a nested class of the current type
830 if (check_type_name.StartsWith (type_name + "+")){
834 if (type_name.StartsWith (container)){
840 case TypeAttributes.NestedFamily:
842 // Only accessible to methods in current type or any subtypes
844 return FamilyAccessible (tb, check_type);
846 case TypeAttributes.NestedFamANDAssem:
847 return (check_type.Assembly == tb.Assembly) &&
848 FamilyAccessible (tb, check_type);
850 case TypeAttributes.NestedFamORAssem:
851 return (check_type.Assembly == tb.Assembly) ||
852 FamilyAccessible (tb, check_type);
854 case TypeAttributes.NestedAssembly:
855 return check_type.Assembly == tb.Assembly;
858 Console.WriteLine ("HERE: " + check_attr);
863 protected bool FamilyAccessible (TypeBuilder tb, Type check_type)
865 Type declaring = check_type.DeclaringType;
866 if (tb.IsSubclassOf (declaring))
869 string check_type_name = check_type.FullName;
871 int cio = check_type_name.LastIndexOf ('+');
872 string container = check_type_name.Substring (0, cio);
875 // Check if the check_type is a nested class of the current type
877 if (check_type_name.StartsWith (container + "+"))
883 // Access level of a type.
885 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
886 // Public Assembly Protected
887 Protected = (0 << 0) | (0 << 1) | (X << 2),
888 Public = (X << 0) | (X << 1) | (X << 2),
889 Private = (0 << 0) | (0 << 1) | (0 << 2),
890 Internal = (0 << 0) | (X << 1) | (0 << 2),
891 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
894 static AccessLevel GetAccessLevelFromModifiers (int flags)
896 if ((flags & Modifiers.INTERNAL) != 0) {
898 if ((flags & Modifiers.PROTECTED) != 0)
899 return AccessLevel.ProtectedOrInternal;
901 return AccessLevel.Internal;
903 } else if ((flags & Modifiers.PROTECTED) != 0)
904 return AccessLevel.Protected;
905 else if ((flags & Modifiers.PRIVATE) != 0)
906 return AccessLevel.Private;
908 return AccessLevel.Public;
911 // What is the effective access level of this?
913 AccessLevel EffectiveAccessLevel {
915 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
916 if (!IsTopLevel && (Parent != null))
917 return myAccess & Parent.EffectiveAccessLevel;
922 // Return the access level for type `t'
923 static AccessLevel TypeEffectiveAccessLevel (Type t)
926 return AccessLevel.Public;
927 if (t.IsNestedPrivate)
928 return AccessLevel.Private;
930 return AccessLevel.Internal;
932 // By now, it must be nested
933 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
935 if (t.IsNestedPublic)
937 if (t.IsNestedAssembly)
938 return parentLevel & AccessLevel.Internal;
939 if (t.IsNestedFamily)
940 return parentLevel & AccessLevel.Protected;
941 if (t.IsNestedFamORAssem)
942 return parentLevel & AccessLevel.ProtectedOrInternal;
943 if (t.IsNestedFamANDAssem)
944 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
946 // nested private is taken care of
948 throw new Exception ("I give up, what are you?");
952 // This answers `is the type P, as accessible as a member M which has the
953 // accessability @flags which is declared as a nested member of the type T, this declspace'
955 public bool AsAccessible (Type p, int flags)
957 if (p.IsGenericParameter)
958 return true; // FIXME
961 // 1) if M is private, its accessability is the same as this declspace.
962 // we already know that P is accessible to T before this method, so we
966 if ((flags & Modifiers.PRIVATE) != 0)
969 while (p.IsArray || p.IsPointer || p.IsByRef)
970 p = TypeManager.GetElementType (p);
972 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
973 AccessLevel mAccess = this.EffectiveAccessLevel &
974 GetAccessLevelFromModifiers (flags);
976 // for every place from which we can access M, we must
977 // be able to access P as well. So, we want
978 // For every bit in M and P, M_i -> P_1 == true
979 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
981 return ~ (~ mAccess | pAccess) == 0;
984 static DoubleHash dh = new DoubleHash (1000);
986 Type DefineTypeAndParents (DeclSpace tc)
988 DeclSpace container = tc.Parent;
990 if (container.TypeBuilder == null && container.Name != "")
991 DefineTypeAndParents (container);
993 return tc.DefineType ();
996 Type LookupInterfaceOrClass (string ns, string name, out bool error)
1004 if (dh.Lookup (ns, name, out r))
1008 if (Namespace.IsNamespace (ns)){
1009 string fullname = (ns != "") ? ns + "." + name : name;
1010 t = TypeManager.LookupType (fullname);
1014 t = TypeManager.LookupType (name);
1018 dh.Insert (ns, name, t);
1023 // In case we are fed a composite name, normalize it.
1025 int p = name.LastIndexOf ('.');
1027 ns = MakeFQN (ns, name.Substring (0, p));
1028 name = name.Substring (p+1);
1031 parent = RootContext.Tree.LookupByNamespace (ns, name);
1032 if (parent == null) {
1033 dh.Insert (ns, name, null);
1037 t = DefineTypeAndParents (parent);
1043 dh.Insert (ns, name, t);
1047 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
1049 Report.Error (104, loc,
1050 "`{0}' is an ambiguous reference ({1} or {2})",
1054 public Type FindNestedType (Location loc, string name,
1055 out DeclSpace containing_ds)
1060 containing_ds = this;
1061 while (containing_ds != null){
1062 Type container_type = containing_ds.TypeBuilder;
1063 Type current_type = container_type;
1065 while (current_type != null && current_type != TypeManager.object_type) {
1066 string pre = current_type.FullName;
1068 t = LookupInterfaceOrClass (pre, name, out error);
1072 if ((t != null) && containing_ds.CheckAccessLevel (t))
1075 current_type = current_type.BaseType;
1077 containing_ds = containing_ds.Parent;
1084 /// GetType is used to resolve type names at the DeclSpace level.
1085 /// Use this to lookup class/struct bases, interface bases or
1086 /// delegate type references
1090 /// Contrast this to LookupType which is used inside method bodies to
1091 /// lookup types that have already been defined. GetType is used
1092 /// during the tree resolution process and potentially define
1093 /// recursively the type
1095 public Type FindType (Location loc, string name)
1101 // For the case the type we are looking for is nested within this one
1102 // or is in any base class
1104 DeclSpace containing_ds = this;
1106 while (containing_ds != null){
1107 Type container_type = containing_ds.TypeBuilder;
1108 Type current_type = container_type;
1110 while (current_type != null && current_type != TypeManager.object_type) {
1111 string pre = current_type.FullName;
1113 t = LookupInterfaceOrClass (pre, name, out error);
1117 if ((t != null) && containing_ds.CheckAccessLevel (t))
1120 current_type = current_type.BaseType;
1122 containing_ds = containing_ds.Parent;
1126 // Attempt to lookup the class on our namespace and all it's implicit parents
1128 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1129 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1138 // Attempt to do a direct unqualified lookup
1140 t = LookupInterfaceOrClass ("", name, out error);
1148 // Attempt to lookup the class on any of the `using'
1152 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1154 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1161 if (name.IndexOf ('.') > 0)
1164 IAlias alias_value = ns.LookupAlias (name);
1165 if (alias_value != null) {
1166 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1175 // Now check the using clause list
1178 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1179 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1183 if (match != null) {
1185 if (CheckAccessLevel (match)) {
1186 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1199 //Report.Error (246, Location, "Can not find type `"+name+"'");
1204 /// This function is broken and not what you're looking for. It should only
1205 /// be used while the type is still being created since it doesn't use the cache
1206 /// and relies on the filter doing the member name check.
1208 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1209 MemberFilter filter, object criteria);
1212 /// If we have a MemberCache, return it. This property may return null if the
1213 /// class doesn't have a member cache or while it's still being created.
1215 public abstract MemberCache MemberCache {
1219 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1222 TypeBuilder.SetCustomAttribute (cb);
1223 } catch (System.ArgumentException e) {
1224 Report.Warning (-21, a.Location,
1225 "The CharSet named property on StructLayout\n"+
1226 "\tdoes not work correctly on Microsoft.NET\n"+
1227 "\tYou might want to remove the CharSet declaration\n"+
1228 "\tor compile using the Mono runtime instead of the\n"+
1229 "\tMicrosoft .NET runtime\n"+
1230 "\tThe runtime gave the error: " + e);
1235 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1236 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1238 public bool GetClsCompliantAttributeValue ()
1240 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1241 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1243 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1245 if (OptAttributes != null) {
1246 EmitContext ec = new EmitContext (Parent, this, Location,
1247 null, null, ModFlags, false);
1248 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1249 if (cls_attribute != null) {
1250 caching_flags |= Flags.HasClsCompliantAttribute;
1251 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1252 caching_flags |= Flags.ClsCompliantAttributeTrue;
1259 if (Parent == null) {
1260 if (CodeGen.Assembly.IsClsCompliant) {
1261 caching_flags |= Flags.ClsCompliantAttributeTrue;
1267 if (Parent.GetClsCompliantAttributeValue ()) {
1268 caching_flags |= Flags.ClsCompliantAttributeTrue;
1275 // Extensions for generics
1277 TypeParameter[] type_params;
1278 TypeParameter[] type_param_list;
1280 protected string GetInstantiationName ()
1282 StringBuilder sb = new StringBuilder (Name);
1284 for (int i = 0; i < type_param_list.Length; i++) {
1287 sb.Append (type_param_list [i].Name);
1290 return sb.ToString ();
1293 bool check_type_parameter (ArrayList list, int start, string name)
1295 for (int i = 0; i < start; i++) {
1296 TypeParameter param = (TypeParameter) list [i];
1298 if (param.Name != name)
1301 if (RootContext.WarningLevel >= 3)
1304 "Type parameter `{0}' has same name " +
1305 "as type parameter from outer type `{1}'",
1306 name, Parent.GetInstantiationName ());
1314 TypeParameter[] initialize_type_params ()
1316 if (type_param_list != null)
1317 return type_param_list;
1319 DeclSpace the_parent = Parent;
1320 if (this is GenericMethod)
1324 TypeParameter[] parent_params = null;
1325 if ((the_parent != null) && the_parent.IsGeneric) {
1326 parent_params = the_parent.initialize_type_params ();
1327 start = parent_params != null ? parent_params.Length : 0;
1330 ArrayList list = new ArrayList ();
1331 if (parent_params != null)
1332 list.AddRange (parent_params);
1334 int count = type_params != null ? type_params.Length : 0;
1335 for (int i = 0; i < count; i++) {
1336 TypeParameter param = type_params [i];
1337 check_type_parameter (list, start, param.Name);
1341 type_param_list = new TypeParameter [list.Count];
1342 list.CopyTo (type_param_list, 0);
1343 return type_param_list;
1346 public void SetParameterInfo (ArrayList constraints_list)
1349 if (constraints_list != null) {
1351 80, Location, "Contraints are not allowed " +
1352 "on non-generic declarations");
1358 string[] names = MemberName.TypeArguments.GetDeclarations ();
1359 type_params = new TypeParameter [names.Length];
1362 // Register all the names
1364 for (int i = 0; i < type_params.Length; i++) {
1365 string name = names [i];
1367 Constraints constraints = null;
1368 if (constraints_list != null) {
1369 foreach (Constraints constraint in constraints_list) {
1370 if (constraint.TypeParameter == name) {
1371 constraints = constraint;
1377 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1379 string full_name = Name + "." + name;
1380 AddToContainer (type_params [i], false, full_name, name);
1384 public TypeParameter[] TypeParameters {
1387 throw new InvalidOperationException ();
1388 if (type_param_list == null)
1389 initialize_type_params ();
1391 return type_param_list;
1395 protected TypeParameter[] CurrentTypeParameters {
1398 throw new InvalidOperationException ();
1399 if (type_params != null)
1402 return new TypeParameter [0];
1406 public int CountTypeParameters {
1408 return count_type_params;
1412 public TypeParameterExpr LookupGeneric (string name, Location loc)
1417 foreach (TypeParameter type_param in CurrentTypeParameters) {
1418 if (type_param.Name != name)
1421 return new TypeParameterExpr (type_param, loc);
1425 return Parent.LookupGeneric (name, loc);
1430 bool IAlias.IsType {
1431 get { return true; }
1434 string IAlias.Name {
1435 get { return Name; }
1438 TypeExpr IAlias.Type
1441 if (TypeBuilder == null)
1442 throw new InvalidOperationException ();
1444 if (CurrentType != null)
1447 return new TypeExpression (TypeBuilder, Location);
1451 public override string[] ValidAttributeTargets {
1453 return attribute_targets;
1459 /// This is a readonly list of MemberInfo's.
1461 public class MemberList : IList {
1462 public readonly IList List;
1466 /// Create a new MemberList from the given IList.
1468 public MemberList (IList list)
1473 this.List = new ArrayList ();
1478 /// Concatenate the ILists `first' and `second' to a new MemberList.
1480 public MemberList (IList first, IList second)
1482 ArrayList list = new ArrayList ();
1483 list.AddRange (first);
1484 list.AddRange (second);
1489 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1492 /// Cast the MemberList into a MemberInfo[] array.
1495 /// This is an expensive operation, only use it if it's really necessary.
1497 public static explicit operator MemberInfo [] (MemberList list)
1499 Timer.StartTimer (TimerType.MiscTimer);
1500 MemberInfo [] result = new MemberInfo [list.Count];
1501 list.CopyTo (result, 0);
1502 Timer.StopTimer (TimerType.MiscTimer);
1514 public bool IsSynchronized {
1516 return List.IsSynchronized;
1520 public object SyncRoot {
1522 return List.SyncRoot;
1526 public void CopyTo (Array array, int index)
1528 List.CopyTo (array, index);
1533 public IEnumerator GetEnumerator ()
1535 return List.GetEnumerator ();
1540 public bool IsFixedSize {
1546 public bool IsReadOnly {
1552 object IList.this [int index] {
1554 return List [index];
1558 throw new NotSupportedException ();
1562 // FIXME: try to find out whether we can avoid the cast in this indexer.
1563 public MemberInfo this [int index] {
1565 return (MemberInfo) List [index];
1569 public int Add (object value)
1571 throw new NotSupportedException ();
1574 public void Clear ()
1576 throw new NotSupportedException ();
1579 public bool Contains (object value)
1581 return List.Contains (value);
1584 public int IndexOf (object value)
1586 return List.IndexOf (value);
1589 public void Insert (int index, object value)
1591 throw new NotSupportedException ();
1594 public void Remove (object value)
1596 throw new NotSupportedException ();
1599 public void RemoveAt (int index)
1601 throw new NotSupportedException ();
1606 /// This interface is used to get all members of a class when creating the
1607 /// member cache. It must be implemented by all DeclSpace derivatives which
1608 /// want to support the member cache and by TypeHandle to get caching of
1609 /// non-dynamic types.
1611 public interface IMemberContainer {
1613 /// The name of the IMemberContainer. This is only used for
1614 /// debugging purposes.
1621 /// The type of this IMemberContainer.
1628 /// Returns the IMemberContainer of the parent class or null if this
1629 /// is an interface or TypeManger.object_type.
1630 /// This is used when creating the member cache for a class to get all
1631 /// members from the parent class.
1633 IMemberContainer ParentContainer {
1638 /// Whether this is an interface.
1645 /// Returns all members of this class with the corresponding MemberTypes
1646 /// and BindingFlags.
1649 /// When implementing this method, make sure not to return any inherited
1650 /// members and check the MemberTypes and BindingFlags properly.
1651 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1652 /// get the BindingFlags (static/non-static,public/non-public) in the
1653 /// MemberInfo class, but the cache needs this information. That's why
1654 /// this method is called multiple times with different BindingFlags.
1656 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1659 /// Return the container's member cache.
1661 MemberCache MemberCache {
1667 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1668 /// member lookups. It has a member name based hash table; it maps each member
1669 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1670 /// and the BindingFlags that were initially used to get it. The cache contains
1671 /// all members of the current class and all inherited members. If this cache is
1672 /// for an interface types, it also contains all inherited members.
1674 /// There are two ways to get a MemberCache:
1675 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1676 /// use the DeclSpace.MemberCache property.
1677 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1678 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1680 public class MemberCache {
1681 public readonly IMemberContainer Container;
1682 protected Hashtable member_hash;
1683 protected Hashtable method_hash;
1686 /// Create a new MemberCache for the given IMemberContainer `container'.
1688 public MemberCache (IMemberContainer container)
1690 this.Container = container;
1692 Timer.IncrementCounter (CounterType.MemberCache);
1693 Timer.StartTimer (TimerType.CacheInit);
1697 // If we have a parent class (we have a parent class unless we're
1698 // TypeManager.object_type), we deep-copy its MemberCache here.
1699 if (Container.IsInterface) {
1702 if (Container.ParentContainer != null)
1703 parent = Container.ParentContainer.MemberCache;
1705 parent = TypeHandle.ObjectType.MemberCache;
1706 member_hash = SetupCacheForInterface (parent);
1707 } else if (Container.ParentContainer != null)
1708 member_hash = SetupCache (Container.ParentContainer.MemberCache);
1710 member_hash = new Hashtable ();
1712 // If this is neither a dynamic type nor an interface, create a special
1713 // method cache with all declared and inherited methods.
1714 Type type = container.Type;
1715 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1716 method_hash = new Hashtable ();
1720 // Add all members from the current class.
1721 AddMembers (Container);
1723 Timer.StopTimer (TimerType.CacheInit);
1727 /// Bootstrap this member cache by doing a deep-copy of our parent.
1729 Hashtable SetupCache (MemberCache parent)
1731 Hashtable hash = new Hashtable ();
1733 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1734 while (it.MoveNext ()) {
1735 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1743 /// Add the contents of `new_hash' to `hash'.
1745 void AddHashtable (Hashtable hash, MemberCache cache)
1747 Hashtable new_hash = cache.member_hash;
1748 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1749 while (it.MoveNext ()) {
1750 ArrayList list = (ArrayList) hash [it.Key];
1752 hash [it.Key] = list = new ArrayList ();
1754 foreach (CacheEntry entry in (ArrayList) it.Value) {
1755 if (entry.Container != cache.Container)
1763 /// Bootstrap the member cache for an interface type.
1764 /// Type.GetMembers() won't return any inherited members for interface types,
1765 /// so we need to do this manually. Interfaces also inherit from System.Object.
1767 Hashtable SetupCacheForInterface (MemberCache parent)
1769 Hashtable hash = SetupCache (parent);
1770 Type [] ifaces = TypeManager.GetInterfaces (Container.Type);
1772 foreach (Type itype in ifaces) {
1773 IMemberContainer iface_container =
1774 TypeManager.LookupMemberContainer (itype);
1776 MemberCache iface_cache = iface_container.MemberCache;
1778 AddHashtable (hash, iface_cache);
1785 /// Add all members from class `container' to the cache.
1787 void AddMembers (IMemberContainer container)
1789 // We need to call AddMembers() with a single member type at a time
1790 // to get the member type part of CacheEntry.EntryType right.
1791 AddMembers (MemberTypes.Constructor, container);
1792 AddMembers (MemberTypes.Field, container);
1793 AddMembers (MemberTypes.Method, container);
1794 AddMembers (MemberTypes.Property, container);
1795 AddMembers (MemberTypes.Event, container);
1796 // Nested types are returned by both Static and Instance searches.
1797 AddMembers (MemberTypes.NestedType,
1798 BindingFlags.Static | BindingFlags.Public, container);
1799 AddMembers (MemberTypes.NestedType,
1800 BindingFlags.Static | BindingFlags.NonPublic, container);
1803 void AddMembers (MemberTypes mt, IMemberContainer container)
1805 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1806 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1807 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1808 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1812 /// Add all members from class `container' with the requested MemberTypes and
1813 /// BindingFlags to the cache. This method is called multiple times with different
1814 /// MemberTypes and BindingFlags.
1816 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1818 MemberList members = container.GetMembers (mt, bf);
1820 foreach (MemberInfo member in members) {
1821 string name = member.Name;
1823 int pos = name.IndexOf ('<');
1825 name = name.Substring (0, pos);
1827 // We use a name-based hash table of ArrayList's.
1828 ArrayList list = (ArrayList) member_hash [name];
1830 list = new ArrayList ();
1831 member_hash.Add (name, list);
1834 // When this method is called for the current class, the list will
1835 // already contain all inherited members from our parent classes.
1836 // We cannot add new members in front of the list since this'd be an
1837 // expensive operation, that's why the list is sorted in reverse order
1838 // (ie. members from the current class are coming last).
1839 list.Add (new CacheEntry (container, member, mt, bf));
1844 /// Add all declared and inherited methods from class `type' to the method cache.
1846 void AddMethods (Type type)
1848 AddMethods (BindingFlags.Static | BindingFlags.Public |
1849 BindingFlags.FlattenHierarchy, type);
1850 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1851 BindingFlags.FlattenHierarchy, type);
1852 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1853 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1856 void AddMethods (BindingFlags bf, Type type)
1858 MemberInfo [] members = type.GetMethods (bf);
1860 Array.Reverse (members);
1862 foreach (MethodBase member in members) {
1863 string name = member.Name;
1865 // We use a name-based hash table of ArrayList's.
1866 ArrayList list = (ArrayList) method_hash [name];
1868 list = new ArrayList ();
1869 method_hash.Add (name, list);
1872 // Unfortunately, the elements returned by Type.GetMethods() aren't
1873 // sorted so we need to do this check for every member.
1874 BindingFlags new_bf = bf;
1875 if (member.DeclaringType == type)
1876 new_bf |= BindingFlags.DeclaredOnly;
1878 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1883 /// Compute and return a appropriate `EntryType' magic number for the given
1884 /// MemberTypes and BindingFlags.
1886 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1888 EntryType type = EntryType.None;
1890 if ((mt & MemberTypes.Constructor) != 0)
1891 type |= EntryType.Constructor;
1892 if ((mt & MemberTypes.Event) != 0)
1893 type |= EntryType.Event;
1894 if ((mt & MemberTypes.Field) != 0)
1895 type |= EntryType.Field;
1896 if ((mt & MemberTypes.Method) != 0)
1897 type |= EntryType.Method;
1898 if ((mt & MemberTypes.Property) != 0)
1899 type |= EntryType.Property;
1900 // Nested types are returned by static and instance searches.
1901 if ((mt & MemberTypes.NestedType) != 0)
1902 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1904 if ((bf & BindingFlags.Instance) != 0)
1905 type |= EntryType.Instance;
1906 if ((bf & BindingFlags.Static) != 0)
1907 type |= EntryType.Static;
1908 if ((bf & BindingFlags.Public) != 0)
1909 type |= EntryType.Public;
1910 if ((bf & BindingFlags.NonPublic) != 0)
1911 type |= EntryType.NonPublic;
1912 if ((bf & BindingFlags.DeclaredOnly) != 0)
1913 type |= EntryType.Declared;
1919 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1920 /// denote multiple member types. Returns true if the given flags value denotes a
1921 /// single member types.
1923 public static bool IsSingleMemberType (MemberTypes mt)
1926 case MemberTypes.Constructor:
1927 case MemberTypes.Event:
1928 case MemberTypes.Field:
1929 case MemberTypes.Method:
1930 case MemberTypes.Property:
1931 case MemberTypes.NestedType:
1940 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1941 /// number to speed up the searching process.
1944 protected enum EntryType {
1949 MaskStatic = Instance|Static,
1953 MaskProtection = Public|NonPublic,
1957 Constructor = 0x020,
1964 MaskType = Constructor|Event|Field|Method|Property|NestedType
1967 protected struct CacheEntry {
1968 public readonly IMemberContainer Container;
1969 public readonly EntryType EntryType;
1970 public readonly MemberInfo Member;
1972 public CacheEntry (IMemberContainer container, MemberInfo member,
1973 MemberTypes mt, BindingFlags bf)
1975 this.Container = container;
1976 this.Member = member;
1977 this.EntryType = GetEntryType (mt, bf);
1982 /// This is called each time we're walking up one level in the class hierarchy
1983 /// and checks whether we can abort the search since we've already found what
1984 /// we were looking for.
1986 protected bool DoneSearching (ArrayList list)
1989 // We've found exactly one member in the current class and it's not
1990 // a method or constructor.
1992 if (list.Count == 1 && !(list [0] is MethodBase))
1996 // Multiple properties: we query those just to find out the indexer
1999 if ((list.Count > 0) && (list [0] is PropertyInfo))
2006 /// Looks up members with name `name'. If you provide an optional
2007 /// filter function, it'll only be called with members matching the
2008 /// requested member name.
2010 /// This method will try to use the cache to do the lookup if possible.
2012 /// Unlike other FindMembers implementations, this method will always
2013 /// check all inherited members - even when called on an interface type.
2015 /// If you know that you're only looking for methods, you should use
2016 /// MemberTypes.Method alone since this speeds up the lookup a bit.
2017 /// When doing a method-only search, it'll try to use a special method
2018 /// cache (unless it's a dynamic type or an interface) and the returned
2019 /// MemberInfo's will have the correct ReflectedType for inherited methods.
2020 /// The lookup process will automatically restart itself in method-only
2021 /// search mode if it discovers that it's about to return methods.
2023 ArrayList global = new ArrayList ();
2024 bool using_global = false;
2026 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
2028 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
2029 MemberFilter filter, object criteria)
2032 throw new Exception ();
2034 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
2035 bool method_search = mt == MemberTypes.Method;
2036 // If we have a method cache and we aren't already doing a method-only search,
2037 // then we restart a method search if the first match is a method.
2038 bool do_method_search = !method_search && (method_hash != null);
2040 ArrayList applicable;
2042 // If this is a method-only search, we try to use the method cache if
2043 // possible; a lookup in the method cache will return a MemberInfo with
2044 // the correct ReflectedType for inherited methods.
2046 if (method_search && (method_hash != null))
2047 applicable = (ArrayList) method_hash [name];
2049 applicable = (ArrayList) member_hash [name];
2051 if (applicable == null)
2052 return emptyMemberInfo;
2055 // 32 slots gives 53 rss/54 size
2056 // 2/4 slots gives 55 rss
2058 // Strange: from 25,000 calls, only 1,800
2059 // are above 2. Why does this impact it?
2062 using_global = true;
2064 Timer.StartTimer (TimerType.CachedLookup);
2066 EntryType type = GetEntryType (mt, bf);
2068 IMemberContainer current = Container;
2071 // `applicable' is a list of all members with the given member name `name'
2072 // in the current class and all its parent classes. The list is sorted in
2073 // reverse order due to the way how the cache is initialy created (to speed
2074 // things up, we're doing a deep-copy of our parent).
2076 for (int i = applicable.Count-1; i >= 0; i--) {
2077 CacheEntry entry = (CacheEntry) applicable [i];
2079 // This happens each time we're walking one level up in the class
2080 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2081 // the first time this happens (this may already happen in the first
2082 // iteration of this loop if there are no members with the name we're
2083 // looking for in the current class).
2084 if (entry.Container != current) {
2085 if (declared_only || DoneSearching (global))
2088 current = entry.Container;
2091 // Is the member of the correct type ?
2092 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2095 // Is the member static/non-static ?
2096 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2099 // Apply the filter to it.
2100 if (filter (entry.Member, criteria)) {
2101 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2102 do_method_search = false;
2103 global.Add (entry.Member);
2107 Timer.StopTimer (TimerType.CachedLookup);
2109 // If we have a method cache and we aren't already doing a method-only
2110 // search, we restart in method-only search mode if the first match is
2111 // a method. This ensures that we return a MemberInfo with the correct
2112 // ReflectedType for inherited methods.
2113 if (do_method_search && (global.Count > 0)){
2114 using_global = false;
2116 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2119 using_global = false;
2120 MemberInfo [] copy = new MemberInfo [global.Count];
2121 global.CopyTo (copy);
2126 // This finds the method or property for us to override. invocationType is the type where
2127 // the override is going to be declared, name is the name of the method/property, and
2128 // paramTypes is the parameters, if any to the method or property
2130 // Because the MemberCache holds members from this class and all the base classes,
2131 // we can avoid tons of reflection stuff.
2133 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2135 ArrayList applicable;
2136 if (method_hash != null && !is_property)
2137 applicable = (ArrayList) method_hash [name];
2139 applicable = (ArrayList) member_hash [name];
2141 if (applicable == null)
2144 // Walk the chain of methods, starting from the top.
2146 for (int i = applicable.Count - 1; i >= 0; i--) {
2147 CacheEntry entry = (CacheEntry) applicable [i];
2149 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2152 PropertyInfo pi = null;
2153 MethodInfo mi = null;
2154 FieldInfo fi = null;
2155 Type [] cmpAttrs = null;
2158 if ((entry.EntryType & EntryType.Field) != 0) {
2159 fi = (FieldInfo)entry.Member;
2161 // TODO: For this case we ignore member type
2162 //fb = TypeManager.GetField (fi);
2163 //cmpAttrs = new Type[] { fb.MemberType };
2165 pi = (PropertyInfo) entry.Member;
2166 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2169 mi = (MethodInfo) entry.Member;
2170 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2174 // TODO: Almost duplicate !
2176 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2177 case FieldAttributes.Private:
2179 // A private method is Ok if we are a nested subtype.
2180 // The spec actually is not very clear about this, see bug 52458.
2182 if (invocationType != entry.Container.Type &
2183 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2187 case FieldAttributes.FamANDAssem:
2188 case FieldAttributes.Assembly:
2190 // Check for assembly methods
2192 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2196 return entry.Member;
2200 // Check the arguments
2202 if (cmpAttrs.Length != paramTypes.Length)
2205 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2206 if (!paramTypes [j].Equals (cmpAttrs [j]))
2211 // get one of the methods because this has the visibility info.
2214 mi = pi.GetGetMethod (true);
2216 mi = pi.GetSetMethod (true);
2222 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2223 case MethodAttributes.Private:
2225 // A private method is Ok if we are a nested subtype.
2226 // The spec actually is not very clear about this, see bug 52458.
2228 if (invocationType == entry.Container.Type ||
2229 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2230 return entry.Member;
2233 case MethodAttributes.FamANDAssem:
2234 case MethodAttributes.Assembly:
2236 // Check for assembly methods
2238 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2239 return entry.Member;
2244 // A protected method is ok, because we are overriding.
2245 // public is always ok.
2247 return entry.Member;
2257 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2258 /// We handle two cases. The first is for types without parameters (events, field, properties).
2259 /// The second are methods, indexers and this is why ignore_complex_types is here.
2260 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2262 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2264 ArrayList applicable = null;
2266 if (method_hash != null)
2267 applicable = (ArrayList) method_hash [name];
2269 if (applicable != null) {
2270 for (int i = applicable.Count - 1; i >= 0; i--) {
2271 CacheEntry entry = (CacheEntry) applicable [i];
2272 if ((entry.EntryType & EntryType.Public) != 0)
2273 return entry.Member;
2277 if (member_hash == null)
2279 applicable = (ArrayList) member_hash [name];
2281 if (applicable != null) {
2282 for (int i = applicable.Count - 1; i >= 0; i--) {
2283 CacheEntry entry = (CacheEntry) applicable [i];
2284 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2285 if (ignore_complex_types) {
2286 if ((entry.EntryType & EntryType.Method) != 0)
2289 // Does exist easier way how to detect indexer ?
2290 if ((entry.EntryType & EntryType.Property) != 0) {
2291 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2292 if (arg_types.Length == 1)
2296 return entry.Member;
2303 Hashtable locase_table;
2306 /// Builds low-case table for CLS Compliance test
2308 public Hashtable GetPublicMembers ()
2310 if (locase_table != null)
2311 return locase_table;
2313 locase_table = new Hashtable ();
2314 foreach (DictionaryEntry entry in member_hash) {
2315 ArrayList members = (ArrayList)entry.Value;
2316 for (int ii = 0; ii < members.Count; ++ii) {
2317 CacheEntry member_entry = (CacheEntry) members [ii];
2319 if ((member_entry.EntryType & EntryType.Public) == 0)
2322 // TODO: Does anyone know easier way how to detect that member is internal ?
2323 switch (member_entry.EntryType & EntryType.MaskType) {
2324 case EntryType.Constructor:
2327 case EntryType.Field:
2328 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2332 case EntryType.Method:
2333 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2337 case EntryType.Property:
2338 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2339 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2343 case EntryType.Event:
2344 EventInfo ei = (EventInfo)member_entry.Member;
2345 MethodInfo mi = ei.GetAddMethod ();
2346 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2350 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2351 locase_table [lcase] = member_entry.Member;
2355 return locase_table;
2358 public Hashtable Members {
2365 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2367 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2369 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2371 for (int i = 0; i < al.Count; ++i) {
2372 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2375 if (entry.Member == this_builder)
2378 if ((entry.EntryType & tested_type) != tested_type)
2381 MethodBase method_to_compare = (MethodBase)entry.Member;
2382 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2385 IMethodData md = TypeManager.GetMethod (method_to_compare);
2387 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2388 // However it is exactly what csc does.
2389 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2392 Report.SymbolRelatedToPreviousError (entry.Member);
2393 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());