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 ArrayList Arguments;
77 public readonly Location Location;
81 // Is non-null if type is AttributeUsageAttribute
82 AttributeUsageAttribute usage_attribute;
84 public AttributeUsageAttribute UsageAttribute {
86 return usage_attribute;
90 MethodImplOptions ImplOptions;
91 UnmanagedType UnmanagedType;
92 CustomAttributeBuilder cb;
94 // non-null if named args present after Resolve () is called
95 PropertyInfo [] prop_info_arr;
96 FieldInfo [] field_info_arr;
97 object [] field_values_arr;
98 object [] prop_values_arr;
101 static PtrHashtable usage_attr_cache = new PtrHashtable ();
103 public Attribute (string target, string name, ArrayList args, Location loc)
108 ExplicitTarget = target;
111 void Error_InvalidNamedArgument (string name)
113 Report.Error (617, Location, "Invalid attribute argument: '{0}'. Argument must be fields " +
114 "fields which are not readonly, static or const; or read-write instance properties.",
118 static void Error_AttributeArgumentNotValid (Location loc)
120 Report.Error (182, loc,
121 "An attribute argument must be a constant expression, typeof " +
122 "expression or array creation expression");
125 static void Error_TypeParameterInAttribute (Location loc)
128 -202, loc, "Can not use a type parameter in an attribute");
132 /// This is rather hack. We report many emit attribute error with same error to be compatible with
133 /// csc. But because csc has to report them this way because error came from ilasm we needn't.
135 public void Error_AttributeEmitError (string inner)
137 Report.Error (647, Location, "Error emitting '{0}' attribute because '{1}'", Name, inner);
140 public void Error_InvalidSecurityParent ()
142 Error_AttributeEmitError ("it is attached to invalid parent");
145 void Error_AttributeConstructorMismatch ()
147 Report.Error (-6, Location,
148 "Could not find a constructor for this argument list.");
152 /// Tries to resolve the type of the attribute. Flags an error if it can't, and complain is true.
154 protected virtual Type CheckAttributeType (EmitContext ec)
156 string NameAttribute = Name + "Attribute";
157 Type t1 = ec.ResolvingTypeTree
158 ? ec.DeclSpace.FindType (Location, Name)
159 : RootContext.LookupType (ec.DeclSpace, Name, true, Location);
161 // FIXME: Shouldn't do this for quoted attributes: [@A]
162 Type t2 = ec.ResolvingTypeTree
163 ? ec.DeclSpace.FindType (Location, NameAttribute)
164 : RootContext.LookupType (ec.DeclSpace, NameAttribute, true, Location);
166 String err0616 = null;
167 if (t1 != null && ! t1.IsSubclassOf (TypeManager.attribute_type)) {
169 err0616 = "'" + Name + "': is not an attribute class";
171 if (t2 != null && ! t2.IsSubclassOf (TypeManager.attribute_type)) {
173 err0616 = (err0616 != null)
174 ? "Neither '" + Name + "' nor '" + NameAttribute +"' is an attribute class"
175 : "'" + Name + "Attribute': is not an attribute class";
178 if (t1 != null && t2 != null) {
179 Report.Error(1614, Location, "'" + Name + "': is ambiguous; "
180 + " use either '@" + Name + "' or '" + NameAttribute + "'");
187 if (err0616 != null) {
188 Report.Error (616, Location, err0616);
192 Report.Error (246, Location,
193 "Could not find attribute '" + Name
194 + "' (are you missing a using directive or an assembly reference ?)");
199 public Type ResolveType (EmitContext ec)
202 Type = CheckAttributeType (ec);
207 /// Validates the guid string
209 bool ValidateGuid (string guid)
215 Report.Error (647, Location, "Format of GUID is invalid: " + guid);
220 string GetFullMemberName (string member)
222 return Type.FullName + '.' + member;
226 // Given an expression, if the expression is a valid attribute-argument-expression
227 // returns an object that can be used to encode it, or null on failure.
229 public static bool GetAttributeArgumentExpression (Expression e, Location loc, Type arg_type, out object result)
231 if (e is EnumConstant) {
232 if (RootContext.StdLib)
233 result = ((EnumConstant)e).GetValueAsEnumType ();
235 result = ((EnumConstant)e).GetValue ();
240 Constant constant = e as Constant;
241 if (constant != null) {
242 if (e.Type != arg_type) {
243 constant = Const.ChangeType (loc, constant, arg_type);
244 if (constant == null) {
246 Error_AttributeArgumentNotValid (loc);
250 result = constant.GetValue ();
252 } else if (e is TypeOf) {
253 result = ((TypeOf) e).TypeArg;
255 } else if (e is ArrayCreation){
256 result = ((ArrayCreation) e).EncodeAsAttribute ();
259 } else if (e is EmptyCast) {
260 Expression child = ((EmptyCast)e).Child;
261 return GetAttributeArgumentExpression (child, loc, child.Type, out result);
265 Error_AttributeArgumentNotValid (loc);
269 public CustomAttributeBuilder Resolve (EmitContext ec)
274 Type = CheckAttributeType (ec);
276 if (oldType == null && Type == null)
278 if (oldType != null && oldType != Type){
279 Report.Error (-27, Location,
280 "Attribute {0} resolved to different types at different times: {1} vs. {2}",
281 Name, oldType, Type);
285 if (Type.IsAbstract) {
286 Report.Error (653, Location, "Cannot apply attribute class '{0}' because it is abstract", Name);
290 bool MethodImplAttr = false;
291 bool MarshalAsAttr = false;
292 bool GuidAttr = false;
293 bool usage_attr = false;
295 bool DoCompares = true;
298 // If we are a certain special attribute, we
299 // set the information accordingly
302 if (Type == TypeManager.attribute_usage_type)
304 else if (Type == TypeManager.methodimpl_attr_type)
305 MethodImplAttr = true;
306 else if (Type == TypeManager.marshal_as_attr_type)
307 MarshalAsAttr = true;
308 else if (Type == TypeManager.guid_attr_type)
313 // Now we extract the positional and named arguments
315 ArrayList pos_args = new ArrayList ();
316 ArrayList named_args = new ArrayList ();
317 int pos_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];
327 pos_values = new object [pos_arg_count];
330 // First process positional arguments
334 for (i = 0; i < pos_arg_count; i++) {
335 Argument a = (Argument) pos_args [i];
338 if (!a.Resolve (ec, Location))
344 if (!GetAttributeArgumentExpression (e, Location, a.Type, out val))
347 pos_values [i] = val;
351 usage_attribute = new AttributeUsageAttribute ((AttributeTargets)val);
352 } else if (MethodImplAttr) {
353 this.ImplOptions = (MethodImplOptions) val;
354 } else if (GuidAttr){
356 // we will later check the validity of the type
359 if (!ValidateGuid ((string) val))
363 } else if (MarshalAsAttr)
365 (System.Runtime.InteropServices.UnmanagedType) val;
370 // Now process named arguments
373 ArrayList field_infos = null;
374 ArrayList prop_infos = null;
375 ArrayList field_values = null;
376 ArrayList prop_values = null;
378 if (named_args.Count > 0) {
379 field_infos = new ArrayList ();
380 prop_infos = new ArrayList ();
381 field_values = new ArrayList ();
382 prop_values = new ArrayList ();
385 Hashtable seen_names = new Hashtable();
387 for (i = 0; i < named_args.Count; i++) {
388 DictionaryEntry de = (DictionaryEntry) named_args [i];
389 string member_name = (string) de.Key;
390 Argument a = (Argument) de.Value;
393 if (seen_names.Contains(member_name)) {
394 Report.Error(643, Location, "'" + member_name + "' duplicate named attribute argument");
397 seen_names.Add(member_name, 1);
399 if (!a.Resolve (ec, Location))
402 Expression member = Expression.MemberLookup (
403 ec, Type, member_name,
404 MemberTypes.Field | MemberTypes.Property,
405 BindingFlags.Public | BindingFlags.Instance,
408 if (member == null) {
409 member = Expression.MemberLookup (ec, Type, member_name,
410 MemberTypes.Field | MemberTypes.Property, BindingFlags.NonPublic | BindingFlags.Instance,
413 if (member != null) {
414 Report.Error (122, Location, "'{0}' is inaccessible due to its protection level", GetFullMemberName (member_name));
420 Report.Error (117, Location, "Attribute `{0}' does not contain a definition for `{1}'",
425 if (!(member is PropertyExpr || member is FieldExpr)) {
426 Error_InvalidNamedArgument (member_name);
431 if (e is TypeParameterExpr){
432 Error_TypeParameterInAttribute (Location);
436 if (member is PropertyExpr) {
437 PropertyExpr pe = (PropertyExpr) member;
438 PropertyInfo pi = pe.PropertyInfo;
440 if (!pi.CanWrite || !pi.CanRead) {
441 Report.SymbolRelatedToPreviousError (pi);
442 Error_InvalidNamedArgument (member_name);
447 if (!GetAttributeArgumentExpression (e, Location, pi.PropertyType, out value))
450 if (usage_attribute != null) {
451 if (member_name == "AllowMultiple")
452 usage_attribute.AllowMultiple = (bool) value;
453 if (member_name == "Inherited")
454 usage_attribute.Inherited = (bool) value;
457 prop_values.Add (value);
460 } else if (member is FieldExpr) {
461 FieldExpr fe = (FieldExpr) member;
462 FieldInfo fi = fe.FieldInfo;
465 Error_InvalidNamedArgument (member_name);
470 if (!GetAttributeArgumentExpression (e, Location, fi.FieldType, out value))
473 field_values.Add (value);
475 field_infos.Add (fi);
479 Expression mg = Expression.MemberLookup (
480 ec, Type, ".ctor", MemberTypes.Constructor,
481 BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly,
485 Error_AttributeConstructorMismatch ();
489 MethodBase constructor = Invocation.OverloadResolve (
490 ec, (MethodGroupExpr) mg, pos_args, false, Location);
492 if (constructor == null) {
497 // Now we perform some checks on the positional args as they
498 // cannot be null for a constructor which expects a parameter
502 ParameterData pd = Invocation.GetParameterData (constructor);
504 int last_real_param = pd.Count;
506 // When the params is not filled we need to put one
507 if (last_real_param > pos_arg_count) {
508 object [] new_pos_values = new object [pos_arg_count + 1];
509 pos_values.CopyTo (new_pos_values, 0);
510 new_pos_values [pos_arg_count] = new object [] {} ;
511 pos_values = new_pos_values;
516 for (int j = 0; j < pos_arg_count; ++j) {
517 Argument a = (Argument) pos_args [j];
519 if (a.Expr is NullLiteral && pd.ParameterType (j) == TypeManager.object_type) {
520 Error_AttributeArgumentNotValid (Location);
524 if (j < last_real_param)
527 if (j == last_real_param) {
528 object [] array = new object [pos_arg_count - last_real_param];
529 array [0] = pos_values [j];
530 pos_values [j] = array;
534 object [] params_array = (object []) pos_values [last_real_param];
535 params_array [j - last_real_param] = pos_values [j];
538 // Adjust the size of the pos_values if it had params
539 if (last_real_param != pos_arg_count) {
540 object [] new_pos_values = new object [last_real_param + 1];
541 Array.Copy (pos_values, new_pos_values, last_real_param + 1);
542 pos_values = new_pos_values;
546 if (named_args.Count > 0) {
547 prop_info_arr = new PropertyInfo [prop_infos.Count];
548 field_info_arr = new FieldInfo [field_infos.Count];
549 field_values_arr = new object [field_values.Count];
550 prop_values_arr = new object [prop_values.Count];
552 field_infos.CopyTo (field_info_arr, 0);
553 field_values.CopyTo (field_values_arr, 0);
555 prop_values.CopyTo (prop_values_arr, 0);
556 prop_infos.CopyTo (prop_info_arr, 0);
558 cb = new CustomAttributeBuilder (
559 (ConstructorInfo) constructor, pos_values,
560 prop_info_arr, prop_values_arr,
561 field_info_arr, field_values_arr);
564 cb = new CustomAttributeBuilder (
565 (ConstructorInfo) constructor, pos_values);
566 } catch (NullReferenceException) {
568 // Don't know what to do here
571 -101, Location, "NullReferenceException while trying to create attribute." +
572 "Something's wrong!");
573 } catch (Exception e) {
576 // using System.ComponentModel;
577 // [DefaultValue (CollectionChangeAction.Add)]
578 // class X { static void Main () {} }
581 -23, Location, "The compiler can not encode this attribute in .NET due to a bug in the .NET runtime. Try the Mono runtime. The exception was: " + e.Message);
588 /// Get a string containing a list of valid targets for the attribute 'attr'
590 public string GetValidTargets ()
592 StringBuilder sb = new StringBuilder ();
593 AttributeTargets targets = GetAttributeUsage ().ValidOn;
595 if ((targets & AttributeTargets.Assembly) != 0)
596 sb.Append ("'assembly' ");
598 if ((targets & AttributeTargets.Class) != 0)
599 sb.Append ("'class' ");
601 if ((targets & AttributeTargets.Constructor) != 0)
602 sb.Append ("'constructor' ");
604 if ((targets & AttributeTargets.Delegate) != 0)
605 sb.Append ("'delegate' ");
607 if ((targets & AttributeTargets.Enum) != 0)
608 sb.Append ("'enum' ");
610 if ((targets & AttributeTargets.Event) != 0)
611 sb.Append ("'event' ");
613 if ((targets & AttributeTargets.Field) != 0)
614 sb.Append ("'field' ");
616 if ((targets & AttributeTargets.Interface) != 0)
617 sb.Append ("'interface' ");
619 if ((targets & AttributeTargets.Method) != 0)
620 sb.Append ("'method' ");
622 if ((targets & AttributeTargets.Module) != 0)
623 sb.Append ("'module' ");
625 if ((targets & AttributeTargets.Parameter) != 0)
626 sb.Append ("'parameter' ");
628 if ((targets & AttributeTargets.Property) != 0)
629 sb.Append ("'property' ");
631 if ((targets & AttributeTargets.ReturnValue) != 0)
632 sb.Append ("'return' ");
634 if ((targets & AttributeTargets.Struct) != 0)
635 sb.Append ("'struct' ");
637 return sb.ToString ();
642 /// Returns AttributeUsage attribute for this type
644 public AttributeUsageAttribute GetAttributeUsage ()
646 AttributeUsageAttribute ua = usage_attr_cache [Type] as AttributeUsageAttribute;
650 Class attr_class = TypeManager.LookupClass (Type);
652 if (attr_class == null) {
653 object[] usage_attr = Type.GetCustomAttributes (TypeManager.attribute_usage_type, true);
654 ua = (AttributeUsageAttribute)usage_attr [0];
655 usage_attr_cache.Add (Type, ua);
659 return attr_class.AttributeUsage;
663 /// Returns custom name of indexer
665 public string GetIndexerAttributeValue (EmitContext ec)
667 if (pos_values == null) {
668 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
669 // But because a lot of attribute class code must be rewritten will be better to wait...
673 return pos_values [0] as string;
677 /// Returns condition of ConditionalAttribute
679 public string GetConditionalAttributeValue (DeclSpace ds)
681 if (pos_values == null) {
682 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
684 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
685 // But because a lot of attribute class code must be rewritten will be better to wait...
689 // Some error occurred
690 if (pos_values [0] == null)
693 return (string)pos_values [0];
697 /// Creates the instance of ObsoleteAttribute from this attribute instance
699 public ObsoleteAttribute GetObsoleteAttribute (DeclSpace ds)
701 if (pos_values == null) {
702 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
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...
709 // Some error occurred
710 if (pos_values == null)
713 if (pos_values.Length == 0)
714 return new ObsoleteAttribute ();
716 if (pos_values.Length == 1)
717 return new ObsoleteAttribute ((string)pos_values [0]);
719 return new ObsoleteAttribute ((string)pos_values [0], (bool)pos_values [1]);
723 /// Returns value of CLSCompliantAttribute contructor parameter but because the method can be called
724 /// before ApplyAttribute. We need to resolve the arguments.
725 /// This situation occurs when class deps is differs from Emit order.
727 public bool GetClsCompliantAttributeValue (DeclSpace ds)
729 if (pos_values == null) {
730 EmitContext ec = new EmitContext (ds, ds, Location, null, null, 0, false);
732 // TODO: It is not neccessary to call whole Resolve (ApplyAttribute does it now) we need only ctor args.
733 // But because a lot of attribute class code must be rewritten will be better to wait...
737 // Some error occurred
738 if (pos_values [0] == null)
741 return (bool)pos_values [0];
745 /// Tests permitted SecurityAction for assembly or other types
747 public bool CheckSecurityActionValidity (bool for_assembly)
749 SecurityAction action = GetSecurityActionValue ();
751 if ((action == SecurityAction.RequestMinimum || action == SecurityAction.RequestOptional || action == SecurityAction.RequestRefuse) && for_assembly)
755 if (action < SecurityAction.Demand || action > SecurityAction.InheritanceDemand) {
756 Error_AttributeEmitError ("SecurityAction is out of range");
760 if ((action != SecurityAction.RequestMinimum && action != SecurityAction.RequestOptional && action != SecurityAction.RequestRefuse) && !for_assembly)
764 Error_AttributeEmitError (String.Concat ("SecurityAction '", action, "' is not valid for this declaration"));
768 System.Security.Permissions.SecurityAction GetSecurityActionValue ()
770 return (SecurityAction)pos_values [0];
774 /// Creates instance of SecurityAttribute class and add result of CreatePermission method to permission table.
776 /// <returns></returns>
777 public void ExtractSecurityPermissionSet (ListDictionary permissions)
779 if (TypeManager.LookupDeclSpace (Type) != null && RootContext.StdLib) {
780 Error_AttributeEmitError ("security custom attributes can not be referenced from defining assembly");
784 SecurityAttribute sa;
785 // For all assemblies except corlib we can avoid all hacks
786 if (RootContext.StdLib) {
787 sa = (SecurityAttribute) Activator.CreateInstance (Type, pos_values);
789 if (prop_info_arr != null) {
790 for (int i = 0; i < prop_info_arr.Length; ++i) {
791 PropertyInfo pi = prop_info_arr [i];
792 pi.SetValue (sa, prop_values_arr [i], null);
796 Type temp_type = Type.GetType (Type.FullName);
797 // HACK: All mscorlib attributes have same ctor syntax
798 sa = (SecurityAttribute) Activator.CreateInstance (temp_type, new object[] { GetSecurityActionValue () } );
800 // All types are from newly created corlib but for invocation with old we need to convert them
801 if (prop_info_arr != null) {
802 for (int i = 0; i < prop_info_arr.Length; ++i) {
803 PropertyInfo emited_pi = prop_info_arr [i];
804 PropertyInfo pi = temp_type.GetProperty (emited_pi.Name, emited_pi.PropertyType);
806 object old_instance = pi.PropertyType.IsEnum ?
807 System.Enum.ToObject (pi.PropertyType, prop_values_arr [i]) :
810 pi.SetValue (sa, old_instance, null);
815 IPermission perm = sa.CreatePermission ();
816 SecurityAction action;
818 // IS is correct because for corlib we are using an instance from old corlib
819 if (perm is System.Security.CodeAccessPermission) {
820 action = GetSecurityActionValue ();
822 switch (GetSecurityActionValue ()) {
823 case SecurityAction.Demand:
824 action = (SecurityAction)13;
826 case SecurityAction.LinkDemand:
827 action = (SecurityAction)14;
829 case SecurityAction.InheritanceDemand:
830 action = (SecurityAction)15;
833 Error_AttributeEmitError ("Invalid SecurityAction for non-Code Access Security permission");
838 PermissionSet ps = (PermissionSet)permissions [action];
840 ps = new PermissionSet (PermissionState.None);
841 permissions.Add (action, ps);
843 ps.AddPermission (sa.CreatePermission ());
846 object GetValue (object value)
848 if (value is EnumConstant)
849 return ((EnumConstant) value).GetValue ();
854 public object GetPositionalValue (int i)
856 return (pos_values == null) ? null : pos_values[i];
859 object GetFieldValue (string name)
862 if (field_info_arr == null)
865 foreach (FieldInfo fi in field_info_arr) {
867 return GetValue (field_values_arr [i]);
873 public UnmanagedMarshal GetMarshal (Attributable attr)
875 object value = GetFieldValue ("SizeParamIndex");
876 if (value != null && UnmanagedType != UnmanagedType.LPArray) {
877 Error_AttributeEmitError ("SizeParamIndex field is not valid for the specified unmanaged type");
881 object o = GetFieldValue ("ArraySubType");
882 UnmanagedType array_sub_type = o == null ? UnmanagedType.I4 : (UnmanagedType) o;
884 switch (UnmanagedType) {
885 case UnmanagedType.CustomMarshaler:
886 MethodInfo define_custom = typeof (UnmanagedMarshal).GetMethod ("DefineCustom",
887 BindingFlags.Static | BindingFlags.Public);
888 if (define_custom == null) {
889 Report.RuntimeMissingSupport (Location, "set marshal info");
893 object [] args = new object [4];
894 args [0] = GetFieldValue ("MarshalTypeRef");
895 args [1] = GetFieldValue ("MarshalCookie");
896 args [2] = GetFieldValue ("MarshalType");
897 args [3] = Guid.Empty;
898 return (UnmanagedMarshal) define_custom.Invoke (null, args);
900 case UnmanagedType.LPArray:
901 return UnmanagedMarshal.DefineLPArray (array_sub_type);
903 case UnmanagedType.SafeArray:
904 return UnmanagedMarshal.DefineSafeArray (array_sub_type);
906 case UnmanagedType.ByValArray:
907 FieldMember fm = attr as FieldMember;
909 Error_AttributeEmitError ("Specified unmanaged type is only valid on fields");
912 return UnmanagedMarshal.DefineByValArray ((int) GetFieldValue ("SizeConst"));
914 case UnmanagedType.ByValTStr:
915 return UnmanagedMarshal.DefineByValTStr ((int) GetFieldValue ("SizeConst"));
918 return UnmanagedMarshal.DefineUnmanagedMarshal (UnmanagedType);
922 public bool IsInternalCall
924 get { return ImplOptions == MethodImplOptions.InternalCall; }
928 /// Emit attribute for Attributable symbol
930 public void Emit (EmitContext ec, Attributable ias, ListDictionary emitted_attr)
932 CustomAttributeBuilder cb = Resolve (ec);
936 AttributeUsageAttribute usage_attr = GetAttributeUsage ();
937 if ((usage_attr.ValidOn & Target) == 0) {
938 Report.Error (592, Location, "Attribute '{0}' is not valid on this declaration type. It is valid on {1} declarations only.", Name, GetValidTargets ());
942 ias.ApplyAttributeBuilder (this, cb);
944 if (!usage_attr.AllowMultiple) {
945 ArrayList emitted_targets = (ArrayList)emitted_attr [Type];
946 if (emitted_targets == null) {
947 emitted_targets = new ArrayList ();
948 emitted_attr.Add (Type, emitted_targets);
949 } else if (emitted_targets.Contains (Target)) {
950 Report.Error (579, Location, "Duplicate '" + Name + "' attribute");
953 emitted_targets.Add (Target);
956 if (!RootContext.VerifyClsCompliance)
959 // Here we are testing attribute arguments for array usage (error 3016)
960 if (ias.IsClsCompliaceRequired (ec.DeclSpace)) {
961 if (Arguments == null)
964 ArrayList pos_args = (ArrayList) Arguments [0];
965 if (pos_args != null) {
966 foreach (Argument arg in pos_args) {
967 // Type is undefined (was error 246)
968 if (arg.Type == null)
971 if (arg.Type.IsArray) {
972 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
978 if (Arguments.Count < 2)
981 ArrayList named_args = (ArrayList) Arguments [1];
982 foreach (DictionaryEntry de in named_args) {
983 Argument arg = (Argument) de.Value;
985 // Type is undefined (was error 246)
986 if (arg.Type == null)
989 if (arg.Type.IsArray) {
990 Report.Error (3016, Location, "Arrays as attribute arguments are not CLS-compliant");
997 public object GetValue (EmitContext ec, Constant c, Type target)
999 if (Convert.ImplicitConversionExists (ec, c, target))
1000 return c.GetValue ();
1002 Convert.Error_CannotImplicitConversion (Location, c.Type, target);
1006 public MethodBuilder DefinePInvokeMethod (EmitContext ec, TypeBuilder builder, string name,
1007 MethodAttributes flags, Type ret_type, Type [] param_types)
1010 // We extract from the attribute the information we need
1013 if (Arguments == null) {
1014 Console.WriteLine ("Internal error : this is not supposed to happen !");
1022 ArrayList named_args = new ArrayList ();
1024 ArrayList pos_args = (ArrayList) Arguments [0];
1025 if (Arguments.Count > 1)
1026 named_args = (ArrayList) Arguments [1];
1029 string dll_name = null;
1031 Argument tmp = (Argument) pos_args [0];
1033 if (!tmp.Resolve (ec, Location))
1036 if (tmp.Expr is Constant)
1037 dll_name = (string) ((Constant) tmp.Expr).GetValue ();
1039 Error_AttributeArgumentNotValid (Location);
1043 // Now we process the named arguments
1044 CallingConvention cc = CallingConvention.Winapi;
1045 CharSet charset = CharSet.Ansi;
1046 bool preserve_sig = true;
1048 bool exact_spelling = false;
1050 bool set_last_err = false;
1051 string entry_point = null;
1053 for (int i = 0; i < named_args.Count; i++) {
1055 DictionaryEntry de = (DictionaryEntry) named_args [i];
1057 string member_name = (string) de.Key;
1058 Argument a = (Argument) de.Value;
1060 if (!a.Resolve (ec, Location))
1063 Expression member = Expression.MemberLookup (
1064 ec, Type, member_name,
1065 MemberTypes.Field | MemberTypes.Property,
1066 BindingFlags.Public | BindingFlags.Instance,
1069 if (member == null || !(member is FieldExpr)) {
1070 Error_InvalidNamedArgument (member_name);
1074 if (member is FieldExpr) {
1075 FieldExpr fe = (FieldExpr) member;
1076 FieldInfo fi = fe.FieldInfo;
1078 if (fi.IsInitOnly) {
1079 Error_InvalidNamedArgument (member_name);
1083 if (a.Expr is Constant) {
1084 Constant c = (Constant) a.Expr;
1087 if (member_name == "CallingConvention"){
1088 object val = GetValue (ec, c, typeof (CallingConvention));
1091 cc = (CallingConvention) val;
1092 } else if (member_name == "CharSet"){
1093 charset = (CharSet) c.GetValue ();
1094 } else if (member_name == "EntryPoint")
1095 entry_point = (string) c.GetValue ();
1096 else if (member_name == "SetLastError")
1097 set_last_err = (bool) c.GetValue ();
1099 else if (member_name == "ExactSpelling")
1100 exact_spelling = (bool) c.GetValue ();
1102 else if (member_name == "PreserveSig")
1103 preserve_sig = (bool) c.GetValue ();
1104 } catch (InvalidCastException){
1105 Error_InvalidNamedArgument (member_name);
1106 Error_AttributeArgumentNotValid (Location);
1109 Error_AttributeArgumentNotValid (Location);
1116 if (entry_point == null)
1119 charset = (CharSet)((int)charset | 0x40);
1121 MethodBuilder mb = builder.DefinePInvokeMethod (
1122 name, dll_name, entry_point, flags | MethodAttributes.HideBySig,
1123 CallingConventions.Standard,
1130 mb.SetImplementationFlags (MethodImplAttributes.PreserveSig);
1135 private Expression GetValue ()
1137 if ((Arguments == null) || (Arguments.Count < 1))
1139 ArrayList al = (ArrayList) Arguments [0];
1140 if ((al == null) || (al.Count < 1))
1142 Argument arg = (Argument) al [0];
1143 if ((arg == null) || (arg.Expr == null))
1148 public string GetString ()
1150 Expression e = GetValue ();
1151 if (e is StringLiteral)
1152 return (e as StringLiteral).Value;
1156 public bool GetBoolean ()
1158 Expression e = GetValue ();
1159 if (e is BoolLiteral)
1160 return (e as BoolLiteral).Value;
1167 /// For global attributes (assembly, module) we need special handling.
1168 /// Attributes can be located in the several files
1170 public class GlobalAttribute: Attribute
1172 public readonly NamespaceEntry ns;
1174 public GlobalAttribute (TypeContainer container, string target, string name, ArrayList args, Location loc):
1175 base (target, name, args, loc)
1177 ns = container.NamespaceEntry;
1180 protected override Type CheckAttributeType (EmitContext ec)
1182 // RootContext.Tree.Types has a single NamespaceEntry which gets overwritten
1183 // each time a new file is parsed. However, we need to use the NamespaceEntry
1184 // in effect where the attribute was used. Since code elsewhere cannot assume
1185 // that the NamespaceEntry is right, just overwrite it.
1187 // FIXME: Check every place the NamespaceEntry of RootContext.Tree.Types is used
1188 // to ensure the right one is used.
1189 if (ec.DeclSpace == RootContext.Tree.Types)
1190 ec.DeclSpace.NamespaceEntry = ns;
1192 return base.CheckAttributeType (ec);
1196 public class Attributes {
1197 public ArrayList Attrs;
1199 public Attributes (Attribute a)
1201 Attrs = new ArrayList ();
1205 public Attributes (ArrayList attrs)
1210 public void AddAttributes (ArrayList attrs)
1212 Attrs.AddRange (attrs);
1216 /// Checks whether attribute target is valid for the current element
1218 public bool CheckTargets (Attributable member)
1220 string[] valid_targets = member.ValidAttributeTargets;
1221 foreach (Attribute a in Attrs) {
1222 if (a.ExplicitTarget == null || a.ExplicitTarget == valid_targets [0]) {
1223 a.Target = member.AttributeTargets;
1227 // TODO: we can skip the first item
1228 if (((IList) valid_targets).Contains (a.ExplicitTarget)) {
1229 switch (a.ExplicitTarget) {
1230 case "return": a.Target = AttributeTargets.ReturnValue; continue;
1231 case "param": a.Target = AttributeTargets.Parameter; continue;
1232 case "field": a.Target = AttributeTargets.Field; continue;
1233 case "method": a.Target = AttributeTargets.Method; continue;
1234 case "property": a.Target = AttributeTargets.Property; continue;
1236 throw new InternalErrorException ("Unknown explicit target: " + a.ExplicitTarget);
1239 StringBuilder sb = new StringBuilder ();
1240 foreach (string s in valid_targets) {
1244 sb.Remove (sb.Length - 2, 2);
1245 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 ());
1251 public Attribute Search (Type t, EmitContext ec)
1253 foreach (Attribute a in Attrs) {
1254 if (a.ResolveType (ec) == t)
1261 /// Returns all attributes of type 't'. Use it when attribute is AllowMultiple = true
1263 public Attribute[] SearchMulti (Type t, EmitContext ec)
1265 ArrayList ar = null;
1267 foreach (Attribute a in Attrs) {
1268 if (a.ResolveType (ec) == t) {
1270 ar = new ArrayList ();
1275 return ar == null ? null : ar.ToArray (typeof (Attribute)) as Attribute[];
1278 public void Emit (EmitContext ec, Attributable ias)
1280 if (!CheckTargets (ias))
1283 ListDictionary ld = new ListDictionary ();
1285 foreach (Attribute a in Attrs)
1286 a.Emit (ec, ias, ld);
1289 public bool Contains (Type t, EmitContext ec)
1291 return Search (t, ec) != null;
1296 /// Helper class for attribute verification routine.
1298 sealed class AttributeTester
1300 static PtrHashtable analyzed_types = new PtrHashtable ();
1301 static PtrHashtable analyzed_types_obsolete = new PtrHashtable ();
1302 static PtrHashtable analyzed_member_obsolete = new PtrHashtable ();
1303 static PtrHashtable analyzed_method_excluded = new PtrHashtable ();
1305 private AttributeTester ()
1310 /// Returns true if parameters of two compared methods are CLS-Compliant.
1311 /// It tests differing only in ref or out, or in array rank.
1313 public static bool AreOverloadedMethodParamsClsCompliant (Type[] types_a, Type[] types_b)
1315 if (types_a == null || types_b == null)
1318 if (types_a.Length != types_b.Length)
1321 for (int i = 0; i < types_b.Length; ++i) {
1322 Type aType = types_a [i];
1323 Type bType = types_b [i];
1325 if (aType.IsArray && bType.IsArray && aType.GetArrayRank () != bType.GetArrayRank () && aType.GetElementType () == bType.GetElementType ()) {
1329 Type aBaseType = aType;
1330 bool is_either_ref_or_out = false;
1332 if (aType.IsByRef || aType.IsPointer) {
1333 aBaseType = aType.GetElementType ();
1334 is_either_ref_or_out = true;
1337 Type bBaseType = bType;
1338 if (bType.IsByRef || bType.IsPointer)
1340 bBaseType = bType.GetElementType ();
1341 is_either_ref_or_out = !is_either_ref_or_out;
1344 if (aBaseType != bBaseType)
1347 if (is_either_ref_or_out)
1354 /// Goes through all parameters and test if they are CLS-Compliant.
1356 public static bool AreParametersCompliant (Parameter[] fixedParameters, Location loc)
1358 if (fixedParameters == null)
1361 foreach (Parameter arg in fixedParameters) {
1362 if (!AttributeTester.IsClsCompliant (arg.ParameterType)) {
1363 Report.Error (3001, loc, "Argument type '{0}' is not CLS-compliant", arg.GetSignatureForError ());
1372 /// This method tests the CLS compliance of external types. It doesn't test type visibility.
1374 public static bool IsClsCompliant (Type type)
1379 object type_compliance = analyzed_types[type];
1380 if (type_compliance != null)
1381 return type_compliance == TRUE;
1383 if (type.IsPointer) {
1384 analyzed_types.Add (type, null);
1389 if (type.IsArray || type.IsByRef) {
1390 result = IsClsCompliant (TypeManager.GetElementType (type));
1392 result = AnalyzeTypeCompliance (type);
1394 analyzed_types.Add (type, result ? TRUE : FALSE);
1398 static object TRUE = new object ();
1399 static object FALSE = new object ();
1401 public static void VerifyModulesClsCompliance ()
1403 Module[] modules = TypeManager.Modules;
1404 if (modules == null)
1407 // The first module is generated assembly
1408 for (int i = 1; i < modules.Length; ++i) {
1409 Module module = modules [i];
1410 if (!IsClsCompliant (module)) {
1411 Report.Error (3013, "Added modules must be marked with the CLSCompliant attribute to match the assembly", module.Name);
1418 /// Tests container name for CLS-Compliant name (differing only in case)
1420 public static void VerifyTopLevelNameClsCompliance ()
1422 Hashtable locase_table = new Hashtable ();
1424 // Convert imported type names to lower case and ignore not cls compliant
1425 foreach (DictionaryEntry de in TypeManager.all_imported_types) {
1426 Type t = (Type)de.Value;
1427 if (!AttributeTester.IsClsCompliant (t))
1430 locase_table.Add (((string)de.Key).ToLower (System.Globalization.CultureInfo.InvariantCulture), t);
1433 foreach (DictionaryEntry de in RootContext.Tree.Decls) {
1434 DeclSpace decl = (DeclSpace)de.Value;
1435 if (!decl.IsClsCompliaceRequired (decl))
1438 string lcase = decl.Name.ToLower (System.Globalization.CultureInfo.InvariantCulture);
1439 if (!locase_table.Contains (lcase)) {
1440 locase_table.Add (lcase, decl);
1444 object conflict = locase_table [lcase];
1445 if (conflict is Type)
1446 Report.SymbolRelatedToPreviousError ((Type)conflict);
1448 Report.SymbolRelatedToPreviousError ((MemberCore)conflict);
1450 Report.Error (3005, decl.Location, "Identifier '{0}' differing only in case is not CLS-compliant", decl.GetSignatureForError ());
1454 static bool IsClsCompliant (ICustomAttributeProvider attribute_provider)
1456 object[] CompliantAttribute = attribute_provider.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1457 if (CompliantAttribute.Length == 0)
1460 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1463 static bool AnalyzeTypeCompliance (Type type)
1465 DeclSpace ds = TypeManager.LookupDeclSpace (type);
1467 return ds.IsClsCompliaceRequired (ds.Parent);
1470 if (type.IsGenericParameter || type.IsGenericInstance)
1473 object[] CompliantAttribute = type.GetCustomAttributes (TypeManager.cls_compliant_attribute_type, false);
1474 if (CompliantAttribute.Length == 0)
1475 return IsClsCompliant (type.Assembly);
1477 return ((CLSCompliantAttribute)CompliantAttribute[0]).IsCompliant;
1481 /// Returns instance of ObsoleteAttribute when type is obsolete
1483 public static ObsoleteAttribute GetObsoleteAttribute (Type type)
1485 object type_obsolete = analyzed_types_obsolete [type];
1486 if (type_obsolete == FALSE)
1489 if (type_obsolete != null)
1490 return (ObsoleteAttribute)type_obsolete;
1492 ObsoleteAttribute result = null;
1493 if (type.IsByRef || type.IsArray || type.IsPointer) {
1494 result = GetObsoleteAttribute (TypeManager.GetElementType (type));
1495 } else if (type.IsGenericParameter || type.IsGenericInstance)
1498 DeclSpace type_ds = TypeManager.LookupDeclSpace (type);
1500 // Type is external, we can get attribute directly
1501 if (type_ds == null) {
1502 object[] attribute = type.GetCustomAttributes (TypeManager.obsolete_attribute_type, false);
1503 if (attribute.Length == 1)
1504 result = (ObsoleteAttribute)attribute [0];
1506 result = type_ds.GetObsoleteAttribute (type_ds);
1510 analyzed_types_obsolete.Add (type, result == null ? FALSE : result);
1515 /// Returns instance of ObsoleteAttribute when method is obsolete
1517 public static ObsoleteAttribute GetMethodObsoleteAttribute (MethodBase mb)
1519 IMethodData mc = TypeManager.GetMethod (mb);
1521 return mc.GetObsoleteAttribute ();
1523 // compiler generated methods are not registered by AddMethod
1524 if (mb.DeclaringType is TypeBuilder)
1527 return GetMemberObsoleteAttribute (mb);
1531 /// Returns instance of ObsoleteAttribute when member is obsolete
1533 public static ObsoleteAttribute GetMemberObsoleteAttribute (MemberInfo mi)
1535 object type_obsolete = analyzed_member_obsolete [mi];
1536 if (type_obsolete == FALSE)
1539 if (type_obsolete != null)
1540 return (ObsoleteAttribute)type_obsolete;
1542 if ((mi.DeclaringType is TypeBuilder) || mi.DeclaringType.IsGenericInstance)
1545 ObsoleteAttribute oa = System.Attribute.GetCustomAttribute (mi, TypeManager.obsolete_attribute_type, false) as ObsoleteAttribute;
1546 analyzed_member_obsolete.Add (mi, oa == null ? FALSE : oa);
1551 /// Common method for Obsolete error/warning reporting.
1553 public static void Report_ObsoleteMessage (ObsoleteAttribute oa, string member, Location loc)
1556 Report.Error (619, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1560 if (oa.Message == null) {
1561 Report.Warning (612, loc, "'{0}' is obsolete", member);
1564 if (RootContext.WarningLevel >= 2)
1565 Report.Warning (618, loc, "'{0}' is obsolete: '{1}'", member, oa.Message);
1568 public static bool IsConditionalMethodExcluded (MethodBase mb)
1570 object excluded = analyzed_method_excluded [mb];
1571 if (excluded != null)
1572 return excluded == TRUE ? true : false;
1574 if (mb.Mono_IsInflatedMethod)
1577 ConditionalAttribute[] attrs = mb.GetCustomAttributes (TypeManager.conditional_attribute_type, true) as ConditionalAttribute[];
1578 if (attrs.Length == 0) {
1579 analyzed_method_excluded.Add (mb, FALSE);
1583 foreach (ConditionalAttribute a in attrs) {
1584 if (RootContext.AllDefines.Contains (a.ConditionString)) {
1585 analyzed_method_excluded.Add (mb, FALSE);
1589 analyzed_method_excluded.Add (mb, TRUE);