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);
128 static void Error_TypeParameterInAttribute (Location loc)
131 -202, loc, "Can not use a type parameter in an attribute");
135 /// This is rather hack. We report many emit attribute error with same error to be compatible with
136 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
138 public void Error_AttributeEmitError (string inner)
140 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
143 public void Error_InvalidSecurityParent ()
145 Error_AttributeEmitError ("it is attached to invalid parent");
148 void Error_AttributeConstructorMismatch ()
150 Report.Error (-6, Location,
151 "Could not find a constructor for this argument list.");
154 void ResolvePossibleAttributeTypes (EmitContext ec, out Type t1, out Type t2)
159 FullNamedExpression n1 = null;
160 FullNamedExpression n2 = null;
161 string IdentifierAttribute = Identifier + "Attribute";
162 if (LeftExpr == null) {
163 n1 = new SimpleName (Identifier, Location).ResolveAsTypeStep (ec);
165 // FIXME: Shouldn't do this for quoted attributes: [@A]
166 n2 = new SimpleName (IdentifierAttribute, Location).ResolveAsTypeStep (ec);
168 FullNamedExpression l = LeftExpr.ResolveAsTypeStep (ec);
170 Report.Error (246, Location, "Couldn't find namespace or type '{0}'", LeftExpr);
173 n1 = new MemberAccess (l, Identifier, Location).ResolveNamespaceOrType (ec, true);
175 // FIXME: Shouldn't do this for quoted attributes: [X.@A]
176 n2 = new MemberAccess (l, IdentifierAttribute, Location).ResolveNamespaceOrType (ec, true);
179 TypeExpr te1 = n1 == null ? null : n1 as TypeExpr;
180 TypeExpr te2 = n2 == null ? null : n2 as TypeExpr;
183 t1 = te1.ResolveType (ec);
185 t2 = te2.ResolveType (ec);
189 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
191 Type CheckAttributeType (EmitContext ec)
194 ResolvePossibleAttributeTypes (ec, out t1, out t2);
196 string NameAttribute = Name + "Attribute";
198 String err0616 = null;
199 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
201 err0616 = "'" + Name + "': is not an attribute class";
203 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
205 err0616 = (err0616 != null)
206 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
207 : "'" + Name + "Attribute': is not an attribute class";
210 if (t1 != null && t2 != null) {
211 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
212 + " use either '@" + Name + "' or '" + NameAttribute + "'");
219 if (err0616 != null) {
220 Report.Error (616, Location, err0616);
224 Report.Error (246, Location,
225 "Could not find attribute '" + Name
226 + "' (are you missing a using directive or an assembly reference ?)");
228 resolve_error = true;
232 public virtual Type ResolveType (EmitContext ec)
234 if (Type == null && !resolve_error)
235 Type = CheckAttributeType (ec);
239 string GetFullMemberName (string member)
241 return Type.FullName + '.' + member;
245 // Given an expression, if the expression is a valid attribute-argument-expression
246 // returns an object that can be used to encode it, or null on failure.
248 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
250 if (e is EnumConstant) {
251 if (RootContext.StdLib)
252 result = ((EnumConstant)e).GetValueAsEnumType ();
254 result = ((EnumConstant)e).GetValue ();
259 Constant constant = e as Constant;
260 if (constant != null) {
261 if (e.Type != arg_type) {
262 constant = Const.ChangeType (loc, constant, arg_type);
263 if (constant == null) {
265 Error_AttributeArgumentNotValid (loc);
269 result = constant.GetValue ();
271 } else if (e is TypeOf) {
272 result = ((TypeOf) e).TypeArg;
274 } else if (e is ArrayCreation){
275 result = ((ArrayCreation) e).EncodeAsAttribute ();
278 } else if (e is EmptyCast) {
279 Expression child = ((EmptyCast)e).Child;
280 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
284 Error_AttributeArgumentNotValid (loc);
288 // Cache for parameter-less attributes
289 static PtrHashtable att_cache = new PtrHashtable ();
291 public virtual CustomAttributeBuilder Resolve (EmitContext ec)
296 resolve_error = true;
299 Type = CheckAttributeType (ec);
304 if (Type.IsAbstract) {
305 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
309 if (Arguments == null) {
310 object o = att_cache [Type];
312 resolve_error = false;
313 return (CustomAttributeBuilder)o;
317 // Now we extract the positional and named arguments
319 ArrayList pos_args = new ArrayList ();
320 ArrayList named_args = new ArrayList ();
321 int pos_arg_count = 0;
323 if (Arguments != null) {
324 pos_args = (ArrayList) Arguments [0];
325 if (pos_args != null)
326 pos_arg_count = pos_args.Count;
327 if (Arguments.Count > 1)
328 named_args = (ArrayList) Arguments [1];
331 pos_values = new object [pos_arg_count];
334 // First process positional arguments
338 for (i = 0; i < pos_arg_count; i++) {
339 Argument a = (Argument) pos_args [i];
342 if (!a.Resolve (ec, Location))
348 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
351 pos_values [i] = val;
353 if (i == 0 && Type == TypeManager.attribute_usage_type && (int)val == 0) {
354 Report.Error (591, Location, "Invalid value for argument to 'System.AttributeUsage' attribute");
360 // Now process named arguments
363 ArrayList field_infos = null;
364 ArrayList prop_infos = null;
365 ArrayList field_values = null;
366 ArrayList prop_values = null;
368 if (named_args.Count > 0) {
369 field_infos = new ArrayList ();
370 prop_infos = new ArrayList ();
371 field_values = new ArrayList ();
372 prop_values = new ArrayList ();
375 Hashtable seen_names = new Hashtable();
377 for (i = 0; i < named_args.Count; i++) {
378 DictionaryEntry de = (DictionaryEntry) named_args [i];
379 string member_name = (string) de.Key;
380 Argument a = (Argument) de.Value;
383 if (seen_names.Contains(member_name)) {
384 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
387 seen_names.Add(member_name, 1);
389 if (!a.Resolve (ec, Location))
392 Expression member = Expression.MemberLookup (
393 ec, Type, member_name,
394 MemberTypes.Field | MemberTypes.Property,
395 BindingFlags.Public | BindingFlags.Instance,
398 if (member == null) {
399 member = Expression.MemberLookup (ec, Type, member_name,
400 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
403 if (member != null) {
404 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
410 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
415 if (!(member is PropertyExpr || member is FieldExpr)) {
416 Error_InvalidNamedArgument (member_name);
421 if (e is TypeParameterExpr){
422 Error_TypeParameterInAttribute (Location);
426 if (member is PropertyExpr) {
427 PropertyExpr pe = (PropertyExpr) member;
428 PropertyInfo pi = pe.PropertyInfo;
430 if (!pi.CanWrite || !pi.CanRead) {
431 Report.SymbolRelatedToPreviousError (pi);
432 Error_InvalidNamedArgument (member_name);
437 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
440 prop_values.Add (value);
443 } else if (member is FieldExpr) {
444 FieldExpr fe = (FieldExpr) member;
445 FieldInfo fi = fe.FieldInfo;
448 Error_InvalidNamedArgument (member_name);
453 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
456 field_values.Add (value);
458 field_infos.Add (fi);
462 Expression mg = Expression.MemberLookup (
463 ec, Type, ".ctor", MemberTypes.Constructor,
464 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
468 Error_AttributeConstructorMismatch ();
472 MethodBase constructor = Invocation.OverloadResolve (
473 ec, (MethodGroupExpr) mg, pos_args, false, Location);
475 if (constructor == null) {
480 // Now we perform some checks on the positional args as they
481 // cannot be null for a constructor which expects a parameter
485 ParameterData pd = TypeManager.GetParameterData (constructor);
487 int last_real_param = pd.Count;
489 // When the params is not filled we need to put one
490 if (last_real_param > pos_arg_count) {
491 object [] new_pos_values = new object [pos_arg_count + 1];
492 pos_values.CopyTo (new_pos_values, 0);
493 new_pos_values [pos_arg_count] = new object [] {} ;
494 pos_values = new_pos_values;
499 for (int j = 0; j < pos_arg_count; ++j) {
500 Argument a = (Argument) pos_args [j];
502 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
503 Error_AttributeArgumentNotValid (Location);
507 object value = pos_values [j];
508 if (value != null && a.Type != value.GetType () && a.Type.IsPrimitive) {
510 pos_values [j] = TypeManager.ChangeType (value, a.Type, out fail);
512 // TODO: Can failed ?
513 throw new NotImplementedException ();
517 if (j < last_real_param)
520 if (j == last_real_param) {
521 object [] array = new object [pos_arg_count - last_real_param];
522 array [0] = pos_values [j];
523 pos_values [j] = array;
527 object [] params_array = (object []) pos_values [last_real_param];
528 params_array [j - last_real_param] = pos_values [j];
531 // Adjust the size of the pos_values if it had params
532 if (last_real_param != pos_arg_count) {
533 object [] new_pos_values = new object [last_real_param + 1];
534 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
535 pos_values = new_pos_values;
539 if (named_args.Count > 0) {
540 prop_info_arr = new PropertyInfo [prop_infos.Count];
541 field_info_arr = new FieldInfo [field_infos.Count];
542 field_values_arr = new object [field_values.Count];
543 prop_values_arr = new object [prop_values.Count];
545 field_infos.CopyTo (field_info_arr, 0);
546 field_values.CopyTo (field_values_arr, 0);
548 prop_values.CopyTo (prop_values_arr, 0);
549 prop_infos.CopyTo (prop_info_arr, 0);
551 cb = new CustomAttributeBuilder (
552 (ConstructorInfo) constructor, pos_values,
553 prop_info_arr, prop_values_arr,
554 field_info_arr, field_values_arr);
557 cb = new CustomAttributeBuilder (
558 (ConstructorInfo) constructor, pos_values);
560 if (pos_values.Length == 0)
561 att_cache.Add (Type, cb);
563 } catch (Exception) {
566 // using System.ComponentModel;
567 // [DefaultValue (CollectionChangeAction.Add)]
568 // class X { static void Main () {} }
570 Error_AttributeArgumentNotValid (Location);
574 resolve_error = false;
579 /// Get a string containing a list of valid targets for the attribute 'attr'
581 public string GetValidTargets ()
583 StringBuilder sb = new StringBuilder ();
584 AttributeTargets targets = GetAttributeUsage (null).ValidOn;
586 if ((targets & AttributeTargets.Assembly) != 0)
587 sb.Append ("'assembly' ");
589 if ((targets & AttributeTargets.Class) != 0)
590 sb.Append ("'class' ");
592 if ((targets & AttributeTargets.Constructor) != 0)
593 sb.Append ("'constructor' ");
595 if ((targets & AttributeTargets.Delegate) != 0)
596 sb.Append ("'delegate' ");
598 if ((targets & AttributeTargets.Enum) != 0)
599 sb.Append ("'enum' ");
601 if ((targets & AttributeTargets.Event) != 0)
602 sb.Append ("'event' ");
604 if ((targets & AttributeTargets.Field) != 0)
605 sb.Append ("'field' ");
607 if ((targets & AttributeTargets.Interface) != 0)
608 sb.Append ("'interface' ");
610 if ((targets & AttributeTargets.Method) != 0)
611 sb.Append ("'method' ");
613 if ((targets & AttributeTargets.Module) != 0)
614 sb.Append ("'module' ");
616 if ((targets & AttributeTargets.Parameter) != 0)
617 sb.Append ("'parameter' ");
619 if ((targets & AttributeTargets.Property) != 0)
620 sb.Append ("'property' ");
622 if ((targets & AttributeTargets.ReturnValue) != 0)
623 sb.Append ("'return' ");
625 if ((targets & AttributeTargets.Struct) != 0)
626 sb.Append ("'struct' ");
628 return sb.ToString ();
633 /// Returns AttributeUsage attribute for this type
635 AttributeUsageAttribute GetAttributeUsage (EmitContext ec)
637 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
641 Class attr_class = TypeManager.LookupClass (Type);
643 if (attr_class == null) {
644 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
645 ua = (AttributeUsageAttribute)usage_attr [0];
646 usage_attr_cache.Add (Type, ua);
650 if (attr_class.OptAttributes == null) {
651 usage_attr_cache.Add (Type, DefaultUsageAttribute);
652 return DefaultUsageAttribute;
655 Attribute a = attr_class.OptAttributes.Search (TypeManager.attribute_usage_type, ec);
657 usage_attr_cache.Add (Type, DefaultUsageAttribute);
658 return DefaultUsageAttribute;
661 ua = a.GetAttributeUsageAttribute (ec);
662 usage_attr_cache.Add (Type, ua);
666 AttributeUsageAttribute GetAttributeUsageAttribute (EmitContext ec)
668 if (pos_values == null)
669 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
670 // But because a lot of attribute class code must be rewritten will be better to wait...
674 return DefaultUsageAttribute;
676 AttributeUsageAttribute usage_attribute = new AttributeUsageAttribute ((AttributeTargets)pos_values [0]);
678 object field = GetPropertyValue ("AllowMultiple");
680 usage_attribute.AllowMultiple = (bool)field;
682 field = GetPropertyValue ("Inherited");
684 usage_attribute.Inherited = (bool)field;
686 return usage_attribute;
690 /// Returns custom name of indexer
692 public string GetIndexerAttributeValue (EmitContext ec)
694 if (pos_values == null)
695 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
696 // But because a lot of attribute class code must be rewritten will be better to wait...
702 return pos_values [0] as string;
706 /// Returns condition of ConditionalAttribute
708 public string GetConditionalAttributeValue (EmitContext ec)
710 if (pos_values == null)
711 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
712 // But because a lot of attribute class code must be rewritten will be better to wait...
718 return (string)pos_values [0];
722 /// Creates the instance of ObsoleteAttribute from this attribute instance
724 public ObsoleteAttribute GetObsoleteAttribute (EmitContext ec)
726 if (pos_values == null)
727 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
728 // But because a lot of attribute class code must be rewritten will be better to wait...
734 if (pos_values == null || pos_values.Length == 0)
735 return new ObsoleteAttribute ();
737 if (pos_values.Length == 1)
738 return new ObsoleteAttribute ((string)pos_values [0]);
740 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
744 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
745 /// before ApplyAttribute. We need to resolve the arguments.
746 /// This situation occurs when class deps is differs from Emit order.
748 public bool GetClsCompliantAttributeValue (EmitContext ec)
750 if (pos_values == null)
751 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
752 // But because a lot of attribute class code must be rewritten will be better to wait...
758 return (bool)pos_values [0];
762 /// Tests permitted SecurityAction for assembly or other types
764 public bool CheckSecurityActionValidity (bool for_assembly)
766 SecurityAction action = GetSecurityActionValue ();
768 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
772 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
773 Error_AttributeEmitError ("SecurityAction is out of range");
777 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
781 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
785 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
787 return (SecurityAction)pos_values [0];
791 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
793 /// <returns></returns>
794 public void ExtractSecurityPermissionSet (ListDictionary permissions)
796 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
797 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
801 SecurityAttribute sa;
802 // For all assemblies except corlib we can avoid all hacks
803 if (RootContext.StdLib) {
804 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
806 if (prop_info_arr != null) {
807 for (int i = 0; i < prop_info_arr.Length; ++i) {
808 PropertyInfo pi = prop_info_arr [i];
809 pi.SetValue (sa, prop_values_arr [i], null);
813 Type temp_type = Type.GetType (Type.FullName);
814 // HACK: All mscorlib attributes have same ctor syntax
815 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
817 // All types are from newly created corlib but for invocation with old we need to convert them
818 if (prop_info_arr != null) {
819 for (int i = 0; i < prop_info_arr.Length; ++i) {
820 PropertyInfo emited_pi = prop_info_arr [i];
821 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
823 object old_instance = pi.PropertyType.IsEnum ?
824 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
827 pi.SetValue (sa, old_instance, null);
833 perm = sa.CreatePermission ();
834 SecurityAction action = GetSecurityActionValue ();
836 // IS is correct because for corlib we are using an instance from old corlib
837 if (!(perm is System.Security.CodeAccessPermission)) {
839 case SecurityAction.Demand:
840 action = (SecurityAction)13;
842 case SecurityAction.LinkDemand:
843 action = (SecurityAction)14;
845 case SecurityAction.InheritanceDemand:
846 action = (SecurityAction)15;
851 PermissionSet ps = (PermissionSet)permissions [action];
853 if (sa is PermissionSetAttribute)
854 ps = new PermissionSet (sa.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
856 ps = new PermissionSet (PermissionState.None);
858 permissions.Add (action, ps);
859 } else if (!ps.IsUnrestricted () && sa.Unrestricted) {
860 ps = ps.Union (new PermissionSet (PermissionState.Unrestricted));
861 permissions [action] = ps;
863 ps.AddPermission (perm);
866 object GetValue (object value)
868 if (value is EnumConstant)
869 return ((EnumConstant) value).GetValue ();
874 object GetPropertyValue (string name)
876 if (prop_info_arr == null)
879 for (int i = 0; i < prop_info_arr.Length; ++i) {
880 if (prop_info_arr [i].Name == name)
881 return prop_values_arr [i];
887 object GetFieldValue (string name)
890 if (field_info_arr == null)
893 foreach (FieldInfo fi in field_info_arr) {
895 return GetValue (field_values_arr [i]);
901 public UnmanagedMarshal GetMarshal (Attributable attr)
903 UnmanagedType UnmanagedType = (UnmanagedType)System.Enum.Parse (typeof (UnmanagedType), pos_values [0].ToString ());
905 object value = GetFieldValue ("SizeParamIndex");
906 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
907 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
911 object o = GetFieldValue ("ArraySubType");
912 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
914 switch (UnmanagedType) {
915 case UnmanagedType.CustomMarshaler: {
916 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
917 BindingFlags.Static | BindingFlags.Public);
918 if (define_custom == null) {
919 Report.RuntimeMissingSupport (Location, "set marshal info");
923 object [] args = new object [4];
924 args [0] = GetFieldValue ("MarshalTypeRef");
925 args [1] = GetFieldValue ("MarshalCookie");
926 args [2] = GetFieldValue ("MarshalType");
927 args [3] = Guid.Empty;
928 return (UnmanagedMarshal) define_custom.Invoke (null, args);
930 case UnmanagedType.LPArray: {
931 object size_const = GetFieldValue ("SizeConst");
932 object size_param_index = GetFieldValue ("SizeParamIndex");
934 if ((size_const != null) || (size_param_index != null)) {
935 MethodInfo define_array = typeof (UnmanagedMarshal).GetMethod ("DefineLPArrayInternal", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
936 if (define_array == null) {
937 Report.RuntimeMissingSupport (Location, "set marshal info");
941 object [] args = new object [3];
942 args [0] = array_sub_type;
943 args [1] = size_const == null ? -1 : size_const;
944 args [2] = size_param_index == null ? -1 : size_param_index;
945 return (UnmanagedMarshal) define_array.Invoke (null, args);
948 return UnmanagedMarshal.DefineLPArray (array_sub_type);
950 case UnmanagedType.SafeArray:
951 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
953 case UnmanagedType.ByValArray:
954 FieldMember fm = attr as FieldMember;
956 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
959 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
961 case UnmanagedType.ByValTStr:
962 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
965 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
969 public MethodImplOptions GetMethodImplOptions ()
971 return (MethodImplOptions)System.Enum.Parse (typeof (MethodImplOptions), pos_values [0].ToString ());
974 public LayoutKind GetLayoutKindValue ()
976 return (LayoutKind)System.Enum.Parse (typeof (LayoutKind), pos_values [0].ToString ());
980 /// Emit attribute for Attributable symbol
982 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
984 CustomAttributeBuilder cb = Resolve (ec);
988 AttributeUsageAttribute usage_attr = GetAttributeUsage (ec);
989 if ((usage_attr.ValidOn & Target) == 0) {
990 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
995 ias.ApplyAttributeBuilder (this, cb);
997 catch (Exception e) {
998 Error_AttributeEmitError (e.Message);
1002 if (!usage_attr.AllowMultiple) {
1003 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
1004 if (emitted_targets == null) {
1005 emitted_targets = new ArrayList ();
1006 emitted_attr.Add (Type, emitted_targets);
1007 } else if (emitted_targets.Contains (Target)) {
1008 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
1011 emitted_targets.Add (Target);
1014 if (!RootContext.VerifyClsCompliance)
1017 // Here we are testing attribute arguments for array usage (error 3016)
1018 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
1019 if (Arguments == null)
1022 ArrayList pos_args = (ArrayList) Arguments [0];
1023 if (pos_args != null) {
1024 foreach (Argument arg in pos_args) {
1025 // Type is undefined (was error 246)
1026 if (arg.Type == null)
1029 if (arg.Type.IsArray) {
1030 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1036 if (Arguments.Count < 2)
1039 ArrayList named_args = (ArrayList) Arguments [1];
1040 foreach (DictionaryEntry de in named_args) {
1041 Argument arg = (Argument) de.Value;
1043 // Type is undefined (was error 246)
1044 if (arg.Type == null)
1047 if (arg.Type.IsArray) {
1048 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
1055 object GetValue (EmitContext ec, Constant c, Type target)
1057 if (Convert.ImplicitConversionExists (ec, c, target))
1058 return c.GetValue ();
1060 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1064 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1065 MethodAttributes flags, Type ret_type, Type [] param_types)
1067 if (pos_values == null)
1068 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
1069 // But because a lot of attribute class code must be rewritten will be better to wait...
1075 string dll_name = (string)pos_values [0];
1078 CallingConvention cc = CallingConvention.Winapi;
1079 CharSet charset = CharSet.Ansi;
1080 bool preserve_sig = true;
1081 string entry_point = name;
1083 if (field_info_arr != null) {
1084 int char_set_extra = 0;
1086 for (int i = 0; i < field_info_arr.Length; i++) {
1087 switch (field_info_arr [i].Name) {
1088 case "BestFitMapping":
1089 throw new NotImplementedException ();
1090 case "CallingConvention":
1091 cc = (CallingConvention) field_values_arr [i];
1094 charset = (CharSet) field_values_arr [i];
1097 entry_point = (string) field_values_arr [i];
1099 case "ExactSpelling":
1100 char_set_extra |= 0x01;
1103 preserve_sig = (bool) field_values_arr [i];
1105 case "SetLastError":
1106 char_set_extra |= 0x40;
1108 case "ThrowOnUnmappableChar":
1109 throw new NotImplementedException ();
1111 throw new InternalErrorException (field_info_arr [i].ToString ());
1114 charset |= (CharSet)char_set_extra;
1118 MethodBuilder mb = builder.DefinePInvokeMethod (
1119 name, dll_name, entry_point, flags | MethodAttributes.HideBySig | MethodAttributes.PinvokeImpl,
1120 CallingConventions.Standard, ret_type, param_types, cc, charset);
1123 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1127 catch (ArgumentException e) {
1128 Error_AttributeEmitError (e.Message);
1133 private Expression GetValue ()
1135 if ((Arguments == null) || (Arguments.Count < 1))
1137 ArrayList al = (ArrayList) Arguments [0];
1138 if ((al == null) || (al.Count < 1))
1140 Argument arg = (Argument) al [0];
1141 if ((arg == null) || (arg.Expr == null))
1146 public string GetString ()
1148 Expression e = GetValue ();
1149 if (e is StringLiteral)
1150 return (e as StringLiteral).Value;
1154 public bool GetBoolean ()
1156 Expression e = GetValue ();
1157 if (e is BoolLiteral)
1158 return (e as BoolLiteral).Value;
1165 /// For global attributes (assembly, module) we need special handling.
1166 /// Attributes can be located in the several files
1168 public class GlobalAttribute: Attribute
1170 public readonly NamespaceEntry ns;
1172 public GlobalAttribute (TypeContainer container, string target,
1173 Expression left_expr, string identifier, ArrayList args, Location loc):
1174 base (target, left_expr, identifier, args, loc)
1176 ns = container.NamespaceEntry;
1181 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1182 // each time a new file is parsed. However, we need to use the NamespaceEntry
1183 // in effect where the attribute was used. Since code elsewhere cannot assume
1184 // that the NamespaceEntry is right, just overwrite it.
1186 // Precondition: RootContext.Tree.Types == null
1188 if (RootContext.Tree.Types.NamespaceEntry != null)
1189 throw new InternalErrorException (Location + " non-null NamespaceEntry");
1191 RootContext.Tree.Types.NamespaceEntry = ns;
1196 RootContext.Tree.Types.NamespaceEntry = null;
1199 public override Type ResolveType (EmitContext ec)
1202 Type retval = base.ResolveType (ec);
1207 public override CustomAttributeBuilder Resolve (EmitContext ec)
1210 CustomAttributeBuilder retval = base.Resolve (ec);
1216 public class Attributes {
1217 public ArrayList Attrs;
1219 public Attributes (Attribute a)
1221 Attrs = new ArrayList ();
1225 public Attributes (ArrayList attrs)
1230 public void AddAttributes (ArrayList attrs)
1232 Attrs.AddRange (attrs);
1236 /// Checks whether attribute target is valid for the current element
1238 public bool CheckTargets (Attributable member)
1240 string[] valid_targets = member.ValidAttributeTargets;
1241 foreach (Attribute a in Attrs) {
1242 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1243 a.Target = member.AttributeTargets;
1247 // TODO: we can skip the first item
1248 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1249 switch (a.ExplicitTarget) {
1250 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1251 case "param": a.Target = AttributeTargets.Parameter; continue;
1252 case "field": a.Target = AttributeTargets.Field; continue;
1253 case "method": a.Target = AttributeTargets.Method; continue;
1254 case "property": a.Target = AttributeTargets.Property; continue;
1256 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1259 StringBuilder sb = new StringBuilder ();
1260 foreach (string s in valid_targets) {
1264 sb.Remove (sb.Length - 2, 2);
1265 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 ());
1271 public Attribute Search (Type t, EmitContext ec)
1273 foreach (Attribute a in Attrs) {
1274 if (a.ResolveType (ec) == t)
1281 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1283 public Attribute[] SearchMulti (Type t, EmitContext ec)
1285 ArrayList ar = null;
1287 foreach (Attribute a in Attrs) {
1288 if (a.ResolveType (ec) == t) {
1290 ar = new ArrayList ();
1295 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1298 public void Emit (EmitContext ec, Attributable ias)
1302 ListDictionary ld = new ListDictionary ();
1304 foreach (Attribute a in Attrs)
1305 a.Emit (ec, ias, ld);
1308 public bool Contains (Type t, EmitContext ec)
1310 return Search (t, ec) != null;
1315 /// Helper class for attribute verification routine.
1317 sealed class AttributeTester
1319 static PtrHashtable analyzed_types = new PtrHashtable ();
1320 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1321 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1322 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1323 static PtrHashtable fixed_buffer_cache = new PtrHashtable ();
1325 static object TRUE = new object ();
1326 static object FALSE = new object ();
1328 private AttributeTester ()
1333 /// Returns true if parameters of two compared methods are CLS-Compliant.
1334 /// It tests differing only in ref or out, or in array rank.
1336 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1338 if (types_a == null || types_b == null)
1341 if (types_a.Length != types_b.Length)
1344 for (int i = 0; i < types_b.Length; ++i) {
1345 Type aType = types_a [i];
1346 Type bType = types_b [i];
1348 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1352 Type aBaseType = aType;
1353 bool is_either_ref_or_out = false;
1355 if (aType.IsByRef || aType.IsPointer) {
1356 aBaseType = aType.GetElementType ();
1357 is_either_ref_or_out = true;
1360 Type bBaseType = bType;
1361 if (bType.IsByRef || bType.IsPointer)
1363 bBaseType = bType.GetElementType ();
1364 is_either_ref_or_out = !is_either_ref_or_out;
1367 if (aBaseType != bBaseType)
1370 if (is_either_ref_or_out)
1377 /// Goes through all parameters and test if they are CLS-Compliant.
1379 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1381 if (fixedParameters == null)
1384 foreach (Parameter arg in fixedParameters) {
1385 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1386 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1395 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1397 public static bool IsClsCompliant (Type type)
1402 object type_compliance = analyzed_types[type];
1403 if (type_compliance != null)
1404 return type_compliance == TRUE;
1406 if (type.IsPointer) {
1407 analyzed_types.Add (type, null);
1412 if (type.IsArray || type.IsByRef) {
1413 result = IsClsCompliant (TypeManager.GetElementType (type));
1415 result = AnalyzeTypeCompliance (type);
1417 analyzed_types.Add (type, result ? TRUE : FALSE);
1422 /// Returns IFixedBuffer implementation if field is fixed buffer else null.
1424 public static IFixedBuffer GetFixedBuffer (FieldInfo fi)
1426 FieldBase fb = TypeManager.GetField (fi);
1428 return fb as IFixedBuffer;
1431 object o = fixed_buffer_cache [fi];
1433 if (System.Attribute.GetCustomAttribute (fi, TypeManager.fixed_buffer_attr_type) == null) {
1434 fixed_buffer_cache.Add (fi, FALSE);
1438 IFixedBuffer iff = new FixedFieldExternal (fi);
1439 fixed_buffer_cache.Add (fi, iff);
1446 return (IFixedBuffer)o;
1449 public static void VerifyModulesClsCompliance ()
1451 Module[] modules = TypeManager.Modules;
1452 if (modules == null)
1455 // The first module is generated assembly
1456 for (int i = 1; i < modules.Length; ++i) {
1457 Module module = modules [i];
1458 if (!IsClsCompliant (module)) {
1459 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1466 /// Tests container name for CLS-Compliant name (differing only in case)
1468 public static void VerifyTopLevelNameClsCompliance ()
1470 Hashtable locase_table = new Hashtable ();
1472 // Convert imported type names to lower case and ignore not cls compliant
1473 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1474 Type t = (Type)de.Value;
1475 if (!AttributeTester.IsClsCompliant (t))
1478 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1481 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1482 DeclSpace decl = (DeclSpace)de.Value;
1483 if (!decl.IsClsCompliaceRequired (decl))
1486 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1487 if (!locase_table.Contains (lcase)) {
1488 locase_table.Add (lcase, decl);
1492 object conflict = locase_table [lcase];
1493 if (conflict is Type)
1494 Report.SymbolRelatedToPreviousError ((Type)conflict);
1496 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1498 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1502 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1504 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1505 if (CompliantAttribute.Length == 0)
1508 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1511 static bool AnalyzeTypeCompliance (Type type)
1513 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1515 return ds.IsClsCompliaceRequired (ds.Parent);
1518 if (type.IsGenericParameter || type.IsGenericInstance)
1521 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1522 if (CompliantAttribute.Length == 0)
1523 return IsClsCompliant (type.Assembly);
1525 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1529 /// Returns instance of ObsoleteAttribute when type is obsolete
1531 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1533 object type_obsolete = analyzed_types_obsolete [type];
1534 if (type_obsolete == FALSE)
1537 if (type_obsolete != null)
1538 return (ObsoleteAttribute)type_obsolete;
1540 ObsoleteAttribute result = null;
1541 if (type.IsByRef || type.IsArray || type.IsPointer) {
1542 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1543 } else if (type.IsGenericParameter || type.IsGenericInstance)
1546 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1548 // Type is external, we can get attribute directly
1549 if (type_ds == null) {
1550 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1551 if (attribute.Length == 1)
1552 result = (ObsoleteAttribute)attribute [0];
1554 result = type_ds.GetObsoleteAttribute (type_ds);
1558 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1563 /// Returns instance of ObsoleteAttribute when method is obsolete
1565 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1567 IMethodData mc = TypeManager.GetMethod (mb);
1569 return mc.GetObsoleteAttribute ();
1571 // compiler generated methods are not registered by AddMethod
1572 if (mb.DeclaringType is TypeBuilder)
1575 PropertyInfo pi = PropertyExpr.AccessorTable [mb] as PropertyInfo;
1577 return GetMemberObsoleteAttribute (pi);
1579 return GetMemberObsoleteAttribute (mb);
1583 /// Returns instance of ObsoleteAttribute when member is obsolete
1585 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1587 object type_obsolete = analyzed_member_obsolete [mi];
1588 if (type_obsolete == FALSE)
1591 if (type_obsolete != null)
1592 return (ObsoleteAttribute)type_obsolete;
1594 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1597 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1598 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1603 /// Common method for Obsolete error/warning reporting.
1605 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1608 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1612 if (oa.Message == null) {
1613 Report.Warning (612, loc, "'{0}' is obsolete", member);
1616 if (RootContext.WarningLevel >= 2)
1617 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1620 public static bool IsConditionalMethodExcluded (MethodBase mb)
1622 object excluded = analyzed_method_excluded [mb];
1623 if (excluded != null)
1624 return excluded == TRUE ? true : false;
1626 if (mb.Mono_IsInflatedMethod)
1629 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1630 if (attrs.Length == 0) {
1631 analyzed_method_excluded.Add (mb, FALSE);
1635 foreach (ConditionalAttribute a in attrs) {
1636 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1637 analyzed_method_excluded.Add (mb, FALSE);
1641 analyzed_method_excluded.Add (mb, TRUE);