2 // attribute.cs: Attribute Handler
4 // Author: Ravi Pratap (ravi@ximian.com)
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)
14 using System.Diagnostics;
15 using System.Collections;
16 using System.Collections.Specialized;
17 using System.Reflection;
18 using System.Reflection.Emit;
19 using System.Runtime.InteropServices;
20 using System.Runtime.CompilerServices;
21 using System.Security;
22 using System.Security.Permissions;
25 namespace Mono.CSharp {
28 /// Base class for objects that can have Attributes applied to them.
30 public abstract class Attributable {
32 /// Attributes for this type
34 Attributes attributes;
36 public Attributable (Attributes attrs)
41 public Attributes OptAttributes
52 /// Use member-specific procedure to apply attribute @a in @cb to the entity being built in @builder
54 public abstract void ApplyAttributeBuilder (Attribute a, CustomAttributeBuilder cb);
57 /// Returns one AttributeTarget for this element.
59 public abstract AttributeTargets AttributeTargets { get; }
61 public abstract bool IsClsComplianceRequired (DeclSpace ds);
64 /// Gets list of valid attribute targets for explicit target declaration.
65 /// The first array item is default target. Don't break this rule.
67 public abstract string[] ValidAttributeTargets { get; }
70 public class Attribute {
71 public readonly string ExplicitTarget;
72 public AttributeTargets Target;
74 public readonly string Name;
75 public readonly Expression LeftExpr;
76 public readonly string Identifier;
78 public readonly ArrayList Arguments;
80 public readonly Location Location;
86 static AttributeUsageAttribute DefaultUsageAttribute = new AttributeUsageAttribute (AttributeTargets.All);
88 // non-null if named args present after Resolve () is called
89 PropertyInfo [] prop_info_arr;
90 FieldInfo [] field_info_arr;
91 object [] field_values_arr;
92 object [] prop_values_arr;
95 static PtrHashtable usage_attr_cache = new PtrHashtable ();
97 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
100 Identifier = identifier;
101 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
104 ExplicitTarget = target;
107 void Error_InvalidNamedArgument (string name)
109 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
110 "fields which are not readonly, static or const; or read-write instance properties.",
114 void Error_InvalidNamedAgrumentType (string name)
116 Report.Error (655, Location, "'{0}' is not a valid named attribute argument because its type is not valid attribute type", name);
119 static void Error_AttributeArgumentNotValid (string extra, Location loc)
121 Report.Error (182, loc,
122 "An attribute argument must be a constant expression, typeof " +
123 "expression or array creation expression" + extra);
126 static void Error_AttributeArgumentNotValid (Location loc)
128 Error_AttributeArgumentNotValid ("", loc);
131 static void Error_TypeParameterInAttribute (Location loc)
134 -202, loc, "Can not use a type parameter in an attribute");
138 /// This is rather hack. We report many emit attribute error with same error to be compatible with
139 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
141 public void Error_AttributeEmitError (string inner)
143 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
146 public void Error_InvalidSecurityParent ()
148 Error_AttributeEmitError ("it is attached to invalid parent");
151 void Error_AttributeConstructorMismatch ()
153 Report.Error (-6, Location,
154 "Could not find a constructor for this argument list.");
158 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
160 return expr.ResolveAsTypeStep (ec);
163 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
168 FullNamedExpression n1 = null;
169 FullNamedExpression n2 = null;
170 string IdentifierAttribute = Identifier + "Attribute";
171 if (LeftExpr == null) {
172 n1 = ResolveAsTypeStep (new SimpleName (Identifier, Location), ec);
174 // FIXME: Shouldn't do this for quoted attributes: [@A]
175 n2 = ResolveAsTypeStep (new SimpleName (IdentifierAttribute, Location), ec);
177 FullNamedExpression l = ResolveAsTypeStep (LeftExpr, ec);
179 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
182 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
184 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
185 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
188 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
189 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
192 t1 = te1.ResolveType (ec);
194 t2 = te2.ResolveType (ec);
198 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
200 Type CheckAttributeType (EmitContext ec)
203 ResolvePossibleAttributeTypes (ec, out t1, out t2);
205 String err0616 = null;
206 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
208 err0616 = "'{0}' is not an attribute class";
210 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
212 err0616 = (err0616 != null)
213 ? "Neither '{0}' nor '{0}Attribute' is an attribute class"
214 : "'{0}Attribute': is not an attribute class";
217 if (t1 != null && t2 != null) {
218 Report.Error (1614, Location, "'{0}' is ambiguous; use either '@{0}' or '{0}Attribute'", Name);
225 if (err0616 != null) {
226 Report.Error (616, Location, err0616, Name);
230 Report.Error (246, Location,
231 "Could not find attribute '{0}' (are you missing a using directive or an assembly reference ?)",
234 resolve_error = true;
238 public virtual Type ResolveType (EmitContext ec)
240 if (Type == null && !resolve_error)
241 Type = CheckAttributeType (ec);
245 string GetFullMemberName (string member)
247 return Type.FullName + '.' + member;
251 // Given an expression, if the expression is a valid attribute-argument-expression
252 // returns an object that can be used to encode it, or null on failure.
254 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
256 if (e is EnumConstant) {
257 if (RootContext.StdLib)
258 result = ((EnumConstant)e).GetValueAsEnumType ();
260 result = ((EnumConstant)e).GetValue ();
265 Constant constant = e as Constant;
266 if (constant != null) {
267 if (e.Type != arg_type) {
268 constant = Const.ChangeType (loc, constant, arg_type);
269 if (constant == null) {
271 Error_AttributeArgumentNotValid (loc);
275 result = constant.GetValue ();
277 } else if (e is TypeOf) {
278 result = ((TypeOf) e).TypeArg;
280 } else if (e is ArrayCreation){
281 result = ((ArrayCreation) e).EncodeAsAttribute ();
284 } else if (e is EmptyCast) {
285 Expression child = ((EmptyCast)e).Child;
286 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
290 Error_AttributeArgumentNotValid (loc);
294 bool IsValidArgumentType (Type t)
296 return TypeManager.IsPrimitiveType (t) ||
297 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
298 TypeManager.IsEnumType (t) ||
299 t == TypeManager.string_type ||
300 t == TypeManager.object_type ||
301 t == TypeManager.type_type;
304 // Cache for parameter-less attributes
305 static PtrHashtable att_cache = new PtrHashtable ();
307 public CustomAttributeBuilder Resolve (EmitContext ec)
312 resolve_error = true;
315 Type = CheckAttributeType (ec);
321 if (Type.IsAbstract) {
322 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
326 if (Arguments == null) {
327 object o = att_cache [Type];
329 resolve_error = false;
330 return (CustomAttributeBuilder)o;
334 ConstructorInfo ctor = ResolveArguments (ec);
335 CustomAttributeBuilder cb;
338 if (prop_info_arr != null || field_info_arr != null) {
339 cb = new CustomAttributeBuilder (
341 prop_info_arr, prop_values_arr,
342 field_info_arr, field_values_arr);
344 cb = new CustomAttributeBuilder (
347 if (pos_values.Length == 0)
348 att_cache.Add (Type, cb);
352 Error_AttributeArgumentNotValid (Location);
356 resolve_error = false;
360 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
362 // Now we extract the positional and named arguments
364 ArrayList pos_args = null;
365 ArrayList named_args = null;
366 int pos_arg_count = 0;
367 int named_arg_count = 0;
369 if (Arguments != null) {
370 pos_args = (ArrayList) Arguments [0];
371 if (pos_args != null)
372 pos_arg_count = pos_args.Count;
373 if (Arguments.Count > 1) {
374 named_args = (ArrayList) Arguments [1];
375 named_arg_count = named_args.Count;
379 pos_values = new object [pos_arg_count];
382 // First process positional arguments
386 for (i = 0; i < pos_arg_count; i++) {
387 Argument a = (Argument) pos_args [i];
390 if (!a.Resolve (ec, Location))
396 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
399 pos_values [i] = val;
401 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
402 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
408 // Now process named arguments
411 ArrayList field_infos = null;
412 ArrayList prop_infos = null;
413 ArrayList field_values = null;
414 ArrayList prop_values = null;
415 Hashtable seen_names = null;
417 if (named_arg_count > 0) {
418 field_infos = new ArrayList ();
419 prop_infos = new ArrayList ();
420 field_values = new ArrayList ();
421 prop_values = new ArrayList ();
423 seen_names = new Hashtable();
426 for (i = 0; i < named_arg_count; i++) {
427 DictionaryEntry de = (DictionaryEntry) named_args [i];
428 string member_name = (string) de.Key;
429 Argument a = (Argument) de.Value;
432 if (seen_names.Contains(member_name)) {
433 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
436 seen_names.Add(member_name, 1);
438 if (!a.Resolve (ec, Location))
441 Expression member = Expression.MemberLookup (
442 ec, Type, member_name,
443 MemberTypes.Field | MemberTypes.Property,
444 BindingFlags.Public | BindingFlags.Instance,
447 if (member == null) {
448 member = Expression.MemberLookup (ec, Type, member_name,
449 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
452 if (member != null) {
453 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
459 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
464 if (!(member is PropertyExpr || member is FieldExpr)) {
465 Error_InvalidNamedArgument (member_name);
470 if (e is TypeParameterExpr){
471 Error_TypeParameterInAttribute (Location);
475 if (member is PropertyExpr) {
476 PropertyExpr pe = (PropertyExpr) member;
477 PropertyInfo pi = pe.PropertyInfo;
479 if (!pi.CanWrite || !pi.CanRead) {
480 Report.SymbolRelatedToPreviousError (pi);
481 Error_InvalidNamedArgument (member_name);
485 if (!IsValidArgumentType (pi.PropertyType)) {
486 Report.SymbolRelatedToPreviousError (pi);
487 Error_InvalidNamedAgrumentType (member_name);
492 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
495 prop_values.Add (value);
498 } else if (member is FieldExpr) {
499 FieldExpr fe = (FieldExpr) member;
500 FieldInfo fi = fe.FieldInfo;
503 Error_InvalidNamedArgument (member_name);
507 if (!IsValidArgumentType (fi.FieldType)) {
508 Report.SymbolRelatedToPreviousError (fi);
509 Error_InvalidNamedAgrumentType (member_name);
514 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
517 field_values.Add (value);
519 field_infos.Add (fi);
523 Expression mg = Expression.MemberLookup (
524 ec, Type, ".ctor", MemberTypes.Constructor,
525 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
529 Error_AttributeConstructorMismatch ();
533 MethodBase constructor = Invocation.OverloadResolve (
534 ec, (MethodGroupExpr) mg, pos_args, false, Location);
536 if (constructor == null) {
541 // Here we do the checks which should be done by corlib or by runtime.
542 // However Zoltan doesn't like it and every Mono compiler has to do it again.
544 if (Type == TypeManager.guid_attr_type) {
546 new Guid ((string)pos_values [0]);
548 catch (Exception e) {
549 Error_AttributeEmitError (e.Message);
553 // if (Type == TypeManager.methodimpl_attr_type &&
554 // pos_values.Length == 1 && ((Argument)pos_args [0]).Type == TypeManager.short_type &&
555 // !System.Enum.IsDefined (TypeManager.method_impl_options, pos_values [0])) {
556 // Error_AttributeEmitError ("Incorrect argument value.");
560 // Now we perform some checks on the positional args as they
561 // cannot be null for a constructor which expects a parameter
565 ParameterData pd = TypeManager.GetParameterData (constructor);
567 int last_real_param = pd.Count;
569 // When the params is not filled we need to put one
570 if (last_real_param > pos_arg_count) {
571 object [] new_pos_values = new object [pos_arg_count + 1];
572 pos_values.CopyTo (new_pos_values, 0);
573 new_pos_values [pos_arg_count] = new object [] {} ;
574 pos_values = new_pos_values;
579 for (int j = 0; j < pos_arg_count; ++j) {
580 Argument a = (Argument) pos_args [j];
582 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
583 Error_AttributeArgumentNotValid (Location);
587 object value = pos_values [j];
588 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
590 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
592 // TODO: Can failed ?
593 throw new NotImplementedException ();
597 if (j < last_real_param)
600 if (j == last_real_param) {
601 object [] array = new object [pos_arg_count - last_real_param];
602 array [0] = pos_values [j];
603 pos_values [j] = array;
607 object [] params_array = (object []) pos_values [last_real_param];
608 params_array [j - last_real_param] = pos_values [j];
611 // Adjust the size of the pos_values if it had params
612 if (last_real_param != pos_arg_count) {
613 object [] new_pos_values = new object [last_real_param + 1];
614 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
615 pos_values = new_pos_values;
618 if (named_arg_count > 0) {
619 prop_info_arr = new PropertyInfo [prop_infos.Count];
620 field_info_arr = new FieldInfo [field_infos.Count];
621 field_values_arr = new object [field_values.Count];
622 prop_values_arr = new object [prop_values.Count];
624 field_infos.CopyTo (field_info_arr, 0);
625 field_values.CopyTo (field_values_arr, 0);
627 prop_values.CopyTo (prop_values_arr, 0);
628 prop_infos.CopyTo (prop_info_arr, 0);
631 return (ConstructorInfo) constructor;
635 /// Get a string containing a list of valid targets for the attribute 'attr'
637 public string GetValidTargets ()
639 StringBuilder sb = new StringBuilder ();
640 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
642 if ((targets & AttributeTargets.Assembly) != 0)
643 sb.Append ("'assembly' ");
645 if ((targets & AttributeTargets.Class) != 0)
646 sb.Append ("'class' ");
648 if ((targets & AttributeTargets.Constructor) != 0)
649 sb.Append ("'constructor' ");
651 if ((targets & AttributeTargets.Delegate) != 0)
652 sb.Append ("'delegate' ");
654 if ((targets & AttributeTargets.Enum) != 0)
655 sb.Append ("'enum' ");
657 if ((targets & AttributeTargets.Event) != 0)
658 sb.Append ("'event' ");
660 if ((targets & AttributeTargets.Field) != 0)
661 sb.Append ("'field' ");
663 if ((targets & AttributeTargets.Interface) != 0)
664 sb.Append ("'interface' ");
666 if ((targets & AttributeTargets.Method) != 0)
667 sb.Append ("'method' ");
669 if ((targets & AttributeTargets.Module) != 0)
670 sb.Append ("'module' ");
672 if ((targets & AttributeTargets.Parameter) != 0)
673 sb.Append ("'parameter' ");
675 if ((targets & AttributeTargets.Property) != 0)
676 sb.Append ("'property' ");
678 if ((targets & AttributeTargets.ReturnValue) != 0)
679 sb.Append ("'return' ");
681 if ((targets & AttributeTargets.Struct) != 0)
682 sb.Append ("'struct' ");
684 return sb.ToString ();
689 /// Returns AttributeUsage attribute for this type
691 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
693 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
697 Class attr_class = TypeManager.LookupClass (Type);
699 if (attr_class == null) {
700 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
701 ua = (AttributeUsageAttribute)usage_attr [0];
702 usage_attr_cache.Add (Type, ua);
706 Attribute a = attr_class.OptAttributes == null
708 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
711 ? DefaultUsageAttribute
712 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
714 usage_attr_cache.Add (Type, ua);
718 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
720 if (pos_values == null)
721 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
722 // But because a lot of attribute class code must be rewritten will be better to wait...
726 return DefaultUsageAttribute;
728 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
730 object field = GetPropertyValue ("AllowMultiple");
732 usage_attribute.AllowMultiple = (bool)field;
734 field = GetPropertyValue ("Inherited");
736 usage_attribute.Inherited = (bool)field;
738 return usage_attribute;
742 /// Returns custom name of indexer
744 public string GetIndexerAttributeValue (EmitContext ec)
746 if (pos_values == null)
747 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
748 // But because a lot of attribute class code must be rewritten will be better to wait...
754 return pos_values [0] as string;
758 /// Returns condition of ConditionalAttribute
760 public string GetConditionalAttributeValue (EmitContext ec)
762 if (pos_values == null)
763 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
764 // But because a lot of attribute class code must be rewritten will be better to wait...
770 return (string)pos_values [0];
774 /// Creates the instance of ObsoleteAttribute from this attribute instance
776 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
778 if (pos_values == null)
779 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
780 // But because a lot of attribute class code must be rewritten will be better to wait...
786 if (pos_values == null || pos_values.Length == 0)
787 return new ObsoleteAttribute ();
789 if (pos_values.Length == 1)
790 return new ObsoleteAttribute ((string)pos_values [0]);
792 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
796 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
797 /// before ApplyAttribute. We need to resolve the arguments.
798 /// This situation occurs when class deps is differs from Emit order.
800 public bool GetClsCompliantAttributeValue (EmitContext ec)
802 if (pos_values == null)
803 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
804 // But because a lot of attribute class code must be rewritten will be better to wait...
810 return (bool)pos_values [0];
814 /// Tests permitted SecurityAction for assembly or other types
816 public bool CheckSecurityActionValidity (bool for_assembly)
818 SecurityAction action = GetSecurityActionValue ();
821 case SecurityAction.Demand:
822 case SecurityAction.Assert:
823 case SecurityAction.Deny:
824 case SecurityAction.PermitOnly:
825 case SecurityAction.LinkDemand:
826 case SecurityAction.InheritanceDemand:
827 case SecurityAction.LinkDemandChoice:
828 case SecurityAction.InheritanceDemandChoice:
829 case SecurityAction.DemandChoice:
834 case SecurityAction.RequestMinimum:
835 case SecurityAction.RequestOptional:
836 case SecurityAction.RequestRefuse:
842 Error_AttributeEmitError ("SecurityAction is out of range X");
846 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
850 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
852 return (SecurityAction)pos_values [0];
856 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
858 /// <returns></returns>
859 public void ExtractSecurityPermissionSet (ListDictionary permissions)
861 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
862 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
866 SecurityAttribute sa;
867 // For all assemblies except corlib we can avoid all hacks
868 if (RootContext.StdLib) {
869 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
871 if (prop_info_arr != null) {
872 for (int i = 0; i < prop_info_arr.Length; ++i) {
873 PropertyInfo pi = prop_info_arr [i];
874 pi.SetValue (sa, prop_values_arr [i], null);
878 Type temp_type = Type.GetType (Type.FullName);
879 // HACK: All mscorlib attributes have same ctor syntax
880 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
882 // All types are from newly created corlib but for invocation with old we need to convert them
883 if (prop_info_arr != null) {
884 for (int i = 0; i < prop_info_arr.Length; ++i) {
885 PropertyInfo emited_pi = prop_info_arr [i];
886 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
888 object old_instance = pi.PropertyType.IsEnum ?
889 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
892 pi.SetValue (sa, old_instance, null);
898 perm = sa.CreatePermission ();
899 SecurityAction action = GetSecurityActionValue ();
901 // IS is correct because for corlib we are using an instance from old corlib
902 if (!(perm is System.Security.CodeAccessPermission)) {
904 case SecurityAction.Demand:
905 action = (SecurityAction)13;
907 case SecurityAction.LinkDemand:
908 action = (SecurityAction)14;
910 case SecurityAction.InheritanceDemand:
911 action = (SecurityAction)15;
916 PermissionSet ps = (PermissionSet)permissions [action];
918 if (sa is PermissionSetAttribute)
919 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
921 ps = new PermissionSet (PermissionState.None);
923 permissions.Add (action, ps);
924 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
925 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
926 permissions [action] = ps;
928 ps.AddPermission (perm);
931 object GetValue (object value)
933 if (value is EnumConstant)
934 return ((EnumConstant) value).GetValue ();
939 object GetPropertyValue (string name)
941 if (prop_info_arr == null)
944 for (int i = 0; i < prop_info_arr.Length; ++i) {
945 if (prop_info_arr [i].Name == name)
946 return prop_values_arr [i];
952 object GetFieldValue (string name)
955 if (field_info_arr == null)
958 foreach (FieldInfo fi in field_info_arr) {
960 return GetValue (field_values_arr [i]);
966 public UnmanagedMarshal GetMarshal (Attributable attr)
968 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
970 object value = GetFieldValue ("SizeParamIndex");
971 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
972 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
976 object o = GetFieldValue ("ArraySubType");
977 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
979 switch (UnmanagedType) {
980 case UnmanagedType.CustomMarshaler: {
981 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
982 BindingFlags.Static | BindingFlags.Public);
983 if (define_custom == null) {
984 Report.RuntimeMissingSupport (Location, "set marshal info");
988 object [] args = new object [4];
989 args [0] = GetFieldValue ("MarshalTypeRef");
990 args [1] = GetFieldValue ("MarshalCookie");
991 args [2] = GetFieldValue ("MarshalType");
992 args [3] = Guid.Empty;
993 return (UnmanagedMarshal) define_custom.Invoke (null, args);
995 case UnmanagedType.LPArray: {
996 object size_const = GetFieldValue ("SizeConst");
997 object size_param_index = GetFieldValue ("SizeParamIndex");
999 if ((size_const != null) || (size_param_index != null)) {
1000 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
1001 if (define_array == null) {
1002 Report.RuntimeMissingSupport (Location, "set marshal info");
1006 object [] args = new object [3];
1007 args [0] = array_sub_type;
1008 args [1] = size_const == null ? -1 : size_const;
1009 args [2] = size_param_index == null ? -1 : size_param_index;
1010 return (UnmanagedMarshal) define_array.Invoke (null, args);
1013 return UnmanagedMarshal.DefineLPArray (array_sub_type);
1015 case UnmanagedType.SafeArray:
1016 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
1018 case UnmanagedType.ByValArray:
1019 FieldMember fm = attr as FieldMember;
1021 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
1024 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
1026 case UnmanagedType.ByValTStr:
1027 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
1030 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
1034 public CharSet GetCharSetValue ()
1036 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
1039 public MethodImplOptions GetMethodImplOptions ()
1041 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1044 public LayoutKind GetLayoutKindValue ()
1046 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1050 /// Emit attribute for Attributable symbol
1052 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1054 CustomAttributeBuilder cb = Resolve (ec);
1058 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1059 if ((usage_attr.ValidOn & Target) == 0) {
1060 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
1065 ias.ApplyAttributeBuilder (this, cb);
1067 catch (Exception e) {
1068 Error_AttributeEmitError (e.Message);
1072 if (!usage_attr.AllowMultiple) {
1073 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1074 if (emitted_targets == null) {
1075 emitted_targets = new ArrayList ();
1076 emitted_attr.Add (Type, emitted_targets);
1077 } else if (emitted_targets.Contains (Target)) {
1078 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1081 emitted_targets.Add (Target);
1084 if (!RootContext.VerifyClsCompliance)
1087 // Here we are testing attribute arguments for array usage (error 3016)
1088 if (ias.IsClsComplianceRequired (ec.DeclSpace)) {
1089 if (Arguments == null)
1092 ArrayList pos_args = (ArrayList) Arguments [0];
1093 if (pos_args != null) {
1094 foreach (Argument arg in pos_args) {
1095 // Type is undefined (was error 246)
1096 if (arg.Type == null)
1099 if (arg.Type.IsArray) {
1100 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1106 if (Arguments.Count < 2)
1109 ArrayList named_args = (ArrayList) Arguments [1];
1110 foreach (DictionaryEntry de in named_args) {
1111 Argument arg = (Argument) de.Value;
1113 // Type is undefined (was error 246)
1114 if (arg.Type == null)
1117 if (arg.Type.IsArray) {
1118 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1125 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1126 MethodAttributes flags, Type ret_type, Type [] param_types)
1128 if (pos_values == null)
1129 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1130 // But because a lot of attribute class code must be rewritten will be better to wait...
1136 string dll_name = (string)pos_values [0];
1139 CallingConvention cc = CallingConvention.Winapi;
1140 CharSet charset = CodeGen.Module.DefaultCharSet;
1141 bool preserve_sig = true;
1142 string entry_point = name;
1143 bool best_fit_mapping = false;
1144 bool throw_on_unmappable = false;
1146 bool best_fit_mapping_set = false;
1147 bool throw_on_unmappable_set = false;
1149 MethodInfo set_best_fit = null;
1150 MethodInfo set_throw_on = null;
1152 if (field_info_arr != null) {
1153 int char_set_extra = 0;
1155 for (int i = 0; i < field_info_arr.Length; i++) {
1156 switch (field_info_arr [i].Name) {
1157 case "BestFitMapping":
1158 best_fit_mapping = (bool) field_values_arr [i];
1159 best_fit_mapping_set = true;
1161 case "CallingConvention":
1162 cc = (CallingConvention) field_values_arr [i];
1165 charset = (CharSet) field_values_arr [i];
1168 entry_point = (string) field_values_arr [i];
1170 case "ExactSpelling":
1171 char_set_extra |= 0x01;
1174 preserve_sig = (bool) field_values_arr [i];
1176 case "SetLastError":
1177 char_set_extra |= 0x40;
1179 case "ThrowOnUnmappableChar":
1180 throw_on_unmappable = (bool) field_values_arr [i];
1181 throw_on_unmappable_set = true;
1184 throw new InternalErrorException (field_info_arr [i].ToString ());
1187 charset |= (CharSet)char_set_extra;
1190 if (throw_on_unmappable_set || best_fit_mapping_set) {
1191 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1192 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1194 if ((set_best_fit == null) || (set_throw_on == null)) {
1195 Report.Error (-1, Location,
1196 "The ThrowOnUnmappableChar and BestFitMapping attributes can only be emitted when running on the mono runtime.");
1202 MethodBuilder mb = builder.DefinePInvokeMethod (
1203 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1204 CallingConventions.Standard, ret_type, param_types, cc, charset);
1207 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1209 if (throw_on_unmappable_set)
1210 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1211 if (best_fit_mapping_set)
1212 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1216 catch (ArgumentException e) {
1217 Error_AttributeEmitError (e.Message);
1222 private Expression GetValue ()
1224 if ((Arguments == null) || (Arguments.Count < 1))
1226 ArrayList al = (ArrayList) Arguments [0];
1227 if ((al == null) || (al.Count < 1))
1229 Argument arg = (Argument) al [0];
1230 if ((arg == null) || (arg.Expr == null))
1235 public string GetString ()
1237 Expression e = GetValue ();
1238 if (e is StringLiteral)
1239 return (e as StringLiteral).Value;
1243 public bool GetBoolean ()
1245 Expression e = GetValue ();
1246 if (e is BoolLiteral)
1247 return (e as BoolLiteral).Value;
1254 /// For global attributes (assembly, module) we need special handling.
1255 /// Attributes can be located in the several files
1257 public class GlobalAttribute: Attribute
1259 public readonly NamespaceEntry ns;
1261 public GlobalAttribute (TypeContainer container, string target,
1262 Expression left_expr, string identifier, ArrayList args, Location loc):
1263 base (target, left_expr, identifier, args, loc)
1265 ns = container.NamespaceEntry;
1270 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1271 // each time a new file is parsed. However, we need to use the NamespaceEntry
1272 // in effect where the attribute was used. Since code elsewhere cannot assume
1273 // that the NamespaceEntry is right, just overwrite it.
1275 // Precondition: RootContext.Tree.Types == null
1277 if (RootContext.Tree.Types.NamespaceEntry != null)
1278 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1280 RootContext.Tree.Types.NamespaceEntry = ns;
1285 RootContext.Tree.Types.NamespaceEntry = null;
1288 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
1292 return base.ResolveAsTypeStep (expr, ec);
1299 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1303 return base.ResolveArguments (ec);
1311 public class Attributes {
1312 public ArrayList Attrs;
1314 public Attributes (Attribute a)
1316 Attrs = new ArrayList ();
1320 public Attributes (ArrayList attrs)
1325 public void AddAttributes (ArrayList attrs)
1327 Attrs.AddRange (attrs);
1331 /// Checks whether attribute target is valid for the current element
1333 public bool CheckTargets (Attributable member)
1335 string[] valid_targets = member.ValidAttributeTargets;
1336 foreach (Attribute a in Attrs) {
1337 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1338 a.Target = member.AttributeTargets;
1342 // TODO: we can skip the first item
1343 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1344 switch (a.ExplicitTarget) {
1345 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1346 case "param": a.Target = AttributeTargets.Parameter; continue;
1347 case "field": a.Target = AttributeTargets.Field; continue;
1348 case "method": a.Target = AttributeTargets.Method; continue;
1349 case "property": a.Target = AttributeTargets.Property; continue;
1351 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1354 StringBuilder sb = new StringBuilder ();
1355 foreach (string s in valid_targets) {
1359 sb.Remove (sb.Length - 2, 2);
1360 Report.Error (657, a.Location, "'{0}' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are '{1}'", a.ExplicitTarget, sb.ToString ());
1366 public Attribute Search (Type t, EmitContext ec)
1368 foreach (Attribute a in Attrs) {
1369 if (a.ResolveType (ec) == t)
1376 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1378 public Attribute[] SearchMulti (Type t, EmitContext ec)
1380 ArrayList ar = null;
1382 foreach (Attribute a in Attrs) {
1383 if (a.ResolveType (ec) == t) {
1385 ar = new ArrayList ();
1390 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1393 public void Emit (EmitContext ec, Attributable ias)
1397 ListDictionary ld = new ListDictionary ();
1399 foreach (Attribute a in Attrs)
1400 a.Emit (ec, ias, ld);
1403 public bool Contains (Type t, EmitContext ec)
1405 return Search (t, ec) != null;
1410 /// Helper class for attribute verification routine.
1412 sealed class AttributeTester
1414 static PtrHashtable analyzed_types = new PtrHashtable ();
1415 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1416 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1417 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1419 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1421 static object TRUE = new object ();
1422 static object FALSE = new object ();
1424 private AttributeTester ()
1428 public enum Result {
1435 /// Returns true if parameters of two compared methods are CLS-Compliant.
1436 /// It tests differing only in ref or out, or in array rank.
1438 public static Result AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1440 if (types_a == null || types_b == null)
1443 if (types_a.Length != types_b.Length)
1446 Result result = Result.Ok;
1447 for (int i = 0; i < types_b.Length; ++i) {
1448 Type aType = types_a [i];
1449 Type bType = types_b [i];
1451 if (aType.IsArray && bType.IsArray) {
1452 Type a_el_type = aType.GetElementType ();
1453 Type b_el_type = bType.GetElementType ();
1454 if (aType.GetArrayRank () != bType.GetArrayRank () && a_el_type == b_el_type) {
1455 result = Result.RefOutArrayError;
1459 if (a_el_type.IsArray || b_el_type.IsArray) {
1460 result = Result.ArrayArrayError;
1465 Type aBaseType = aType;
1466 bool is_either_ref_or_out = false;
1468 if (aType.IsByRef || aType.IsPointer) {
1469 aBaseType = aType.GetElementType ();
1470 is_either_ref_or_out = true;
1473 Type bBaseType = bType;
1474 if (bType.IsByRef || bType.IsPointer)
1476 bBaseType = bType.GetElementType ();
1477 is_either_ref_or_out = !is_either_ref_or_out;
1480 if (aBaseType != bBaseType)
1483 if (is_either_ref_or_out)
1484 result = Result.RefOutArrayError;
1490 /// Goes through all parameters and test if they are CLS-Compliant.
1492 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1494 if (fixedParameters == null)
1497 foreach (Parameter arg in fixedParameters) {
1498 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1499 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1508 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1510 public static bool IsClsCompliant (Type type)
1515 object type_compliance = analyzed_types[type];
1516 if (type_compliance != null)
1517 return type_compliance == TRUE;
1519 if (type.IsPointer) {
1520 analyzed_types.Add (type, null);
1525 if (type.IsArray || type.IsByRef) {
1526 result = IsClsCompliant (TypeManager.GetElementType (type));
1528 result = AnalyzeTypeCompliance (type);
1530 analyzed_types.Add (type, result ? TRUE : FALSE);
1535 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1537 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1539 FieldBase fb = TypeManager.GetField (fi);
1541 return fb as IFixedBuffer;
1544 object o = fixed_buffer_cache [fi];
1546 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1547 fixed_buffer_cache.Add (fi, FALSE);
1551 IFixedBuffer iff = new FixedFieldExternal (fi);
1552 fixed_buffer_cache.Add (fi, iff);
1559 return (IFixedBuffer)o;
1562 public static void VerifyModulesClsCompliance ()
1564 Module[] modules = TypeManager.Modules;
1565 if (modules == null)
1568 // The first module is generated assembly
1569 for (int i = 1; i < modules.Length; ++i) {
1570 Module module = modules [i];
1571 if (!IsClsCompliant (module)) {
1572 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1579 /// Tests container name for CLS-Compliant name (differing only in case)
1581 public static void VerifyTopLevelNameClsCompliance ()
1583 Hashtable locase_table = new Hashtable ();
1585 // Convert imported type names to lower case and ignore not cls compliant
1586 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1587 Type t = (Type)de.Value;
1588 if (!AttributeTester.IsClsCompliant (t))
1591 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1594 foreach (DictionaryEntry de in RootContext.Tree.AllDecls) {
1595 if (!(de.Key is MemberName))
1596 throw new InternalErrorException ("");
1597 DeclSpace decl = (DeclSpace) de.Value;
1598 if (!decl.IsClsComplianceRequired (decl))
1601 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1602 if (!locase_table.Contains (lcase)) {
1603 locase_table.Add (lcase, decl);
1607 object conflict = locase_table [lcase];
1608 if (conflict is Type)
1609 Report.SymbolRelatedToPreviousError ((Type)conflict);
1611 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1613 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1617 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1619 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1620 if (CompliantAttribute.Length == 0)
1623 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1626 static bool AnalyzeTypeCompliance (Type type)
1628 if (type.IsGenericInstance)
1629 type = type.GetGenericTypeDefinition ();
1630 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1632 return ds.IsClsComplianceRequired (ds.Parent);
1634 if (type.IsGenericParameter)
1637 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1638 if (CompliantAttribute.Length == 0)
1639 return IsClsCompliant (type.Assembly);
1641 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1645 /// Returns instance of ObsoleteAttribute when type is obsolete
1647 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1649 object type_obsolete = analyzed_types_obsolete [type];
1650 if (type_obsolete == FALSE)
1653 if (type_obsolete != null)
1654 return (ObsoleteAttribute)type_obsolete;
1656 ObsoleteAttribute result = null;
1657 if (type.IsByRef || type.IsArray || type.IsPointer) {
1658 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1659 } else if (type.IsGenericParameter || type.IsGenericInstance)
1662 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1664 // Type is external, we can get attribute directly
1665 if (type_ds == null) {
1666 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1667 if (attribute.Length == 1)
1668 result = (ObsoleteAttribute)attribute [0];
1670 result = type_ds.GetObsoleteAttribute (type_ds);
1674 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1679 /// Returns instance of ObsoleteAttribute when method is obsolete
1681 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1683 IMethodData mc = TypeManager.GetMethod (mb);
1685 return mc.GetObsoleteAttribute ();
1687 // compiler generated methods are not registered by AddMethod
1688 if (mb.DeclaringType is TypeBuilder)
1691 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1693 return GetMemberObsoleteAttribute (pi);
1695 return GetMemberObsoleteAttribute (mb);
1699 /// Returns instance of ObsoleteAttribute when member is obsolete
1701 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1703 object type_obsolete = analyzed_member_obsolete [mi];
1704 if (type_obsolete == FALSE)
1707 if (type_obsolete != null)
1708 return (ObsoleteAttribute)type_obsolete;
1710 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1713 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1714 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1719 /// Common method for Obsolete error/warning reporting.
1721 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1724 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1728 if (oa.Message == null) {
1729 Report.Warning (612, loc, "'{0}' is obsolete", member);
1732 if (RootContext.WarningLevel >= 2)
1733 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1736 public static bool IsConditionalMethodExcluded (MethodBase mb)
1738 object excluded = analyzed_method_excluded [mb];
1739 if (excluded != null)
1740 return excluded == TRUE ? true : false;
1742 if (mb.Mono_IsInflatedMethod)
1745 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1746 if (attrs.Length == 0) {
1747 analyzed_method_excluded.Add (mb, FALSE);
1751 foreach (ConditionalAttribute a in attrs) {
1752 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1753 analyzed_method_excluded.Add (mb, FALSE);
1757 analyzed_method_excluded.Add (mb, TRUE);
1762 /// Analyzes class whether it has attribute which has ConditionalAttribute
1763 /// and its condition is not defined.
1765 public static bool IsAttributeExcluded (Type type)
1770 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1772 // TODO: add caching
1773 // TODO: merge all Type bases attribute caching to one cache to save memory
1774 if (class_decl == null) {
1775 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1776 foreach (ConditionalAttribute ca in attributes) {
1777 if (RootContext.AllDefines.Contains (ca.ConditionString))
1780 return attributes.Length > 0;
1783 return class_decl.IsExcluded ();