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.GetTypeName () + "." + Name;
98 public static string MakeName (string name, TypeArguments args)
103 return name + "`" + args.Count;
106 public static string MakeName (string name, int count)
108 return name + "`" + count;
111 public string GetTypeName ()
115 return Left.GetTypeName () + "." +
116 MakeName (Name, TypeArguments);
118 return MakeName (Name, TypeArguments);
121 protected bool IsUnbound {
123 if ((Left != null) && Left.IsUnbound)
125 else if (TypeArguments == null)
128 return TypeArguments.IsUnbound;
132 protected bool CheckUnbound (Location loc)
134 if ((Left != null) && !Left.CheckUnbound (loc))
136 if ((TypeArguments != null) && !TypeArguments.IsUnbound) {
137 Report.Error (1031, loc, "Type expected");
144 public Expression GetTypeExpression (Location loc)
147 if (!CheckUnbound (loc))
150 return new UnboundTypeExpression (GetTypeName ());
154 Expression lexpr = Left.GetTypeExpression (loc);
156 return new MemberAccess (lexpr, Name, TypeArguments, loc);
158 if (TypeArguments != null)
159 return new ConstructedType (Name, TypeArguments, loc);
161 return new SimpleName (Name, loc);
165 public MemberName Clone ()
168 return new MemberName (Left.Clone (), Name, TypeArguments);
170 return new MemberName (Name, TypeArguments);
173 public string Basename {
175 if (TypeArguments != null)
176 return MakeName (Name, TypeArguments);
182 public override string ToString ()
184 throw new Exception ("This exception is thrown because someone is miss-using\n" +
185 "MemberName.ToString in the compiler. Please report this bug");
188 if (TypeArguments != null)
189 full_name = Name + "<" + TypeArguments + ">";
194 return Left + "." + full_name;
201 /// Base representation for members. This is used to keep track
202 /// of Name, Location and Modifier flags, and handling Attributes.
204 public abstract class MemberCore : Attributable {
210 return MemberName.GetName (!(this is GenericMethod) && !(this is Method));
214 public readonly MemberName MemberName;
217 /// Modifier flags that the user specified in the source code
221 public readonly TypeContainer Parent;
224 /// Location where this declaration happens
226 public readonly Location Location;
230 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
231 Obsolete = 1 << 1, // Type has obsolete attribute
232 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
233 ClsCompliant = 1 << 3, // Type is CLS Compliant
234 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
235 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
236 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
237 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
238 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
239 Excluded = 1 << 9, // Method is conditional
240 TestMethodDuplication = 1 << 10 // Test for duplication must be performed
244 /// MemberCore flags at first detected then cached
246 internal Flags caching_flags;
248 public MemberCore (TypeContainer parent, MemberName name, Attributes attrs,
255 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
259 /// Tests presence of ObsoleteAttribute and report proper error
261 protected void CheckUsageOfObsoleteAttribute (Type type)
266 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
267 if (obsolete_attr == null)
270 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
273 public abstract bool Define ();
276 // Returns full member name for error message
278 public virtual string GetSignatureForError ()
284 /// Use this method when MethodBuilder is null
286 public virtual string GetSignatureForError (TypeContainer tc)
292 /// Base Emit method. This is also entry point for CLS-Compliant verification.
294 public virtual void Emit ()
296 VerifyObsoleteAttribute ();
298 if (!RootContext.VerifyClsCompliance)
301 VerifyClsCompliance (Parent);
304 public bool InUnsafe {
306 return ((ModFlags & Modifiers.UNSAFE) != 0) || Parent.UnsafeContext;
311 // Whehter is it ok to use an unsafe pointer in this type container
313 public bool UnsafeOK (DeclSpace parent)
316 // First check if this MemberCore modifier flags has unsafe set
318 if ((ModFlags & Modifiers.UNSAFE) != 0)
321 if (parent.UnsafeContext)
324 Expression.UnsafeError (Location);
329 /// Returns instance of ObsoleteAttribute for this MemberCore
331 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
333 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
334 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
338 caching_flags &= ~Flags.Obsolete_Undetected;
340 if (OptAttributes == null)
343 Attribute obsolete_attr = OptAttributes.Search (
344 TypeManager.obsolete_attribute_type, ds.EmitContext);
345 if (obsolete_attr == null)
348 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
349 if (obsolete == null)
352 caching_flags |= Flags.Obsolete;
357 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
359 public override bool IsClsCompliaceRequired (DeclSpace container)
361 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
362 return (caching_flags & Flags.ClsCompliant) != 0;
364 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
365 caching_flags &= ~Flags.ClsCompliance_Undetected;
366 caching_flags |= Flags.ClsCompliant;
370 caching_flags &= ~Flags.ClsCompliance_Undetected;
375 /// Returns true when MemberCore is exposed from assembly.
377 protected bool IsExposedFromAssembly (DeclSpace ds)
379 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
382 DeclSpace parentContainer = ds;
383 while (parentContainer != null && parentContainer.ModFlags != 0) {
384 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
386 parentContainer = parentContainer.Parent;
392 /// Resolve CLSCompliantAttribute value or gets cached value.
394 bool GetClsCompliantAttributeValue (DeclSpace ds)
396 if (OptAttributes != null) {
397 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ds.EmitContext);
398 if (cls_attribute != null) {
399 caching_flags |= Flags.HasClsCompliantAttribute;
400 return cls_attribute.GetClsCompliantAttributeValue (ds);
403 return ds.GetClsCompliantAttributeValue ();
407 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
409 protected bool HasClsCompliantAttribute {
411 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
416 /// The main virtual method for CLS-Compliant verifications.
417 /// The method returns true if member is CLS-Compliant and false if member is not
418 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
419 /// and add their extra verifications.
421 protected virtual bool VerifyClsCompliance (DeclSpace ds)
423 if (!IsClsCompliaceRequired (ds)) {
424 if ((RootContext.WarningLevel >= 2) && HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
425 Report.Warning (3019, Location, "CLS compliance checking will not be performed on '{0}' because it is private or internal", GetSignatureForError ());
430 if (!CodeGen.Assembly.IsClsCompliant) {
431 if (HasClsCompliantAttribute) {
432 Report.Error (3014, Location, "'{0}' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute", GetSignatureForError ());
437 int index = Name.LastIndexOf ('.');
438 if (Name [index > 0 ? index + 1 : 0] == '_') {
439 Report.Error (3008, Location, "Identifier '{0}' is not CLS-compliant", GetSignatureForError () );
444 protected abstract void VerifyObsoleteAttribute ();
449 /// Base class for structs, classes, enumerations and interfaces.
452 /// They all create new declaration spaces. This
453 /// provides the common foundation for managing those name
456 public abstract class DeclSpace : MemberCore, IAlias {
458 /// This points to the actual definition that is being
459 /// created with System.Reflection.Emit
461 public TypeBuilder TypeBuilder;
464 /// If we are a generic type, this is the type we are
465 /// currently defining. We need to lookup members on this
466 /// instead of the TypeBuilder.
468 public Type CurrentType;
471 // This is the namespace in which this typecontainer
472 // was declared. We use this to resolve names.
474 public NamespaceEntry NamespaceEntry;
476 public Hashtable Cache = new Hashtable ();
478 public string Basename;
480 protected Hashtable defined_names;
482 readonly bool is_generic;
483 readonly int count_type_params;
485 // The emit context for toplevel objects.
486 protected EmitContext ec;
488 public EmitContext EmitContext {
493 // Whether we are Generic
495 public bool IsGeneric {
499 else if (Parent != null)
500 return Parent.IsGeneric;
506 static string[] attribute_targets = new string [] { "type" };
508 public DeclSpace (NamespaceEntry ns, TypeContainer parent, MemberName name,
509 Attributes attrs, Location l)
510 : base (parent, name, attrs, l)
513 Basename = name.Name;
514 defined_names = new Hashtable ();
515 if (name.TypeArguments != null) {
517 count_type_params = name.TypeArguments.Count;
520 count_type_params += parent.count_type_params;
524 /// Adds the member to defined_names table. It tests for duplications and enclosing name conflicts
526 protected bool AddToContainer (MemberCore symbol, bool is_method, string fullname, string basename)
528 if (basename == Basename && !(this is Interface)) {
529 Report.SymbolRelatedToPreviousError (this);
530 Report.Error (542, "'{0}': member names cannot be the same as their enclosing type", symbol.Location, symbol.GetSignatureForError ());
534 MemberCore mc = (MemberCore)defined_names [fullname];
536 if (is_method && (mc is MethodCore || mc is IMethodData)) {
537 symbol.caching_flags |= Flags.TestMethodDuplication;
538 mc.caching_flags |= Flags.TestMethodDuplication;
543 Report.SymbolRelatedToPreviousError (mc);
544 Report.Error (102, symbol.Location, "The type '{0}' already contains a definition for '{1}'", GetSignatureForError (), basename);
548 defined_names.Add (fullname, symbol);
552 public void RecordDecl ()
554 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
555 NamespaceEntry.DefineName (MemberName.Basename, this);
559 /// Returns the MemberCore associated with a given name in the declaration
560 /// space. It doesn't return method based symbols !!
563 public MemberCore GetDefinition (string name)
565 return (MemberCore)defined_names [name];
568 bool in_transit = false;
571 /// This function is used to catch recursive definitions
574 public bool InTransit {
585 /// Looks up the alias for the name
587 public IAlias LookupAlias (string name)
589 if (NamespaceEntry != null)
590 return NamespaceEntry.LookupAlias (name);
596 // root_types contains all the types. All TopLevel types
597 // hence have a parent that points to `root_types', that is
598 // why there is a non-obvious test down here.
600 public bool IsTopLevel {
603 if (Parent.Parent == null)
610 public virtual void CloseType ()
612 if ((caching_flags & Flags.CloseTypeCreated) == 0){
614 TypeBuilder.CreateType ();
617 // The try/catch is needed because
618 // nested enumerations fail to load when they
621 // Even if this is the right order (enumerations
622 // declared after types).
624 // Note that this still creates the type and
625 // it is possible to save it
627 caching_flags |= Flags.CloseTypeCreated;
632 /// Should be overriten by the appropriate declaration space
634 public abstract TypeBuilder DefineType ();
637 /// Define all members, but don't apply any attributes or do anything which may
638 /// access not-yet-defined classes. This method also creates the MemberCache.
640 public abstract bool DefineMembers (TypeContainer parent);
643 // Whether this is an `unsafe context'
645 public bool UnsafeContext {
647 if ((ModFlags & Modifiers.UNSAFE) != 0)
650 return Parent.UnsafeContext;
655 public static string MakeFQN (string nsn, string name)
659 return String.Concat (nsn, ".", name);
662 EmitContext type_resolve_ec;
663 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
665 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
666 type_resolve_ec.ResolvingTypeTree = true;
668 return type_resolve_ec;
671 public Type ResolveNestedType (Type t, Location loc)
673 TypeContainer tc = TypeManager.LookupTypeContainer (t);
674 if ((tc != null) && tc.IsGeneric) {
676 int tnum = TypeManager.GetNumberOfTypeArguments (t);
677 Report.Error (305, loc,
678 "Using the generic type `{0}' " +
679 "requires {1} type arguments",
680 TypeManager.GetFullName (t), tnum);
684 TypeParameter[] args;
685 if (this is GenericMethod)
686 args = Parent.TypeParameters;
688 args = TypeParameters;
690 TypeExpr ctype = new ConstructedType (t, args, loc);
691 ctype = ctype.ResolveAsTypeTerminal (ec);
702 // Resolves the expression `e' for a type, and will recursively define
703 // types. This should only be used for resolving base types.
705 public TypeExpr ResolveTypeExpr (Expression e, Location loc)
707 if (type_resolve_ec == null)
708 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
709 type_resolve_ec.loc = loc;
710 if (this is GenericMethod)
711 type_resolve_ec.ContainerType = Parent.TypeBuilder;
713 type_resolve_ec.ContainerType = TypeBuilder;
715 return e.ResolveAsTypeTerminal (type_resolve_ec);
718 public bool CheckAccessLevel (Type check_type)
721 if ((this is GenericMethod) || (this is Iterator))
722 tb = Parent.TypeBuilder;
726 if (check_type.IsGenericInstance)
727 check_type = check_type.GetGenericTypeDefinition ();
729 if (check_type == tb)
732 if (check_type.IsGenericParameter)
733 return true; // FIXME
735 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
738 // Broken Microsoft runtime, return public for arrays, no matter what
739 // the accessibility is for their underlying class, and they return
740 // NonPublic visibility for pointers
742 if (check_type.IsArray || check_type.IsPointer)
743 return CheckAccessLevel (TypeManager.GetElementType (check_type));
746 case TypeAttributes.Public:
749 case TypeAttributes.NotPublic:
751 if (TypeBuilder == null)
752 // FIXME: TypeBuilder will be null when invoked by Class.GetNormalBases().
753 // However, this is invoked again later -- so safe to return true.
754 // May also be null when resolving top-level attributes.
757 // This test should probably use the declaringtype.
759 return check_type.Assembly == TypeBuilder.Assembly;
761 case TypeAttributes.NestedPublic:
764 case TypeAttributes.NestedPrivate:
765 return NestedAccessible (tb, check_type);
767 case TypeAttributes.NestedFamily:
769 // Only accessible to methods in current type or any subtypes
771 return FamilyAccessible (tb, check_type);
773 case TypeAttributes.NestedFamANDAssem:
774 return (check_type.Assembly == tb.Assembly) &&
775 FamilyAccessible (tb, check_type);
777 case TypeAttributes.NestedFamORAssem:
778 return (check_type.Assembly == tb.Assembly) ||
779 FamilyAccessible (tb, check_type);
781 case TypeAttributes.NestedAssembly:
782 return check_type.Assembly == tb.Assembly;
785 Console.WriteLine ("HERE: " + check_attr);
790 protected bool NestedAccessible (Type tb, Type check_type)
792 string check_type_name = check_type.FullName;
794 // At this point, we already know check_type is a nested class.
795 int cio = check_type_name.LastIndexOf ('+');
797 // Ensure that the string 'container' has a '+' in it to avoid false matches
798 string container = check_type_name.Substring (0, cio + 1);
800 // Ensure that type_name ends with a '+' so that it can match 'container', if necessary
801 string type_name = tb.FullName + "+";
803 // If the current class is nested inside the container of check_type,
804 // we can access check_type even if it is private or protected.
805 return type_name.StartsWith (container);
808 protected bool FamilyAccessible (Type tb, Type check_type)
810 Type declaring = check_type.DeclaringType;
811 if (tb == declaring || TypeManager.IsFamilyAccessible (tb, declaring))
814 return NestedAccessible (tb, check_type);
817 // Access level of a type.
819 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
820 // Public Assembly Protected
821 Protected = (0 << 0) | (0 << 1) | (X << 2),
822 Public = (X << 0) | (X << 1) | (X << 2),
823 Private = (0 << 0) | (0 << 1) | (0 << 2),
824 Internal = (0 << 0) | (X << 1) | (0 << 2),
825 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
828 static AccessLevel GetAccessLevelFromModifiers (int flags)
830 if ((flags & Modifiers.INTERNAL) != 0) {
832 if ((flags & Modifiers.PROTECTED) != 0)
833 return AccessLevel.ProtectedOrInternal;
835 return AccessLevel.Internal;
837 } else if ((flags & Modifiers.PROTECTED) != 0)
838 return AccessLevel.Protected;
839 else if ((flags & Modifiers.PRIVATE) != 0)
840 return AccessLevel.Private;
842 return AccessLevel.Public;
845 // What is the effective access level of this?
847 AccessLevel EffectiveAccessLevel {
849 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
850 if (!IsTopLevel && (Parent != null))
851 return myAccess & Parent.EffectiveAccessLevel;
856 // Return the access level for type `t'
857 static AccessLevel TypeEffectiveAccessLevel (Type t)
860 return AccessLevel.Public;
861 if (t.IsNestedPrivate)
862 return AccessLevel.Private;
864 return AccessLevel.Internal;
866 // By now, it must be nested
867 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
869 if (t.IsNestedPublic)
871 if (t.IsNestedAssembly)
872 return parentLevel & AccessLevel.Internal;
873 if (t.IsNestedFamily)
874 return parentLevel & AccessLevel.Protected;
875 if (t.IsNestedFamORAssem)
876 return parentLevel & AccessLevel.ProtectedOrInternal;
877 if (t.IsNestedFamANDAssem)
878 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
880 // nested private is taken care of
882 throw new Exception ("I give up, what are you?");
886 // This answers `is the type P, as accessible as a member M which has the
887 // accessability @flags which is declared as a nested member of the type T, this declspace'
889 public bool AsAccessible (Type p, int flags)
891 if (p.IsGenericParameter)
892 return true; // FIXME
895 // 1) if M is private, its accessability is the same as this declspace.
896 // we already know that P is accessible to T before this method, so we
900 if ((flags & Modifiers.PRIVATE) != 0)
903 while (p.IsArray || p.IsPointer || p.IsByRef)
904 p = TypeManager.GetElementType (p);
906 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
907 AccessLevel mAccess = this.EffectiveAccessLevel &
908 GetAccessLevelFromModifiers (flags);
910 // for every place from which we can access M, we must
911 // be able to access P as well. So, we want
912 // For every bit in M and P, M_i -> P_1 == true
913 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
915 return ~ (~ mAccess | pAccess) == 0;
918 static DoubleHash dh = new DoubleHash (1000);
920 Type DefineTypeAndParents (DeclSpace tc)
922 DeclSpace container = tc.Parent;
924 if (container.TypeBuilder == null && container.Name != "")
925 DefineTypeAndParents (container);
927 return tc.DefineType ();
930 Type LookupInterfaceOrClass (string ns, string name, out bool error)
938 if (dh.Lookup (ns, name, out r))
942 if (Namespace.IsNamespace (ns)){
943 string fullname = (ns != "") ? ns + "." + name : name;
944 t = TypeManager.LookupType (fullname);
948 t = TypeManager.LookupType (name);
952 dh.Insert (ns, name, t);
957 // In case we are fed a composite name, normalize it.
959 int p = name.LastIndexOf ('.');
961 ns = MakeFQN (ns, name.Substring (0, p));
962 name = name.Substring (p+1);
965 parent = RootContext.Tree.LookupByNamespace (ns, name);
966 if (parent == null) {
967 dh.Insert (ns, name, null);
971 t = DefineTypeAndParents (parent);
977 dh.Insert (ns, name, t);
981 public static void Error_AmbiguousTypeReference (Location loc, string name, string t1, string t2)
983 Report.Error (104, loc,
984 "`{0}' is an ambiguous reference ({1} or {2})",
988 public Type FindNestedType (Location loc, string name,
989 out DeclSpace containing_ds)
994 containing_ds = this;
995 while (containing_ds != null){
996 Type container_type = containing_ds.TypeBuilder;
997 Type current_type = container_type;
999 while (current_type != null && current_type != TypeManager.object_type) {
1000 string pre = current_type.FullName;
1002 t = LookupInterfaceOrClass (pre, name, out error);
1006 if ((t != null) && containing_ds.CheckAccessLevel (t))
1009 current_type = current_type.BaseType;
1011 containing_ds = containing_ds.Parent;
1018 /// GetType is used to resolve type names at the DeclSpace level.
1019 /// Use this to lookup class/struct bases, interface bases or
1020 /// delegate type references
1024 /// Contrast this to LookupType which is used inside method bodies to
1025 /// lookup types that have already been defined. GetType is used
1026 /// during the tree resolution process and potentially define
1027 /// recursively the type
1029 public Type FindType (Location loc, string name)
1035 // For the case the type we are looking for is nested within this one
1036 // or is in any base class
1038 DeclSpace containing_ds = this;
1040 while (containing_ds != null){
1041 Type container_type = containing_ds.TypeBuilder;
1042 Type current_type = container_type;
1044 while (current_type != null && current_type != TypeManager.object_type) {
1045 string pre = current_type.FullName;
1047 t = LookupInterfaceOrClass (pre, name, out error);
1051 if ((t != null) && containing_ds.CheckAccessLevel (t))
1052 return ResolveNestedType (t, loc);
1054 current_type = current_type.BaseType;
1056 containing_ds = containing_ds.Parent;
1060 // Attempt to lookup the class on our namespace and all it's implicit parents
1062 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
1063 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1072 // Attempt to do a direct unqualified lookup
1074 t = LookupInterfaceOrClass ("", name, out error);
1082 // Attempt to lookup the class on any of the `using'
1086 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
1088 t = LookupInterfaceOrClass (ns.FullName, name, out error);
1095 if (name.IndexOf ('.') > 0)
1098 IAlias alias_value = ns.LookupAlias (name);
1099 if (alias_value != null) {
1100 t = LookupInterfaceOrClass ("", alias_value.Name, out error);
1109 // Now check the using clause list
1112 foreach (Namespace using_ns in ns.GetUsingTable ()) {
1113 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
1117 if (match != null) {
1119 if (CheckAccessLevel (match)) {
1120 Error_AmbiguousTypeReference (loc, name, t.FullName, match.FullName);
1133 //Report.Error (246, Location, "Can not find type `"+name+"'");
1138 /// This function is broken and not what you're looking for. It should only
1139 /// be used while the type is still being created since it doesn't use the cache
1140 /// and relies on the filter doing the member name check.
1142 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1143 MemberFilter filter, object criteria);
1146 /// If we have a MemberCache, return it. This property may return null if the
1147 /// class doesn't have a member cache or while it's still being created.
1149 public abstract MemberCache MemberCache {
1153 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1156 TypeBuilder.SetCustomAttribute (cb);
1157 } catch (System.ArgumentException e) {
1158 Report.Warning (-21, a.Location,
1159 "The CharSet named property on StructLayout\n"+
1160 "\tdoes not work correctly on Microsoft.NET\n"+
1161 "\tYou might want to remove the CharSet declaration\n"+
1162 "\tor compile using the Mono runtime instead of the\n"+
1163 "\tMicrosoft .NET runtime\n"+
1164 "\tThe runtime gave the error: " + e);
1169 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1170 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1172 public bool GetClsCompliantAttributeValue ()
1174 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1175 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1177 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1179 if (OptAttributes != null) {
1180 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1181 if (cls_attribute != null) {
1182 caching_flags |= Flags.HasClsCompliantAttribute;
1183 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1184 caching_flags |= Flags.ClsCompliantAttributeTrue;
1191 if (Parent == null) {
1192 if (CodeGen.Assembly.IsClsCompliant) {
1193 caching_flags |= Flags.ClsCompliantAttributeTrue;
1199 if (Parent.GetClsCompliantAttributeValue ()) {
1200 caching_flags |= Flags.ClsCompliantAttributeTrue;
1207 // Extensions for generics
1209 TypeParameter[] type_params;
1210 TypeParameter[] type_param_list;
1212 protected string GetInstantiationName ()
1214 StringBuilder sb = new StringBuilder (Name);
1216 for (int i = 0; i < type_param_list.Length; i++) {
1219 sb.Append (type_param_list [i].Name);
1222 return sb.ToString ();
1225 bool check_type_parameter (ArrayList list, int start, string name)
1227 for (int i = 0; i < start; i++) {
1228 TypeParameter param = (TypeParameter) list [i];
1230 if (param.Name != name)
1233 if (RootContext.WarningLevel >= 3)
1236 "Type parameter `{0}' has same name " +
1237 "as type parameter from outer type `{1}'",
1238 name, Parent.GetInstantiationName ());
1246 TypeParameter[] initialize_type_params ()
1248 if (type_param_list != null)
1249 return type_param_list;
1251 DeclSpace the_parent = Parent;
1252 if (this is GenericMethod)
1256 TypeParameter[] parent_params = null;
1257 if ((the_parent != null) && the_parent.IsGeneric) {
1258 parent_params = the_parent.initialize_type_params ();
1259 start = parent_params != null ? parent_params.Length : 0;
1262 ArrayList list = new ArrayList ();
1263 if (parent_params != null)
1264 list.AddRange (parent_params);
1266 int count = type_params != null ? type_params.Length : 0;
1267 for (int i = 0; i < count; i++) {
1268 TypeParameter param = type_params [i];
1269 check_type_parameter (list, start, param.Name);
1273 type_param_list = new TypeParameter [list.Count];
1274 list.CopyTo (type_param_list, 0);
1275 return type_param_list;
1278 public void SetParameterInfo (ArrayList constraints_list)
1281 if (constraints_list != null) {
1283 80, Location, "Contraints are not allowed " +
1284 "on non-generic declarations");
1290 string[] names = MemberName.TypeArguments.GetDeclarations ();
1291 type_params = new TypeParameter [names.Length];
1294 // Register all the names
1296 for (int i = 0; i < type_params.Length; i++) {
1297 string name = names [i];
1299 Constraints constraints = null;
1300 if (constraints_list != null) {
1301 foreach (Constraints constraint in constraints_list) {
1302 if (constraint.TypeParameter == name) {
1303 constraints = constraint;
1309 type_params [i] = new TypeParameter (Parent, name, constraints, Location);
1311 string full_name = Name + "." + name;
1312 AddToContainer (type_params [i], false, full_name, name);
1316 public TypeParameter[] TypeParameters {
1319 throw new InvalidOperationException ();
1320 if (type_param_list == null)
1321 initialize_type_params ();
1323 return type_param_list;
1327 protected TypeParameter[] CurrentTypeParameters {
1330 throw new InvalidOperationException ();
1331 if (type_params != null)
1334 return new TypeParameter [0];
1338 public int CountTypeParameters {
1340 return count_type_params;
1344 public TypeParameterExpr LookupGeneric (string name, Location loc)
1349 foreach (TypeParameter type_param in CurrentTypeParameters) {
1350 if (type_param.Name != name)
1353 return new TypeParameterExpr (type_param, loc);
1357 return Parent.LookupGeneric (name, loc);
1362 bool IAlias.IsType {
1363 get { return true; }
1366 string IAlias.Name {
1367 get { return Name; }
1370 TypeExpr IAlias.ResolveAsType (EmitContext ec)
1372 if (TypeBuilder == null)
1373 throw new InvalidOperationException ();
1375 if (CurrentType != null)
1376 return new TypeExpression (CurrentType, Location);
1378 return new TypeExpression (TypeBuilder, Location);
1381 public override string[] ValidAttributeTargets {
1383 return attribute_targets;
1389 /// This is a readonly list of MemberInfo's.
1391 public class MemberList : IList {
1392 public readonly IList List;
1396 /// Create a new MemberList from the given IList.
1398 public MemberList (IList list)
1403 this.List = new ArrayList ();
1408 /// Concatenate the ILists `first' and `second' to a new MemberList.
1410 public MemberList (IList first, IList second)
1412 ArrayList list = new ArrayList ();
1413 list.AddRange (first);
1414 list.AddRange (second);
1419 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1422 /// Cast the MemberList into a MemberInfo[] array.
1425 /// This is an expensive operation, only use it if it's really necessary.
1427 public static explicit operator MemberInfo [] (MemberList list)
1429 Timer.StartTimer (TimerType.MiscTimer);
1430 MemberInfo [] result = new MemberInfo [list.Count];
1431 list.CopyTo (result, 0);
1432 Timer.StopTimer (TimerType.MiscTimer);
1444 public bool IsSynchronized {
1446 return List.IsSynchronized;
1450 public object SyncRoot {
1452 return List.SyncRoot;
1456 public void CopyTo (Array array, int index)
1458 List.CopyTo (array, index);
1463 public IEnumerator GetEnumerator ()
1465 return List.GetEnumerator ();
1470 public bool IsFixedSize {
1476 public bool IsReadOnly {
1482 object IList.this [int index] {
1484 return List [index];
1488 throw new NotSupportedException ();
1492 // FIXME: try to find out whether we can avoid the cast in this indexer.
1493 public MemberInfo this [int index] {
1495 return (MemberInfo) List [index];
1499 public int Add (object value)
1501 throw new NotSupportedException ();
1504 public void Clear ()
1506 throw new NotSupportedException ();
1509 public bool Contains (object value)
1511 return List.Contains (value);
1514 public int IndexOf (object value)
1516 return List.IndexOf (value);
1519 public void Insert (int index, object value)
1521 throw new NotSupportedException ();
1524 public void Remove (object value)
1526 throw new NotSupportedException ();
1529 public void RemoveAt (int index)
1531 throw new NotSupportedException ();
1536 /// This interface is used to get all members of a class when creating the
1537 /// member cache. It must be implemented by all DeclSpace derivatives which
1538 /// want to support the member cache and by TypeHandle to get caching of
1539 /// non-dynamic types.
1541 public interface IMemberContainer {
1543 /// The name of the IMemberContainer. This is only used for
1544 /// debugging purposes.
1551 /// The type of this IMemberContainer.
1558 /// Returns the IMemberContainer of the parent class or null if this
1559 /// is an interface or TypeManger.object_type.
1560 /// This is used when creating the member cache for a class to get all
1561 /// members from the parent class.
1563 MemberCache ParentCache {
1568 /// Whether this is an interface.
1575 /// Returns all members of this class with the corresponding MemberTypes
1576 /// and BindingFlags.
1579 /// When implementing this method, make sure not to return any inherited
1580 /// members and check the MemberTypes and BindingFlags properly.
1581 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1582 /// get the BindingFlags (static/non-static,public/non-public) in the
1583 /// MemberInfo class, but the cache needs this information. That's why
1584 /// this method is called multiple times with different BindingFlags.
1586 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1589 /// Return the container's member cache.
1591 MemberCache MemberCache {
1597 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1598 /// member lookups. It has a member name based hash table; it maps each member
1599 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1600 /// and the BindingFlags that were initially used to get it. The cache contains
1601 /// all members of the current class and all inherited members. If this cache is
1602 /// for an interface types, it also contains all inherited members.
1604 /// There are two ways to get a MemberCache:
1605 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1606 /// use the DeclSpace.MemberCache property.
1607 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1608 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1610 public class MemberCache {
1611 public readonly IMemberContainer Container;
1612 protected Hashtable member_hash;
1613 protected Hashtable method_hash;
1616 /// Create a new MemberCache for the given IMemberContainer `container'.
1618 public MemberCache (IMemberContainer container)
1620 this.Container = container;
1622 Timer.IncrementCounter (CounterType.MemberCache);
1623 Timer.StartTimer (TimerType.CacheInit);
1625 // If we have a parent class (we have a parent class unless we're
1626 // TypeManager.object_type), we deep-copy its MemberCache here.
1627 if (Container.ParentCache != null)
1628 member_hash = SetupCache (Container.ParentCache);
1630 member_hash = new Hashtable ();
1632 // If this is neither a dynamic type nor an interface, create a special
1633 // method cache with all declared and inherited methods.
1634 Type type = container.Type;
1635 if (!(type is TypeBuilder) && !type.IsInterface && !type.IsGenericParameter) {
1636 method_hash = new Hashtable ();
1640 // Add all members from the current class.
1641 AddMembers (Container);
1643 Timer.StopTimer (TimerType.CacheInit);
1646 public MemberCache (Type[] ifaces)
1649 // The members of this cache all belong to other caches.
1650 // So, 'Container' will not be used.
1652 this.Container = null;
1654 member_hash = new Hashtable ();
1658 foreach (Type itype in ifaces)
1659 AddCacheContents (TypeManager.LookupMemberCache (itype));
1663 /// Bootstrap this member cache by doing a deep-copy of our parent.
1665 Hashtable SetupCache (MemberCache parent)
1667 Hashtable hash = new Hashtable ();
1672 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1673 while (it.MoveNext ()) {
1674 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1681 /// Add the contents of `cache' to the member_hash.
1683 void AddCacheContents (MemberCache cache)
1685 IDictionaryEnumerator it = cache.member_hash.GetEnumerator ();
1686 while (it.MoveNext ()) {
1687 ArrayList list = (ArrayList) member_hash [it.Key];
1689 member_hash [it.Key] = list = new ArrayList ();
1691 ArrayList entries = (ArrayList) it.Value;
1692 for (int i = entries.Count-1; i >= 0; i--) {
1693 CacheEntry entry = (CacheEntry) entries [i];
1695 if (entry.Container != cache.Container)
1703 /// Add all members from class `container' to the cache.
1705 void AddMembers (IMemberContainer container)
1707 // We need to call AddMembers() with a single member type at a time
1708 // to get the member type part of CacheEntry.EntryType right.
1709 if (!container.IsInterface) {
1710 AddMembers (MemberTypes.Constructor, container);
1711 AddMembers (MemberTypes.Field, container);
1713 AddMembers (MemberTypes.Method, container);
1714 AddMembers (MemberTypes.Property, container);
1715 AddMembers (MemberTypes.Event, container);
1716 // Nested types are returned by both Static and Instance searches.
1717 AddMembers (MemberTypes.NestedType,
1718 BindingFlags.Static | BindingFlags.Public, container);
1719 AddMembers (MemberTypes.NestedType,
1720 BindingFlags.Static | BindingFlags.NonPublic, container);
1723 void AddMembers (MemberTypes mt, IMemberContainer container)
1725 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1726 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1727 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1728 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1732 /// Add all members from class `container' with the requested MemberTypes and
1733 /// BindingFlags to the cache. This method is called multiple times with different
1734 /// MemberTypes and BindingFlags.
1736 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1738 MemberList members = container.GetMembers (mt, bf);
1740 foreach (MemberInfo member in members) {
1741 string name = member.Name;
1743 int pos = name.IndexOf ('<');
1745 name = name.Substring (0, pos);
1747 // We use a name-based hash table of ArrayList's.
1748 ArrayList list = (ArrayList) member_hash [name];
1750 list = new ArrayList ();
1751 member_hash.Add (name, list);
1754 // When this method is called for the current class, the list will
1755 // already contain all inherited members from our parent classes.
1756 // We cannot add new members in front of the list since this'd be an
1757 // expensive operation, that's why the list is sorted in reverse order
1758 // (ie. members from the current class are coming last).
1759 list.Add (new CacheEntry (container, member, mt, bf));
1764 /// Add all declared and inherited methods from class `type' to the method cache.
1766 void AddMethods (Type type)
1768 AddMethods (BindingFlags.Static | BindingFlags.Public |
1769 BindingFlags.FlattenHierarchy, type);
1770 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1771 BindingFlags.FlattenHierarchy, type);
1772 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1773 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1776 void AddMethods (BindingFlags bf, Type type)
1778 MemberInfo [] members = type.GetMethods (bf);
1780 Array.Reverse (members);
1782 foreach (MethodBase member in members) {
1783 string name = member.Name;
1785 // We use a name-based hash table of ArrayList's.
1786 ArrayList list = (ArrayList) method_hash [name];
1788 list = new ArrayList ();
1789 method_hash.Add (name, list);
1792 // Unfortunately, the elements returned by Type.GetMethods() aren't
1793 // sorted so we need to do this check for every member.
1794 BindingFlags new_bf = bf;
1795 if (member.DeclaringType == type)
1796 new_bf |= BindingFlags.DeclaredOnly;
1798 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1803 /// Compute and return a appropriate `EntryType' magic number for the given
1804 /// MemberTypes and BindingFlags.
1806 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1808 EntryType type = EntryType.None;
1810 if ((mt & MemberTypes.Constructor) != 0)
1811 type |= EntryType.Constructor;
1812 if ((mt & MemberTypes.Event) != 0)
1813 type |= EntryType.Event;
1814 if ((mt & MemberTypes.Field) != 0)
1815 type |= EntryType.Field;
1816 if ((mt & MemberTypes.Method) != 0)
1817 type |= EntryType.Method;
1818 if ((mt & MemberTypes.Property) != 0)
1819 type |= EntryType.Property;
1820 // Nested types are returned by static and instance searches.
1821 if ((mt & MemberTypes.NestedType) != 0)
1822 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1824 if ((bf & BindingFlags.Instance) != 0)
1825 type |= EntryType.Instance;
1826 if ((bf & BindingFlags.Static) != 0)
1827 type |= EntryType.Static;
1828 if ((bf & BindingFlags.Public) != 0)
1829 type |= EntryType.Public;
1830 if ((bf & BindingFlags.NonPublic) != 0)
1831 type |= EntryType.NonPublic;
1832 if ((bf & BindingFlags.DeclaredOnly) != 0)
1833 type |= EntryType.Declared;
1839 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1840 /// denote multiple member types. Returns true if the given flags value denotes a
1841 /// single member types.
1843 public static bool IsSingleMemberType (MemberTypes mt)
1846 case MemberTypes.Constructor:
1847 case MemberTypes.Event:
1848 case MemberTypes.Field:
1849 case MemberTypes.Method:
1850 case MemberTypes.Property:
1851 case MemberTypes.NestedType:
1860 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1861 /// number to speed up the searching process.
1864 protected enum EntryType {
1869 MaskStatic = Instance|Static,
1873 MaskProtection = Public|NonPublic,
1877 Constructor = 0x020,
1884 MaskType = Constructor|Event|Field|Method|Property|NestedType
1887 protected struct CacheEntry {
1888 public readonly IMemberContainer Container;
1889 public readonly EntryType EntryType;
1890 public readonly MemberInfo Member;
1892 public CacheEntry (IMemberContainer container, MemberInfo member,
1893 MemberTypes mt, BindingFlags bf)
1895 this.Container = container;
1896 this.Member = member;
1897 this.EntryType = GetEntryType (mt, bf);
1900 public override string ToString ()
1902 return String.Format ("CacheEntry ({0}:{1}:{2})", Container.Name,
1908 /// This is called each time we're walking up one level in the class hierarchy
1909 /// and checks whether we can abort the search since we've already found what
1910 /// we were looking for.
1912 protected bool DoneSearching (ArrayList list)
1915 // We've found exactly one member in the current class and it's not
1916 // a method or constructor.
1918 if (list.Count == 1 && !(list [0] is MethodBase))
1922 // Multiple properties: we query those just to find out the indexer
1925 if ((list.Count > 0) && (list [0] is PropertyInfo))
1932 /// Looks up members with name `name'. If you provide an optional
1933 /// filter function, it'll only be called with members matching the
1934 /// requested member name.
1936 /// This method will try to use the cache to do the lookup if possible.
1938 /// Unlike other FindMembers implementations, this method will always
1939 /// check all inherited members - even when called on an interface type.
1941 /// If you know that you're only looking for methods, you should use
1942 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1943 /// When doing a method-only search, it'll try to use a special method
1944 /// cache (unless it's a dynamic type or an interface) and the returned
1945 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1946 /// The lookup process will automatically restart itself in method-only
1947 /// search mode if it discovers that it's about to return methods.
1949 ArrayList global = new ArrayList ();
1950 bool using_global = false;
1952 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1954 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1955 MemberFilter filter, object criteria)
1958 throw new Exception ();
1960 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1961 bool method_search = mt == MemberTypes.Method;
1962 // If we have a method cache and we aren't already doing a method-only search,
1963 // then we restart a method search if the first match is a method.
1964 bool do_method_search = !method_search && (method_hash != null);
1966 ArrayList applicable;
1968 // If this is a method-only search, we try to use the method cache if
1969 // possible; a lookup in the method cache will return a MemberInfo with
1970 // the correct ReflectedType for inherited methods.
1972 if (method_search && (method_hash != null))
1973 applicable = (ArrayList) method_hash [name];
1975 applicable = (ArrayList) member_hash [name];
1977 if (applicable == null)
1978 return emptyMemberInfo;
1981 // 32 slots gives 53 rss/54 size
1982 // 2/4 slots gives 55 rss
1984 // Strange: from 25,000 calls, only 1,800
1985 // are above 2. Why does this impact it?
1988 using_global = true;
1990 Timer.StartTimer (TimerType.CachedLookup);
1992 EntryType type = GetEntryType (mt, bf);
1994 IMemberContainer current = Container;
1997 // `applicable' is a list of all members with the given member name `name'
1998 // in the current class and all its parent classes. The list is sorted in
1999 // reverse order due to the way how the cache is initialy created (to speed
2000 // things up, we're doing a deep-copy of our parent).
2002 for (int i = applicable.Count-1; i >= 0; i--) {
2003 CacheEntry entry = (CacheEntry) applicable [i];
2005 // This happens each time we're walking one level up in the class
2006 // hierarchy. If we're doing a DeclaredOnly search, we must abort
2007 // the first time this happens (this may already happen in the first
2008 // iteration of this loop if there are no members with the name we're
2009 // looking for in the current class).
2010 if (entry.Container != current) {
2011 if (declared_only || DoneSearching (global))
2014 current = entry.Container;
2017 // Is the member of the correct type ?
2018 if ((entry.EntryType & type & EntryType.MaskType) == 0)
2021 // Is the member static/non-static ?
2022 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
2025 // Apply the filter to it.
2026 if (filter (entry.Member, criteria)) {
2027 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
2028 do_method_search = false;
2029 global.Add (entry.Member);
2033 Timer.StopTimer (TimerType.CachedLookup);
2035 // If we have a method cache and we aren't already doing a method-only
2036 // search, we restart in method-only search mode if the first match is
2037 // a method. This ensures that we return a MemberInfo with the correct
2038 // ReflectedType for inherited methods.
2039 if (do_method_search && (global.Count > 0)){
2040 using_global = false;
2042 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
2045 using_global = false;
2046 MemberInfo [] copy = new MemberInfo [global.Count];
2047 global.CopyTo (copy);
2052 // This finds the method or property for us to override. invocationType is the type where
2053 // the override is going to be declared, name is the name of the method/property, and
2054 // paramTypes is the parameters, if any to the method or property
2056 // Because the MemberCache holds members from this class and all the base classes,
2057 // we can avoid tons of reflection stuff.
2059 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
2061 ArrayList applicable;
2062 if (method_hash != null && !is_property)
2063 applicable = (ArrayList) method_hash [name];
2065 applicable = (ArrayList) member_hash [name];
2067 if (applicable == null)
2070 // Walk the chain of methods, starting from the top.
2072 for (int i = applicable.Count - 1; i >= 0; i--) {
2073 CacheEntry entry = (CacheEntry) applicable [i];
2075 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
2078 PropertyInfo pi = null;
2079 MethodInfo mi = null;
2080 FieldInfo fi = null;
2081 Type [] cmpAttrs = null;
2084 if ((entry.EntryType & EntryType.Field) != 0) {
2085 fi = (FieldInfo)entry.Member;
2087 // TODO: For this case we ignore member type
2088 //fb = TypeManager.GetField (fi);
2089 //cmpAttrs = new Type[] { fb.MemberType };
2091 pi = (PropertyInfo) entry.Member;
2092 cmpAttrs = TypeManager.GetArgumentTypes (pi);
2095 mi = (MethodInfo) entry.Member;
2096 cmpAttrs = TypeManager.GetArgumentTypes (mi);
2100 // TODO: Almost duplicate !
2102 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
2103 case FieldAttributes.Private:
2105 // A private method is Ok if we are a nested subtype.
2106 // The spec actually is not very clear about this, see bug 52458.
2108 if (invocationType != entry.Container.Type &
2109 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2113 case FieldAttributes.FamANDAssem:
2114 case FieldAttributes.Assembly:
2116 // Check for assembly methods
2118 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
2122 return entry.Member;
2126 // Check the arguments
2128 if (cmpAttrs.Length != paramTypes.Length)
2131 for (int j = cmpAttrs.Length - 1; j >= 0; j --) {
2132 if (!TypeManager.IsEqual (paramTypes [j], cmpAttrs [j]))
2137 // get one of the methods because this has the visibility info.
2140 mi = pi.GetGetMethod (true);
2142 mi = pi.GetSetMethod (true);
2148 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
2149 case MethodAttributes.Private:
2151 // A private method is Ok if we are a nested subtype.
2152 // The spec actually is not very clear about this, see bug 52458.
2154 if (invocationType.Equals (entry.Container.Type) ||
2155 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
2156 return entry.Member;
2159 case MethodAttributes.FamANDAssem:
2160 case MethodAttributes.Assembly:
2162 // Check for assembly methods
2164 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
2165 return entry.Member;
2170 // A protected method is ok, because we are overriding.
2171 // public is always ok.
2173 return entry.Member;
2183 /// The method is looking for conflict with inherited symbols (errors CS0108, CS0109).
2184 /// We handle two cases. The first is for types without parameters (events, field, properties).
2185 /// The second are methods, indexers and this is why ignore_complex_types is here.
2186 /// The latest param is temporary hack. See DoDefineMembers method for more info.
2188 public MemberInfo FindMemberWithSameName (string name, bool ignore_complex_types, MemberInfo ignore_member)
2190 ArrayList applicable = null;
2192 if (method_hash != null)
2193 applicable = (ArrayList) method_hash [name];
2195 if (applicable != null) {
2196 for (int i = applicable.Count - 1; i >= 0; i--) {
2197 CacheEntry entry = (CacheEntry) applicable [i];
2198 if ((entry.EntryType & EntryType.Public) != 0)
2199 return entry.Member;
2203 if (member_hash == null)
2205 applicable = (ArrayList) member_hash [name];
2207 if (applicable != null) {
2208 for (int i = applicable.Count - 1; i >= 0; i--) {
2209 CacheEntry entry = (CacheEntry) applicable [i];
2210 if ((entry.EntryType & EntryType.Public) != 0 & entry.Member != ignore_member) {
2211 if (ignore_complex_types) {
2212 if ((entry.EntryType & EntryType.Method) != 0)
2215 // Does exist easier way how to detect indexer ?
2216 if ((entry.EntryType & EntryType.Property) != 0) {
2217 Type[] arg_types = TypeManager.GetArgumentTypes ((PropertyInfo)entry.Member);
2218 if (arg_types.Length > 0)
2222 return entry.Member;
2229 Hashtable locase_table;
2232 /// Builds low-case table for CLS Compliance test
2234 public Hashtable GetPublicMembers ()
2236 if (locase_table != null)
2237 return locase_table;
2239 locase_table = new Hashtable ();
2240 foreach (DictionaryEntry entry in member_hash) {
2241 ArrayList members = (ArrayList)entry.Value;
2242 for (int ii = 0; ii < members.Count; ++ii) {
2243 CacheEntry member_entry = (CacheEntry) members [ii];
2245 if ((member_entry.EntryType & EntryType.Public) == 0)
2248 // TODO: Does anyone know easier way how to detect that member is internal ?
2249 switch (member_entry.EntryType & EntryType.MaskType) {
2250 case EntryType.Constructor:
2253 case EntryType.Field:
2254 if ((((FieldInfo)member_entry.Member).Attributes & (FieldAttributes.Assembly | FieldAttributes.Public)) == FieldAttributes.Assembly)
2258 case EntryType.Method:
2259 if ((((MethodInfo)member_entry.Member).Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2263 case EntryType.Property:
2264 PropertyInfo pi = (PropertyInfo)member_entry.Member;
2265 if (pi.GetSetMethod () == null && pi.GetGetMethod () == null)
2269 case EntryType.Event:
2270 EventInfo ei = (EventInfo)member_entry.Member;
2271 MethodInfo mi = ei.GetAddMethod ();
2272 if ((mi.Attributes & (MethodAttributes.Assembly | MethodAttributes.Public)) == MethodAttributes.Assembly)
2276 string lcase = ((string)entry.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture);
2277 locase_table [lcase] = member_entry.Member;
2281 return locase_table;
2284 public Hashtable Members {
2291 /// Cls compliance check whether methods or constructors parameters differing only in ref or out, or in array rank
2293 public void VerifyClsParameterConflict (ArrayList al, MethodCore method, MemberInfo this_builder)
2295 EntryType tested_type = (method is Constructor ? EntryType.Constructor : EntryType.Method) | EntryType.Public;
2297 for (int i = 0; i < al.Count; ++i) {
2298 MemberCache.CacheEntry entry = (MemberCache.CacheEntry) al [i];
2301 if (entry.Member == this_builder)
2304 if ((entry.EntryType & tested_type) != tested_type)
2307 MethodBase method_to_compare = (MethodBase)entry.Member;
2308 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (method.ParameterTypes, TypeManager.GetArgumentTypes (method_to_compare)))
2311 IMethodData md = TypeManager.GetMethod (method_to_compare);
2313 // TODO: now we are ignoring CLSCompliance(false) on method from other assembly which is buggy.
2314 // However it is exactly what csc does.
2315 if (md != null && !md.IsClsCompliaceRequired (method.Parent))
2318 Report.SymbolRelatedToPreviousError (entry.Member);
2319 Report.Error (3006, method.Location, "Overloaded method '{0}' differing only in ref or out, or in array rank, is not CLS-compliant", method.GetSignatureForError ());