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
37 public readonly TypeContainer Parent;
40 /// Location where this declaration happens
42 public readonly Location Location;
46 Obsolete_Undetected = 1, // Obsolete attribute has not been detected yet
47 Obsolete = 1 << 1, // Type has obsolete attribute
48 ClsCompliance_Undetected = 1 << 2, // CLS Compliance has not been detected yet
49 ClsCompliant = 1 << 3, // Type is CLS Compliant
50 CloseTypeCreated = 1 << 4, // Tracks whether we have Closed the type
51 HasCompliantAttribute_Undetected = 1 << 5, // Presence of CLSCompliantAttribute has not been detected
52 HasClsCompliantAttribute = 1 << 6, // Type has CLSCompliantAttribute
53 ClsCompliantAttributeTrue = 1 << 7, // Type has CLSCompliant (true)
54 Excluded_Undetected = 1 << 8, // Conditional attribute has not been detected yet
55 Excluded = 1 << 9 // Method is conditional
60 /// MemberCore flags at first detected then cached
62 protected Flags caching_flags;
64 public MemberCore (TypeContainer parent, string name, Attributes attrs,
71 caching_flags = Flags.Obsolete_Undetected | Flags.ClsCompliance_Undetected | Flags.HasCompliantAttribute_Undetected | Flags.Excluded_Undetected;
75 /// Tests presence of ObsoleteAttribute and report proper error
77 protected void CheckUsageOfObsoleteAttribute (Type type)
82 ObsoleteAttribute obsolete_attr = AttributeTester.GetObsoleteAttribute (type);
83 if (obsolete_attr == null)
86 AttributeTester.Report_ObsoleteMessage (obsolete_attr, type.FullName, Location);
89 public abstract bool Define ();
92 // Returns full member name for error message
94 public virtual string GetSignatureForError ()
100 /// Base Emit method. This is also entry point for CLS-Compliant verification.
102 public virtual void Emit ()
104 VerifyObsoleteAttribute ();
106 if (!RootContext.VerifyClsCompliance)
109 VerifyClsCompliance (Parent);
113 // Whehter is it ok to use an unsafe pointer in this type container
115 public bool UnsafeOK (DeclSpace parent)
118 // First check if this MemberCore modifier flags has unsafe set
120 if ((ModFlags & Modifiers.UNSAFE) != 0)
123 if (parent.UnsafeContext)
126 Expression.UnsafeError (Location);
131 /// Returns instance of ObsoleteAttribute for this MemberCore
133 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
135 // ((flags & (Flags.Obsolete_Undetected | Flags.Obsolete)) == 0) is slower, but why ?
136 if ((caching_flags & Flags.Obsolete_Undetected) == 0 && (caching_flags & Flags.Obsolete) == 0) {
140 caching_flags &= ~Flags.Obsolete_Undetected;
142 if (OptAttributes == null)
145 // TODO: remove this allocation
146 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
147 null, null, ds.ModFlags, false);
149 Attribute obsolete_attr = OptAttributes.Search (TypeManager.obsolete_attribute_type, ec);
150 if (obsolete_attr == null)
153 ObsoleteAttribute obsolete = obsolete_attr.GetObsoleteAttribute (ds);
154 if (obsolete == null)
157 caching_flags |= Flags.Obsolete;
162 /// Analyze whether CLS-Compliant verification must be execute for this MemberCore.
164 public override bool IsClsCompliaceRequired (DeclSpace container)
166 if ((caching_flags & Flags.ClsCompliance_Undetected) == 0)
167 return (caching_flags & Flags.ClsCompliant) != 0;
169 if (GetClsCompliantAttributeValue (container) && IsExposedFromAssembly (container)) {
170 caching_flags &= ~Flags.ClsCompliance_Undetected;
171 caching_flags |= Flags.ClsCompliant;
175 caching_flags &= ~Flags.ClsCompliance_Undetected;
180 /// Returns true when MemberCore is exposed from assembly.
182 protected bool IsExposedFromAssembly (DeclSpace ds)
184 if ((ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
187 DeclSpace parentContainer = ds;
188 while (parentContainer != null && parentContainer.ModFlags != 0) {
189 if ((parentContainer.ModFlags & (Modifiers.PUBLIC | Modifiers.PROTECTED)) == 0)
191 parentContainer = parentContainer.Parent;
197 /// Resolve CLSCompliantAttribute value or gets cached value.
199 bool GetClsCompliantAttributeValue (DeclSpace ds)
201 if (OptAttributes != null) {
202 EmitContext ec = new EmitContext (ds.Parent, ds, ds.Location,
203 null, null, ds.ModFlags, false);
204 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
205 if (cls_attribute != null) {
206 caching_flags |= Flags.HasClsCompliantAttribute;
207 return cls_attribute.GetClsCompliantAttributeValue (ds);
210 return ds.GetClsCompliantAttributeValue ();
214 /// Returns true if MemberCore is explicitly marked with CLSCompliantAttribute
216 protected bool HasClsCompliantAttribute {
218 return (caching_flags & Flags.HasClsCompliantAttribute) != 0;
223 /// This method is used to testing error 3005 (Method or parameter name collision).
225 protected abstract bool IsIdentifierClsCompliant (DeclSpace ds);
228 /// Common helper method for identifier and parameters CLS-Compliant testing.
229 /// When return false error 3005 is reported. True means no violation.
230 /// And error 3006 tests are peformed here because of speed.
232 protected bool IsIdentifierAndParamClsCompliant (DeclSpace ds, string name, MemberInfo methodBuilder, Type[] paramTypes)
234 MemberList ml = ds.FindMembers (MemberTypes.Event | MemberTypes.Field | MemberTypes.Method | MemberTypes.Property,
235 BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance, System.Type.FilterNameIgnoreCase, name);
240 bool error3006 = false;
241 for (int i = 0; i < ml.Count; ++i) {
242 MemberInfo mi = ml [i];
243 if (name == mi.Name) {
244 MethodBase method = mi as MethodBase;
245 if (method == null || method == methodBuilder || paramTypes == null || paramTypes.Length == 0)
248 if (AttributeTester.AreOverloadedMethodParamsClsCompliant (paramTypes, TypeManager.GetArgumentTypes (method))) {
256 // We need to test if member is not marked as CLSCompliant (false) and if type is not only internal
257 // because BindingFlags.Public returns internal types too
258 DeclSpace temp_ds = TypeManager.LookupDeclSpace (mi.DeclaringType);
260 // Type is external, we can get attribute directly
261 if (temp_ds == null) {
262 object[] cls_attribute = mi.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
263 if (cls_attribute.Length == 1 && (!((CLSCompliantAttribute)cls_attribute[0]).IsCompliant))
266 string tmp_name = String.Concat (temp_ds.Name, '.', mi.Name);
268 MemberCore mc = temp_ds.GetDefinition (tmp_name) as MemberCore;
269 if (!mc.IsClsCompliaceRequired (ds))
273 for (int ii = 0; ii < ml.Count; ++ii) {
277 Report.SymbolRelatedToPreviousError (mi);
281 Report.Error_T (Message.CS3006_Overloaded_method_differing_only_in_ref_or_out_or_in_array_rank_is_not_CLS_compliant, Location, GetSignatureForError ());
290 /// The main virtual method for CLS-Compliant verifications.
291 /// The method returns true if member is CLS-Compliant and false if member is not
292 /// CLS-Compliant which means that CLS-Compliant tests are not necessary. A descendants override it
293 /// and add their extra verifications.
295 protected virtual bool VerifyClsCompliance (DeclSpace ds)
297 if (!IsClsCompliaceRequired (ds)) {
298 if (HasClsCompliantAttribute && !IsExposedFromAssembly (ds)) {
299 Report.Warning (Message.CS3019_CLS_compliance_checking_will_not_be_performed_on_because_it_is_private_or_internal, Location, GetSignatureForError ());
304 if (!CodeGen.Assembly.IsClsCompliant) {
305 if (HasClsCompliantAttribute) {
306 Report.Error_T (Message.CS3014_cannot_be_marked_as_CLS_compliant_because_the_assembly_does_not_have_a_CLSCompliant_attribute, Location, GetSignatureForError ());
310 int index = Name.LastIndexOf ('.');
311 if (Name [index > 0 ? index + 1 : 0] == '_') {
312 Report.Error_T (Message.CS3008_Identifier_is_not_CLS_compliant, Location, GetSignatureForError () );
315 if (!IsIdentifierClsCompliant (ds)) {
316 Report.Error_T (Message.CS3005_Identifier_differing_only_in_case_is_not_CLS_compliant, Location, GetSignatureForError ());
322 protected abstract void VerifyObsoleteAttribute ();
327 /// Base class for structs, classes, enumerations and interfaces.
330 /// They all create new declaration spaces. This
331 /// provides the common foundation for managing those name
334 public abstract class DeclSpace : MemberCore {
336 /// this points to the actual definition that is being
337 /// created with System.Reflection.Emit
339 public TypeBuilder TypeBuilder;
342 // This is the namespace in which this typecontainer
343 // was declared. We use this to resolve names.
345 public NamespaceEntry NamespaceEntry;
347 public Hashtable Cache = new Hashtable ();
349 public string Basename;
352 /// defined_names is used for toplevel objects
354 protected Hashtable defined_names;
356 static string[] attribute_targets = new string [] { "type" };
358 public DeclSpace (NamespaceEntry ns, TypeContainer parent, string name, Attributes attrs, Location l)
359 : base (parent, name, attrs, l)
362 Basename = name.Substring (1 + name.LastIndexOf ('.'));
363 defined_names = new Hashtable ();
366 public void RecordDecl ()
368 if ((NamespaceEntry != null) && (Parent == RootContext.Tree.Types))
369 NamespaceEntry.DefineName (Basename, this);
373 /// The result value from adding an declaration into
374 /// a struct or a class
376 public enum AdditionResult {
378 /// The declaration has been successfully
379 /// added to the declation space.
384 /// The symbol has already been defined.
389 /// Returned if the declation being added to the
390 /// name space clashes with its container name.
392 /// The only exceptions for this are constructors
393 /// and static constructors
398 /// Returned if a constructor was created (because syntactically
399 /// it looked like a constructor) but was not (because the name
400 /// of the method is not the same as the container class
405 /// This is only used by static constructors to emit the
406 /// error 111, but this error for other things really
407 /// happens at another level for other functions.
412 /// Some other error.
418 /// Returns a status code based purely on the name
419 /// of the member being added
421 protected AdditionResult IsValid (string basename, string name)
423 if (basename == Basename)
424 return AdditionResult.EnclosingClash;
426 if (defined_names.Contains (name))
427 return AdditionResult.NameExists;
429 return AdditionResult.Success;
432 public static int length;
433 public static int small;
436 /// Introduce @name into this declaration space and
437 /// associates it with the object @o. Note that for
438 /// methods this will just point to the first method. o
440 public void DefineName (string name, object o)
442 defined_names.Add (name, o);
445 int p = name.LastIndexOf ('.');
453 /// Returns the object associated with a given name in the declaration
454 /// space. This is the inverse operation of `DefineName'
456 public object GetDefinition (string name)
458 return defined_names [name];
461 bool in_transit = false;
464 /// This function is used to catch recursive definitions
467 public bool InTransit {
478 /// Looks up the alias for the name
480 public string LookupAlias (string name)
482 if (NamespaceEntry != null)
483 return NamespaceEntry.LookupAlias (name);
489 // root_types contains all the types. All TopLevel types
490 // hence have a parent that points to `root_types', that is
491 // why there is a non-obvious test down here.
493 public bool IsTopLevel {
496 if (Parent.Parent == null)
503 public virtual void CloseType ()
505 if ((caching_flags & Flags.CloseTypeCreated) == 0){
507 TypeBuilder.CreateType ();
510 // The try/catch is needed because
511 // nested enumerations fail to load when they
514 // Even if this is the right order (enumerations
515 // declared after types).
517 // Note that this still creates the type and
518 // it is possible to save it
520 caching_flags |= Flags.CloseTypeCreated;
525 /// Should be overriten by the appropriate declaration space
527 public abstract TypeBuilder DefineType ();
530 /// Define all members, but don't apply any attributes or do anything which may
531 /// access not-yet-defined classes. This method also creates the MemberCache.
533 public abstract bool DefineMembers (TypeContainer parent);
536 // Whether this is an `unsafe context'
538 public bool UnsafeContext {
540 if ((ModFlags & Modifiers.UNSAFE) != 0)
543 return Parent.UnsafeContext;
548 public static string MakeFQN (string nsn, string name)
552 return String.Concat (nsn, ".", name);
555 EmitContext type_resolve_ec;
556 EmitContext GetTypeResolveEmitContext (TypeContainer parent, Location loc)
558 type_resolve_ec = new EmitContext (parent, this, loc, null, null, ModFlags, false);
559 type_resolve_ec.ResolvingTypeTree = true;
561 return type_resolve_ec;
565 // Looks up the type, as parsed into the expression `e'
567 public Type ResolveType (Expression e, bool silent, Location loc)
569 if (type_resolve_ec == null)
570 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
571 type_resolve_ec.loc = loc;
572 type_resolve_ec.ContainerType = TypeBuilder;
574 int errors = Report.Errors;
575 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
577 if (d == null || d.eclass != ExprClass.Type){
578 if (!silent && errors == Report.Errors){
579 Report.Error (246, loc, "Cannot find type `"+ e.ToString () +"'");
584 if (!d.CheckAccessLevel (this)) {
585 Report.Error_T (Message.CS0122_is_inaccessible_due_to_its_protection_level, loc, d.Name);
593 // Resolves the expression `e' for a type, and will recursively define
596 public TypeExpr ResolveTypeExpr (Expression e, bool silent, Location loc)
598 if (type_resolve_ec == null)
599 type_resolve_ec = GetTypeResolveEmitContext (Parent, loc);
600 type_resolve_ec.loc = loc;
601 type_resolve_ec.ContainerType = TypeBuilder;
603 TypeExpr d = e.ResolveAsTypeTerminal (type_resolve_ec);
605 if (d == null || d.eclass != ExprClass.Type){
607 Report.Error (246, loc, "Cannot find type `"+ e +"'");
615 public bool CheckAccessLevel (Type check_type)
617 if (check_type == TypeBuilder)
620 TypeAttributes check_attr = check_type.Attributes & TypeAttributes.VisibilityMask;
623 // Broken Microsoft runtime, return public for arrays, no matter what
624 // the accessibility is for their underlying class, and they return
625 // NonPublic visibility for pointers
627 if (check_type.IsArray || check_type.IsPointer)
628 return CheckAccessLevel (TypeManager.GetElementType (check_type));
631 case TypeAttributes.Public:
634 case TypeAttributes.NotPublic:
636 // In same cases is null.
637 if (TypeBuilder == null)
641 // This test should probably use the declaringtype.
643 return check_type.Assembly == TypeBuilder.Assembly;
645 case TypeAttributes.NestedPublic:
648 case TypeAttributes.NestedPrivate:
649 string check_type_name = check_type.FullName;
650 string type_name = TypeBuilder.FullName;
652 int cio = check_type_name.LastIndexOf ('+');
653 string container = check_type_name.Substring (0, cio);
656 // Check if the check_type is a nested class of the current type
658 if (check_type_name.StartsWith (type_name + "+")){
662 if (type_name.StartsWith (container)){
668 case TypeAttributes.NestedFamily:
670 // Only accessible to methods in current type or any subtypes
672 return FamilyAccessible (check_type);
674 case TypeAttributes.NestedFamANDAssem:
675 return (check_type.Assembly == TypeBuilder.Assembly) &&
676 FamilyAccessible (check_type);
678 case TypeAttributes.NestedFamORAssem:
679 return (check_type.Assembly == TypeBuilder.Assembly) ||
680 FamilyAccessible (check_type);
682 case TypeAttributes.NestedAssembly:
683 return check_type.Assembly == TypeBuilder.Assembly;
686 Console.WriteLine ("HERE: " + check_attr);
691 protected bool FamilyAccessible (Type check_type)
693 Type declaring = check_type.DeclaringType;
694 if (TypeBuilder.IsSubclassOf (declaring))
697 string check_type_name = check_type.FullName;
699 int cio = check_type_name.LastIndexOf ('+');
700 string container = check_type_name.Substring (0, cio);
703 // Check if the check_type is a nested class of the current type
705 if (check_type_name.StartsWith (container + "+"))
711 // Access level of a type.
713 enum AccessLevel { // Each column represents `is this scope larger or equal to Blah scope'
714 // Public Assembly Protected
715 Protected = (0 << 0) | (0 << 1) | (X << 2),
716 Public = (X << 0) | (X << 1) | (X << 2),
717 Private = (0 << 0) | (0 << 1) | (0 << 2),
718 Internal = (0 << 0) | (X << 1) | (0 << 2),
719 ProtectedOrInternal = (0 << 0) | (X << 1) | (X << 2),
722 static AccessLevel GetAccessLevelFromModifiers (int flags)
724 if ((flags & Modifiers.INTERNAL) != 0) {
726 if ((flags & Modifiers.PROTECTED) != 0)
727 return AccessLevel.ProtectedOrInternal;
729 return AccessLevel.Internal;
731 } else if ((flags & Modifiers.PROTECTED) != 0)
732 return AccessLevel.Protected;
734 else if ((flags & Modifiers.PRIVATE) != 0)
735 return AccessLevel.Private;
738 return AccessLevel.Public;
741 // What is the effective access level of this?
743 AccessLevel EffectiveAccessLevel {
745 AccessLevel myAccess = GetAccessLevelFromModifiers (ModFlags);
746 if (!IsTopLevel && (Parent != null))
747 return myAccess & Parent.EffectiveAccessLevel;
753 // Return the access level for type `t'
754 static AccessLevel TypeEffectiveAccessLevel (Type t)
757 return AccessLevel.Public;
758 if (t.IsNestedPrivate)
759 return AccessLevel.Private;
761 return AccessLevel.Internal;
763 // By now, it must be nested
764 AccessLevel parentLevel = TypeEffectiveAccessLevel (t.DeclaringType);
766 if (t.IsNestedPublic)
768 if (t.IsNestedAssembly)
769 return parentLevel & AccessLevel.Internal;
770 if (t.IsNestedFamily)
771 return parentLevel & AccessLevel.Protected;
772 if (t.IsNestedFamORAssem)
773 return parentLevel & AccessLevel.ProtectedOrInternal;
774 if (t.IsNestedFamANDAssem)
775 throw new NotImplementedException ("NestedFamANDAssem not implemented, cant make this kind of type from c# anyways");
777 // nested private is taken care of
779 throw new Exception ("I give up, what are you?");
783 // This answers `is the type P, as accessible as a member M which has the
784 // accessability @flags which is declared as a nested member of the type T, this declspace'
786 public bool AsAccessible (Type p, int flags)
789 // 1) if M is private, its accessability is the same as this declspace.
790 // we already know that P is accessible to T before this method, so we
794 if ((flags & Modifiers.PRIVATE) != 0)
797 while (p.IsArray || p.IsPointer || p.IsByRef)
798 p = TypeManager.GetElementType (p);
800 AccessLevel pAccess = TypeEffectiveAccessLevel (p);
801 AccessLevel mAccess = this.EffectiveAccessLevel &
802 GetAccessLevelFromModifiers (flags);
804 // for every place from which we can access M, we must
805 // be able to access P as well. So, we want
806 // For every bit in M and P, M_i -> P_1 == true
807 // or, ~ (M -> P) == 0 <-> ~ ( ~M | P) == 0
809 return ~ (~ mAccess | pAccess) == 0;
812 static DoubleHash dh = new DoubleHash (1000);
814 Type DefineTypeAndParents (DeclSpace tc)
816 DeclSpace container = tc.Parent;
818 if (container.TypeBuilder == null && container.Name != "")
819 DefineTypeAndParents (container);
821 return tc.DefineType ();
824 Type LookupInterfaceOrClass (string ns, string name, out bool error)
831 int p = name.LastIndexOf ('.');
833 if (dh.Lookup (ns, name, out r))
837 // If the type is not a nested type, we do not need `LookupType's processing.
838 // If the @name does not have a `.' in it, this cant be a nested type.
841 if (Namespace.IsNamespace (ns)) {
843 t = TypeManager.LookupType (ns + "." + name);
845 t = TypeManager.LookupTypeDirect (ns + "." + name);
849 t = TypeManager.LookupType (name);
851 t = TypeManager.LookupTypeDirect (name);
855 dh.Insert (ns, name, t);
860 // In case we are fed a composite name, normalize it.
864 ns = MakeFQN (ns, name.Substring (0, p));
865 name = name.Substring (p+1);
868 parent = RootContext.Tree.LookupByNamespace (ns, name);
869 if (parent == null) {
870 dh.Insert (ns, name, null);
874 t = DefineTypeAndParents (parent);
880 dh.Insert (ns, name, t);
884 public static void Error_AmbiguousTypeReference (Location loc, string name, Type t1, Type t2)
886 Report.Error (104, loc,
887 String.Format ("`{0}' is an ambiguous reference ({1} or {2}) ", name,
888 t1.FullName, t2.FullName));
892 /// GetType is used to resolve type names at the DeclSpace level.
893 /// Use this to lookup class/struct bases, interface bases or
894 /// delegate type references
898 /// Contrast this to LookupType which is used inside method bodies to
899 /// lookup types that have already been defined. GetType is used
900 /// during the tree resolution process and potentially define
901 /// recursively the type
903 public Type FindType (Location loc, string name)
909 // For the case the type we are looking for is nested within this one
910 // or is in any base class
912 DeclSpace containing_ds = this;
914 while (containing_ds != null){
915 Type container_type = containing_ds.TypeBuilder;
916 Type current_type = container_type;
918 while (current_type != null && current_type != TypeManager.object_type) {
919 string pre = current_type.FullName;
921 t = LookupInterfaceOrClass (pre, name, out error);
925 if ((t != null) && containing_ds.CheckAccessLevel (t))
928 current_type = current_type.BaseType;
930 containing_ds = containing_ds.Parent;
934 // Attempt to lookup the class on our namespace and all it's implicit parents
936 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.ImplicitParent) {
937 t = LookupInterfaceOrClass (ns.FullName, name, out error);
946 // Attempt to do a direct unqualified lookup
948 t = LookupInterfaceOrClass ("", name, out error);
956 // Attempt to lookup the class on any of the `using'
960 for (NamespaceEntry ns = NamespaceEntry; ns != null; ns = ns.Parent){
962 t = LookupInterfaceOrClass (ns.FullName, name, out error);
969 if (name.IndexOf ('.') > 0)
972 string alias_value = ns.LookupAlias (name);
973 if (alias_value != null) {
974 t = LookupInterfaceOrClass ("", alias_value, out error);
983 // Now check the using clause list
986 foreach (Namespace using_ns in ns.GetUsingTable ()) {
987 match = LookupInterfaceOrClass (using_ns.Name, name, out error);
993 if (CheckAccessLevel (match)) {
994 Error_AmbiguousTypeReference (loc, name, t, match);
1007 //Report.Error (246, Location, "Can not find type `"+name+"'");
1012 /// This function is broken and not what you're looking for. It should only
1013 /// be used while the type is still being created since it doesn't use the cache
1014 /// and relies on the filter doing the member name check.
1016 public abstract MemberList FindMembers (MemberTypes mt, BindingFlags bf,
1017 MemberFilter filter, object criteria);
1020 /// If we have a MemberCache, return it. This property may return null if the
1021 /// class doesn't have a member cache or while it's still being created.
1023 public abstract MemberCache MemberCache {
1027 public override void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb)
1030 TypeBuilder.SetCustomAttribute (cb);
1031 } catch (System.ArgumentException e) {
1032 Report.Warning (-21, a.Location,
1033 "The CharSet named property on StructLayout\n"+
1034 "\tdoes not work correctly on Microsoft.NET\n"+
1035 "\tYou might want to remove the CharSet declaration\n"+
1036 "\tor compile using the Mono runtime instead of the\n"+
1037 "\tMicrosoft .NET runtime\n"+
1038 "\tThe runtime gave the error: " + e);
1043 /// Goes through class hierarchy and get value of first CLSCompliantAttribute that found.
1044 /// If no is attribute exists then return assembly CLSCompliantAttribute.
1046 public bool GetClsCompliantAttributeValue ()
1048 if ((caching_flags & Flags.HasCompliantAttribute_Undetected) == 0)
1049 return (caching_flags & Flags.ClsCompliantAttributeTrue) != 0;
1051 caching_flags &= ~Flags.HasCompliantAttribute_Undetected;
1053 if (OptAttributes != null) {
1054 EmitContext ec = new EmitContext (Parent, this, Location,
1055 null, null, ModFlags, false);
1056 Attribute cls_attribute = OptAttributes.GetClsCompliantAttribute (ec);
1057 if (cls_attribute != null) {
1058 caching_flags |= Flags.HasClsCompliantAttribute;
1059 if (cls_attribute.GetClsCompliantAttributeValue (this)) {
1060 caching_flags |= Flags.ClsCompliantAttributeTrue;
1067 if (Parent == null) {
1068 if (CodeGen.Assembly.IsClsCompliant) {
1069 caching_flags |= Flags.ClsCompliantAttributeTrue;
1075 if (Parent.GetClsCompliantAttributeValue ()) {
1076 caching_flags |= Flags.ClsCompliantAttributeTrue;
1083 // Tests container name for CLS-Compliant name (differing only in case)
1084 // Possible optimalization: search in same namespace only
1085 protected override bool IsIdentifierClsCompliant (DeclSpace ds)
1087 int l = Name.Length;
1089 if (Namespace.LookupNamespace (NamespaceEntry.FullName, false) != null) {
1090 // Seek through all imported types
1091 foreach (string type_name in TypeManager.all_imported_types.Keys)
1093 if (l != type_name.Length)
1096 if (String.Compare (Name, type_name, true, CultureInfo.InvariantCulture) == 0 &&
1097 AttributeTester.IsClsCompliant (TypeManager.all_imported_types [type_name] as Type)) {
1098 Report.SymbolRelatedToPreviousError ((Type)TypeManager.all_imported_types [type_name]);
1104 // Seek through generated types
1105 foreach (string name in RootContext.Tree.Decls.Keys) {
1106 if (l != name.Length)
1109 if (String.Compare (Name, name, true, CultureInfo.InvariantCulture) == 0) {
1114 DeclSpace found_ds = RootContext.Tree.Decls[name] as DeclSpace;
1115 if (found_ds.IsClsCompliaceRequired (found_ds.Parent)) {
1116 Report.SymbolRelatedToPreviousError (found_ds.Location, found_ds.GetSignatureForError ());
1125 public override string[] ValidAttributeTargets {
1127 return attribute_targets;
1133 /// This is a readonly list of MemberInfo's.
1135 public class MemberList : IList {
1136 public readonly IList List;
1140 /// Create a new MemberList from the given IList.
1142 public MemberList (IList list)
1147 this.List = new ArrayList ();
1152 /// Concatenate the ILists `first' and `second' to a new MemberList.
1154 public MemberList (IList first, IList second)
1156 ArrayList list = new ArrayList ();
1157 list.AddRange (first);
1158 list.AddRange (second);
1163 public static readonly MemberList Empty = new MemberList (new ArrayList ());
1166 /// Cast the MemberList into a MemberInfo[] array.
1169 /// This is an expensive operation, only use it if it's really necessary.
1171 public static explicit operator MemberInfo [] (MemberList list)
1173 Timer.StartTimer (TimerType.MiscTimer);
1174 MemberInfo [] result = new MemberInfo [list.Count];
1175 list.CopyTo (result, 0);
1176 Timer.StopTimer (TimerType.MiscTimer);
1188 public bool IsSynchronized {
1190 return List.IsSynchronized;
1194 public object SyncRoot {
1196 return List.SyncRoot;
1200 public void CopyTo (Array array, int index)
1202 List.CopyTo (array, index);
1207 public IEnumerator GetEnumerator ()
1209 return List.GetEnumerator ();
1214 public bool IsFixedSize {
1220 public bool IsReadOnly {
1226 object IList.this [int index] {
1228 return List [index];
1232 throw new NotSupportedException ();
1236 // FIXME: try to find out whether we can avoid the cast in this indexer.
1237 public MemberInfo this [int index] {
1239 return (MemberInfo) List [index];
1243 public int Add (object value)
1245 throw new NotSupportedException ();
1248 public void Clear ()
1250 throw new NotSupportedException ();
1253 public bool Contains (object value)
1255 return List.Contains (value);
1258 public int IndexOf (object value)
1260 return List.IndexOf (value);
1263 public void Insert (int index, object value)
1265 throw new NotSupportedException ();
1268 public void Remove (object value)
1270 throw new NotSupportedException ();
1273 public void RemoveAt (int index)
1275 throw new NotSupportedException ();
1280 /// This interface is used to get all members of a class when creating the
1281 /// member cache. It must be implemented by all DeclSpace derivatives which
1282 /// want to support the member cache and by TypeHandle to get caching of
1283 /// non-dynamic types.
1285 public interface IMemberContainer {
1287 /// The name of the IMemberContainer. This is only used for
1288 /// debugging purposes.
1295 /// The type of this IMemberContainer.
1302 /// Returns the IMemberContainer of the parent class or null if this
1303 /// is an interface or TypeManger.object_type.
1304 /// This is used when creating the member cache for a class to get all
1305 /// members from the parent class.
1307 IMemberContainer Parent {
1312 /// Whether this is an interface.
1319 /// Returns all members of this class with the corresponding MemberTypes
1320 /// and BindingFlags.
1323 /// When implementing this method, make sure not to return any inherited
1324 /// members and check the MemberTypes and BindingFlags properly.
1325 /// Unfortunately, System.Reflection is lame and doesn't provide a way to
1326 /// get the BindingFlags (static/non-static,public/non-public) in the
1327 /// MemberInfo class, but the cache needs this information. That's why
1328 /// this method is called multiple times with different BindingFlags.
1330 MemberList GetMembers (MemberTypes mt, BindingFlags bf);
1333 /// Return the container's member cache.
1335 MemberCache MemberCache {
1341 /// The MemberCache is used by dynamic and non-dynamic types to speed up
1342 /// member lookups. It has a member name based hash table; it maps each member
1343 /// name to a list of CacheEntry objects. Each CacheEntry contains a MemberInfo
1344 /// and the BindingFlags that were initially used to get it. The cache contains
1345 /// all members of the current class and all inherited members. If this cache is
1346 /// for an interface types, it also contains all inherited members.
1348 /// There are two ways to get a MemberCache:
1349 /// * if this is a dynamic type, lookup the corresponding DeclSpace and then
1350 /// use the DeclSpace.MemberCache property.
1351 /// * if this not a dynamic type, call TypeHandle.GetTypeHandle() to get a
1352 /// TypeHandle instance for the type and then use TypeHandle.MemberCache.
1354 public class MemberCache {
1355 public readonly IMemberContainer Container;
1356 protected Hashtable member_hash;
1357 protected Hashtable method_hash;
1360 /// Create a new MemberCache for the given IMemberContainer `container'.
1362 public MemberCache (IMemberContainer container)
1364 this.Container = container;
1366 Timer.IncrementCounter (CounterType.MemberCache);
1367 Timer.StartTimer (TimerType.CacheInit);
1371 // If we have a parent class (we have a parent class unless we're
1372 // TypeManager.object_type), we deep-copy its MemberCache here.
1373 if (Container.IsInterface) {
1376 if (Container.Parent != null)
1377 parent = Container.Parent.MemberCache;
1379 parent = TypeHandle.ObjectType.MemberCache;
1380 member_hash = SetupCacheForInterface (parent);
1381 } else if (Container.Parent != null)
1382 member_hash = SetupCache (Container.Parent.MemberCache);
1384 member_hash = new Hashtable ();
1386 // If this is neither a dynamic type nor an interface, create a special
1387 // method cache with all declared and inherited methods.
1388 Type type = container.Type;
1389 if (!(type is TypeBuilder) && !type.IsInterface) {
1390 method_hash = new Hashtable ();
1394 // Add all members from the current class.
1395 AddMembers (Container);
1397 Timer.StopTimer (TimerType.CacheInit);
1401 /// Bootstrap this member cache by doing a deep-copy of our parent.
1403 Hashtable SetupCache (MemberCache parent)
1405 Hashtable hash = new Hashtable ();
1407 IDictionaryEnumerator it = parent.member_hash.GetEnumerator ();
1408 while (it.MoveNext ()) {
1409 hash [it.Key] = ((ArrayList) it.Value).Clone ();
1417 /// Add the contents of `new_hash' to `hash'.
1419 void AddHashtable (Hashtable hash, MemberCache cache)
1421 Hashtable new_hash = cache.member_hash;
1422 IDictionaryEnumerator it = new_hash.GetEnumerator ();
1423 while (it.MoveNext ()) {
1424 ArrayList list = (ArrayList) hash [it.Key];
1426 hash [it.Key] = list = new ArrayList ();
1428 foreach (CacheEntry entry in (ArrayList) it.Value) {
1429 if (entry.Container != cache.Container)
1437 /// Bootstrap the member cache for an interface type.
1438 /// Type.GetMembers() won't return any inherited members for interface types,
1439 /// so we need to do this manually. Interfaces also inherit from System.Object.
1441 Hashtable SetupCacheForInterface (MemberCache parent)
1443 Hashtable hash = SetupCache (parent);
1444 TypeExpr [] ifaces = TypeManager.GetInterfaces (Container.Type);
1446 foreach (TypeExpr iface in ifaces) {
1447 Type itype = iface.Type;
1449 IMemberContainer iface_container =
1450 TypeManager.LookupMemberContainer (itype);
1452 MemberCache iface_cache = iface_container.MemberCache;
1454 AddHashtable (hash, iface_cache);
1461 /// Add all members from class `container' to the cache.
1463 void AddMembers (IMemberContainer container)
1465 // We need to call AddMembers() with a single member type at a time
1466 // to get the member type part of CacheEntry.EntryType right.
1467 AddMembers (MemberTypes.Constructor, container);
1468 AddMembers (MemberTypes.Field, container);
1469 AddMembers (MemberTypes.Method, container);
1470 AddMembers (MemberTypes.Property, container);
1471 AddMembers (MemberTypes.Event, container);
1472 // Nested types are returned by both Static and Instance searches.
1473 AddMembers (MemberTypes.NestedType,
1474 BindingFlags.Static | BindingFlags.Public, container);
1475 AddMembers (MemberTypes.NestedType,
1476 BindingFlags.Static | BindingFlags.NonPublic, container);
1479 void AddMembers (MemberTypes mt, IMemberContainer container)
1481 AddMembers (mt, BindingFlags.Static | BindingFlags.Public, container);
1482 AddMembers (mt, BindingFlags.Static | BindingFlags.NonPublic, container);
1483 AddMembers (mt, BindingFlags.Instance | BindingFlags.Public, container);
1484 AddMembers (mt, BindingFlags.Instance | BindingFlags.NonPublic, container);
1488 /// Add all members from class `container' with the requested MemberTypes and
1489 /// BindingFlags to the cache. This method is called multiple times with different
1490 /// MemberTypes and BindingFlags.
1492 void AddMembers (MemberTypes mt, BindingFlags bf, IMemberContainer container)
1494 MemberList members = container.GetMembers (mt, bf);
1496 foreach (MemberInfo member in members) {
1497 string name = member.Name;
1499 // We use a name-based hash table of ArrayList's.
1500 ArrayList list = (ArrayList) member_hash [name];
1502 list = new ArrayList ();
1503 member_hash.Add (name, list);
1506 // When this method is called for the current class, the list will
1507 // already contain all inherited members from our parent classes.
1508 // We cannot add new members in front of the list since this'd be an
1509 // expensive operation, that's why the list is sorted in reverse order
1510 // (ie. members from the current class are coming last).
1511 list.Add (new CacheEntry (container, member, mt, bf));
1516 /// Add all declared and inherited methods from class `type' to the method cache.
1518 void AddMethods (Type type)
1520 AddMethods (BindingFlags.Static | BindingFlags.Public |
1521 BindingFlags.FlattenHierarchy, type);
1522 AddMethods (BindingFlags.Static | BindingFlags.NonPublic |
1523 BindingFlags.FlattenHierarchy, type);
1524 AddMethods (BindingFlags.Instance | BindingFlags.Public, type);
1525 AddMethods (BindingFlags.Instance | BindingFlags.NonPublic, type);
1528 void AddMethods (BindingFlags bf, Type type)
1530 MemberInfo [] members = type.GetMethods (bf);
1532 Array.Reverse (members);
1534 foreach (MethodBase member in members) {
1535 string name = member.Name;
1537 // We use a name-based hash table of ArrayList's.
1538 ArrayList list = (ArrayList) method_hash [name];
1540 list = new ArrayList ();
1541 method_hash.Add (name, list);
1544 // Unfortunately, the elements returned by Type.GetMethods() aren't
1545 // sorted so we need to do this check for every member.
1546 BindingFlags new_bf = bf;
1547 if (member.DeclaringType == type)
1548 new_bf |= BindingFlags.DeclaredOnly;
1550 list.Add (new CacheEntry (Container, member, MemberTypes.Method, new_bf));
1557 /// Compute and return a appropriate `EntryType' magic number for the given
1558 /// MemberTypes and BindingFlags.
1560 protected static EntryType GetEntryType (MemberTypes mt, BindingFlags bf)
1562 EntryType type = EntryType.None;
1564 if ((mt & MemberTypes.Constructor) != 0)
1565 type |= EntryType.Constructor;
1566 if ((mt & MemberTypes.Event) != 0)
1567 type |= EntryType.Event;
1568 if ((mt & MemberTypes.Field) != 0)
1569 type |= EntryType.Field;
1570 if ((mt & MemberTypes.Method) != 0)
1571 type |= EntryType.Method;
1572 if ((mt & MemberTypes.Property) != 0)
1573 type |= EntryType.Property;
1574 // Nested types are returned by static and instance searches.
1575 if ((mt & MemberTypes.NestedType) != 0)
1576 type |= EntryType.NestedType | EntryType.Static | EntryType.Instance;
1578 if ((bf & BindingFlags.Instance) != 0)
1579 type |= EntryType.Instance;
1580 if ((bf & BindingFlags.Static) != 0)
1581 type |= EntryType.Static;
1582 if ((bf & BindingFlags.Public) != 0)
1583 type |= EntryType.Public;
1584 if ((bf & BindingFlags.NonPublic) != 0)
1585 type |= EntryType.NonPublic;
1586 if ((bf & BindingFlags.DeclaredOnly) != 0)
1587 type |= EntryType.Declared;
1593 /// The `MemberTypes' enumeration type is a [Flags] type which means that it may
1594 /// denote multiple member types. Returns true if the given flags value denotes a
1595 /// single member types.
1597 public static bool IsSingleMemberType (MemberTypes mt)
1600 case MemberTypes.Constructor:
1601 case MemberTypes.Event:
1602 case MemberTypes.Field:
1603 case MemberTypes.Method:
1604 case MemberTypes.Property:
1605 case MemberTypes.NestedType:
1614 /// We encode the MemberTypes and BindingFlags of each members in a "magic"
1615 /// number to speed up the searching process.
1618 protected enum EntryType {
1623 MaskStatic = Instance|Static,
1627 MaskProtection = Public|NonPublic,
1631 Constructor = 0x020,
1638 MaskType = Constructor|Event|Field|Method|Property|NestedType
1641 protected struct CacheEntry {
1642 public readonly IMemberContainer Container;
1643 public readonly EntryType EntryType;
1644 public readonly MemberInfo Member;
1646 public CacheEntry (IMemberContainer container, MemberInfo member,
1647 MemberTypes mt, BindingFlags bf)
1649 this.Container = container;
1650 this.Member = member;
1651 this.EntryType = GetEntryType (mt, bf);
1656 /// This is called each time we're walking up one level in the class hierarchy
1657 /// and checks whether we can abort the search since we've already found what
1658 /// we were looking for.
1660 protected bool DoneSearching (ArrayList list)
1663 // We've found exactly one member in the current class and it's not
1664 // a method or constructor.
1666 if (list.Count == 1 && !(list [0] is MethodBase))
1670 // Multiple properties: we query those just to find out the indexer
1673 if ((list.Count > 0) && (list [0] is PropertyInfo))
1680 /// Looks up members with name `name'. If you provide an optional
1681 /// filter function, it'll only be called with members matching the
1682 /// requested member name.
1684 /// This method will try to use the cache to do the lookup if possible.
1686 /// Unlike other FindMembers implementations, this method will always
1687 /// check all inherited members - even when called on an interface type.
1689 /// If you know that you're only looking for methods, you should use
1690 /// MemberTypes.Method alone since this speeds up the lookup a bit.
1691 /// When doing a method-only search, it'll try to use a special method
1692 /// cache (unless it's a dynamic type or an interface) and the returned
1693 /// MemberInfo's will have the correct ReflectedType for inherited methods.
1694 /// The lookup process will automatically restart itself in method-only
1695 /// search mode if it discovers that it's about to return methods.
1697 ArrayList global = new ArrayList ();
1698 bool using_global = false;
1700 static MemberInfo [] emptyMemberInfo = new MemberInfo [0];
1702 public MemberInfo [] FindMembers (MemberTypes mt, BindingFlags bf, string name,
1703 MemberFilter filter, object criteria)
1706 throw new Exception ();
1708 bool declared_only = (bf & BindingFlags.DeclaredOnly) != 0;
1709 bool method_search = mt == MemberTypes.Method;
1710 // If we have a method cache and we aren't already doing a method-only search,
1711 // then we restart a method search if the first match is a method.
1712 bool do_method_search = !method_search && (method_hash != null);
1714 ArrayList applicable;
1716 // If this is a method-only search, we try to use the method cache if
1717 // possible; a lookup in the method cache will return a MemberInfo with
1718 // the correct ReflectedType for inherited methods.
1720 if (method_search && (method_hash != null))
1721 applicable = (ArrayList) method_hash [name];
1723 applicable = (ArrayList) member_hash [name];
1725 if (applicable == null)
1726 return emptyMemberInfo;
1729 // 32 slots gives 53 rss/54 size
1730 // 2/4 slots gives 55 rss
1732 // Strange: from 25,000 calls, only 1,800
1733 // are above 2. Why does this impact it?
1736 using_global = true;
1738 Timer.StartTimer (TimerType.CachedLookup);
1740 EntryType type = GetEntryType (mt, bf);
1742 IMemberContainer current = Container;
1745 // `applicable' is a list of all members with the given member name `name'
1746 // in the current class and all its parent classes. The list is sorted in
1747 // reverse order due to the way how the cache is initialy created (to speed
1748 // things up, we're doing a deep-copy of our parent).
1750 for (int i = applicable.Count-1; i >= 0; i--) {
1751 CacheEntry entry = (CacheEntry) applicable [i];
1753 // This happens each time we're walking one level up in the class
1754 // hierarchy. If we're doing a DeclaredOnly search, we must abort
1755 // the first time this happens (this may already happen in the first
1756 // iteration of this loop if there are no members with the name we're
1757 // looking for in the current class).
1758 if (entry.Container != current) {
1759 if (declared_only || DoneSearching (global))
1762 current = entry.Container;
1765 // Is the member of the correct type ?
1766 if ((entry.EntryType & type & EntryType.MaskType) == 0)
1769 // Is the member static/non-static ?
1770 if ((entry.EntryType & type & EntryType.MaskStatic) == 0)
1773 // Apply the filter to it.
1774 if (filter (entry.Member, criteria)) {
1775 if ((entry.EntryType & EntryType.MaskType) != EntryType.Method)
1776 do_method_search = false;
1777 global.Add (entry.Member);
1781 Timer.StopTimer (TimerType.CachedLookup);
1783 // If we have a method cache and we aren't already doing a method-only
1784 // search, we restart in method-only search mode if the first match is
1785 // a method. This ensures that we return a MemberInfo with the correct
1786 // ReflectedType for inherited methods.
1787 if (do_method_search && (global.Count > 0)){
1788 using_global = false;
1790 return FindMembers (MemberTypes.Method, bf, name, filter, criteria);
1793 using_global = false;
1794 MemberInfo [] copy = new MemberInfo [global.Count];
1795 global.CopyTo (copy);
1799 // find the nested type @name in @this.
1800 public Type FindNestedType (string name)
1802 ArrayList applicable = (ArrayList) member_hash [name];
1803 if (applicable == null)
1806 for (int i = applicable.Count-1; i >= 0; i--) {
1807 CacheEntry entry = (CacheEntry) applicable [i];
1808 if ((entry.EntryType & EntryType.NestedType & EntryType.MaskType) != 0)
1809 return (Type) entry.Member;
1816 // This finds the method or property for us to override. invocationType is the type where
1817 // the override is going to be declared, name is the name of the method/property, and
1818 // paramTypes is the parameters, if any to the method or property
1820 // Because the MemberCache holds members from this class and all the base classes,
1821 // we can avoid tons of reflection stuff.
1823 public MemberInfo FindMemberToOverride (Type invocationType, string name, Type [] paramTypes, bool is_property)
1825 ArrayList applicable;
1826 if (method_hash != null && !is_property)
1827 applicable = (ArrayList) method_hash [name];
1829 applicable = (ArrayList) member_hash [name];
1831 if (applicable == null)
1834 // Walk the chain of methods, starting from the top.
1836 for (int i = applicable.Count - 1; i >= 0; i--) {
1837 CacheEntry entry = (CacheEntry) applicable [i];
1839 if ((entry.EntryType & (is_property ? (EntryType.Property | EntryType.Field) : EntryType.Method)) == 0)
1842 PropertyInfo pi = null;
1843 MethodInfo mi = null;
1844 FieldInfo fi = null;
1845 Type [] cmpAttrs = null;
1848 if ((entry.EntryType & EntryType.Field) != 0) {
1849 fi = (FieldInfo)entry.Member;
1851 // TODO: For this case we ignore member type
1852 //fb = TypeManager.GetField (fi);
1853 //cmpAttrs = new Type[] { fb.MemberType };
1855 pi = (PropertyInfo) entry.Member;
1856 cmpAttrs = TypeManager.GetArgumentTypes (pi);
1859 mi = (MethodInfo) entry.Member;
1860 cmpAttrs = TypeManager.GetArgumentTypes (mi);
1864 // TODO: Almost duplicate !
1866 switch (fi.Attributes & FieldAttributes.FieldAccessMask) {
1867 case FieldAttributes.Private:
1869 // A private method is Ok if we are a nested subtype.
1870 // The spec actually is not very clear about this, see bug 52458.
1872 if (invocationType != entry.Container.Type &
1873 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1877 case FieldAttributes.FamANDAssem:
1878 case FieldAttributes.Assembly:
1880 // Check for assembly methods
1882 if (mi.DeclaringType.Assembly != CodeGen.Assembly.Builder)
1886 return entry.Member;
1890 // Check the arguments
1892 if (cmpAttrs.Length != paramTypes.Length)
1895 for (int j = cmpAttrs.Length - 1; j >= 0; j --)
1896 if (paramTypes [j] != cmpAttrs [j])
1900 // get one of the methods because this has the visibility info.
1903 mi = pi.GetGetMethod (true);
1905 mi = pi.GetSetMethod (true);
1911 switch (mi.Attributes & MethodAttributes.MemberAccessMask) {
1912 case MethodAttributes.Private:
1914 // A private method is Ok if we are a nested subtype.
1915 // The spec actually is not very clear about this, see bug 52458.
1917 if (invocationType == entry.Container.Type ||
1918 TypeManager.IsNestedChildOf (invocationType, entry.Container.Type))
1919 return entry.Member;
1922 case MethodAttributes.FamANDAssem:
1923 case MethodAttributes.Assembly:
1925 // Check for assembly methods
1927 if (mi.DeclaringType.Assembly == CodeGen.Assembly.Builder)
1928 return entry.Member;
1933 // A protected method is ok, because we are overriding.
1934 // public is always ok.
1936 return entry.Member;