2 // decl.cs: Declaration base class for structs, classes, enums and interfaces.
4 // Author: Miguel de Icaza (miguel@gnu.org)
6 // Licensed under the terms of the GNU GPL
8 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 // TODO: Move the method verification stuff from the class.cs and interface.cs here
14 using System.Collections;
15 using System.Globalization;
16 using System.Reflection.Emit;
17 using System.Reflection;
19 namespace Mono.CSharp {
22 /// Base representation for members. This is used to keep track
23 /// of Name, Location and Modifier flags, and handling Attributes.
25 public abstract class MemberCore : Attributable {
32 /// Modifier flags that the user specified in the source code
37 /// Location where this declaration happens
39 public readonly Location Location;
43 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
44 Obsolete = 1 << 1, // Type has obsolete attribute
45 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
46 ClsCompliant = 1 << 3, // Type is CLS Compliant
47 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
48 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
49 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
50 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
54 /// MemberCore flags at first detected then cached
56 protected Flags caching_flags;
58 public MemberCore (string name, Attributes attrs, Location loc)
63 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected;
66 public abstract bool Define (TypeContainer parent);
69 // Returns full member name for error message
71 public virtual string GetSignatureForError ()
77 /// Base Emit method. This is also entry point for CLS-Compliant verification.
79 public virtual void Emit (TypeContainer container)
81 if (!RootContext.VerifyClsCompliance)
84 VerifyClsCompliance (container);
88 // Whehter is it ok to use an unsafe pointer in this type container
90 public bool UnsafeOK (DeclSpace parent)
93 // First check if this MemberCore modifier flags has unsafe set
95 if ((ModFlags & Modifiers.UNSAFE) != 0)
98 if (parent.UnsafeContext)
101 Expression.UnsafeError (Location);
106 /// Returns instance of ObsoleteAttribute for this MemberCore
108 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
110 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
111 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
115 caching_flags &= ~Flags.Obsolete_Undetected;
117 if (OptAttributes == null)
120 // TODO: remove this allocation
121 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
122 null, null, ds.ModFlags, false);
124 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
125 if (obsolete_attr == null)
128 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
129 if (obsolete == null)
132 caching_flags |= Flags.Obsolete;
137 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
139 public override bool IsClsCompliaceRequired (DeclSpace container)
141 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
142 return (caching_flags & Flags.ClsCompliant) != 0;
144 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
145 caching_flags &= ~Flags.ClsCompliance_Undetected;
146 caching_flags |= Flags.ClsCompliant;
150 caching_flags &= ~Flags.ClsCompliance_Undetected;
155 /// Returns true when MemberCore is exposed from assembly.
157 protected bool IsExposedFromAssembly (DeclSpace ds)
159 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
162 DeclSpace parentContainer = ds;
163 while (parentContainer != null && parentContainer.ModFlags != 0) {
164 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
166 parentContainer = parentContainer.Parent;
172 /// Resolve CLSCompliantAttribute value or gets cached value.
174 bool GetClsCompliantAttributeValue (DeclSpace ds)
176 if (OptAttributes != null) {
177 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
178 null, null, ds.ModFlags, false);
179 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
180 if (cls_attribute != null) {
181 caching_flags |= Flags.HasClsCompliantAttribute;
182 return cls_attribute.GetClsCompliantAttributeValue (ds);
185 return ds.GetClsCompliantAttributeValue ();
189 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
191 protected bool HasClsCompliantAttribute {
193 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
198 /// This method is used to testing error 3005 (Method or parameter name collision).
200 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
203 /// Common helper method for identifier and parameters CLS-Compliant testing.
204 /// When return false error 3005 is reported. True means no violation.
205 /// And error 3006 tests are peformed here because of speed.
207 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
209 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
210 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
215 bool error3006 = false;
216 for (int i = 0; i < ml.Count; ++i) {
217 MemberInfo mi = ml [i];
218 if (name == mi.Name) {
219 MethodBase method = mi as MethodBase;
220 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
223 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
231 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
232 // because BindingFlags.Public returns internal types too
233 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
235 // Type is external, we can get attribute directly
236 if (temp_ds == null) {
237 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
238 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
241 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
243 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
244 if (!mc.IsClsCompliaceRequired (ds))
248 for (int ii = 0; ii < ml.Count; ++ii) {
252 Report.SymbolRelatedToPreviousError (mi);
256 Report.Error_T (3006, Location, GetSignatureForError ());
265 /// The main virtual method for CLS-Compliant verifications.
266 /// The method returns true if member is CLS-Compliant and false if member is not
267 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
268 /// and add their extra verifications.
270 protected virtual bool VerifyClsCompliance (DeclSpace ds)
272 if (!IsClsCompliaceRequired (ds)) {
273 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
274 Report.Warning_T (3019, Location, GetSignatureForError ());
279 if (!CodeGen.Assembly.IsClsCompliant) {
280 if (HasClsCompliantAttribute) {
281 Report.Error_T (3014, Location, GetSignatureForError ());
285 int index = Name.LastIndexOf ('.');
286 if (Name [index > 0 ? index + 1 : 0] == '_') {
287 Report.Error_T (3008, Location, GetSignatureForError () );
290 if (!IsIdentifierClsCompliant (ds)) {
291 Report.Error_T (3005, Location, GetSignatureForError ());
300 /// Base class for structs, classes, enumerations and interfaces.
303 /// They all create new declaration spaces. This
304 /// provides the common foundation for managing those name
307 public abstract class DeclSpace : MemberCore {
309 /// this points to the actual definition that is being
310 /// created with System.Reflection.Emit
312 public TypeBuilder TypeBuilder;
315 // This is the namespace in which this typecontainer
316 // was declared. We use this to resolve names.
318 public NamespaceEntry NamespaceEntry;
320 public Hashtable Cache = new Hashtable ();
322 public string Basename;
325 /// defined_names is used for toplevel objects
327 protected Hashtable defined_names;
329 TypeContainer parent;
331 static string[] attribute_targets = new string [] { "type" };
333 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
334 : base (name, attrs, l)
337 Basename = name.Substring (1 + name.LastIndexOf ('.'));
338 defined_names = new Hashtable ();
339 this.parent = parent;
342 public void RecordDecl ()
344 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
345 NamespaceEntry.DefineName (Basename, this);
349 /// The result value from adding an declaration into
350 /// a struct or a class
352 public enum AdditionResult {
354 /// The declaration has been successfully
355 /// added to the declation space.
360 /// The symbol has already been defined.
365 /// Returned if the declation being added to the
366 /// name space clashes with its container name.
368 /// The only exceptions for this are constructors
369 /// and static constructors
374 /// Returned if a constructor was created (because syntactically
375 /// it looked like a constructor) but was not (because the name
376 /// of the method is not the same as the container class
381 /// This is only used by static constructors to emit the
382 /// error 111, but this error for other things really
383 /// happens at another level for other functions.
388 /// Some other error.
394 /// Returns a status code based purely on the name
395 /// of the member being added
397 protected AdditionResult IsValid (string basename, string name)
399 if (basename == Basename)
400 return AdditionResult.EnclosingClash;
402 if (defined_names.Contains (name))
403 return AdditionResult.NameExists;
405 return AdditionResult.Success;
408 public static int length;
409 public static int small;
412 /// Introduce @name into this declaration space and
413 /// associates it with the object @o. Note that for
414 /// methods this will just point to the first method. o
416 public void DefineName (string name, object o)
418 defined_names.Add (name, o);
421 int p = name.LastIndexOf ('.');
429 /// Returns the object associated with a given name in the declaration
430 /// space. This is the inverse operation of `DefineName'
432 public object GetDefinition (string name)
434 return defined_names [name];
437 bool in_transit = false;
440 /// This function is used to catch recursive definitions
443 public bool InTransit {
453 public TypeContainer Parent {
460 /// Looks up the alias for the name
462 public string LookupAlias (string name)
464 if (NamespaceEntry != null)
465 return NamespaceEntry.LookupAlias (name);
471 // root_types contains all the types. All TopLevel types
472 // hence have a parent that points to `root_types', that is
473 // why there is a non-obvious test down here.
475 public bool IsTopLevel {
478 if (parent.parent == null)
485 public virtual void CloseType ()
487 if ((caching_flags & Flags.CloseTypeCreated) == 0){
489 TypeBuilder.CreateType ();
492 // The try/catch is needed because
493 // nested enumerations fail to load when they
496 // Even if this is the right order (enumerations
497 // declared after types).
499 // Note that this still creates the type and
500 // it is possible to save it
502 caching_flags |= Flags.CloseTypeCreated;
507 /// Should be overriten by the appropriate declaration space
509 public abstract TypeBuilder DefineType ();
512 /// Define all members, but don't apply any attributes or do anything which may
513 /// access not-yet-defined classes. This method also creates the MemberCache.
515 public abstract bool DefineMembers (TypeContainer parent);
518 // Whether this is an `unsafe context'
520 public bool UnsafeContext {
522 if ((ModFlags & Modifiers.UNSAFE) != 0)
525 return parent.UnsafeContext;
530 public static string MakeFQN (string nsn, string name)
534 return String.Concat (nsn, ".", name);
537 EmitContext type_resolve_ec;
538 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
540 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
541 type_resolve_ec.ResolvingTypeTree = true;
543 return type_resolve_ec;
547 // Looks up the type, as parsed into the expression `e'
549 public Type ResolveType (Expression e, bool silent, Location loc)
551 if (type_resolve_ec == null)
552 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
553 type_resolve_ec.loc = loc;
554 type_resolve_ec.ContainerType = TypeBuilder;
556 int errors = Report.Errors;
557 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
559 if (d == null || d.eclass != ExprClass.Type){
560 if (!silent && errors == Report.Errors){
561 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
566 if (!d.CheckAccessLevel (this)) {
567 Report.Error_T (122, loc, d.Name);
575 // Resolves the expression `e' for a type, and will recursively define
578 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
580 if (type_resolve_ec == null)
581 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
582 type_resolve_ec.loc = loc;
583 type_resolve_ec.ContainerType = TypeBuilder;
585 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
587 if (d == null || d.eclass != ExprClass.Type){
589 Report.Error (246, loc, "Cannot find type `"+ e +"'");
597 public bool CheckAccessLevel (Type check_type)
599 if (check_type == TypeBuilder)
602 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
605 // Broken Microsoft runtime, return public for arrays, no matter what
606 // the accessibility is for their underlying class, and they return
607 // NonPublic visibility for pointers
609 if (check_type.IsArray || check_type.IsPointer)
610 return CheckAccessLevel (TypeManager.GetElementType (check_type));
613 case TypeAttributes.Public:
616 case TypeAttributes.NotPublic:
618 // In same cases is null.
619 if (TypeBuilder == null)
623 // This test should probably use the declaringtype.
625 return check_type.Assembly == TypeBuilder.Assembly;
627 case TypeAttributes.NestedPublic:
630 case TypeAttributes.NestedPrivate:
631 string check_type_name = check_type.FullName;
632 string type_name = TypeBuilder.FullName;
634 int cio = check_type_name.LastIndexOf ('+');
635 string container = check_type_name.Substring (0, cio);
638 // Check if the check_type is a nested class of the current type
640 if (check_type_name.StartsWith (type_name + "+")){
644 if (type_name.StartsWith (container)){
650 case TypeAttributes.NestedFamily:
652 // Only accessible to methods in current type or any subtypes
654 return FamilyAccessible (check_type);
656 case TypeAttributes.NestedFamANDAssem:
657 return (check_type.Assembly == TypeBuilder.Assembly) &&
658 FamilyAccessible (check_type);
660 case TypeAttributes.NestedFamORAssem:
661 return (check_type.Assembly == TypeBuilder.Assembly) ||
662 FamilyAccessible (check_type);
664 case TypeAttributes.NestedAssembly:
665 return check_type.Assembly == TypeBuilder.Assembly;
668 Console.WriteLine ("HERE: " + check_attr);
673 protected bool FamilyAccessible (Type check_type)
675 Type declaring = check_type.DeclaringType;
676 if (TypeBuilder.IsSubclassOf (declaring))
679 string check_type_name = check_type.FullName;
681 int cio = check_type_name.LastIndexOf ('+');
682 string container = check_type_name.Substring (0, cio);
685 // Check if the check_type is a nested class of the current type
687 if (check_type_name.StartsWith (container + "+"))
693 // Access level of a type.
695 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
696 // Public Assembly Protected
697 Protected = (0 << 0) | (0 << 1) | (X << 2),
698 Public = (X << 0) | (X << 1) | (X << 2),
699 Private = (0 << 0) | (0 << 1) | (0 << 2),
700 Internal = (0 << 0) | (X << 1) | (0 << 2),
701 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
704 static AccessLevel GetAccessLevelFromModifiers (int flags)
706 if ((flags & Modifiers.INTERNAL) != 0) {
708 if ((flags & Modifiers.PROTECTED) != 0)
709 return AccessLevel.ProtectedOrInternal;
711 return AccessLevel.Internal;
713 } else if ((flags & Modifiers.PROTECTED) != 0)
714 return AccessLevel.Protected;
716 else if ((flags & Modifiers.PRIVATE) != 0)
717 return AccessLevel.Private;
720 return AccessLevel.Public;
723 // What is the effective access level of this?
725 AccessLevel EffectiveAccessLevel {
727 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
728 if (!IsTopLevel && (Parent != null))
729 return myAccess & Parent.EffectiveAccessLevel;
735 // Return the access level for type `t'
736 static AccessLevel TypeEffectiveAccessLevel (Type t)
739 return AccessLevel.Public;
740 if (t.IsNestedPrivate)
741 return AccessLevel.Private;
743 return AccessLevel.Internal;
745 // By now, it must be nested
746 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
748 if (t.IsNestedPublic)
750 if (t.IsNestedAssembly)
751 return parentLevel & AccessLevel.Internal;
752 if (t.IsNestedFamily)
753 return parentLevel & AccessLevel.Protected;
754 if (t.IsNestedFamORAssem)
755 return parentLevel & AccessLevel.ProtectedOrInternal;
756 if (t.IsNestedFamANDAssem)
757 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
759 // nested private is taken care of
761 throw new Exception ("I give up, what are you?");
765 // This answers `is the type P, as accessible as a member M which has the
766 // accessability @flags which is declared as a nested member of the type T, this declspace'
768 public bool AsAccessible (Type p, int flags)
771 // 1) if M is private, its accessability is the same as this declspace.
772 // we already know that P is accessible to T before this method, so we
776 if ((flags & Modifiers.PRIVATE) != 0)
779 while (p.IsArray || p.IsPointer || p.IsByRef)
780 p = TypeManager.GetElementType (p);
782 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
783 AccessLevel mAccess = this.EffectiveAccessLevel &
784 GetAccessLevelFromModifiers (flags);
786 // for every place from which we can access M, we must
787 // be able to access P as well. So, we want
788 // For every bit in M and P, M_i -> P_1 == true
789 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
791 return ~ (~ mAccess | pAccess) == 0;
794 static DoubleHash dh = new DoubleHash (1000);
796 Type DefineTypeAndParents (DeclSpace tc)
798 DeclSpace container = tc.Parent;
800 if (container.TypeBuilder == null && container.Name != "")
801 DefineTypeAndParents (container);
803 return tc.DefineType ();
806 Type LookupInterfaceOrClass (string ns, string name, out bool error)
814 if (dh.Lookup (ns, name, out r))
818 if (Namespace.IsNamespace (ns)){
819 string fullname = (ns != "") ? ns + "." + name : name;
820 t = TypeManager.LookupType (fullname);
824 t = TypeManager.LookupType (name);
828 dh.Insert (ns, name, t);
833 // In case we are fed a composite name, normalize it.
835 int p = name.LastIndexOf ('.');
837 ns = MakeFQN (ns, name.Substring (0, p));
838 name = name.Substring (p+1);
841 parent = RootContext.Tree.LookupByNamespace (ns, name);
842 if (parent == null) {
843 dh.Insert (ns, name, null);
847 t = DefineTypeAndParents (parent);
853 dh.Insert (ns, name, t);
857 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
859 Report.Error (104, loc,
860 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
861 t1.FullName, t2.FullName));
865 /// GetType is used to resolve type names at the DeclSpace level.
866 /// Use this to lookup class/struct bases, interface bases or
867 /// delegate type references
871 /// Contrast this to LookupType which is used inside method bodies to
872 /// lookup types that have already been defined. GetType is used
873 /// during the tree resolution process and potentially define
874 /// recursively the type
876 public Type FindType (Location loc, string name)
882 // For the case the type we are looking for is nested within this one
883 // or is in any base class
885 DeclSpace containing_ds = this;
887 while (containing_ds != null){
888 Type container_type = containing_ds.TypeBuilder;
889 Type current_type = container_type;
891 while (current_type != null && current_type != TypeManager.object_type) {
892 string pre = current_type.FullName;
894 t = LookupInterfaceOrClass (pre, name, out error);
898 if ((t != null) && containing_ds.CheckAccessLevel (t))
901 current_type = current_type.BaseType;
903 containing_ds = containing_ds.Parent;
907 // Attempt to lookup the class on our namespace and all it's implicit parents
909 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
910 t = LookupInterfaceOrClass (ns.FullName, name, out error);
919 // Attempt to do a direct unqualified lookup
921 t = LookupInterfaceOrClass ("", name, out error);
929 // Attempt to lookup the class on any of the `using'
933 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
935 t = LookupInterfaceOrClass (ns.FullName, name, out error);
942 if (name.IndexOf ('.') > 0)
945 string alias_value = ns.LookupAlias (name);
946 if (alias_value != null) {
947 t = LookupInterfaceOrClass ("", alias_value, out error);
956 // Now check the using clause list
959 foreach (Namespace using_ns in ns.GetUsingTable ()) {
960 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
966 if (CheckAccessLevel (match)) {
967 Error_AmbiguousTypeReference (loc, name, t, match);
980 //Report.Error (246, Location, "Can not find type `"+name+"'");
985 /// This function is broken and not what you're looking for. It should only
986 /// be used while the type is still being created since it doesn't use the cache
987 /// and relies on the filter doing the member name check.
989 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
990 MemberFilter filter, object criteria);
993 /// If we have a MemberCache, return it. This property may return null if the
994 /// class doesn't have a member cache or while it's still being created.
996 public abstract MemberCache MemberCache {
1000 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1003 TypeBuilder.SetCustomAttribute (cb);
1004 } catch (System.ArgumentException e) {
1005 Report.Warning (-21, a.Location,
1006 "The CharSet named property on StructLayout\n"+
1007 "\tdoes not work correctly on Microsoft.NET\n"+
1008 "\tYou might want to remove the CharSet declaration\n"+
1009 "\tor compile using the Mono runtime instead of the\n"+
1010 "\tMicrosoft .NET runtime\n"+
1011 "\tThe runtime gave the error: " + e);
1016 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1017 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1019 public bool GetClsCompliantAttributeValue ()
1021 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1022 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1024 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1026 if (OptAttributes != null) {
1027 EmitContext ec = new EmitContext (parent, this, Location,
1028 null, null, ModFlags, false);
1029 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1030 if (cls_attribute != null) {
1031 caching_flags |= Flags.HasClsCompliantAttribute;
1032 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1033 caching_flags |= Flags.ClsCompliantAttributeTrue;
1040 if (parent == null) {
1041 if (CodeGen.Assembly.IsClsCompliant) {
1042 caching_flags |= Flags.ClsCompliantAttributeTrue;
1048 if (parent.GetClsCompliantAttributeValue ()) {
1049 caching_flags |= Flags.ClsCompliantAttributeTrue;
1056 // Tests container name for CLS-Compliant name (differing only in case)
1057 // Possible optimalization: search in same namespace only
1058 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1060 int l = Name.Length;
1062 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1063 // Seek through all imported types
1064 foreach (string type_name in TypeManager.all_imported_types.Keys)
1066 if (l != type_name.Length)
1069 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1070 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1071 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1077 // Seek through generated types
1078 foreach (string name in RootContext.Tree.Decls.Keys) {
1079 if (l != name.Length)
1082 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1087 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1088 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1089 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1098 protected override string[] ValidAttributeTargets {
1100 return attribute_targets;
1106 /// This is a readonly list of MemberInfo's.
1108 public class MemberList : IList {
1109 public readonly IList List;
1113 /// Create a new MemberList from the given IList.
1115 public MemberList (IList list)
1120 this.List = new ArrayList ();
1125 /// Concatenate the ILists `first' and `second' to a new MemberList.
1127 public MemberList (IList first, IList second)
1129 ArrayList list = new ArrayList ();
1130 list.AddRange (first);
1131 list.AddRange (second);
1136 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1139 /// Cast the MemberList into a MemberInfo[] array.
1142 /// This is an expensive operation, only use it if it's really necessary.
1144 public static explicit operator MemberInfo [] (MemberList list)
1146 Timer.StartTimer (TimerType.MiscTimer);
1147 MemberInfo [] result = new MemberInfo [list.Count];
1148 list.CopyTo (result, 0);
1149 Timer.StopTimer (TimerType.MiscTimer);
1161 public bool IsSynchronized {
1163 return List.IsSynchronized;
1167 public object SyncRoot {
1169 return List.SyncRoot;
1173 public void CopyTo (Array array, int index)
1175 List.CopyTo (array, index);
1180 public IEnumerator GetEnumerator ()
1182 return List.GetEnumerator ();
1187 public bool IsFixedSize {
1193 public bool IsReadOnly {
1199 object IList.this [int index] {
1201 return List [index];
1205 throw new NotSupportedException ();
1209 // FIXME: try to find out whether we can avoid the cast in this indexer.
1210 public MemberInfo this [int index] {
1212 return (MemberInfo) List [index];
1216 public int Add (object value)
1218 throw new NotSupportedException ();
1221 public void Clear ()
1223 throw new NotSupportedException ();
1226 public bool Contains (object value)
1228 return List.Contains (value);
1231 public int IndexOf (object value)
1233 return List.IndexOf (value);
1236 public void Insert (int index, object value)
1238 throw new NotSupportedException ();
1241 public void Remove (object value)
1243 throw new NotSupportedException ();
1246 public void RemoveAt (int index)
1248 throw new NotSupportedException ();
1253 /// This interface is used to get all members of a class when creating the
1254 /// member cache. It must be implemented by all DeclSpace derivatives which
1255 /// want to support the member cache and by TypeHandle to get caching of
1256 /// non-dynamic types.
1258 public interface IMemberContainer {
1260 /// The name of the IMemberContainer. This is only used for
1261 /// debugging purposes.
1268 /// The type of this IMemberContainer.
1275 /// Returns the IMemberContainer of the parent class or null if this
1276 /// is an interface or TypeManger.object_type.
1277 /// This is used when creating the member cache for a class to get all
1278 /// members from the parent class.
1280 IMemberContainer Parent {
1285 /// Whether this is an interface.
1292 /// Returns all members of this class with the corresponding MemberTypes
1293 /// and BindingFlags.
1296 /// When implementing this method, make sure not to return any inherited
1297 /// members and check the MemberTypes and BindingFlags properly.
1298 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1299 /// get the BindingFlags (static/non-static,public/non-public) in the
1300 /// MemberInfo class, but the cache needs this information. That's why
1301 /// this method is called multiple times with different BindingFlags.
1303 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1306 /// Return the container's member cache.
1308 MemberCache MemberCache {
1314 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1315 /// member lookups. It has a member name based hash table; it maps each member
1316 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1317 /// and the BindingFlags that were initially used to get it. The cache contains
1318 /// all members of the current class and all inherited members. If this cache is
1319 /// for an interface types, it also contains all inherited members.
1321 /// There are two ways to get a MemberCache:
1322 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1323 /// use the DeclSpace.MemberCache property.
1324 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1325 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1327 public class MemberCache {
1328 public readonly IMemberContainer Container;
1329 protected Hashtable member_hash;
1330 protected Hashtable method_hash;
1333 /// Create a new MemberCache for the given IMemberContainer `container'.
1335 public MemberCache (IMemberContainer container)
1337 this.Container = container;
1339 Timer.IncrementCounter (CounterType.MemberCache);
1340 Timer.StartTimer (TimerType.CacheInit);
1344 // If we have a parent class (we have a parent class unless we're
1345 // TypeManager.object_type), we deep-copy its MemberCache here.
1346 if (Container.IsInterface) {
1349 if (Container.Parent != null)
1350 parent = Container.Parent.MemberCache;
1352 parent = TypeHandle.ObjectType.MemberCache;
1353 member_hash = SetupCacheForInterface (parent);
1354 } else if (Container.Parent != null)
1355 member_hash = SetupCache (Container.Parent.MemberCache);
1357 member_hash = new Hashtable ();
1359 // If this is neither a dynamic type nor an interface, create a special
1360 // method cache with all declared and inherited methods.
1361 Type type = container.Type;
1362 if (!(type is TypeBuilder) && !type.IsInterface) {
1363 method_hash = new Hashtable ();
1367 // Add all members from the current class.
1368 AddMembers (Container);
1370 Timer.StopTimer (TimerType.CacheInit);
1374 /// Bootstrap this member cache by doing a deep-copy of our parent.
1376 Hashtable SetupCache (MemberCache parent)
1378 Hashtable hash = new Hashtable ();
1380 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1381 while (it.MoveNext ()) {
1382 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1390 /// Add the contents of `new_hash' to `hash'.
1392 void AddHashtable (Hashtable hash, MemberCache cache)
1394 Hashtable new_hash = cache.member_hash;
1395 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1396 while (it.MoveNext ()) {
1397 ArrayList list = (ArrayList) hash [it.Key];
1399 hash [it.Key] = list = new ArrayList ();
1401 foreach (CacheEntry entry in (ArrayList) it.Value) {
1402 if (entry.Container != cache.Container)
1410 /// Bootstrap the member cache for an interface type.
1411 /// Type.GetMembers() won't return any inherited members for interface types,
1412 /// so we need to do this manually. Interfaces also inherit from System.Object.
1414 Hashtable SetupCacheForInterface (MemberCache parent)
1416 Hashtable hash = SetupCache (parent);
1417 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1419 foreach (TypeExpr iface in ifaces) {
1420 Type itype = iface.Type;
1422 IMemberContainer iface_container =
1423 TypeManager.LookupMemberContainer (itype);
1425 MemberCache iface_cache = iface_container.MemberCache;
1427 AddHashtable (hash, iface_cache);
1434 /// Add all members from class `container' to the cache.
1436 void AddMembers (IMemberContainer container)
1438 // We need to call AddMembers() with a single member type at a time
1439 // to get the member type part of CacheEntry.EntryType right.
1440 AddMembers (MemberTypes.Constructor, container);
1441 AddMembers (MemberTypes.Field, container);
1442 AddMembers (MemberTypes.Method, container);
1443 AddMembers (MemberTypes.Property, container);
1444 AddMembers (MemberTypes.Event, container);
1445 // Nested types are returned by both Static and Instance searches.
1446 AddMembers (MemberTypes.NestedType,
1447 BindingFlags.Static | BindingFlags.Public, container);
1448 AddMembers (MemberTypes.NestedType,
1449 BindingFlags.Static | BindingFlags.NonPublic, container);
1452 void AddMembers (MemberTypes mt, IMemberContainer container)
1454 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1455 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1456 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1457 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1461 /// Add all members from class `container' with the requested MemberTypes and
1462 /// BindingFlags to the cache. This method is called multiple times with different
1463 /// MemberTypes and BindingFlags.
1465 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1467 MemberList members = container.GetMembers (mt, bf);
1469 foreach (MemberInfo member in members) {
1470 string name = member.Name;
1472 // We use a name-based hash table of ArrayList's.
1473 ArrayList list = (ArrayList) member_hash [name];
1475 list = new ArrayList ();
1476 member_hash.Add (name, list);
1479 // When this method is called for the current class, the list will
1480 // already contain all inherited members from our parent classes.
1481 // We cannot add new members in front of the list since this'd be an
1482 // expensive operation, that's why the list is sorted in reverse order
1483 // (ie. members from the current class are coming last).
1484 list.Add (new CacheEntry (container, member, mt, bf));
1489 /// Add all declared and inherited methods from class `type' to the method cache.
1491 void AddMethods (Type type)
1493 AddMethods (BindingFlags.Static | BindingFlags.Public |
1494 BindingFlags.FlattenHierarchy, type);
1495 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1496 BindingFlags.FlattenHierarchy, type);
1497 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1498 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1501 void AddMethods (BindingFlags bf, Type type)
1503 MemberInfo [] members = type.GetMethods (bf);
1505 Array.Reverse (members);
1507 foreach (MethodBase member in members) {
1508 string name = member.Name;
1510 // Varargs methods aren't allowed in C# code.
1511 if ((member.CallingConvention & CallingConventions.VarArgs) != 0)
1514 // We use a name-based hash table of ArrayList's.
1515 ArrayList list = (ArrayList) method_hash [name];
1517 list = new ArrayList ();
1518 method_hash.Add (name, list);
1521 // Unfortunately, the elements returned by Type.GetMethods() aren't
1522 // sorted so we need to do this check for every member.
1523 BindingFlags new_bf = bf;
1524 if (member.DeclaringType == type)
1525 new_bf |= BindingFlags.DeclaredOnly;
1527 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1534 /// Compute and return a appropriate `EntryType' magic number for the given
1535 /// MemberTypes and BindingFlags.
1537 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1539 EntryType type = EntryType.None;
1541 if ((mt & MemberTypes.Constructor) != 0)
1542 type |= EntryType.Constructor;
1543 if ((mt & MemberTypes.Event) != 0)
1544 type |= EntryType.Event;
1545 if ((mt & MemberTypes.Field) != 0)
1546 type |= EntryType.Field;
1547 if ((mt & MemberTypes.Method) != 0)
1548 type |= EntryType.Method;
1549 if ((mt & MemberTypes.Property) != 0)
1550 type |= EntryType.Property;
1551 // Nested types are returned by static and instance searches.
1552 if ((mt & MemberTypes.NestedType) != 0)
1553 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1555 if ((bf & BindingFlags.Instance) != 0)
1556 type |= EntryType.Instance;
1557 if ((bf & BindingFlags.Static) != 0)
1558 type |= EntryType.Static;
1559 if ((bf & BindingFlags.Public) != 0)
1560 type |= EntryType.Public;
1561 if ((bf & BindingFlags.NonPublic) != 0)
1562 type |= EntryType.NonPublic;
1563 if ((bf & BindingFlags.DeclaredOnly) != 0)
1564 type |= EntryType.Declared;
1570 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1571 /// denote multiple member types. Returns true if the given flags value denotes a
1572 /// single member types.
1574 public static bool IsSingleMemberType (MemberTypes mt)
1577 case MemberTypes.Constructor:
1578 case MemberTypes.Event:
1579 case MemberTypes.Field:
1580 case MemberTypes.Method:
1581 case MemberTypes.Property:
1582 case MemberTypes.NestedType:
1591 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1592 /// number to speed up the searching process.
1595 protected enum EntryType {
1600 MaskStatic = Instance|Static,
1604 MaskProtection = Public|NonPublic,
1608 Constructor = 0x020,
1615 MaskType = Constructor|Event|Field|Method|Property|NestedType
1618 protected struct CacheEntry {
1619 public readonly IMemberContainer Container;
1620 public readonly EntryType EntryType;
1621 public readonly MemberInfo Member;
1623 public CacheEntry (IMemberContainer container, MemberInfo member,
1624 MemberTypes mt, BindingFlags bf)
1626 this.Container = container;
1627 this.Member = member;
1628 this.EntryType = GetEntryType (mt, bf);
1633 /// This is called each time we're walking up one level in the class hierarchy
1634 /// and checks whether we can abort the search since we've already found what
1635 /// we were looking for.
1637 protected bool DoneSearching (ArrayList list)
1640 // We've found exactly one member in the current class and it's not
1641 // a method or constructor.
1643 if (list.Count == 1 && !(list [0] is MethodBase))
1647 // Multiple properties: we query those just to find out the indexer
1650 if ((list.Count > 0) && (list [0] is PropertyInfo))
1657 /// Looks up members with name `name'. If you provide an optional
1658 /// filter function, it'll only be called with members matching the
1659 /// requested member name.
1661 /// This method will try to use the cache to do the lookup if possible.
1663 /// Unlike other FindMembers implementations, this method will always
1664 /// check all inherited members - even when called on an interface type.
1666 /// If you know that you're only looking for methods, you should use
1667 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1668 /// When doing a method-only search, it'll try to use a special method
1669 /// cache (unless it's a dynamic type or an interface) and the returned
1670 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1671 /// The lookup process will automatically restart itself in method-only
1672 /// search mode if it discovers that it's about to return methods.
1674 ArrayList global = new ArrayList ();
1675 bool using_global = false;
1677 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1679 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1680 MemberFilter filter, object criteria)
1683 throw new Exception ();
1685 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1686 bool method_search = mt == MemberTypes.Method;
1687 // If we have a method cache and we aren't already doing a method-only search,
1688 // then we restart a method search if the first match is a method.
1689 bool do_method_search = !method_search && (method_hash != null);
1691 ArrayList applicable;
1693 // If this is a method-only search, we try to use the method cache if
1694 // possible; a lookup in the method cache will return a MemberInfo with
1695 // the correct ReflectedType for inherited methods.
1697 if (method_search && (method_hash != null))
1698 applicable = (ArrayList) method_hash [name];
1700 applicable = (ArrayList) member_hash [name];
1702 if (applicable == null)
1703 return emptyMemberInfo;
1706 // 32 slots gives 53 rss/54 size
1707 // 2/4 slots gives 55 rss
1709 // Strange: from 25,000 calls, only 1,800
1710 // are above 2. Why does this impact it?
1713 using_global = true;
1715 Timer.StartTimer (TimerType.CachedLookup);
1717 EntryType type = GetEntryType (mt, bf);
1719 IMemberContainer current = Container;
1722 // `applicable' is a list of all members with the given member name `name'
1723 // in the current class and all its parent classes. The list is sorted in
1724 // reverse order due to the way how the cache is initialy created (to speed
1725 // things up, we're doing a deep-copy of our parent).
1727 for (int i = applicable.Count-1; i >= 0; i--) {
1728 CacheEntry entry = (CacheEntry) applicable [i];
1730 // This happens each time we're walking one level up in the class
1731 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1732 // the first time this happens (this may already happen in the first
1733 // iteration of this loop if there are no members with the name we're
1734 // looking for in the current class).
1735 if (entry.Container != current) {
1736 if (declared_only || DoneSearching (global))
1739 current = entry.Container;
1742 // Is the member of the correct type ?
1743 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1746 // Is the member static/non-static ?
1747 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1750 // Apply the filter to it.
1751 if (filter (entry.Member, criteria)) {
1752 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1753 do_method_search = false;
1754 global.Add (entry.Member);
1758 Timer.StopTimer (TimerType.CachedLookup);
1760 // If we have a method cache and we aren't already doing a method-only
1761 // search, we restart in method-only search mode if the first match is
1762 // a method. This ensures that we return a MemberInfo with the correct
1763 // ReflectedType for inherited methods.
1764 if (do_method_search && (global.Count > 0)){
1765 using_global = false;
1767 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1770 using_global = false;
1771 MemberInfo [] copy = new MemberInfo [global.Count];
1772 global.CopyTo (copy);
1777 // This finds the method or property for us to override. invocationType is the type where
1778 // the override is going to be declared, name is the name of the method/property, and
1779 // paramTypes is the parameters, if any to the method or property
1781 // Because the MemberCache holds members from this class and all the base classes,
1782 // we can avoid tons of reflection stuff.
1784 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1786 ArrayList applicable;
1787 if (method_hash != null && !is_property)
1788 applicable = (ArrayList) method_hash [name];
1790 applicable = (ArrayList) member_hash [name];
1792 if (applicable == null)
1795 // Walk the chain of methods, starting from the top.
1797 for (int i = applicable.Count - 1; i >= 0; i--) {
1798 CacheEntry entry = (CacheEntry) applicable [i];
1800 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1803 PropertyInfo pi = null;
1804 MethodInfo mi = null;
1805 FieldInfo fi = null;
1806 Type [] cmpAttrs = null;
1809 if ((entry.EntryType & EntryType.Field) != 0) {
1810 fi = (FieldInfo)entry.Member;
1812 // TODO: For this case we ignore member type
1813 //fb = TypeManager.GetField (fi);
1814 //cmpAttrs = new Type[] { fb.MemberType };
1816 pi = (PropertyInfo) entry.Member;
1817 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1820 mi = (MethodInfo) entry.Member;
1821 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1825 // TODO: Almost duplicate !
1827 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1828 case FieldAttributes.Private:
1830 // A private method is Ok if we are a nested subtype.
1831 // The spec actually is not very clear about this, see bug 52458.
1833 if (invocationType != entry.Container.Type &
1834 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1838 case FieldAttributes.FamANDAssem:
1839 case FieldAttributes.Assembly:
1841 // Check for assembly methods
1843 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1847 return entry.Member;
1851 // Check the arguments
1853 if (cmpAttrs.Length != paramTypes.Length)
1856 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1857 if (paramTypes [j] != cmpAttrs [j])
1861 // get one of the methods because this has the visibility info.
1864 mi = pi.GetGetMethod (true);
1866 mi = pi.GetSetMethod (true);
1872 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1873 case MethodAttributes.Private:
1875 // A private method is Ok if we are a nested subtype.
1876 // The spec actually is not very clear about this, see bug 52458.
1878 if (invocationType == entry.Container.Type ||
1879 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1880 return entry.Member;
1883 case MethodAttributes.FamANDAssem:
1884 case MethodAttributes.Assembly:
1886 // Check for assembly methods
1888 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1889 return entry.Member;
1894 // A protected method is ok, because we are overriding.
1895 // public is always ok.
1897 return entry.Member;