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
15 using System.Collections;
16 using System.Globalization;
17 using System.Reflection.Emit;
18 using System.Reflection;
20 namespace Mono.CSharp {
23 /// Base representation for members. This is used to keep track
24 /// of Name, Location and Modifier flags, and handling Attributes.
26 public abstract class MemberCore : Attributable {
33 /// Modifier flags that the user specified in the source code
38 /// Location where this declaration happens
40 public readonly Location Location;
44 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
45 Obsolete = 1 << 1, // Type has obsolete attribute
46 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
47 ClsCompliant = 1 << 3, // Type is CLS Compliant
48 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
49 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
50 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
51 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
52 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
53 Excluded = 1 << 9 // Method is conditional
58 /// MemberCore flags at first detected then cached
60 protected Flags caching_flags;
62 public MemberCore (string name, Attributes attrs, Location loc)
67 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
71 /// Tests presence of ObsoleteAttribute and report proper error
73 protected void CheckUsageOfObsoleteAttribute (Type type)
78 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
79 if (obsolete_attr == null)
82 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
85 public abstract bool Define (TypeContainer parent);
88 // Returns full member name for error message
90 public virtual string GetSignatureForError ()
96 /// Base Emit method. This is also entry point for CLS-Compliant verification.
98 public virtual void Emit (TypeContainer container)
100 VerifyObsoleteAttribute ();
102 if (!RootContext.VerifyClsCompliance)
105 VerifyClsCompliance (container);
109 // Whehter is it ok to use an unsafe pointer in this type container
111 public bool UnsafeOK (DeclSpace parent)
114 // First check if this MemberCore modifier flags has unsafe set
116 if ((ModFlags & Modifiers.UNSAFE) != 0)
119 if (parent.UnsafeContext)
122 Expression.UnsafeError (Location);
127 /// Returns instance of ObsoleteAttribute for this MemberCore
129 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
131 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
132 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
136 caching_flags &= ~Flags.Obsolete_Undetected;
138 if (OptAttributes == null)
141 // TODO: remove this allocation
142 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
143 null, null, ds.ModFlags, false);
145 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
146 if (obsolete_attr == null)
149 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
150 if (obsolete == null)
153 caching_flags |= Flags.Obsolete;
158 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
160 public override bool IsClsCompliaceRequired (DeclSpace container)
162 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
163 return (caching_flags & Flags.ClsCompliant) != 0;
165 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
166 caching_flags &= ~Flags.ClsCompliance_Undetected;
167 caching_flags |= Flags.ClsCompliant;
171 caching_flags &= ~Flags.ClsCompliance_Undetected;
176 /// Returns true when MemberCore is exposed from assembly.
178 protected bool IsExposedFromAssembly (DeclSpace ds)
180 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
183 DeclSpace parentContainer = ds;
184 while (parentContainer != null && parentContainer.ModFlags != 0) {
185 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
187 parentContainer = parentContainer.Parent;
193 /// Resolve CLSCompliantAttribute value or gets cached value.
195 bool GetClsCompliantAttributeValue (DeclSpace ds)
197 if (OptAttributes != null) {
198 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
199 null, null, ds.ModFlags, false);
200 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
201 if (cls_attribute != null) {
202 caching_flags |= Flags.HasClsCompliantAttribute;
203 return cls_attribute.GetClsCompliantAttributeValue (ds);
206 return ds.GetClsCompliantAttributeValue ();
210 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
212 protected bool HasClsCompliantAttribute {
214 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
219 /// This method is used to testing error 3005 (Method or parameter name collision).
221 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
224 /// Common helper method for identifier and parameters CLS-Compliant testing.
225 /// When return false error 3005 is reported. True means no violation.
226 /// And error 3006 tests are peformed here because of speed.
228 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
230 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
231 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
236 bool error3006 = false;
237 for (int i = 0; i < ml.Count; ++i) {
238 MemberInfo mi = ml [i];
239 if (name == mi.Name) {
240 MethodBase method = mi as MethodBase;
241 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
244 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
252 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
253 // because BindingFlags.Public returns internal types too
254 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
256 // Type is external, we can get attribute directly
257 if (temp_ds == null) {
258 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
259 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
262 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
264 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
265 if (!mc.IsClsCompliaceRequired (ds))
269 for (int ii = 0; ii < ml.Count; ++ii) {
273 Report.SymbolRelatedToPreviousError (mi);
277 Report.Error_T (3006, Location, GetSignatureForError ());
286 /// The main virtual method for CLS-Compliant verifications.
287 /// The method returns true if member is CLS-Compliant and false if member is not
288 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
289 /// and add their extra verifications.
291 protected virtual bool VerifyClsCompliance (DeclSpace ds)
293 if (!IsClsCompliaceRequired (ds)) {
294 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
295 Report.Warning_T (3019, Location, GetSignatureForError ());
300 if (!CodeGen.Assembly.IsClsCompliant) {
301 if (HasClsCompliantAttribute) {
302 Report.Error_T (3014, Location, GetSignatureForError ());
306 int index = Name.LastIndexOf ('.');
307 if (Name [index > 0 ? index + 1 : 0] == '_') {
308 Report.Error_T (3008, Location, GetSignatureForError () );
311 if (!IsIdentifierClsCompliant (ds)) {
312 Report.Error_T (3005, Location, GetSignatureForError ());
318 protected abstract void VerifyObsoleteAttribute ();
323 /// Base class for structs, classes, enumerations and interfaces.
326 /// They all create new declaration spaces. This
327 /// provides the common foundation for managing those name
330 public abstract class DeclSpace : MemberCore {
332 /// this points to the actual definition that is being
333 /// created with System.Reflection.Emit
335 public TypeBuilder TypeBuilder;
338 // This is the namespace in which this typecontainer
339 // was declared. We use this to resolve names.
341 public NamespaceEntry NamespaceEntry;
343 public Hashtable Cache = new Hashtable ();
345 public string Basename;
348 /// defined_names is used for toplevel objects
350 protected Hashtable defined_names;
352 TypeContainer parent;
354 static string[] attribute_targets = new string [] { "type" };
356 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
357 : base (name, attrs, l)
360 Basename = name.Substring (1 + name.LastIndexOf ('.'));
361 defined_names = new Hashtable ();
362 this.parent = parent;
365 public void RecordDecl ()
367 if ((NamespaceEntry != null) && (parent == RootContext.Tree.Types))
368 NamespaceEntry.DefineName (Basename, this);
372 /// The result value from adding an declaration into
373 /// a struct or a class
375 public enum AdditionResult {
377 /// The declaration has been successfully
378 /// added to the declation space.
383 /// The symbol has already been defined.
388 /// Returned if the declation being added to the
389 /// name space clashes with its container name.
391 /// The only exceptions for this are constructors
392 /// and static constructors
397 /// Returned if a constructor was created (because syntactically
398 /// it looked like a constructor) but was not (because the name
399 /// of the method is not the same as the container class
404 /// This is only used by static constructors to emit the
405 /// error 111, but this error for other things really
406 /// happens at another level for other functions.
411 /// Some other error.
417 /// Returns a status code based purely on the name
418 /// of the member being added
420 protected AdditionResult IsValid (string basename, string name)
422 if (basename == Basename)
423 return AdditionResult.EnclosingClash;
425 if (defined_names.Contains (name))
426 return AdditionResult.NameExists;
428 return AdditionResult.Success;
431 public static int length;
432 public static int small;
435 /// Introduce @name into this declaration space and
436 /// associates it with the object @o. Note that for
437 /// methods this will just point to the first method. o
439 public void DefineName (string name, object o)
441 defined_names.Add (name, o);
444 int p = name.LastIndexOf ('.');
452 /// Returns the object associated with a given name in the declaration
453 /// space. This is the inverse operation of `DefineName'
455 public object GetDefinition (string name)
457 return defined_names [name];
460 bool in_transit = false;
463 /// This function is used to catch recursive definitions
466 public bool InTransit {
476 public TypeContainer Parent {
483 /// Looks up the alias for the name
485 public string LookupAlias (string name)
487 if (NamespaceEntry != null)
488 return NamespaceEntry.LookupAlias (name);
494 // root_types contains all the types. All TopLevel types
495 // hence have a parent that points to `root_types', that is
496 // why there is a non-obvious test down here.
498 public bool IsTopLevel {
501 if (parent.parent == null)
508 public virtual void CloseType ()
510 if ((caching_flags & Flags.CloseTypeCreated) == 0){
512 TypeBuilder.CreateType ();
515 // The try/catch is needed because
516 // nested enumerations fail to load when they
519 // Even if this is the right order (enumerations
520 // declared after types).
522 // Note that this still creates the type and
523 // it is possible to save it
525 caching_flags |= Flags.CloseTypeCreated;
530 /// Should be overriten by the appropriate declaration space
532 public abstract TypeBuilder DefineType ();
535 /// Define all members, but don't apply any attributes or do anything which may
536 /// access not-yet-defined classes. This method also creates the MemberCache.
538 public abstract bool DefineMembers (TypeContainer parent);
541 // Whether this is an `unsafe context'
543 public bool UnsafeContext {
545 if ((ModFlags & Modifiers.UNSAFE) != 0)
548 return parent.UnsafeContext;
553 public static string MakeFQN (string nsn, string name)
557 return String.Concat (nsn, ".", name);
560 EmitContext type_resolve_ec;
561 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
563 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
564 type_resolve_ec.ResolvingTypeTree = true;
566 return type_resolve_ec;
570 // Looks up the type, as parsed into the expression `e'
572 public Type ResolveType (Expression e, bool silent, Location loc)
574 if (type_resolve_ec == null)
575 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
576 type_resolve_ec.loc = loc;
577 type_resolve_ec.ContainerType = TypeBuilder;
579 int errors = Report.Errors;
580 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
582 if (d == null || d.eclass != ExprClass.Type){
583 if (!silent && errors == Report.Errors){
584 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
589 if (!d.CheckAccessLevel (this)) {
590 Report.Error_T (122, loc, d.Name);
598 // Resolves the expression `e' for a type, and will recursively define
601 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
603 if (type_resolve_ec == null)
604 type_resolve_ec = GetTypeResolveEmitContext (parent, loc);
605 type_resolve_ec.loc = loc;
606 type_resolve_ec.ContainerType = TypeBuilder;
608 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
610 if (d == null || d.eclass != ExprClass.Type){
612 Report.Error (246, loc, "Cannot find type `"+ e +"'");
620 public bool CheckAccessLevel (Type check_type)
622 if (check_type == TypeBuilder)
625 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
628 // Broken Microsoft runtime, return public for arrays, no matter what
629 // the accessibility is for their underlying class, and they return
630 // NonPublic visibility for pointers
632 if (check_type.IsArray || check_type.IsPointer)
633 return CheckAccessLevel (TypeManager.GetElementType (check_type));
636 case TypeAttributes.Public:
639 case TypeAttributes.NotPublic:
641 // In same cases is null.
642 if (TypeBuilder == null)
646 // This test should probably use the declaringtype.
648 return check_type.Assembly == TypeBuilder.Assembly;
650 case TypeAttributes.NestedPublic:
653 case TypeAttributes.NestedPrivate:
654 string check_type_name = check_type.FullName;
655 string type_name = TypeBuilder.FullName;
657 int cio = check_type_name.LastIndexOf ('+');
658 string container = check_type_name.Substring (0, cio);
661 // Check if the check_type is a nested class of the current type
663 if (check_type_name.StartsWith (type_name + "+")){
667 if (type_name.StartsWith (container)){
673 case TypeAttributes.NestedFamily:
675 // Only accessible to methods in current type or any subtypes
677 return FamilyAccessible (check_type);
679 case TypeAttributes.NestedFamANDAssem:
680 return (check_type.Assembly == TypeBuilder.Assembly) &&
681 FamilyAccessible (check_type);
683 case TypeAttributes.NestedFamORAssem:
684 return (check_type.Assembly == TypeBuilder.Assembly) ||
685 FamilyAccessible (check_type);
687 case TypeAttributes.NestedAssembly:
688 return check_type.Assembly == TypeBuilder.Assembly;
691 Console.WriteLine ("HERE: " + check_attr);
696 protected bool FamilyAccessible (Type check_type)
698 Type declaring = check_type.DeclaringType;
699 if (TypeBuilder.IsSubclassOf (declaring))
702 string check_type_name = check_type.FullName;
704 int cio = check_type_name.LastIndexOf ('+');
705 string container = check_type_name.Substring (0, cio);
708 // Check if the check_type is a nested class of the current type
710 if (check_type_name.StartsWith (container + "+"))
716 // Access level of a type.
718 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
719 // Public Assembly Protected
720 Protected = (0 << 0) | (0 << 1) | (X << 2),
721 Public = (X << 0) | (X << 1) | (X << 2),
722 Private = (0 << 0) | (0 << 1) | (0 << 2),
723 Internal = (0 << 0) | (X << 1) | (0 << 2),
724 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
727 static AccessLevel GetAccessLevelFromModifiers (int flags)
729 if ((flags & Modifiers.INTERNAL) != 0) {
731 if ((flags & Modifiers.PROTECTED) != 0)
732 return AccessLevel.ProtectedOrInternal;
734 return AccessLevel.Internal;
736 } else if ((flags & Modifiers.PROTECTED) != 0)
737 return AccessLevel.Protected;
739 else if ((flags & Modifiers.PRIVATE) != 0)
740 return AccessLevel.Private;
743 return AccessLevel.Public;
746 // What is the effective access level of this?
748 AccessLevel EffectiveAccessLevel {
750 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
751 if (!IsTopLevel && (Parent != null))
752 return myAccess & Parent.EffectiveAccessLevel;
758 // Return the access level for type `t'
759 static AccessLevel TypeEffectiveAccessLevel (Type t)
762 return AccessLevel.Public;
763 if (t.IsNestedPrivate)
764 return AccessLevel.Private;
766 return AccessLevel.Internal;
768 // By now, it must be nested
769 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
771 if (t.IsNestedPublic)
773 if (t.IsNestedAssembly)
774 return parentLevel & AccessLevel.Internal;
775 if (t.IsNestedFamily)
776 return parentLevel & AccessLevel.Protected;
777 if (t.IsNestedFamORAssem)
778 return parentLevel & AccessLevel.ProtectedOrInternal;
779 if (t.IsNestedFamANDAssem)
780 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
782 // nested private is taken care of
784 throw new Exception ("I give up, what are you?");
788 // This answers `is the type P, as accessible as a member M which has the
789 // accessability @flags which is declared as a nested member of the type T, this declspace'
791 public bool AsAccessible (Type p, int flags)
794 // 1) if M is private, its accessability is the same as this declspace.
795 // we already know that P is accessible to T before this method, so we
799 if ((flags & Modifiers.PRIVATE) != 0)
802 while (p.IsArray || p.IsPointer || p.IsByRef)
803 p = TypeManager.GetElementType (p);
805 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
806 AccessLevel mAccess = this.EffectiveAccessLevel &
807 GetAccessLevelFromModifiers (flags);
809 // for every place from which we can access M, we must
810 // be able to access P as well. So, we want
811 // For every bit in M and P, M_i -> P_1 == true
812 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
814 return ~ (~ mAccess | pAccess) == 0;
817 static DoubleHash dh = new DoubleHash (1000);
819 Type DefineTypeAndParents (DeclSpace tc)
821 DeclSpace container = tc.Parent;
823 if (container.TypeBuilder == null && container.Name != "")
824 DefineTypeAndParents (container);
826 return tc.DefineType ();
829 Type LookupInterfaceOrClass (string ns, string name, out bool error)
836 int p = name.LastIndexOf ('.');
838 if (dh.Lookup (ns, name, out r))
842 // If the type is not a nested type, we do not need `LookupType's processing.
843 // If the @name does not have a `.' in it, this cant be a nested type.
846 if (Namespace.IsNamespace (ns)) {
848 t = TypeManager.LookupType (ns + "." + name);
850 t = TypeManager.LookupTypeDirect (ns + "." + name);
854 t = TypeManager.LookupType (name);
856 t = TypeManager.LookupTypeDirect (name);
860 dh.Insert (ns, name, t);
865 // In case we are fed a composite name, normalize it.
869 ns = MakeFQN (ns, name.Substring (0, p));
870 name = name.Substring (p+1);
873 parent = RootContext.Tree.LookupByNamespace (ns, name);
874 if (parent == null) {
875 dh.Insert (ns, name, null);
879 t = DefineTypeAndParents (parent);
885 dh.Insert (ns, name, t);
889 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
891 Report.Error (104, loc,
892 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
893 t1.FullName, t2.FullName));
897 /// GetType is used to resolve type names at the DeclSpace level.
898 /// Use this to lookup class/struct bases, interface bases or
899 /// delegate type references
903 /// Contrast this to LookupType which is used inside method bodies to
904 /// lookup types that have already been defined. GetType is used
905 /// during the tree resolution process and potentially define
906 /// recursively the type
908 public Type FindType (Location loc, string name)
914 // For the case the type we are looking for is nested within this one
915 // or is in any base class
917 DeclSpace containing_ds = this;
919 while (containing_ds != null){
920 Type container_type = containing_ds.TypeBuilder;
921 Type current_type = container_type;
923 while (current_type != null && current_type != TypeManager.object_type) {
924 string pre = current_type.FullName;
926 t = LookupInterfaceOrClass (pre, name, out error);
930 if ((t != null) && containing_ds.CheckAccessLevel (t))
933 current_type = current_type.BaseType;
935 containing_ds = containing_ds.Parent;
939 // Attempt to lookup the class on our namespace and all it's implicit parents
941 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
942 t = LookupInterfaceOrClass (ns.FullName, name, out error);
951 // Attempt to do a direct unqualified lookup
953 t = LookupInterfaceOrClass ("", name, out error);
961 // Attempt to lookup the class on any of the `using'
965 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
967 t = LookupInterfaceOrClass (ns.FullName, name, out error);
974 if (name.IndexOf ('.') > 0)
977 string alias_value = ns.LookupAlias (name);
978 if (alias_value != null) {
979 t = LookupInterfaceOrClass ("", alias_value, out error);
988 // Now check the using clause list
991 foreach (Namespace using_ns in ns.GetUsingTable ()) {
992 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
998 if (CheckAccessLevel (match)) {
999 Error_AmbiguousTypeReference (loc, name, t, match);
1012 //Report.Error (246, Location, "Can not find type `"+name+"'");
1017 /// This function is broken and not what you're looking for. It should only
1018 /// be used while the type is still being created since it doesn't use the cache
1019 /// and relies on the filter doing the member name check.
1021 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1022 MemberFilter filter, object criteria);
1025 /// If we have a MemberCache, return it. This property may return null if the
1026 /// class doesn't have a member cache or while it's still being created.
1028 public abstract MemberCache MemberCache {
1032 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1035 TypeBuilder.SetCustomAttribute (cb);
1036 } catch (System.ArgumentException e) {
1037 Report.Warning (-21, a.Location,
1038 "The CharSet named property on StructLayout\n"+
1039 "\tdoes not work correctly on Microsoft.NET\n"+
1040 "\tYou might want to remove the CharSet declaration\n"+
1041 "\tor compile using the Mono runtime instead of the\n"+
1042 "\tMicrosoft .NET runtime\n"+
1043 "\tThe runtime gave the error: " + e);
1048 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1049 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1051 public bool GetClsCompliantAttributeValue ()
1053 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1054 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1056 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1058 if (OptAttributes != null) {
1059 EmitContext ec = new EmitContext (parent, this, Location,
1060 null, null, ModFlags, false);
1061 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1062 if (cls_attribute != null) {
1063 caching_flags |= Flags.HasClsCompliantAttribute;
1064 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1065 caching_flags |= Flags.ClsCompliantAttributeTrue;
1072 if (parent == null) {
1073 if (CodeGen.Assembly.IsClsCompliant) {
1074 caching_flags |= Flags.ClsCompliantAttributeTrue;
1080 if (parent.GetClsCompliantAttributeValue ()) {
1081 caching_flags |= Flags.ClsCompliantAttributeTrue;
1088 // Tests container name for CLS-Compliant name (differing only in case)
1089 // Possible optimalization: search in same namespace only
1090 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1092 int l = Name.Length;
1094 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1095 // Seek through all imported types
1096 foreach (string type_name in TypeManager.all_imported_types.Keys)
1098 if (l != type_name.Length)
1101 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1102 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1103 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1109 // Seek through generated types
1110 foreach (string name in RootContext.Tree.Decls.Keys) {
1111 if (l != name.Length)
1114 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1119 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1120 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1121 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1130 protected override string[] ValidAttributeTargets {
1132 return attribute_targets;
1138 /// This is a readonly list of MemberInfo's.
1140 public class MemberList : IList {
1141 public readonly IList List;
1145 /// Create a new MemberList from the given IList.
1147 public MemberList (IList list)
1152 this.List = new ArrayList ();
1157 /// Concatenate the ILists `first' and `second' to a new MemberList.
1159 public MemberList (IList first, IList second)
1161 ArrayList list = new ArrayList ();
1162 list.AddRange (first);
1163 list.AddRange (second);
1168 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1171 /// Cast the MemberList into a MemberInfo[] array.
1174 /// This is an expensive operation, only use it if it's really necessary.
1176 public static explicit operator MemberInfo [] (MemberList list)
1178 Timer.StartTimer (TimerType.MiscTimer);
1179 MemberInfo [] result = new MemberInfo [list.Count];
1180 list.CopyTo (result, 0);
1181 Timer.StopTimer (TimerType.MiscTimer);
1193 public bool IsSynchronized {
1195 return List.IsSynchronized;
1199 public object SyncRoot {
1201 return List.SyncRoot;
1205 public void CopyTo (Array array, int index)
1207 List.CopyTo (array, index);
1212 public IEnumerator GetEnumerator ()
1214 return List.GetEnumerator ();
1219 public bool IsFixedSize {
1225 public bool IsReadOnly {
1231 object IList.this [int index] {
1233 return List [index];
1237 throw new NotSupportedException ();
1241 // FIXME: try to find out whether we can avoid the cast in this indexer.
1242 public MemberInfo this [int index] {
1244 return (MemberInfo) List [index];
1248 public int Add (object value)
1250 throw new NotSupportedException ();
1253 public void Clear ()
1255 throw new NotSupportedException ();
1258 public bool Contains (object value)
1260 return List.Contains (value);
1263 public int IndexOf (object value)
1265 return List.IndexOf (value);
1268 public void Insert (int index, object value)
1270 throw new NotSupportedException ();
1273 public void Remove (object value)
1275 throw new NotSupportedException ();
1278 public void RemoveAt (int index)
1280 throw new NotSupportedException ();
1285 /// This interface is used to get all members of a class when creating the
1286 /// member cache. It must be implemented by all DeclSpace derivatives which
1287 /// want to support the member cache and by TypeHandle to get caching of
1288 /// non-dynamic types.
1290 public interface IMemberContainer {
1292 /// The name of the IMemberContainer. This is only used for
1293 /// debugging purposes.
1300 /// The type of this IMemberContainer.
1307 /// Returns the IMemberContainer of the parent class or null if this
1308 /// is an interface or TypeManger.object_type.
1309 /// This is used when creating the member cache for a class to get all
1310 /// members from the parent class.
1312 IMemberContainer Parent {
1317 /// Whether this is an interface.
1324 /// Returns all members of this class with the corresponding MemberTypes
1325 /// and BindingFlags.
1328 /// When implementing this method, make sure not to return any inherited
1329 /// members and check the MemberTypes and BindingFlags properly.
1330 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1331 /// get the BindingFlags (static/non-static,public/non-public) in the
1332 /// MemberInfo class, but the cache needs this information. That's why
1333 /// this method is called multiple times with different BindingFlags.
1335 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1338 /// Return the container's member cache.
1340 MemberCache MemberCache {
1346 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1347 /// member lookups. It has a member name based hash table; it maps each member
1348 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1349 /// and the BindingFlags that were initially used to get it. The cache contains
1350 /// all members of the current class and all inherited members. If this cache is
1351 /// for an interface types, it also contains all inherited members.
1353 /// There are two ways to get a MemberCache:
1354 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1355 /// use the DeclSpace.MemberCache property.
1356 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1357 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1359 public class MemberCache {
1360 public readonly IMemberContainer Container;
1361 protected Hashtable member_hash;
1362 protected Hashtable method_hash;
1365 /// Create a new MemberCache for the given IMemberContainer `container'.
1367 public MemberCache (IMemberContainer container)
1369 this.Container = container;
1371 Timer.IncrementCounter (CounterType.MemberCache);
1372 Timer.StartTimer (TimerType.CacheInit);
1376 // If we have a parent class (we have a parent class unless we're
1377 // TypeManager.object_type), we deep-copy its MemberCache here.
1378 if (Container.IsInterface) {
1381 if (Container.Parent != null)
1382 parent = Container.Parent.MemberCache;
1384 parent = TypeHandle.ObjectType.MemberCache;
1385 member_hash = SetupCacheForInterface (parent);
1386 } else if (Container.Parent != null)
1387 member_hash = SetupCache (Container.Parent.MemberCache);
1389 member_hash = new Hashtable ();
1391 // If this is neither a dynamic type nor an interface, create a special
1392 // method cache with all declared and inherited methods.
1393 Type type = container.Type;
1394 if (!(type is TypeBuilder) && !type.IsInterface) {
1395 method_hash = new Hashtable ();
1399 // Add all members from the current class.
1400 AddMembers (Container);
1402 Timer.StopTimer (TimerType.CacheInit);
1406 /// Bootstrap this member cache by doing a deep-copy of our parent.
1408 Hashtable SetupCache (MemberCache parent)
1410 Hashtable hash = new Hashtable ();
1412 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1413 while (it.MoveNext ()) {
1414 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1422 /// Add the contents of `new_hash' to `hash'.
1424 void AddHashtable (Hashtable hash, MemberCache cache)
1426 Hashtable new_hash = cache.member_hash;
1427 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1428 while (it.MoveNext ()) {
1429 ArrayList list = (ArrayList) hash [it.Key];
1431 hash [it.Key] = list = new ArrayList ();
1433 foreach (CacheEntry entry in (ArrayList) it.Value) {
1434 if (entry.Container != cache.Container)
1442 /// Bootstrap the member cache for an interface type.
1443 /// Type.GetMembers() won't return any inherited members for interface types,
1444 /// so we need to do this manually. Interfaces also inherit from System.Object.
1446 Hashtable SetupCacheForInterface (MemberCache parent)
1448 Hashtable hash = SetupCache (parent);
1449 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1451 foreach (TypeExpr iface in ifaces) {
1452 Type itype = iface.Type;
1454 IMemberContainer iface_container =
1455 TypeManager.LookupMemberContainer (itype);
1457 MemberCache iface_cache = iface_container.MemberCache;
1459 AddHashtable (hash, iface_cache);
1466 /// Add all members from class `container' to the cache.
1468 void AddMembers (IMemberContainer container)
1470 // We need to call AddMembers() with a single member type at a time
1471 // to get the member type part of CacheEntry.EntryType right.
1472 AddMembers (MemberTypes.Constructor, container);
1473 AddMembers (MemberTypes.Field, container);
1474 AddMembers (MemberTypes.Method, container);
1475 AddMembers (MemberTypes.Property, container);
1476 AddMembers (MemberTypes.Event, container);
1477 // Nested types are returned by both Static and Instance searches.
1478 AddMembers (MemberTypes.NestedType,
1479 BindingFlags.Static | BindingFlags.Public, container);
1480 AddMembers (MemberTypes.NestedType,
1481 BindingFlags.Static | BindingFlags.NonPublic, container);
1484 void AddMembers (MemberTypes mt, IMemberContainer container)
1486 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1487 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1488 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1489 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1493 /// Add all members from class `container' with the requested MemberTypes and
1494 /// BindingFlags to the cache. This method is called multiple times with different
1495 /// MemberTypes and BindingFlags.
1497 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1499 MemberList members = container.GetMembers (mt, bf);
1501 foreach (MemberInfo member in members) {
1502 string name = member.Name;
1504 // We use a name-based hash table of ArrayList's.
1505 ArrayList list = (ArrayList) member_hash [name];
1507 list = new ArrayList ();
1508 member_hash.Add (name, list);
1511 // When this method is called for the current class, the list will
1512 // already contain all inherited members from our parent classes.
1513 // We cannot add new members in front of the list since this'd be an
1514 // expensive operation, that's why the list is sorted in reverse order
1515 // (ie. members from the current class are coming last).
1516 list.Add (new CacheEntry (container, member, mt, bf));
1521 /// Add all declared and inherited methods from class `type' to the method cache.
1523 void AddMethods (Type type)
1525 AddMethods (BindingFlags.Static | BindingFlags.Public |
1526 BindingFlags.FlattenHierarchy, type);
1527 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1528 BindingFlags.FlattenHierarchy, type);
1529 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1530 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1533 void AddMethods (BindingFlags bf, Type type)
1535 MemberInfo [] members = type.GetMethods (bf);
1537 Array.Reverse (members);
1539 foreach (MethodBase member in members) {
1540 string name = member.Name;
1542 // We use a name-based hash table of ArrayList's.
1543 ArrayList list = (ArrayList) method_hash [name];
1545 list = new ArrayList ();
1546 method_hash.Add (name, list);
1549 // Unfortunately, the elements returned by Type.GetMethods() aren't
1550 // sorted so we need to do this check for every member.
1551 BindingFlags new_bf = bf;
1552 if (member.DeclaringType == type)
1553 new_bf |= BindingFlags.DeclaredOnly;
1555 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1562 /// Compute and return a appropriate `EntryType' magic number for the given
1563 /// MemberTypes and BindingFlags.
1565 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1567 EntryType type = EntryType.None;
1569 if ((mt & MemberTypes.Constructor) != 0)
1570 type |= EntryType.Constructor;
1571 if ((mt & MemberTypes.Event) != 0)
1572 type |= EntryType.Event;
1573 if ((mt & MemberTypes.Field) != 0)
1574 type |= EntryType.Field;
1575 if ((mt & MemberTypes.Method) != 0)
1576 type |= EntryType.Method;
1577 if ((mt & MemberTypes.Property) != 0)
1578 type |= EntryType.Property;
1579 // Nested types are returned by static and instance searches.
1580 if ((mt & MemberTypes.NestedType) != 0)
1581 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1583 if ((bf & BindingFlags.Instance) != 0)
1584 type |= EntryType.Instance;
1585 if ((bf & BindingFlags.Static) != 0)
1586 type |= EntryType.Static;
1587 if ((bf & BindingFlags.Public) != 0)
1588 type |= EntryType.Public;
1589 if ((bf & BindingFlags.NonPublic) != 0)
1590 type |= EntryType.NonPublic;
1591 if ((bf & BindingFlags.DeclaredOnly) != 0)
1592 type |= EntryType.Declared;
1598 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1599 /// denote multiple member types. Returns true if the given flags value denotes a
1600 /// single member types.
1602 public static bool IsSingleMemberType (MemberTypes mt)
1605 case MemberTypes.Constructor:
1606 case MemberTypes.Event:
1607 case MemberTypes.Field:
1608 case MemberTypes.Method:
1609 case MemberTypes.Property:
1610 case MemberTypes.NestedType:
1619 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1620 /// number to speed up the searching process.
1623 protected enum EntryType {
1628 MaskStatic = Instance|Static,
1632 MaskProtection = Public|NonPublic,
1636 Constructor = 0x020,
1643 MaskType = Constructor|Event|Field|Method|Property|NestedType
1646 protected struct CacheEntry {
1647 public readonly IMemberContainer Container;
1648 public readonly EntryType EntryType;
1649 public readonly MemberInfo Member;
1651 public CacheEntry (IMemberContainer container, MemberInfo member,
1652 MemberTypes mt, BindingFlags bf)
1654 this.Container = container;
1655 this.Member = member;
1656 this.EntryType = GetEntryType (mt, bf);
1661 /// This is called each time we're walking up one level in the class hierarchy
1662 /// and checks whether we can abort the search since we've already found what
1663 /// we were looking for.
1665 protected bool DoneSearching (ArrayList list)
1668 // We've found exactly one member in the current class and it's not
1669 // a method or constructor.
1671 if (list.Count == 1 && !(list [0] is MethodBase))
1675 // Multiple properties: we query those just to find out the indexer
1678 if ((list.Count > 0) && (list [0] is PropertyInfo))
1685 /// Looks up members with name `name'. If you provide an optional
1686 /// filter function, it'll only be called with members matching the
1687 /// requested member name.
1689 /// This method will try to use the cache to do the lookup if possible.
1691 /// Unlike other FindMembers implementations, this method will always
1692 /// check all inherited members - even when called on an interface type.
1694 /// If you know that you're only looking for methods, you should use
1695 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1696 /// When doing a method-only search, it'll try to use a special method
1697 /// cache (unless it's a dynamic type or an interface) and the returned
1698 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1699 /// The lookup process will automatically restart itself in method-only
1700 /// search mode if it discovers that it's about to return methods.
1702 ArrayList global = new ArrayList ();
1703 bool using_global = false;
1705 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1707 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1708 MemberFilter filter, object criteria)
1711 throw new Exception ();
1713 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1714 bool method_search = mt == MemberTypes.Method;
1715 // If we have a method cache and we aren't already doing a method-only search,
1716 // then we restart a method search if the first match is a method.
1717 bool do_method_search = !method_search && (method_hash != null);
1719 ArrayList applicable;
1721 // If this is a method-only search, we try to use the method cache if
1722 // possible; a lookup in the method cache will return a MemberInfo with
1723 // the correct ReflectedType for inherited methods.
1725 if (method_search && (method_hash != null))
1726 applicable = (ArrayList) method_hash [name];
1728 applicable = (ArrayList) member_hash [name];
1730 if (applicable == null)
1731 return emptyMemberInfo;
1734 // 32 slots gives 53 rss/54 size
1735 // 2/4 slots gives 55 rss
1737 // Strange: from 25,000 calls, only 1,800
1738 // are above 2. Why does this impact it?
1741 using_global = true;
1743 Timer.StartTimer (TimerType.CachedLookup);
1745 EntryType type = GetEntryType (mt, bf);
1747 IMemberContainer current = Container;
1750 // `applicable' is a list of all members with the given member name `name'
1751 // in the current class and all its parent classes. The list is sorted in
1752 // reverse order due to the way how the cache is initialy created (to speed
1753 // things up, we're doing a deep-copy of our parent).
1755 for (int i = applicable.Count-1; i >= 0; i--) {
1756 CacheEntry entry = (CacheEntry) applicable [i];
1758 // This happens each time we're walking one level up in the class
1759 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1760 // the first time this happens (this may already happen in the first
1761 // iteration of this loop if there are no members with the name we're
1762 // looking for in the current class).
1763 if (entry.Container != current) {
1764 if (declared_only || DoneSearching (global))
1767 current = entry.Container;
1770 // Is the member of the correct type ?
1771 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1774 // Is the member static/non-static ?
1775 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1778 // Apply the filter to it.
1779 if (filter (entry.Member, criteria)) {
1780 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1781 do_method_search = false;
1782 global.Add (entry.Member);
1786 Timer.StopTimer (TimerType.CachedLookup);
1788 // If we have a method cache and we aren't already doing a method-only
1789 // search, we restart in method-only search mode if the first match is
1790 // a method. This ensures that we return a MemberInfo with the correct
1791 // ReflectedType for inherited methods.
1792 if (do_method_search && (global.Count > 0)){
1793 using_global = false;
1795 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1798 using_global = false;
1799 MemberInfo [] copy = new MemberInfo [global.Count];
1800 global.CopyTo (copy);
1804 // find the nested type @name in @this.
1805 public Type FindNestedType (string name)
1807 ArrayList applicable = (ArrayList) member_hash [name];
1808 if (applicable == null)
1811 for (int i = applicable.Count-1; i >= 0; i--) {
1812 CacheEntry entry = (CacheEntry) applicable [i];
1813 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
1814 return (Type) entry.Member;
1821 // This finds the method or property for us to override. invocationType is the type where
1822 // the override is going to be declared, name is the name of the method/property, and
1823 // paramTypes is the parameters, if any to the method or property
1825 // Because the MemberCache holds members from this class and all the base classes,
1826 // we can avoid tons of reflection stuff.
1828 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1830 ArrayList applicable;
1831 if (method_hash != null && !is_property)
1832 applicable = (ArrayList) method_hash [name];
1834 applicable = (ArrayList) member_hash [name];
1836 if (applicable == null)
1839 // Walk the chain of methods, starting from the top.
1841 for (int i = applicable.Count - 1; i >= 0; i--) {
1842 CacheEntry entry = (CacheEntry) applicable [i];
1844 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1847 PropertyInfo pi = null;
1848 MethodInfo mi = null;
1849 FieldInfo fi = null;
1850 Type [] cmpAttrs = null;
1853 if ((entry.EntryType & EntryType.Field) != 0) {
1854 fi = (FieldInfo)entry.Member;
1856 // TODO: For this case we ignore member type
1857 //fb = TypeManager.GetField (fi);
1858 //cmpAttrs = new Type[] { fb.MemberType };
1860 pi = (PropertyInfo) entry.Member;
1861 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1864 mi = (MethodInfo) entry.Member;
1865 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1869 // TODO: Almost duplicate !
1871 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1872 case FieldAttributes.Private:
1874 // A private method is Ok if we are a nested subtype.
1875 // The spec actually is not very clear about this, see bug 52458.
1877 if (invocationType != entry.Container.Type &
1878 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1882 case FieldAttributes.FamANDAssem:
1883 case FieldAttributes.Assembly:
1885 // Check for assembly methods
1887 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1891 return entry.Member;
1895 // Check the arguments
1897 if (cmpAttrs.Length != paramTypes.Length)
1900 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1901 if (paramTypes [j] != cmpAttrs [j])
1905 // get one of the methods because this has the visibility info.
1908 mi = pi.GetGetMethod (true);
1910 mi = pi.GetSetMethod (true);
1916 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1917 case MethodAttributes.Private:
1919 // A private method is Ok if we are a nested subtype.
1920 // The spec actually is not very clear about this, see bug 52458.
1922 if (invocationType == entry.Container.Type ||
1923 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1924 return entry.Member;
1927 case MethodAttributes.FamANDAssem:
1928 case MethodAttributes.Assembly:
1930 // Check for assembly methods
1932 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1933 return entry.Member;
1938 // A protected method is ok, because we are overriding.
1939 // public is always ok.
1941 return entry.Member;