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 NameAttribute = Name + "Attribute";
194 String err0616 = null;
196 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
198 err0616 = "'" + Name + "': is not an attribute class";
200 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
202 err0616 = (err0616 != null)
203 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
204 : "'" + Name + "Attribute': is not an attribute class";
207 if (t1 != null && t2 != null) {
208 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
209 + " use either '@" + Name + "' or '" + NameAttribute + "'");
217 if (err0616 != null) {
218 Report.Error (616, Location, err0616);
222 Report.Error (246, Location,
223 "Could not find attribute '" + Name
224 + "' (are you missing a using directive or an assembly reference ?)");
226 resolve_error = true;
230 public virtual Type ResolveType (EmitContext ec)
232 if (Type == null && !resolve_error)
233 Type = CheckAttributeType (ec);
237 string GetFullMemberName (string member)
239 return Type.FullName + '.' + member;
243 // Given an expression, if the expression is a valid attribute-argument-expression
244 // returns an object that can be used to encode it, or null on failure.
246 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
248 if (e is EnumConstant) {
249 if (RootContext.StdLib)
250 result = ((EnumConstant)e).GetValueAsEnumType ();
252 result = ((EnumConstant)e).GetValue ();
257 Constant constant = e as Constant;
258 if (constant != null) {
259 if (e.Type != arg_type) {
260 constant = Const.ChangeType (loc, constant, arg_type);
261 if (constant == null) {
263 Error_AttributeArgumentNotValid (loc);
267 result = constant.GetValue ();
269 } else if (e is TypeOf) {
270 result = ((TypeOf) e).TypeArg;
272 } else if (e is ArrayCreation){
273 result = ((ArrayCreation) e).EncodeAsAttribute ();
276 } else if (e is EmptyCast) {
277 Expression child = ((EmptyCast)e).Child;
278 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
282 Error_AttributeArgumentNotValid (loc);
286 // Cache for parameter-less attributes
287 static PtrHashtable att_cache = new PtrHashtable ();
289 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
294 resolve_error = true;
297 Type = CheckAttributeType (ec);
302 if (Type.IsAbstract) {
303 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
307 if (Arguments == null) {
308 object o = att_cache [Type];
310 resolve_error = false;
311 return (CustomAttributeBuilder)o;
315 // Now we extract the positional and named arguments
317 ArrayList pos_args = new ArrayList ();
318 ArrayList named_args = new ArrayList ();
319 int pos_arg_count = 0;
321 if (Arguments != null) {
322 pos_args = (ArrayList) Arguments [0];
323 if (pos_args != null)
324 pos_arg_count = pos_args.Count;
325 if (Arguments.Count > 1)
326 named_args = (ArrayList) Arguments [1];
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;
366 if (named_args.Count > 0) {
367 field_infos = new ArrayList ();
368 prop_infos = new ArrayList ();
369 field_values = new ArrayList ();
370 prop_values = new ArrayList ();
373 Hashtable seen_names = new Hashtable();
375 for (i = 0; i < named_args.Count; i++) {
376 DictionaryEntry de = (DictionaryEntry) named_args [i];
377 string member_name = (string) de.Key;
378 Argument a = (Argument) de.Value;
381 if (seen_names.Contains(member_name)) {
382 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
385 seen_names.Add(member_name, 1);
387 if (!a.Resolve (ec, Location))
390 Expression member = Expression.MemberLookup (
391 ec, Type, member_name,
392 MemberTypes.Field | MemberTypes.Property,
393 BindingFlags.Public | BindingFlags.Instance,
396 if (member == null) {
397 member = Expression.MemberLookup (ec, Type, member_name,
398 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
401 if (member != null) {
402 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
408 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
413 if (!(member is PropertyExpr || member is FieldExpr)) {
414 Error_InvalidNamedArgument (member_name);
419 if (member is PropertyExpr) {
420 PropertyExpr pe = (PropertyExpr) member;
421 PropertyInfo pi = pe.PropertyInfo;
423 if (!pi.CanWrite || !pi.CanRead) {
424 Report.SymbolRelatedToPreviousError (pi);
425 Error_InvalidNamedArgument (member_name);
430 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
433 prop_values.Add (value);
436 } else if (member is FieldExpr) {
437 FieldExpr fe = (FieldExpr) member;
438 FieldInfo fi = fe.FieldInfo;
441 Error_InvalidNamedArgument (member_name);
446 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
449 field_values.Add (value);
450 field_infos.Add (fi);
454 Expression mg = Expression.MemberLookup (
455 ec, Type, ".ctor", MemberTypes.Constructor,
456 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
460 Error_AttributeConstructorMismatch ();
464 MethodBase constructor = Invocation.OverloadResolve (
465 ec, (MethodGroupExpr) mg, pos_args, false, Location);
467 if (constructor == null) {
472 // Now we perform some checks on the positional args as they
473 // cannot be null for a constructor which expects a parameter
477 ParameterData pd = TypeManager.GetParameterData (constructor);
479 int last_real_param = pd.Count;
481 // When the params is not filled we need to put one
482 if (last_real_param > pos_arg_count) {
483 object [] new_pos_values = new object [pos_arg_count + 1];
484 pos_values.CopyTo (new_pos_values, 0);
485 new_pos_values [pos_arg_count] = new object [] {} ;
486 pos_values = new_pos_values;
491 for (int j = 0; j < pos_arg_count; ++j) {
492 Argument a = (Argument) pos_args [j];
494 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
495 Error_AttributeArgumentNotValid (Location);
499 object value = pos_values [j];
500 if (value != null && a.Type != value.GetType () && a.Type.IsPrimitive) {
502 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
504 // TODO: Can failed ?
505 throw new NotImplementedException ();
509 if (j < last_real_param)
512 if (j == last_real_param) {
513 object [] array = new object [pos_arg_count - last_real_param];
514 array [0] = pos_values [j];
515 pos_values [j] = array;
519 object [] params_array = (object []) pos_values [last_real_param];
520 params_array [j - last_real_param] = pos_values [j];
523 // Adjust the size of the pos_values if it had params
524 if (last_real_param != pos_arg_count) {
525 object [] new_pos_values = new object [last_real_param + 1];
526 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
527 pos_values = new_pos_values;
531 if (named_args.Count > 0) {
532 prop_info_arr = new PropertyInfo [prop_infos.Count];
533 field_info_arr = new FieldInfo [field_infos.Count];
534 field_values_arr = new object [field_values.Count];
535 prop_values_arr = new object [prop_values.Count];
537 field_infos.CopyTo (field_info_arr, 0);
538 field_values.CopyTo (field_values_arr, 0);
540 prop_values.CopyTo (prop_values_arr, 0);
541 prop_infos.CopyTo (prop_info_arr, 0);
543 cb = new CustomAttributeBuilder (
544 (ConstructorInfo) constructor, pos_values,
545 prop_info_arr, prop_values_arr,
546 field_info_arr, field_values_arr);
549 cb = new CustomAttributeBuilder (
550 (ConstructorInfo) constructor, pos_values);
552 if (pos_values.Length == 0)
553 att_cache.Add (Type, cb);
555 } catch (Exception) {
558 // using System.ComponentModel;
559 // [DefaultValue (CollectionChangeAction.Add)]
560 // class X { static void Main () {} }
562 Error_AttributeArgumentNotValid (Location);
566 resolve_error = false;
571 /// Get a string containing a list of valid targets for the attribute 'attr'
573 public string GetValidTargets ()
575 StringBuilder sb = new StringBuilder ();
576 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
578 if ((targets & AttributeTargets.Assembly) != 0)
579 sb.Append ("'assembly' ");
581 if ((targets & AttributeTargets.Class) != 0)
582 sb.Append ("'class' ");
584 if ((targets & AttributeTargets.Constructor) != 0)
585 sb.Append ("'constructor' ");
587 if ((targets & AttributeTargets.Delegate) != 0)
588 sb.Append ("'delegate' ");
590 if ((targets & AttributeTargets.Enum) != 0)
591 sb.Append ("'enum' ");
593 if ((targets & AttributeTargets.Event) != 0)
594 sb.Append ("'event' ");
596 if ((targets & AttributeTargets.Field) != 0)
597 sb.Append ("'field' ");
599 if ((targets & AttributeTargets.Interface) != 0)
600 sb.Append ("'interface' ");
602 if ((targets & AttributeTargets.Method) != 0)
603 sb.Append ("'method' ");
605 if ((targets & AttributeTargets.Module) != 0)
606 sb.Append ("'module' ");
608 if ((targets & AttributeTargets.Parameter) != 0)
609 sb.Append ("'parameter' ");
611 if ((targets & AttributeTargets.Property) != 0)
612 sb.Append ("'property' ");
614 if ((targets & AttributeTargets.ReturnValue) != 0)
615 sb.Append ("'return' ");
617 if ((targets & AttributeTargets.Struct) != 0)
618 sb.Append ("'struct' ");
620 return sb.ToString ();
625 /// Returns AttributeUsage attribute for this type
627 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
629 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
633 Class attr_class = TypeManager.LookupClass (Type);
635 if (attr_class == null) {
636 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
637 ua = (AttributeUsageAttribute)usage_attr [0];
638 usage_attr_cache.Add (Type, ua);
642 if (attr_class.OptAttributes == null) {
643 usage_attr_cache.Add (Type, DefaultUsageAttribute);
644 return DefaultUsageAttribute;
647 Attribute a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, ec);
649 usage_attr_cache.Add (Type, DefaultUsageAttribute);
650 return DefaultUsageAttribute;
653 ua = a.GetAttributeUsageAttribute (ec);
654 usage_attr_cache.Add (Type, ua);
658 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
660 if (pos_values == null)
661 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
662 // But because a lot of attribute class code must be rewritten will be better to wait...
666 return DefaultUsageAttribute;
668 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
670 object field = GetPropertyValue ("AllowMultiple");
672 usage_attribute.AllowMultiple = (bool)field;
674 field = GetPropertyValue ("Inherited");
676 usage_attribute.Inherited = (bool)field;
678 return usage_attribute;
682 /// Returns custom name of indexer
684 public string GetIndexerAttributeValue (EmitContext ec)
686 if (pos_values == null)
687 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
688 // But because a lot of attribute class code must be rewritten will be better to wait...
694 return pos_values [0] as string;
698 /// Returns condition of ConditionalAttribute
700 public string GetConditionalAttributeValue (EmitContext ec)
702 if (pos_values == null)
703 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
704 // But because a lot of attribute class code must be rewritten will be better to wait...
710 return (string)pos_values [0];
714 /// Creates the instance of ObsoleteAttribute from this attribute instance
716 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
718 if (pos_values == null)
719 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
720 // But because a lot of attribute class code must be rewritten will be better to wait...
726 if (pos_values == null || pos_values.Length == 0)
727 return new ObsoleteAttribute ();
729 if (pos_values.Length == 1)
730 return new ObsoleteAttribute ((string)pos_values [0]);
732 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
736 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
737 /// before ApplyAttribute. We need to resolve the arguments.
738 /// This situation occurs when class deps is differs from Emit order.
740 public bool GetClsCompliantAttributeValue (EmitContext ec)
742 if (pos_values == null)
743 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
744 // But because a lot of attribute class code must be rewritten will be better to wait...
750 return (bool)pos_values [0];
754 /// Tests permitted SecurityAction for assembly or other types
756 public bool CheckSecurityActionValidity (bool for_assembly)
758 SecurityAction action = GetSecurityActionValue ();
760 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
764 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
765 Error_AttributeEmitError ("SecurityAction is out of range");
769 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
773 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
777 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
779 return (SecurityAction)pos_values [0];
783 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
785 /// <returns></returns>
786 public void ExtractSecurityPermissionSet (ListDictionary permissions)
788 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
789 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
793 SecurityAttribute sa;
794 // For all assemblies except corlib we can avoid all hacks
795 if (RootContext.StdLib) {
796 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
798 if (prop_info_arr != null) {
799 for (int i = 0; i < prop_info_arr.Length; ++i) {
800 PropertyInfo pi = prop_info_arr [i];
801 pi.SetValue (sa, prop_values_arr [i], null);
805 Type temp_type = Type.GetType (Type.FullName);
806 // HACK: All mscorlib attributes have same ctor syntax
807 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
809 // All types are from newly created corlib but for invocation with old we need to convert them
810 if (prop_info_arr != null) {
811 for (int i = 0; i < prop_info_arr.Length; ++i) {
812 PropertyInfo emited_pi = prop_info_arr [i];
813 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
815 object old_instance = pi.PropertyType.IsEnum ?
816 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
819 pi.SetValue (sa, old_instance, null);
825 perm = sa.CreatePermission ();
826 SecurityAction action = GetSecurityActionValue ();
828 // IS is correct because for corlib we are using an instance from old corlib
829 if (!(perm is System.Security.CodeAccessPermission)) {
831 case SecurityAction.Demand:
832 action = (SecurityAction)13;
834 case SecurityAction.LinkDemand:
835 action = (SecurityAction)14;
837 case SecurityAction.InheritanceDemand:
838 action = (SecurityAction)15;
843 PermissionSet ps = (PermissionSet)permissions [action];
845 if (sa is PermissionSetAttribute)
846 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
848 ps = new PermissionSet (PermissionState.None);
850 permissions.Add (action, ps);
851 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
852 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
853 permissions [action] = ps;
855 ps.AddPermission (perm);
858 object GetValue (object value)
860 if (value is EnumConstant)
861 return ((EnumConstant) value).GetValue ();
866 object GetPropertyValue (string name)
868 if (prop_info_arr == null)
871 for (int i = 0; i < prop_info_arr.Length; ++i) {
872 if (prop_info_arr [i].Name == name)
873 return prop_values_arr [i];
879 object GetFieldValue (string name)
882 if (field_info_arr == null)
885 foreach (FieldInfo fi in field_info_arr) {
887 return GetValue (field_values_arr [i]);
893 public UnmanagedMarshal GetMarshal (Attributable attr)
895 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
897 object value = GetFieldValue ("SizeParamIndex");
898 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
899 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
903 object o = GetFieldValue ("ArraySubType");
904 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
906 switch (UnmanagedType) {
907 case UnmanagedType.CustomMarshaler: {
908 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
909 BindingFlags.Static | BindingFlags.Public);
910 if (define_custom == null) {
911 Report.RuntimeMissingSupport (Location, "set marshal info");
915 object [] args = new object [4];
916 args [0] = GetFieldValue ("MarshalTypeRef");
917 args [1] = GetFieldValue ("MarshalCookie");
918 args [2] = GetFieldValue ("MarshalType");
919 args [3] = Guid.Empty;
920 return (UnmanagedMarshal) define_custom.Invoke (null, args);
922 case UnmanagedType.LPArray: {
923 object size_const = GetFieldValue ("SizeConst");
924 object size_param_index = GetFieldValue ("SizeParamIndex");
926 if ((size_const != null) || (size_param_index != null)) {
927 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
928 if (define_array == null) {
929 Report.RuntimeMissingSupport (Location, "set marshal info");
933 object [] args = new object [3];
934 args [0] = array_sub_type;
935 args [1] = size_const == null ? -1 : size_const;
936 args [2] = size_param_index == null ? -1 : size_param_index;
937 return (UnmanagedMarshal) define_array.Invoke (null, args);
940 return UnmanagedMarshal.DefineLPArray (array_sub_type);
942 case UnmanagedType.SafeArray:
943 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
945 case UnmanagedType.ByValArray:
946 FieldMember fm = attr as FieldMember;
948 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
951 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
953 case UnmanagedType.ByValTStr:
954 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
957 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
961 public MethodImplOptions GetMethodImplOptions ()
963 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
966 public LayoutKind GetLayoutKindValue ()
968 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
972 /// Emit attribute for Attributable symbol
974 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
976 CustomAttributeBuilder cb = Resolve (ec);
980 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
981 if ((usage_attr.ValidOn & Target) == 0) {
982 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
987 ias.ApplyAttributeBuilder (this, cb);
989 catch (Exception e) {
990 Error_AttributeEmitError (e.Message);
994 if (!usage_attr.AllowMultiple) {
995 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
996 if (emitted_targets == null) {
997 emitted_targets = new ArrayList ();
998 emitted_attr.Add (Type, emitted_targets);
999 } else if (emitted_targets.Contains (Target)) {
1000 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1003 emitted_targets.Add (Target);
1006 if (!RootContext.VerifyClsCompliance)
1009 // Here we are testing attribute arguments for array usage (error 3016)
1010 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1011 if (Arguments == null)
1014 ArrayList pos_args = (ArrayList) Arguments [0];
1015 if (pos_args != null) {
1016 foreach (Argument arg in pos_args) {
1017 // Type is undefined (was error 246)
1018 if (arg.Type == null)
1021 if (arg.Type.IsArray) {
1022 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1028 if (Arguments.Count < 2)
1031 ArrayList named_args = (ArrayList) Arguments [1];
1032 foreach (DictionaryEntry de in named_args) {
1033 Argument arg = (Argument) de.Value;
1035 // Type is undefined (was error 246)
1036 if (arg.Type == null)
1039 if (arg.Type.IsArray) {
1040 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1047 object GetValue (EmitContext ec, Constant c, Type target)
1049 if (Convert.ImplicitConversionExists (ec, c, target))
1050 return c.GetValue ();
1052 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1056 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1057 MethodAttributes flags, Type ret_type, Type [] param_types)
1059 if (pos_values == null)
1060 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1061 // But because a lot of attribute class code must be rewritten will be better to wait...
1067 string dll_name = (string)pos_values [0];
1070 CallingConvention cc = CallingConvention.Winapi;
1071 CharSet charset = CharSet.Ansi;
1072 bool preserve_sig = true;
1073 string entry_point = name;
1075 if (field_info_arr != null) {
1076 int char_set_extra = 0;
1078 for (int i = 0; i < field_info_arr.Length; i++) {
1079 switch (field_info_arr [i].Name) {
1080 case "BestFitMapping":
1081 throw new NotImplementedException ();
1082 case "CallingConvention":
1083 cc = (CallingConvention) field_values_arr [i];
1086 charset = (CharSet) field_values_arr [i];
1089 entry_point = (string) field_values_arr [i];
1091 case "ExactSpelling":
1092 char_set_extra |= 0x01;
1095 preserve_sig = (bool) field_values_arr [i];
1097 case "SetLastError":
1098 char_set_extra |= 0x40;
1100 case "ThrowOnUnmappableChar":
1101 throw new NotImplementedException ();
1103 throw new InternalErrorException (field_info_arr [i].ToString ());
1106 charset |= (CharSet)char_set_extra;
1110 MethodBuilder mb = builder.DefinePInvokeMethod (
1111 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1112 CallingConventions.Standard, ret_type, param_types, cc, charset);
1115 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1119 catch (ArgumentException e) {
1120 Error_AttributeEmitError (e.Message);
1125 private Expression GetValue ()
1127 if ((Arguments == null) || (Arguments.Count < 1))
1129 ArrayList al = (ArrayList) Arguments [0];
1130 if ((al == null) || (al.Count < 1))
1132 Argument arg = (Argument) al [0];
1133 if ((arg == null) || (arg.Expr == null))
1138 public string GetString ()
1140 Expression e = GetValue ();
1141 if (e is StringLiteral)
1142 return (e as StringLiteral).Value;
1146 public bool GetBoolean ()
1148 Expression e = GetValue ();
1149 if (e is BoolLiteral)
1150 return (e as BoolLiteral).Value;
1157 /// For global attributes (assembly, module) we need special handling.
1158 /// Attributes can be located in the several files
1160 public class GlobalAttribute: Attribute
1162 public readonly NamespaceEntry ns;
1164 public GlobalAttribute (TypeContainer container, string target,
1165 Expression left_expr, string identifier, ArrayList args, Location loc):
1166 base (target, left_expr, identifier, args, loc)
1168 ns = container.NamespaceEntry;
1173 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1174 // each time a new file is parsed. However, we need to use the NamespaceEntry
1175 // in effect where the attribute was used. Since code elsewhere cannot assume
1176 // that the NamespaceEntry is right, just overwrite it.
1178 // Precondition: RootContext.Tree.Types == null
1180 if (RootContext.Tree.Types.NamespaceEntry != null)
1181 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1183 RootContext.Tree.Types.NamespaceEntry = ns;
1188 RootContext.Tree.Types.NamespaceEntry = null;
1191 public override Type ResolveType (EmitContext ec)
1194 Type retval = base.ResolveType (ec);
1199 public override CustomAttributeBuilder Resolve (EmitContext ec)
1202 CustomAttributeBuilder retval = base.Resolve (ec);
1208 public class Attributes {
1209 public ArrayList Attrs;
1211 public Attributes (Attribute a)
1213 Attrs = new ArrayList ();
1217 public Attributes (ArrayList attrs)
1222 public void AddAttributes (ArrayList attrs)
1224 Attrs.AddRange (attrs);
1228 /// Checks whether attribute target is valid for the current element
1230 public bool CheckTargets (Attributable member)
1232 string[] valid_targets = member.ValidAttributeTargets;
1233 foreach (Attribute a in Attrs) {
1234 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1235 a.Target = member.AttributeTargets;
1239 // TODO: we can skip the first item
1240 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1241 switch (a.ExplicitTarget) {
1242 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1243 case "param": a.Target = AttributeTargets.Parameter; continue;
1244 case "field": a.Target = AttributeTargets.Field; continue;
1245 case "method": a.Target = AttributeTargets.Method; continue;
1246 case "property": a.Target = AttributeTargets.Property; continue;
1248 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1251 StringBuilder sb = new StringBuilder ();
1252 foreach (string s in valid_targets) {
1256 sb.Remove (sb.Length - 2, 2);
1257 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 ());
1263 public Attribute Search (Type t, EmitContext ec)
1265 foreach (Attribute a in Attrs) {
1266 if (a.ResolveType (ec) == t)
1273 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1275 public Attribute[] SearchMulti (Type t, EmitContext ec)
1277 ArrayList ar = null;
1279 foreach (Attribute a in Attrs) {
1280 if (a.ResolveType (ec) == t) {
1282 ar = new ArrayList ();
1287 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1290 public void Emit (EmitContext ec, Attributable ias)
1292 if (!CheckTargets (ias))
1295 ListDictionary ld = new ListDictionary ();
1297 foreach (Attribute a in Attrs)
1298 a.Emit (ec, ias, ld);
1301 public bool Contains (Type t, EmitContext ec)
1303 return Search (t, ec) != null;
1308 /// Helper class for attribute verification routine.
1310 sealed class AttributeTester
1312 static PtrHashtable analyzed_types = new PtrHashtable ();
1313 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1314 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1315 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1316 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1318 static object TRUE = new object ();
1319 static object FALSE = new object ();
1321 private AttributeTester ()
1326 /// Returns true if parameters of two compared methods are CLS-Compliant.
1327 /// It tests differing only in ref or out, or in array rank.
1329 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1331 if (types_a == null || types_b == null)
1334 if (types_a.Length != types_b.Length)
1337 for (int i = 0; i < types_b.Length; ++i) {
1338 Type aType = types_a [i];
1339 Type bType = types_b [i];
1341 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1345 Type aBaseType = aType;
1346 bool is_either_ref_or_out = false;
1348 if (aType.IsByRef || aType.IsPointer) {
1349 aBaseType = aType.GetElementType ();
1350 is_either_ref_or_out = true;
1353 Type bBaseType = bType;
1354 if (bType.IsByRef || bType.IsPointer)
1356 bBaseType = bType.GetElementType ();
1357 is_either_ref_or_out = !is_either_ref_or_out;
1360 if (aBaseType != bBaseType)
1363 if (is_either_ref_or_out)
1370 /// Goes through all parameters and test if they are CLS-Compliant.
1372 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1374 if (fixedParameters == null)
1377 foreach (Parameter arg in fixedParameters) {
1378 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1379 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1388 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1390 public static bool IsClsCompliant (Type type)
1395 object type_compliance = analyzed_types[type];
1396 if (type_compliance != null)
1397 return type_compliance == TRUE;
1399 if (type.IsPointer) {
1400 analyzed_types.Add (type, null);
1405 if (type.IsArray || type.IsByRef) {
1406 result = IsClsCompliant (TypeManager.GetElementType (type));
1408 result = AnalyzeTypeCompliance (type);
1410 analyzed_types.Add (type, result ? TRUE : FALSE);
1415 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1417 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1419 FieldBase fb = TypeManager.GetField (fi);
1421 return fb as IFixedBuffer;
1425 object o = fixed_buffer_cache [fi];
1427 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1428 fixed_buffer_cache.Add (fi, FALSE);
1432 IFixedBuffer iff = new FixedFieldExternal (fi);
1433 fixed_buffer_cache.Add (fi, iff);
1440 return (IFixedBuffer)o;
1446 public static void VerifyModulesClsCompliance ()
1448 Module[] modules = TypeManager.Modules;
1449 if (modules == null)
1452 // The first module is generated assembly
1453 for (int i = 1; i < modules.Length; ++i) {
1454 Module module = modules [i];
1455 if (!IsClsCompliant (module)) {
1456 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1463 /// Tests container name for CLS-Compliant name (differing only in case)
1465 public static void VerifyTopLevelNameClsCompliance ()
1467 Hashtable locase_table = new Hashtable ();
1469 // Convert imported type names to lower case and ignore not cls compliant
1470 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1471 Type t = (Type)de.Value;
1472 if (!AttributeTester.IsClsCompliant (t))
1475 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1478 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1479 DeclSpace decl = (DeclSpace)de.Value;
1480 if (!decl.IsClsCompliaceRequired (decl))
1483 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1484 if (!locase_table.Contains (lcase)) {
1485 locase_table.Add (lcase, decl);
1489 object conflict = locase_table [lcase];
1490 if (conflict is Type)
1491 Report.SymbolRelatedToPreviousError ((Type)conflict);
1493 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1495 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1499 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1501 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1502 if (CompliantAttribute.Length == 0)
1505 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1508 static bool AnalyzeTypeCompliance (Type type)
1510 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1512 return ds.IsClsCompliaceRequired (ds.Parent);
1515 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1516 if (CompliantAttribute.Length == 0)
1517 return IsClsCompliant (type.Assembly);
1519 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1523 /// Returns instance of ObsoleteAttribute when type is obsolete
1525 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1527 object type_obsolete = analyzed_types_obsolete [type];
1528 if (type_obsolete == FALSE)
1531 if (type_obsolete != null)
1532 return (ObsoleteAttribute)type_obsolete;
1534 ObsoleteAttribute result = null;
1535 if (type.IsByRef || type.IsArray || type.IsPointer) {
1536 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1538 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1540 // Type is external, we can get attribute directly
1541 if (type_ds == null) {
1542 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1543 if (attribute.Length == 1)
1544 result = (ObsoleteAttribute)attribute [0];
1546 result = type_ds.GetObsoleteAttribute (type_ds);
1550 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1555 /// Returns instance of ObsoleteAttribute when method is obsolete
1557 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1559 IMethodData mc = TypeManager.GetMethod (mb);
1561 return mc.GetObsoleteAttribute ();
1563 // compiler generated methods are not registered by AddMethod
1564 if (mb.DeclaringType is TypeBuilder)
1567 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1569 return GetMemberObsoleteAttribute (pi);
1571 return GetMemberObsoleteAttribute (mb);
1575 /// Returns instance of ObsoleteAttribute when member is obsolete
1577 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1579 object type_obsolete = analyzed_member_obsolete [mi];
1580 if (type_obsolete == FALSE)
1583 if (type_obsolete != null)
1584 return (ObsoleteAttribute)type_obsolete;
1586 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1587 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1592 /// Common method for Obsolete error/warning reporting.
1594 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1597 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1601 if (oa.Message == null) {
1602 Report.Warning (612, loc, "'{0}' is obsolete", member);
1605 if (RootContext.WarningLevel >= 2)
1606 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1609 public static bool IsConditionalMethodExcluded (MethodBase mb)
1611 object excluded = analyzed_method_excluded [mb];
1612 if (excluded != null)
1613 return excluded == TRUE ? true : false;
1615 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1616 if (attrs.Length == 0) {
1617 analyzed_method_excluded.Add (mb, FALSE);
1621 foreach (ConditionalAttribute a in attrs) {
1622 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1623 analyzed_method_excluded.Add (mb, FALSE);
1627 analyzed_method_excluded.Add (mb, TRUE);