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 CustomAttributeBuilder cb;
90 // non-null if named args present after Resolve () is called
91 PropertyInfo [] prop_info_arr;
92 FieldInfo [] field_info_arr;
93 object [] field_values_arr;
94 object [] prop_values_arr;
97 static PtrHashtable usage_attr_cache = new PtrHashtable ();
99 public Attribute (string target, Expression left_expr, string identifier, ArrayList args, Location loc)
101 LeftExpr = left_expr;
102 Identifier = identifier;
103 Name = LeftExpr == null ? identifier : LeftExpr + "." + identifier;
106 ExplicitTarget = target;
109 void Error_InvalidNamedArgument (string name)
111 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
112 "fields which are not readonly, static or const; or read-write instance properties.",
116 static void Error_AttributeArgumentNotValid (string extra, Location loc)
118 Report.Error (182, loc,
119 "An attribute argument must be a constant expression, typeof " +
120 "expression or array creation expression" + extra);
123 static void Error_AttributeArgumentNotValid (Location loc)
125 Error_AttributeArgumentNotValid ("", loc);
130 /// This is rather hack. We report many emit attribute error with same error to be compatible with
131 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
133 public void Error_AttributeEmitError (string inner)
135 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
138 public void Error_InvalidSecurityParent ()
140 Error_AttributeEmitError ("it is attached to invalid parent");
143 void Error_AttributeConstructorMismatch ()
145 Report.Error (-6, Location,
146 "Could not find a constructor for this argument list.");
149 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
154 FullNamedExpression n1 = null;
155 FullNamedExpression n2 = null;
156 string IdentifierAttribute = Identifier + "Attribute";
157 if (LeftExpr == null) {
158 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
160 // FIXME: Shouldn't do this for quoted attributes: [@A]
161 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
163 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
165 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
168 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
170 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
171 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
174 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
175 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
178 t1 = te1.ResolveType (ec);
180 t2 = te2.ResolveType (ec);
184 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
186 Type CheckAttributeType (EmitContext ec)
190 ResolvePossibleAttributeTypes (ec, out t1, out t2);
192 String err0616 = null;
194 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
196 err0616 = "'{0}' is not an attribute class";
198 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
200 err0616 = (err0616 != null)
201 ? "Neither '{0}' nor '{0}Attribute' is an attribute class"
202 : "'{0}Attribute': is not an attribute class";
205 if (t1 != null && t2 != null) {
206 Report.Error (1614, Location, "'{0}' is ambiguous; use either '@{0}' or '{0}Attribute'", Name);
214 if (err0616 != null) {
215 Report.Error (616, Location, err0616, Name);
219 Report.Error (246, Location,
220 "Could not find attribute '{0}' (are you missing a using directive or an assembly reference ?)",
223 resolve_error = true;
227 public virtual Type ResolveType (EmitContext ec)
229 if (Type == null && !resolve_error)
230 Type = CheckAttributeType (ec);
234 string GetFullMemberName (string member)
236 return Type.FullName + '.' + member;
240 // Given an expression, if the expression is a valid attribute-argument-expression
241 // returns an object that can be used to encode it, or null on failure.
243 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
245 if (e is EnumConstant) {
246 if (RootContext.StdLib)
247 result = ((EnumConstant)e).GetValueAsEnumType ();
249 result = ((EnumConstant)e).GetValue ();
254 Constant constant = e as Constant;
255 if (constant != null) {
256 if (e.Type != arg_type) {
257 constant = Const.ChangeType (loc, constant, arg_type);
258 if (constant == null) {
260 Error_AttributeArgumentNotValid (loc);
264 result = constant.GetValue ();
266 } else if (e is TypeOf) {
267 result = ((TypeOf) e).TypeArg;
269 } else if (e is ArrayCreation){
270 result = ((ArrayCreation) e).EncodeAsAttribute ();
273 } else if (e is EmptyCast) {
274 Expression child = ((EmptyCast)e).Child;
275 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
279 Error_AttributeArgumentNotValid (loc);
283 // Cache for parameter-less attributes
284 static PtrHashtable att_cache = new PtrHashtable ();
286 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
291 resolve_error = true;
294 Type = CheckAttributeType (ec);
299 if (Type.IsAbstract) {
300 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
304 if (Arguments == null) {
305 object o = att_cache [Type];
307 resolve_error = false;
308 return (CustomAttributeBuilder)o;
312 // Now we extract the positional and named arguments
314 ArrayList pos_args = null;
315 ArrayList named_args = null;
316 int pos_arg_count = 0;
317 int named_arg_count = 0;
319 if (Arguments != null) {
320 pos_args = (ArrayList) Arguments [0];
321 if (pos_args != null)
322 pos_arg_count = pos_args.Count;
323 if (Arguments.Count > 1) {
324 named_args = (ArrayList) Arguments [1];
325 named_arg_count = named_args.Count;
329 pos_values = new object [pos_arg_count];
332 // First process positional arguments
336 for (i = 0; i < pos_arg_count; i++) {
337 Argument a = (Argument) pos_args [i];
340 if (!a.Resolve (ec, Location))
346 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
349 pos_values [i] = val;
351 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
352 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
358 // Now process named arguments
361 ArrayList field_infos = null;
362 ArrayList prop_infos = null;
363 ArrayList field_values = null;
364 ArrayList prop_values = null;
365 Hashtable seen_names = null;
367 if (named_arg_count > 0) {
368 field_infos = new ArrayList ();
369 prop_infos = new ArrayList ();
370 field_values = new ArrayList ();
371 prop_values = new ArrayList ();
373 seen_names = new Hashtable();
376 for (i = 0; i < named_arg_count; i++) {
377 DictionaryEntry de = (DictionaryEntry) named_args [i];
378 string member_name = (string) de.Key;
379 Argument a = (Argument) de.Value;
382 if (seen_names.Contains(member_name)) {
383 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
386 seen_names.Add(member_name, 1);
388 if (!a.Resolve (ec, Location))
391 Expression member = Expression.MemberLookup (
392 ec, Type, member_name,
393 MemberTypes.Field | MemberTypes.Property,
394 BindingFlags.Public | BindingFlags.Instance,
397 if (member == null) {
398 member = Expression.MemberLookup (ec, Type, member_name,
399 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
402 if (member != null) {
403 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
409 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
414 if (!(member is PropertyExpr || member is FieldExpr)) {
415 Error_InvalidNamedArgument (member_name);
420 if (member is PropertyExpr) {
421 PropertyExpr pe = (PropertyExpr) member;
422 PropertyInfo pi = pe.PropertyInfo;
424 if (!pi.CanWrite || !pi.CanRead) {
425 Report.SymbolRelatedToPreviousError (pi);
426 Error_InvalidNamedArgument (member_name);
431 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
434 prop_values.Add (value);
437 } else if (member is FieldExpr) {
438 FieldExpr fe = (FieldExpr) member;
439 FieldInfo fi = fe.FieldInfo;
442 Error_InvalidNamedArgument (member_name);
447 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
450 field_values.Add (value);
451 field_infos.Add (fi);
455 Expression mg = Expression.MemberLookup (
456 ec, Type, ".ctor", MemberTypes.Constructor,
457 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
461 Error_AttributeConstructorMismatch ();
465 MethodBase constructor = Invocation.OverloadResolve (
466 ec, (MethodGroupExpr) mg, pos_args, false, Location);
468 if (constructor == null) {
473 // Now we perform some checks on the positional args as they
474 // cannot be null for a constructor which expects a parameter
478 ParameterData pd = TypeManager.GetParameterData (constructor);
480 int last_real_param = pd.Count;
482 // When the params is not filled we need to put one
483 if (last_real_param > pos_arg_count) {
484 object [] new_pos_values = new object [pos_arg_count + 1];
485 pos_values.CopyTo (new_pos_values, 0);
486 new_pos_values [pos_arg_count] = new object [] {} ;
487 pos_values = new_pos_values;
492 for (int j = 0; j < pos_arg_count; ++j) {
493 Argument a = (Argument) pos_args [j];
495 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
496 Error_AttributeArgumentNotValid (Location);
500 object value = pos_values [j];
501 if (value != null && a.Type != value.GetType () && a.Type.IsPrimitive) {
503 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
505 // TODO: Can failed ?
506 throw new NotImplementedException ();
510 if (j < last_real_param)
513 if (j == last_real_param) {
514 object [] array = new object [pos_arg_count - last_real_param];
515 array [0] = pos_values [j];
516 pos_values [j] = array;
520 object [] params_array = (object []) pos_values [last_real_param];
521 params_array [j - last_real_param] = pos_values [j];
524 // Adjust the size of the pos_values if it had params
525 if (last_real_param != pos_arg_count) {
526 object [] new_pos_values = new object [last_real_param + 1];
527 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
528 pos_values = new_pos_values;
532 if (named_arg_count > 0) {
533 prop_info_arr = new PropertyInfo [prop_infos.Count];
534 field_info_arr = new FieldInfo [field_infos.Count];
535 field_values_arr = new object [field_values.Count];
536 prop_values_arr = new object [prop_values.Count];
538 field_infos.CopyTo (field_info_arr, 0);
539 field_values.CopyTo (field_values_arr, 0);
541 prop_values.CopyTo (prop_values_arr, 0);
542 prop_infos.CopyTo (prop_info_arr, 0);
544 cb = new CustomAttributeBuilder (
545 (ConstructorInfo) constructor, pos_values,
546 prop_info_arr, prop_values_arr,
547 field_info_arr, field_values_arr);
550 cb = new CustomAttributeBuilder (
551 (ConstructorInfo) constructor, pos_values);
553 if (pos_values.Length == 0)
554 att_cache.Add (Type, cb);
556 } catch (Exception) {
559 // using System.ComponentModel;
560 // [DefaultValue (CollectionChangeAction.Add)]
561 // class X { static void Main () {} }
563 Error_AttributeArgumentNotValid (Location);
567 resolve_error = false;
572 /// Get a string containing a list of valid targets for the attribute 'attr'
574 public string GetValidTargets ()
576 StringBuilder sb = new StringBuilder ();
577 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
579 if ((targets & AttributeTargets.Assembly) != 0)
580 sb.Append ("'assembly' ");
582 if ((targets & AttributeTargets.Class) != 0)
583 sb.Append ("'class' ");
585 if ((targets & AttributeTargets.Constructor) != 0)
586 sb.Append ("'constructor' ");
588 if ((targets & AttributeTargets.Delegate) != 0)
589 sb.Append ("'delegate' ");
591 if ((targets & AttributeTargets.Enum) != 0)
592 sb.Append ("'enum' ");
594 if ((targets & AttributeTargets.Event) != 0)
595 sb.Append ("'event' ");
597 if ((targets & AttributeTargets.Field) != 0)
598 sb.Append ("'field' ");
600 if ((targets & AttributeTargets.Interface) != 0)
601 sb.Append ("'interface' ");
603 if ((targets & AttributeTargets.Method) != 0)
604 sb.Append ("'method' ");
606 if ((targets & AttributeTargets.Module) != 0)
607 sb.Append ("'module' ");
609 if ((targets & AttributeTargets.Parameter) != 0)
610 sb.Append ("'parameter' ");
612 if ((targets & AttributeTargets.Property) != 0)
613 sb.Append ("'property' ");
615 if ((targets & AttributeTargets.ReturnValue) != 0)
616 sb.Append ("'return' ");
618 if ((targets & AttributeTargets.Struct) != 0)
619 sb.Append ("'struct' ");
621 return sb.ToString ();
626 /// Returns AttributeUsage attribute for this type
628 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
630 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
634 Class attr_class = TypeManager.LookupClass (Type);
636 if (attr_class == null) {
637 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
638 ua = (AttributeUsageAttribute)usage_attr [0];
639 usage_attr_cache.Add (Type, ua);
643 if (attr_class.OptAttributes == null) {
644 usage_attr_cache.Add (Type, DefaultUsageAttribute);
645 return DefaultUsageAttribute;
648 Attribute a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, ec);
650 usage_attr_cache.Add (Type, DefaultUsageAttribute);
651 return DefaultUsageAttribute;
654 ua = a.GetAttributeUsageAttribute (ec);
655 usage_attr_cache.Add (Type, ua);
659 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
661 if (pos_values == null)
662 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
663 // But because a lot of attribute class code must be rewritten will be better to wait...
667 return DefaultUsageAttribute;
669 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
671 object field = GetPropertyValue ("AllowMultiple");
673 usage_attribute.AllowMultiple = (bool)field;
675 field = GetPropertyValue ("Inherited");
677 usage_attribute.Inherited = (bool)field;
679 return usage_attribute;
683 /// Returns custom name of indexer
685 public string GetIndexerAttributeValue (EmitContext ec)
687 if (pos_values == null)
688 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
689 // But because a lot of attribute class code must be rewritten will be better to wait...
695 return pos_values [0] as string;
699 /// Returns condition of ConditionalAttribute
701 public string GetConditionalAttributeValue (EmitContext ec)
703 if (pos_values == null)
704 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
705 // But because a lot of attribute class code must be rewritten will be better to wait...
711 return (string)pos_values [0];
715 /// Creates the instance of ObsoleteAttribute from this attribute instance
717 public ObsoleteAttribute GetObsoleteAttribute (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 if (pos_values == null || pos_values.Length == 0)
728 return new ObsoleteAttribute ();
730 if (pos_values.Length == 1)
731 return new ObsoleteAttribute ((string)pos_values [0]);
733 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
737 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
738 /// before ApplyAttribute. We need to resolve the arguments.
739 /// This situation occurs when class deps is differs from Emit order.
741 public bool GetClsCompliantAttributeValue (EmitContext ec)
743 if (pos_values == null)
744 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
745 // But because a lot of attribute class code must be rewritten will be better to wait...
751 return (bool)pos_values [0];
755 /// Tests permitted SecurityAction for assembly or other types
757 public bool CheckSecurityActionValidity (bool for_assembly)
759 SecurityAction action = GetSecurityActionValue ();
761 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
765 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
766 Error_AttributeEmitError ("SecurityAction is out of range");
770 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
774 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
778 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
780 return (SecurityAction)pos_values [0];
784 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
786 /// <returns></returns>
787 public void ExtractSecurityPermissionSet (ListDictionary permissions)
789 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
790 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
794 SecurityAttribute sa;
795 // For all assemblies except corlib we can avoid all hacks
796 if (RootContext.StdLib) {
797 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
799 if (prop_info_arr != null) {
800 for (int i = 0; i < prop_info_arr.Length; ++i) {
801 PropertyInfo pi = prop_info_arr [i];
802 pi.SetValue (sa, prop_values_arr [i], null);
806 Type temp_type = Type.GetType (Type.FullName);
807 // HACK: All mscorlib attributes have same ctor syntax
808 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
810 // All types are from newly created corlib but for invocation with old we need to convert them
811 if (prop_info_arr != null) {
812 for (int i = 0; i < prop_info_arr.Length; ++i) {
813 PropertyInfo emited_pi = prop_info_arr [i];
814 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
816 object old_instance = pi.PropertyType.IsEnum ?
817 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
820 pi.SetValue (sa, old_instance, null);
826 perm = sa.CreatePermission ();
827 SecurityAction action = GetSecurityActionValue ();
829 // IS is correct because for corlib we are using an instance from old corlib
830 if (!(perm is System.Security.CodeAccessPermission)) {
832 case SecurityAction.Demand:
833 action = (SecurityAction)13;
835 case SecurityAction.LinkDemand:
836 action = (SecurityAction)14;
838 case SecurityAction.InheritanceDemand:
839 action = (SecurityAction)15;
844 PermissionSet ps = (PermissionSet)permissions [action];
846 if (sa is PermissionSetAttribute)
847 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
849 ps = new PermissionSet (PermissionState.None);
851 permissions.Add (action, ps);
852 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
853 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
854 permissions [action] = ps;
856 ps.AddPermission (perm);
859 object GetValue (object value)
861 if (value is EnumConstant)
862 return ((EnumConstant) value).GetValue ();
867 object GetPropertyValue (string name)
869 if (prop_info_arr == null)
872 for (int i = 0; i < prop_info_arr.Length; ++i) {
873 if (prop_info_arr [i].Name == name)
874 return prop_values_arr [i];
880 object GetFieldValue (string name)
883 if (field_info_arr == null)
886 foreach (FieldInfo fi in field_info_arr) {
888 return GetValue (field_values_arr [i]);
894 public UnmanagedMarshal GetMarshal (Attributable attr)
896 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
898 object value = GetFieldValue ("SizeParamIndex");
899 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
900 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
904 object o = GetFieldValue ("ArraySubType");
905 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
907 switch (UnmanagedType) {
908 case UnmanagedType.CustomMarshaler: {
909 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
910 BindingFlags.Static | BindingFlags.Public);
911 if (define_custom == null) {
912 Report.RuntimeMissingSupport (Location, "set marshal info");
916 object [] args = new object [4];
917 args [0] = GetFieldValue ("MarshalTypeRef");
918 args [1] = GetFieldValue ("MarshalCookie");
919 args [2] = GetFieldValue ("MarshalType");
920 args [3] = Guid.Empty;
921 return (UnmanagedMarshal) define_custom.Invoke (null, args);
923 case UnmanagedType.LPArray: {
924 object size_const = GetFieldValue ("SizeConst");
925 object size_param_index = GetFieldValue ("SizeParamIndex");
927 if ((size_const != null) || (size_param_index != null)) {
928 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
929 if (define_array == null) {
930 Report.RuntimeMissingSupport (Location, "set marshal info");
934 object [] args = new object [3];
935 args [0] = array_sub_type;
936 args [1] = size_const == null ? -1 : size_const;
937 args [2] = size_param_index == null ? -1 : size_param_index;
938 return (UnmanagedMarshal) define_array.Invoke (null, args);
941 return UnmanagedMarshal.DefineLPArray (array_sub_type);
943 case UnmanagedType.SafeArray:
944 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
946 case UnmanagedType.ByValArray:
947 FieldMember fm = attr as FieldMember;
949 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
952 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
954 case UnmanagedType.ByValTStr:
955 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
958 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
962 public MethodImplOptions GetMethodImplOptions ()
964 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
967 public LayoutKind GetLayoutKindValue ()
969 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
973 /// Emit attribute for Attributable symbol
975 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
977 CustomAttributeBuilder cb = Resolve (ec);
981 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
982 if ((usage_attr.ValidOn & Target) == 0) {
983 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
988 ias.ApplyAttributeBuilder (this, cb);
990 catch (Exception e) {
991 Error_AttributeEmitError (e.Message);
995 if (!usage_attr.AllowMultiple) {
996 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
997 if (emitted_targets == null) {
998 emitted_targets = new ArrayList ();
999 emitted_attr.Add (Type, emitted_targets);
1000 } else if (emitted_targets.Contains (Target)) {
1001 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1004 emitted_targets.Add (Target);
1007 if (!RootContext.VerifyClsCompliance)
1010 // Here we are testing attribute arguments for array usage (error 3016)
1011 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1012 if (Arguments == null)
1015 ArrayList pos_args = (ArrayList) Arguments [0];
1016 if (pos_args != null) {
1017 foreach (Argument arg in pos_args) {
1018 // Type is undefined (was error 246)
1019 if (arg.Type == null)
1022 if (arg.Type.IsArray) {
1023 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1029 if (Arguments.Count < 2)
1032 ArrayList named_args = (ArrayList) Arguments [1];
1033 foreach (DictionaryEntry de in named_args) {
1034 Argument arg = (Argument) de.Value;
1036 // Type is undefined (was error 246)
1037 if (arg.Type == null)
1040 if (arg.Type.IsArray) {
1041 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1048 object GetValue (EmitContext ec, Constant c, Type target)
1050 if (Convert.ImplicitConversionExists (ec, c, target))
1051 return c.GetValue ();
1053 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1057 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1058 MethodAttributes flags, Type ret_type, Type [] param_types)
1060 if (pos_values == null)
1061 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1062 // But because a lot of attribute class code must be rewritten will be better to wait...
1068 string dll_name = (string)pos_values [0];
1071 CallingConvention cc = CallingConvention.Winapi;
1072 CharSet charset = CharSet.Ansi;
1073 bool preserve_sig = true;
1074 string entry_point = name;
1075 bool best_fit_mapping = false;
1076 bool throw_on_unmappable = false;
1078 bool best_fit_mapping_set = false;
1079 bool throw_on_unmappable_set = false;
1081 MethodInfo set_best_fit = null;
1082 MethodInfo set_throw_on = null;
1084 if (field_info_arr != null) {
1085 int char_set_extra = 0;
1087 for (int i = 0; i < field_info_arr.Length; i++) {
1088 switch (field_info_arr [i].Name) {
1089 case "BestFitMapping":
1090 best_fit_mapping = (bool) field_values_arr [i];
1091 best_fit_mapping_set = true;
1093 case "CallingConvention":
1094 cc = (CallingConvention) field_values_arr [i];
1097 charset = (CharSet) field_values_arr [i];
1100 entry_point = (string) field_values_arr [i];
1102 case "ExactSpelling":
1103 char_set_extra |= 0x01;
1106 preserve_sig = (bool) field_values_arr [i];
1108 case "SetLastError":
1109 char_set_extra |= 0x40;
1111 case "ThrowOnUnmappableChar":
1112 throw_on_unmappable = (bool) field_values_arr [i];
1113 throw_on_unmappable_set = true;
1116 throw new InternalErrorException (field_info_arr [i].ToString ());
1119 charset |= (CharSet)char_set_extra;
1122 if (throw_on_unmappable_set || best_fit_mapping_set) {
1123 set_best_fit = typeof (MethodBuilder).GetMethod ("set_BestFitMapping", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1124 set_throw_on = typeof (MethodBuilder).GetMethod ("set_ThrowOnUnmappableChar", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
1126 if ((set_best_fit == null) || (set_throw_on == null)) {
1127 Report.Error (-1, Location,
1128 "The ThrowOnUnmappableChar and BestFitMapping attributes can only be emitted when running on the mono runtime.");
1134 MethodBuilder mb = builder.DefinePInvokeMethod (
1135 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1136 CallingConventions.Standard, ret_type, param_types, cc, charset);
1139 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1141 if (throw_on_unmappable_set)
1142 set_throw_on.Invoke (mb, 0, null, new object [] { throw_on_unmappable }, null);
1143 if (best_fit_mapping_set)
1144 set_best_fit.Invoke (mb, 0, null, new object [] { best_fit_mapping }, null);
1148 catch (ArgumentException e) {
1149 Error_AttributeEmitError (e.Message);
1154 private Expression GetValue ()
1156 if ((Arguments == null) || (Arguments.Count < 1))
1158 ArrayList al = (ArrayList) Arguments [0];
1159 if ((al == null) || (al.Count < 1))
1161 Argument arg = (Argument) al [0];
1162 if ((arg == null) || (arg.Expr == null))
1167 public string GetString ()
1169 Expression e = GetValue ();
1170 if (e is StringLiteral)
1171 return (e as StringLiteral).Value;
1175 public bool GetBoolean ()
1177 Expression e = GetValue ();
1178 if (e is BoolLiteral)
1179 return (e as BoolLiteral).Value;
1186 /// For global attributes (assembly, module) we need special handling.
1187 /// Attributes can be located in the several files
1189 public class GlobalAttribute: Attribute
1191 public readonly NamespaceEntry ns;
1193 public GlobalAttribute (TypeContainer container, string target,
1194 Expression left_expr, string identifier, ArrayList args, Location loc):
1195 base (target, left_expr, identifier, args, loc)
1197 ns = container.NamespaceEntry;
1202 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1203 // each time a new file is parsed. However, we need to use the NamespaceEntry
1204 // in effect where the attribute was used. Since code elsewhere cannot assume
1205 // that the NamespaceEntry is right, just overwrite it.
1207 // Precondition: RootContext.Tree.Types == null
1209 if (RootContext.Tree.Types.NamespaceEntry != null)
1210 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1212 RootContext.Tree.Types.NamespaceEntry = ns;
1217 RootContext.Tree.Types.NamespaceEntry = null;
1220 public override Type ResolveType (EmitContext ec)
1223 Type retval = base.ResolveType (ec);
1228 public override CustomAttributeBuilder Resolve (EmitContext ec)
1231 CustomAttributeBuilder retval = base.Resolve (ec);
1237 public class Attributes {
1238 public ArrayList Attrs;
1240 public Attributes (Attribute a)
1242 Attrs = new ArrayList ();
1246 public Attributes (ArrayList attrs)
1251 public void AddAttributes (ArrayList attrs)
1253 Attrs.AddRange (attrs);
1257 /// Checks whether attribute target is valid for the current element
1259 public bool CheckTargets (Attributable member)
1261 string[] valid_targets = member.ValidAttributeTargets;
1262 foreach (Attribute a in Attrs) {
1263 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1264 a.Target = member.AttributeTargets;
1268 // TODO: we can skip the first item
1269 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1270 switch (a.ExplicitTarget) {
1271 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1272 case "param": a.Target = AttributeTargets.Parameter; continue;
1273 case "field": a.Target = AttributeTargets.Field; continue;
1274 case "method": a.Target = AttributeTargets.Method; continue;
1275 case "property": a.Target = AttributeTargets.Property; continue;
1277 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1280 StringBuilder sb = new StringBuilder ();
1281 foreach (string s in valid_targets) {
1285 sb.Remove (sb.Length - 2, 2);
1286 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 ());
1292 public Attribute Search (Type t, EmitContext ec)
1294 foreach (Attribute a in Attrs) {
1295 if (a.ResolveType (ec) == t)
1302 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1304 public Attribute[] SearchMulti (Type t, EmitContext ec)
1306 ArrayList ar = null;
1308 foreach (Attribute a in Attrs) {
1309 if (a.ResolveType (ec) == t) {
1311 ar = new ArrayList ();
1316 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1319 public void Emit (EmitContext ec, Attributable ias)
1323 ListDictionary ld = new ListDictionary ();
1325 foreach (Attribute a in Attrs)
1326 a.Emit (ec, ias, ld);
1329 public bool Contains (Type t, EmitContext ec)
1331 return Search (t, ec) != null;
1336 /// Helper class for attribute verification routine.
1338 sealed class AttributeTester
1340 static PtrHashtable analyzed_types = new PtrHashtable ();
1341 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1342 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1343 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1344 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1346 static object TRUE = new object ();
1347 static object FALSE = new object ();
1349 private AttributeTester ()
1354 /// Returns true if parameters of two compared methods are CLS-Compliant.
1355 /// It tests differing only in ref or out, or in array rank.
1357 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1359 if (types_a == null || types_b == null)
1362 if (types_a.Length != types_b.Length)
1365 for (int i = 0; i < types_b.Length; ++i) {
1366 Type aType = types_a [i];
1367 Type bType = types_b [i];
1369 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1373 Type aBaseType = aType;
1374 bool is_either_ref_or_out = false;
1376 if (aType.IsByRef || aType.IsPointer) {
1377 aBaseType = aType.GetElementType ();
1378 is_either_ref_or_out = true;
1381 Type bBaseType = bType;
1382 if (bType.IsByRef || bType.IsPointer)
1384 bBaseType = bType.GetElementType ();
1385 is_either_ref_or_out = !is_either_ref_or_out;
1388 if (aBaseType != bBaseType)
1391 if (is_either_ref_or_out)
1398 /// Goes through all parameters and test if they are CLS-Compliant.
1400 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1402 if (fixedParameters == null)
1405 foreach (Parameter arg in fixedParameters) {
1406 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1407 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1416 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1418 public static bool IsClsCompliant (Type type)
1423 object type_compliance = analyzed_types[type];
1424 if (type_compliance != null)
1425 return type_compliance == TRUE;
1427 if (type.IsPointer) {
1428 analyzed_types.Add (type, null);
1433 if (type.IsArray || type.IsByRef) {
1434 result = IsClsCompliant (TypeManager.GetElementType (type));
1436 result = AnalyzeTypeCompliance (type);
1438 analyzed_types.Add (type, result ? TRUE : FALSE);
1443 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1445 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1447 FieldBase fb = TypeManager.GetField (fi);
1449 return fb as IFixedBuffer;
1453 object o = fixed_buffer_cache [fi];
1455 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1456 fixed_buffer_cache.Add (fi, FALSE);
1460 IFixedBuffer iff = new FixedFieldExternal (fi);
1461 fixed_buffer_cache.Add (fi, iff);
1468 return (IFixedBuffer)o;
1474 public static void VerifyModulesClsCompliance ()
1476 Module[] modules = TypeManager.Modules;
1477 if (modules == null)
1480 // The first module is generated assembly
1481 for (int i = 1; i < modules.Length; ++i) {
1482 Module module = modules [i];
1483 if (!IsClsCompliant (module)) {
1484 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1491 /// Tests container name for CLS-Compliant name (differing only in case)
1493 public static void VerifyTopLevelNameClsCompliance ()
1495 Hashtable locase_table = new Hashtable ();
1497 // Convert imported type names to lower case and ignore not cls compliant
1498 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1499 Type t = (Type)de.Value;
1500 if (!AttributeTester.IsClsCompliant (t))
1503 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1506 foreach (DictionaryEntry de in RootContext.Tree.AllDecls) {
1507 if (!(de.Key is MemberName))
1508 throw new InternalErrorException ("");
1509 DeclSpace decl = (DeclSpace) de.Value;
1510 if (!decl.IsClsCompliaceRequired (decl))
1513 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1514 if (!locase_table.Contains (lcase)) {
1515 locase_table.Add (lcase, decl);
1519 object conflict = locase_table [lcase];
1520 if (conflict is Type)
1521 Report.SymbolRelatedToPreviousError ((Type)conflict);
1523 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1525 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1529 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1531 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1532 if (CompliantAttribute.Length == 0)
1535 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1538 static bool AnalyzeTypeCompliance (Type type)
1540 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1542 return ds.IsClsCompliaceRequired (ds.Parent);
1545 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1546 if (CompliantAttribute.Length == 0)
1547 return IsClsCompliant (type.Assembly);
1549 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1553 /// Returns instance of ObsoleteAttribute when type is obsolete
1555 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1557 object type_obsolete = analyzed_types_obsolete [type];
1558 if (type_obsolete == FALSE)
1561 if (type_obsolete != null)
1562 return (ObsoleteAttribute)type_obsolete;
1564 ObsoleteAttribute result = null;
1565 if (type.IsByRef || type.IsArray || type.IsPointer) {
1566 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1568 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1570 // Type is external, we can get attribute directly
1571 if (type_ds == null) {
1572 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1573 if (attribute.Length == 1)
1574 result = (ObsoleteAttribute)attribute [0];
1576 result = type_ds.GetObsoleteAttribute (type_ds);
1580 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1585 /// Returns instance of ObsoleteAttribute when method is obsolete
1587 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1589 IMethodData mc = TypeManager.GetMethod (mb);
1591 return mc.GetObsoleteAttribute ();
1593 // compiler generated methods are not registered by AddMethod
1594 if (mb.DeclaringType is TypeBuilder)
1597 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1599 return GetMemberObsoleteAttribute (pi);
1601 return GetMemberObsoleteAttribute (mb);
1605 /// Returns instance of ObsoleteAttribute when member is obsolete
1607 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1609 object type_obsolete = analyzed_member_obsolete [mi];
1610 if (type_obsolete == FALSE)
1613 if (type_obsolete != null)
1614 return (ObsoleteAttribute)type_obsolete;
1616 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1617 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1622 /// Common method for Obsolete error/warning reporting.
1624 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1627 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1631 if (oa.Message == null) {
1632 Report.Warning (612, loc, "'{0}' is obsolete", member);
1635 if (RootContext.WarningLevel >= 2)
1636 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1639 public static bool IsConditionalMethodExcluded (MethodBase mb)
1641 object excluded = analyzed_method_excluded [mb];
1642 if (excluded != null)
1643 return excluded == TRUE ? true : false;
1645 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1646 if (attrs.Length == 0) {
1647 analyzed_method_excluded.Add (mb, FALSE);
1651 foreach (ConditionalAttribute a in attrs) {
1652 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1653 analyzed_method_excluded.Add (mb, FALSE);
1657 analyzed_method_excluded.Add (mb, TRUE);