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 IsClsCompliaceRequired (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);
133 /// This is rather hack. We report many emit attribute error with same error to be compatible with
134 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
136 public void Error_AttributeEmitError (string inner)
138 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
141 public void Error_InvalidSecurityParent ()
143 Error_AttributeEmitError ("it is attached to invalid parent");
146 void Error_AttributeConstructorMismatch ()
148 Report.Error (-6, Location,
149 "Could not find a constructor for this argument list.");
153 protected virtual FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
155 return expr.ResolveAsTypeStep (ec);
158 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
163 FullNamedExpression n1 = null;
164 FullNamedExpression n2 = null;
165 string IdentifierAttribute = Identifier + "Attribute";
166 if (LeftExpr == null) {
167 n1 = ResolveAsTypeStep (new SimpleName (Identifier, Location), ec);
169 // FIXME: Shouldn't do this for quoted attributes: [@A]
170 n2 = ResolveAsTypeStep (new SimpleName (IdentifierAttribute, Location), ec);
172 FullNamedExpression l = ResolveAsTypeStep (LeftExpr, ec);
174 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
177 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
179 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
180 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
183 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
184 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
187 t1 = te1.ResolveType (ec);
189 t2 = te2.ResolveType (ec);
193 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
195 Type CheckAttributeType (EmitContext ec)
199 ResolvePossibleAttributeTypes (ec, out t1, out t2);
201 String err0616 = null;
203 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
205 err0616 = "'{0}' is not an attribute class";
207 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
209 err0616 = (err0616 != null)
210 ? "Neither '{0}' nor '{0}Attribute' is an attribute class"
211 : "'{0}Attribute': is not an attribute class";
214 if (t1 != null && t2 != null) {
215 Report.Error (1614, Location, "'{0}' is ambiguous; use either '@{0}' or '{0}Attribute'", Name);
223 if (err0616 != null) {
224 Report.Error (616, Location, err0616, Name);
228 Report.Error (246, Location,
229 "Could not find attribute '{0}' (are you missing a using directive or an assembly reference ?)",
232 resolve_error = true;
236 public virtual Type ResolveType (EmitContext ec)
238 if (Type == null && !resolve_error)
239 Type = CheckAttributeType (ec);
243 string GetFullMemberName (string member)
245 return Type.FullName + '.' + member;
249 // Given an expression, if the expression is a valid attribute-argument-expression
250 // returns an object that can be used to encode it, or null on failure.
252 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
254 if (e is EnumConstant) {
255 if (RootContext.StdLib)
256 result = ((EnumConstant)e).GetValueAsEnumType ();
258 result = ((EnumConstant)e).GetValue ();
263 Constant constant = e as Constant;
264 if (constant != null) {
265 if (e.Type != arg_type) {
266 constant = Const.ChangeType (loc, constant, arg_type);
267 if (constant == null) {
269 Error_AttributeArgumentNotValid (loc);
273 result = constant.GetValue ();
275 } else if (e is TypeOf) {
276 result = ((TypeOf) e).TypeArg;
278 } else if (e is ArrayCreation){
279 result = ((ArrayCreation) e).EncodeAsAttribute ();
282 } else if (e is EmptyCast) {
283 Expression child = ((EmptyCast)e).Child;
284 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
288 Error_AttributeArgumentNotValid (loc);
292 bool IsValidArgumentType (Type t)
294 return TypeManager.IsPrimitiveType (t) ||
295 (t.IsArray && TypeManager.IsPrimitiveType (t.GetElementType ())) ||
296 TypeManager.IsEnumType (t) ||
297 t == TypeManager.string_type ||
298 t == TypeManager.object_type ||
299 t == TypeManager.type_type;
302 // Cache for parameter-less attributes
303 static PtrHashtable att_cache = new PtrHashtable ();
305 public CustomAttributeBuilder Resolve (EmitContext ec)
310 resolve_error = true;
313 Type = CheckAttributeType (ec);
319 if (Type.IsAbstract) {
320 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
324 if (Arguments == null) {
325 object o = att_cache [Type];
327 resolve_error = false;
328 return (CustomAttributeBuilder)o;
332 ConstructorInfo ctor = ResolveArguments (ec);
333 CustomAttributeBuilder cb;
336 if (prop_info_arr != null || field_info_arr != null) {
337 cb = new CustomAttributeBuilder (
339 prop_info_arr, prop_values_arr,
340 field_info_arr, field_values_arr);
342 cb = new CustomAttributeBuilder (
345 if (pos_values.Length == 0)
346 att_cache.Add (Type, cb);
350 Error_AttributeArgumentNotValid (Location);
354 resolve_error = false;
358 protected virtual ConstructorInfo ResolveArguments (EmitContext ec)
360 // Now we extract the positional and named arguments
362 ArrayList pos_args = null;
363 ArrayList named_args = null;
364 int pos_arg_count = 0;
365 int named_arg_count = 0;
367 if (Arguments != null) {
368 pos_args = (ArrayList) Arguments [0];
369 if (pos_args != null)
370 pos_arg_count = pos_args.Count;
371 if (Arguments.Count > 1) {
372 named_args = (ArrayList) Arguments [1];
373 named_arg_count = named_args.Count;
377 pos_values = new object [pos_arg_count];
380 // First process positional arguments
384 for (i = 0; i < pos_arg_count; i++) {
385 Argument a = (Argument) pos_args [i];
388 if (!a.Resolve (ec, Location))
394 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
397 pos_values [i] = val;
399 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
400 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
406 // Now process named arguments
409 ArrayList field_infos = null;
410 ArrayList prop_infos = null;
411 ArrayList field_values = null;
412 ArrayList prop_values = null;
413 Hashtable seen_names = null;
415 if (named_arg_count > 0) {
416 field_infos = new ArrayList ();
417 prop_infos = new ArrayList ();
418 field_values = new ArrayList ();
419 prop_values = new ArrayList ();
421 seen_names = new Hashtable();
424 for (i = 0; i < named_arg_count; i++) {
425 DictionaryEntry de = (DictionaryEntry) named_args [i];
426 string member_name = (string) de.Key;
427 Argument a = (Argument) de.Value;
430 if (seen_names.Contains(member_name)) {
431 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
434 seen_names.Add(member_name, 1);
436 if (!a.Resolve (ec, Location))
439 Expression member = Expression.MemberLookup (
440 ec, Type, member_name,
441 MemberTypes.Field | MemberTypes.Property,
442 BindingFlags.Public | BindingFlags.Instance,
445 if (member == null) {
446 member = Expression.MemberLookup (ec, Type, member_name,
447 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
450 if (member != null) {
451 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
457 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
462 if (!(member is PropertyExpr || member is FieldExpr)) {
463 Error_InvalidNamedArgument (member_name);
468 if (member is PropertyExpr) {
469 PropertyExpr pe = (PropertyExpr) member;
470 PropertyInfo pi = pe.PropertyInfo;
472 if (!pi.CanWrite || !pi.CanRead) {
473 Report.SymbolRelatedToPreviousError (pi);
474 Error_InvalidNamedArgument (member_name);
478 if (!IsValidArgumentType (pi.PropertyType)) {
479 Report.SymbolRelatedToPreviousError (pi);
480 Error_InvalidNamedAgrumentType (member_name);
485 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
488 prop_values.Add (value);
491 } else if (member is FieldExpr) {
492 FieldExpr fe = (FieldExpr) member;
493 FieldInfo fi = fe.FieldInfo;
496 Error_InvalidNamedArgument (member_name);
500 if (!IsValidArgumentType (fi.FieldType)) {
501 Report.SymbolRelatedToPreviousError (fi);
502 Error_InvalidNamedAgrumentType (member_name);
507 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
510 field_values.Add (value);
511 field_infos.Add (fi);
515 Expression mg = Expression.MemberLookup (
516 ec, Type, ".ctor", MemberTypes.Constructor,
517 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
521 Error_AttributeConstructorMismatch ();
525 MethodBase constructor = Invocation.OverloadResolve (
526 ec, (MethodGroupExpr) mg, pos_args, false, Location);
528 if (constructor == null) {
533 // Now we perform some checks on the positional args as they
534 // cannot be null for a constructor which expects a parameter
538 ParameterData pd = TypeManager.GetParameterData (constructor);
540 int last_real_param = pd.Count;
542 // When the params is not filled we need to put one
543 if (last_real_param > pos_arg_count) {
544 object [] new_pos_values = new object [pos_arg_count + 1];
545 pos_values.CopyTo (new_pos_values, 0);
546 new_pos_values [pos_arg_count] = new object [] {} ;
547 pos_values = new_pos_values;
552 for (int j = 0; j < pos_arg_count; ++j) {
553 Argument a = (Argument) pos_args [j];
555 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
556 Error_AttributeArgumentNotValid (Location);
560 object value = pos_values [j];
561 if (value != null && a.Type != value.GetType () && TypeManager.IsPrimitiveType (a.Type)) {
563 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
565 // TODO: Can failed ?
566 throw new NotImplementedException ();
570 if (j < last_real_param)
573 if (j == last_real_param) {
574 object [] array = new object [pos_arg_count - last_real_param];
575 array [0] = pos_values [j];
576 pos_values [j] = array;
580 object [] params_array = (object []) pos_values [last_real_param];
581 params_array [j - last_real_param] = pos_values [j];
584 // Adjust the size of the pos_values if it had params
585 if (last_real_param != pos_arg_count) {
586 object [] new_pos_values = new object [last_real_param + 1];
587 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
588 pos_values = new_pos_values;
591 if (named_arg_count > 0) {
592 prop_info_arr = new PropertyInfo [prop_infos.Count];
593 field_info_arr = new FieldInfo [field_infos.Count];
594 field_values_arr = new object [field_values.Count];
595 prop_values_arr = new object [prop_values.Count];
597 field_infos.CopyTo (field_info_arr, 0);
598 field_values.CopyTo (field_values_arr, 0);
600 prop_values.CopyTo (prop_values_arr, 0);
601 prop_infos.CopyTo (prop_info_arr, 0);
604 return (ConstructorInfo) constructor;
608 /// Get a string containing a list of valid targets for the attribute 'attr'
610 public string GetValidTargets ()
612 StringBuilder sb = new StringBuilder ();
613 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
615 if ((targets & AttributeTargets.Assembly) != 0)
616 sb.Append ("'assembly' ");
618 if ((targets & AttributeTargets.Class) != 0)
619 sb.Append ("'class' ");
621 if ((targets & AttributeTargets.Constructor) != 0)
622 sb.Append ("'constructor' ");
624 if ((targets & AttributeTargets.Delegate) != 0)
625 sb.Append ("'delegate' ");
627 if ((targets & AttributeTargets.Enum) != 0)
628 sb.Append ("'enum' ");
630 if ((targets & AttributeTargets.Event) != 0)
631 sb.Append ("'event' ");
633 if ((targets & AttributeTargets.Field) != 0)
634 sb.Append ("'field' ");
636 if ((targets & AttributeTargets.Interface) != 0)
637 sb.Append ("'interface' ");
639 if ((targets & AttributeTargets.Method) != 0)
640 sb.Append ("'method' ");
642 if ((targets & AttributeTargets.Module) != 0)
643 sb.Append ("'module' ");
645 if ((targets & AttributeTargets.Parameter) != 0)
646 sb.Append ("'parameter' ");
648 if ((targets & AttributeTargets.Property) != 0)
649 sb.Append ("'property' ");
651 if ((targets & AttributeTargets.ReturnValue) != 0)
652 sb.Append ("'return' ");
654 if ((targets & AttributeTargets.Struct) != 0)
655 sb.Append ("'struct' ");
657 return sb.ToString ();
662 /// Returns AttributeUsage attribute for this type
664 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
666 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
670 Class attr_class = TypeManager.LookupClass (Type);
672 if (attr_class == null) {
673 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
674 ua = (AttributeUsageAttribute)usage_attr [0];
675 usage_attr_cache.Add (Type, ua);
679 Attribute a = attr_class.OptAttributes == null
681 : attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, attr_class.EmitContext);
684 ? DefaultUsageAttribute
685 : a.GetAttributeUsageAttribute (attr_class.EmitContext);
687 usage_attr_cache.Add (Type, ua);
691 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
693 if (pos_values == null)
694 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
695 // But because a lot of attribute class code must be rewritten will be better to wait...
699 return DefaultUsageAttribute;
701 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
703 object field = GetPropertyValue ("AllowMultiple");
705 usage_attribute.AllowMultiple = (bool)field;
707 field = GetPropertyValue ("Inherited");
709 usage_attribute.Inherited = (bool)field;
711 return usage_attribute;
715 /// Returns custom name of indexer
717 public string GetIndexerAttributeValue (EmitContext ec)
719 if (pos_values == null)
720 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
721 // But because a lot of attribute class code must be rewritten will be better to wait...
727 return pos_values [0] as string;
731 /// Returns condition of ConditionalAttribute
733 public string GetConditionalAttributeValue (EmitContext ec)
735 if (pos_values == null)
736 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
737 // But because a lot of attribute class code must be rewritten will be better to wait...
743 return (string)pos_values [0];
747 /// Creates the instance of ObsoleteAttribute from this attribute instance
749 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
751 if (pos_values == null)
752 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
753 // But because a lot of attribute class code must be rewritten will be better to wait...
759 if (pos_values == null || pos_values.Length == 0)
760 return new ObsoleteAttribute ();
762 if (pos_values.Length == 1)
763 return new ObsoleteAttribute ((string)pos_values [0]);
765 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
769 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
770 /// before ApplyAttribute. We need to resolve the arguments.
771 /// This situation occurs when class deps is differs from Emit order.
773 public bool GetClsCompliantAttributeValue (EmitContext ec)
775 if (pos_values == null)
776 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
777 // But because a lot of attribute class code must be rewritten will be better to wait...
783 return (bool)pos_values [0];
787 /// Tests permitted SecurityAction for assembly or other types
789 public bool CheckSecurityActionValidity (bool for_assembly)
791 SecurityAction action = GetSecurityActionValue ();
793 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
797 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
798 Error_AttributeEmitError ("SecurityAction is out of range");
802 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
806 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
810 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
812 return (SecurityAction)pos_values [0];
816 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
818 /// <returns></returns>
819 public void ExtractSecurityPermissionSet (ListDictionary permissions)
821 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
822 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
826 SecurityAttribute sa;
827 // For all assemblies except corlib we can avoid all hacks
828 if (RootContext.StdLib) {
829 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
831 if (prop_info_arr != null) {
832 for (int i = 0; i < prop_info_arr.Length; ++i) {
833 PropertyInfo pi = prop_info_arr [i];
834 pi.SetValue (sa, prop_values_arr [i], null);
838 Type temp_type = Type.GetType (Type.FullName);
839 // HACK: All mscorlib attributes have same ctor syntax
840 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
842 // All types are from newly created corlib but for invocation with old we need to convert them
843 if (prop_info_arr != null) {
844 for (int i = 0; i < prop_info_arr.Length; ++i) {
845 PropertyInfo emited_pi = prop_info_arr [i];
846 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
848 object old_instance = pi.PropertyType.IsEnum ?
849 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
852 pi.SetValue (sa, old_instance, null);
858 perm = sa.CreatePermission ();
859 SecurityAction action = GetSecurityActionValue ();
861 // IS is correct because for corlib we are using an instance from old corlib
862 if (!(perm is System.Security.CodeAccessPermission)) {
864 case SecurityAction.Demand:
865 action = (SecurityAction)13;
867 case SecurityAction.LinkDemand:
868 action = (SecurityAction)14;
870 case SecurityAction.InheritanceDemand:
871 action = (SecurityAction)15;
876 PermissionSet ps = (PermissionSet)permissions [action];
878 if (sa is PermissionSetAttribute)
879 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
881 ps = new PermissionSet (PermissionState.None);
883 permissions.Add (action, ps);
884 } else if (!ps.IsUnrestricted () && (sa is PermissionSetAttribute) && sa.Unrestricted) {
885 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
886 permissions [action] = ps;
888 ps.AddPermission (perm);
891 object GetValue (object value)
893 if (value is EnumConstant)
894 return ((EnumConstant) value).GetValue ();
899 object GetPropertyValue (string name)
901 if (prop_info_arr == null)
904 for (int i = 0; i < prop_info_arr.Length; ++i) {
905 if (prop_info_arr [i].Name == name)
906 return prop_values_arr [i];
912 object GetFieldValue (string name)
915 if (field_info_arr == null)
918 foreach (FieldInfo fi in field_info_arr) {
920 return GetValue (field_values_arr [i]);
926 public UnmanagedMarshal GetMarshal (Attributable attr)
928 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
930 object value = GetFieldValue ("SizeParamIndex");
931 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
932 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
936 object o = GetFieldValue ("ArraySubType");
937 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
939 switch (UnmanagedType) {
940 case UnmanagedType.CustomMarshaler: {
941 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
942 BindingFlags.Static | BindingFlags.Public);
943 if (define_custom == null) {
944 Report.RuntimeMissingSupport (Location, "set marshal info");
948 object [] args = new object [4];
949 args [0] = GetFieldValue ("MarshalTypeRef");
950 args [1] = GetFieldValue ("MarshalCookie");
951 args [2] = GetFieldValue ("MarshalType");
952 args [3] = Guid.Empty;
953 return (UnmanagedMarshal) define_custom.Invoke (null, args);
955 case UnmanagedType.LPArray: {
956 object size_const = GetFieldValue ("SizeConst");
957 object size_param_index = GetFieldValue ("SizeParamIndex");
959 if ((size_const != null) || (size_param_index != null)) {
960 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
961 if (define_array == null) {
962 Report.RuntimeMissingSupport (Location, "set marshal info");
966 object [] args = new object [3];
967 args [0] = array_sub_type;
968 args [1] = size_const == null ? -1 : size_const;
969 args [2] = size_param_index == null ? -1 : size_param_index;
970 return (UnmanagedMarshal) define_array.Invoke (null, args);
973 return UnmanagedMarshal.DefineLPArray (array_sub_type);
975 case UnmanagedType.SafeArray:
976 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
978 case UnmanagedType.ByValArray:
979 FieldMember fm = attr as FieldMember;
981 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
984 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
986 case UnmanagedType.ByValTStr:
987 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
990 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
994 public CharSet GetCharSetValue ()
996 return (CharSet)System.Enum.Parse (typeof (CharSet), pos_values [0].ToString ());
999 public MethodImplOptions GetMethodImplOptions ()
1001 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
1004 public LayoutKind GetLayoutKindValue ()
1006 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
1010 /// Emit attribute for Attributable symbol
1012 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
1014 CustomAttributeBuilder cb = Resolve (ec);
1018 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
1019 if ((usage_attr.ValidOn & Target) == 0) {
1020 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
1025 ias.ApplyAttributeBuilder (this, cb);
1027 catch (Exception e) {
1028 Error_AttributeEmitError (e.Message);
1032 if (!usage_attr.AllowMultiple) {
1033 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1034 if (emitted_targets == null) {
1035 emitted_targets = new ArrayList ();
1036 emitted_attr.Add (Type, emitted_targets);
1037 } else if (emitted_targets.Contains (Target)) {
1038 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1041 emitted_targets.Add (Target);
1044 if (!RootContext.VerifyClsCompliance)
1047 // Here we are testing attribute arguments for array usage (error 3016)
1048 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1049 if (Arguments == null)
1052 ArrayList pos_args = (ArrayList) Arguments [0];
1053 if (pos_args != null) {
1054 foreach (Argument arg in pos_args) {
1055 // Type is undefined (was error 246)
1056 if (arg.Type == null)
1059 if (arg.Type.IsArray) {
1060 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1066 if (Arguments.Count < 2)
1069 ArrayList named_args = (ArrayList) Arguments [1];
1070 foreach (DictionaryEntry de in named_args) {
1071 Argument arg = (Argument) de.Value;
1073 // Type is undefined (was error 246)
1074 if (arg.Type == null)
1077 if (arg.Type.IsArray) {
1078 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1085 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1086 MethodAttributes flags, Type ret_type, Type [] param_types)
1088 if (pos_values == null)
1089 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1090 // But because a lot of attribute class code must be rewritten will be better to wait...
1096 string dll_name = (string)pos_values [0];
1099 CallingConvention cc = CallingConvention.Winapi;
1100 CharSet charset = CodeGen.Module.DefaultCharSet;
1101 bool preserve_sig = true;
1102 string entry_point = name;
1103 bool best_fit_mapping = false;
1104 bool throw_on_unmappable = false;
1106 bool best_fit_mapping_set = false;
1107 bool throw_on_unmappable_set = false;
1109 MethodInfo set_best_fit = null;
1110 MethodInfo set_throw_on = null;
1112 if (field_info_arr != null) {
1113 int char_set_extra = 0;
1115 for (int i = 0; i < field_info_arr.Length; i++) {
1116 switch (field_info_arr [i].Name) {
1117 case "BestFitMapping":
1118 best_fit_mapping = (bool) field_values_arr [i];
1119 best_fit_mapping_set = true;
1121 case "CallingConvention":
1122 cc = (CallingConvention) field_values_arr [i];
1125 charset = (CharSet) field_values_arr [i];
1128 entry_point = (string) field_values_arr [i];
1130 case "ExactSpelling":
1131 char_set_extra |= 0x01;
1134 preserve_sig = (bool) field_values_arr [i];
1136 case "SetLastError":
1137 char_set_extra |= 0x40;
1139 case "ThrowOnUnmappableChar":
1140 throw_on_unmappable = (bool) field_values_arr [i];
1141 throw_on_unmappable_set = true;
1144 throw new InternalErrorException (field_info_arr [i].ToString ());
1147 charset |= (CharSet)char_set_extra;
1150 if (throw_on_unmappable_set || best_fit_mapping_set) {
1151 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1152 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1154 if ((set_best_fit == null) || (set_throw_on == null)) {
1155 Report.Error (-1, Location,
1156 "The ThrowOnUnmappableChar and BestFitMapping attributes can only be emitted when running on the mono runtime.");
1162 MethodBuilder mb = builder.DefinePInvokeMethod (
1163 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1164 CallingConventions.Standard, ret_type, param_types, cc, charset);
1167 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1169 if (throw_on_unmappable_set)
1170 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1171 if (best_fit_mapping_set)
1172 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1176 catch (ArgumentException e) {
1177 Error_AttributeEmitError (e.Message);
1182 private Expression GetValue ()
1184 if ((Arguments == null) || (Arguments.Count < 1))
1186 ArrayList al = (ArrayList) Arguments [0];
1187 if ((al == null) || (al.Count < 1))
1189 Argument arg = (Argument) al [0];
1190 if ((arg == null) || (arg.Expr == null))
1195 public string GetString ()
1197 Expression e = GetValue ();
1198 if (e is StringLiteral)
1199 return (e as StringLiteral).Value;
1203 public bool GetBoolean ()
1205 Expression e = GetValue ();
1206 if (e is BoolLiteral)
1207 return (e as BoolLiteral).Value;
1214 /// For global attributes (assembly, module) we need special handling.
1215 /// Attributes can be located in the several files
1217 public class GlobalAttribute: Attribute
1219 public readonly NamespaceEntry ns;
1221 public GlobalAttribute (TypeContainer container, string target,
1222 Expression left_expr, string identifier, ArrayList args, Location loc):
1223 base (target, left_expr, identifier, args, loc)
1225 ns = container.NamespaceEntry;
1230 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1231 // each time a new file is parsed. However, we need to use the NamespaceEntry
1232 // in effect where the attribute was used. Since code elsewhere cannot assume
1233 // that the NamespaceEntry is right, just overwrite it.
1235 // Precondition: RootContext.Tree.Types == null
1237 if (RootContext.Tree.Types.NamespaceEntry != null)
1238 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1240 RootContext.Tree.Types.NamespaceEntry = ns;
1245 RootContext.Tree.Types.NamespaceEntry = null;
1248 protected override FullNamedExpression ResolveAsTypeStep (Expression expr, EmitContext ec)
1252 return base.ResolveAsTypeStep (expr, ec);
1259 protected override ConstructorInfo ResolveArguments (EmitContext ec)
1263 return base.ResolveArguments (ec);
1271 public class Attributes {
1272 public ArrayList Attrs;
1274 public Attributes (Attribute a)
1276 Attrs = new ArrayList ();
1280 public Attributes (ArrayList attrs)
1285 public void AddAttributes (ArrayList attrs)
1287 Attrs.AddRange (attrs);
1291 /// Checks whether attribute target is valid for the current element
1293 public bool CheckTargets (Attributable member)
1295 string[] valid_targets = member.ValidAttributeTargets;
1296 foreach (Attribute a in Attrs) {
1297 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1298 a.Target = member.AttributeTargets;
1302 // TODO: we can skip the first item
1303 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1304 switch (a.ExplicitTarget) {
1305 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1306 case "param": a.Target = AttributeTargets.Parameter; continue;
1307 case "field": a.Target = AttributeTargets.Field; continue;
1308 case "method": a.Target = AttributeTargets.Method; continue;
1309 case "property": a.Target = AttributeTargets.Property; continue;
1311 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1314 StringBuilder sb = new StringBuilder ();
1315 foreach (string s in valid_targets) {
1319 sb.Remove (sb.Length - 2, 2);
1320 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 ());
1326 public Attribute Search (Type t, EmitContext ec)
1328 foreach (Attribute a in Attrs) {
1329 if (a.ResolveType (ec) == t)
1336 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1338 public Attribute[] SearchMulti (Type t, EmitContext ec)
1340 ArrayList ar = null;
1342 foreach (Attribute a in Attrs) {
1343 if (a.ResolveType (ec) == t) {
1345 ar = new ArrayList ();
1350 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1353 public void Emit (EmitContext ec, Attributable ias)
1357 ListDictionary ld = new ListDictionary ();
1359 foreach (Attribute a in Attrs)
1360 a.Emit (ec, ias, ld);
1363 public bool Contains (Type t, EmitContext ec)
1365 return Search (t, ec) != null;
1370 /// Helper class for attribute verification routine.
1372 sealed class AttributeTester
1374 static PtrHashtable analyzed_types = new PtrHashtable ();
1375 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1376 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1377 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1380 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1383 static object TRUE = new object ();
1384 static object FALSE = new object ();
1386 private AttributeTester ()
1391 /// Returns true if parameters of two compared methods are CLS-Compliant.
1392 /// It tests differing only in ref or out, or in array rank.
1394 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1396 if (types_a == null || types_b == null)
1399 if (types_a.Length != types_b.Length)
1402 for (int i = 0; i < types_b.Length; ++i) {
1403 Type aType = types_a [i];
1404 Type bType = types_b [i];
1406 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1410 Type aBaseType = aType;
1411 bool is_either_ref_or_out = false;
1413 if (aType.IsByRef || aType.IsPointer) {
1414 aBaseType = aType.GetElementType ();
1415 is_either_ref_or_out = true;
1418 Type bBaseType = bType;
1419 if (bType.IsByRef || bType.IsPointer)
1421 bBaseType = bType.GetElementType ();
1422 is_either_ref_or_out = !is_either_ref_or_out;
1425 if (aBaseType != bBaseType)
1428 if (is_either_ref_or_out)
1435 /// Goes through all parameters and test if they are CLS-Compliant.
1437 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1439 if (fixedParameters == null)
1442 foreach (Parameter arg in fixedParameters) {
1443 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1444 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1453 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1455 public static bool IsClsCompliant (Type type)
1460 object type_compliance = analyzed_types[type];
1461 if (type_compliance != null)
1462 return type_compliance == TRUE;
1464 if (type.IsPointer) {
1465 analyzed_types.Add (type, null);
1470 if (type.IsArray || type.IsByRef) {
1471 result = IsClsCompliant (TypeManager.GetElementType (type));
1473 result = AnalyzeTypeCompliance (type);
1475 analyzed_types.Add (type, result ? TRUE : FALSE);
1480 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1482 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1484 FieldBase fb = TypeManager.GetField (fi);
1486 return fb as IFixedBuffer;
1490 object o = fixed_buffer_cache [fi];
1492 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1493 fixed_buffer_cache.Add (fi, FALSE);
1497 IFixedBuffer iff = new FixedFieldExternal (fi);
1498 fixed_buffer_cache.Add (fi, iff);
1505 return (IFixedBuffer)o;
1511 public static void VerifyModulesClsCompliance ()
1513 Module[] modules = TypeManager.Modules;
1514 if (modules == null)
1517 // The first module is generated assembly
1518 for (int i = 1; i < modules.Length; ++i) {
1519 Module module = modules [i];
1520 if (!IsClsCompliant (module)) {
1521 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1528 /// Tests container name for CLS-Compliant name (differing only in case)
1530 public static void VerifyTopLevelNameClsCompliance ()
1532 Hashtable locase_table = new Hashtable ();
1534 // Convert imported type names to lower case and ignore not cls compliant
1535 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1536 Type t = (Type)de.Value;
1537 if (!AttributeTester.IsClsCompliant (t))
1540 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1543 foreach (DictionaryEntry de in RootContext.Tree.AllDecls) {
1544 if (!(de.Key is MemberName))
1545 throw new InternalErrorException ("");
1546 DeclSpace decl = (DeclSpace) de.Value;
1547 if (!decl.IsClsCompliaceRequired (decl))
1550 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1551 if (!locase_table.Contains (lcase)) {
1552 locase_table.Add (lcase, decl);
1556 object conflict = locase_table [lcase];
1557 if (conflict is Type)
1558 Report.SymbolRelatedToPreviousError ((Type)conflict);
1560 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1562 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1566 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1568 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1569 if (CompliantAttribute.Length == 0)
1572 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1575 static bool AnalyzeTypeCompliance (Type type)
1577 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1579 return ds.IsClsCompliaceRequired (ds.Parent);
1582 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1583 if (CompliantAttribute.Length == 0)
1584 return IsClsCompliant (type.Assembly);
1586 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1590 /// Returns instance of ObsoleteAttribute when type is obsolete
1592 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1594 object type_obsolete = analyzed_types_obsolete [type];
1595 if (type_obsolete == FALSE)
1598 if (type_obsolete != null)
1599 return (ObsoleteAttribute)type_obsolete;
1601 ObsoleteAttribute result = null;
1602 if (type.IsByRef || type.IsArray || type.IsPointer) {
1603 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1605 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1607 // Type is external, we can get attribute directly
1608 if (type_ds == null) {
1609 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1610 if (attribute.Length == 1)
1611 result = (ObsoleteAttribute)attribute [0];
1613 result = type_ds.GetObsoleteAttribute (type_ds);
1617 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1622 /// Returns instance of ObsoleteAttribute when method is obsolete
1624 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1626 IMethodData mc = TypeManager.GetMethod (mb);
1628 return mc.GetObsoleteAttribute ();
1630 // compiler generated methods are not registered by AddMethod
1631 if (mb.DeclaringType is TypeBuilder)
1634 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1636 return GetMemberObsoleteAttribute (pi);
1638 return GetMemberObsoleteAttribute (mb);
1642 /// Returns instance of ObsoleteAttribute when member is obsolete
1644 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1646 object type_obsolete = analyzed_member_obsolete [mi];
1647 if (type_obsolete == FALSE)
1650 if (type_obsolete != null)
1651 return (ObsoleteAttribute)type_obsolete;
1653 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1654 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1659 /// Common method for Obsolete error/warning reporting.
1661 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1664 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1668 if (oa.Message == null) {
1669 Report.Warning (612, loc, "'{0}' is obsolete", member);
1672 if (RootContext.WarningLevel >= 2)
1673 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1676 public static bool IsConditionalMethodExcluded (MethodBase mb)
1678 object excluded = analyzed_method_excluded [mb];
1679 if (excluded != null)
1680 return excluded == TRUE ? true : false;
1682 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1683 if (attrs.Length == 0) {
1684 analyzed_method_excluded.Add (mb, FALSE);
1688 foreach (ConditionalAttribute a in attrs) {
1689 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1690 analyzed_method_excluded.Add (mb, FALSE);
1694 analyzed_method_excluded.Add (mb, TRUE);
1699 /// Analyzes class whether it has attribute which has ConditionalAttribute
1700 /// and its condition is not defined.
1702 public static bool IsAttributeExcluded (Type type)
1707 Class class_decl = TypeManager.LookupDeclSpace (type) as Class;
1709 // TODO: add caching
1710 // TODO: merge all Type bases attribute caching to one cache to save memory
1711 if (class_decl == null) {
1712 object[] attributes = type.GetCustomAttributes (TypeManager.conditional_attribute_type, false);
1713 foreach (ConditionalAttribute ca in attributes) {
1714 if (RootContext.AllDefines.Contains (ca.ConditionString))
1717 return attributes.Length > 0;
1720 return class_decl.IsExcluded ();